-
Notifications
You must be signed in to change notification settings - Fork 24
/
nsiqcppstyle_reporter.py
244 lines (195 loc) · 9.02 KB
/
nsiqcppstyle_reporter.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
# Copyright (c) 2009 NHN Inc. All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of NHN Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import csv
import os
import sys
import nsiqcppstyle_checker
import nsiqcppstyle_rulemanager
import nsiqcppstyle_state
from nsiqcppstyle_outputer import _consoleOutputer as console
##########################################################################
csvfile = None
writer = None
target = None
def PrepareReport(outputPath, format):
"""
Set up sth like report headers
"""
global writer
if format == "csv":
if os.path.isdir(outputPath):
outputPath = os.path.join(outputPath, "nsiqcppstyle_report.csv")
csvfile = open(outputPath, "w")
writer = csv.writer(csvfile)
writer.writerow(("File", "Line", "Column", "Message", "Rule", "Rule Url"))
elif format == "xml":
if os.path.isdir(outputPath):
outputPath = os.path.join(outputPath, "nsiqcppstyle_report.xml")
writer = open(outputPath, "w")
writer.write("<?xml version='1.0'?>\n<checkstyle version='4.4'>\n")
def ReportSummaryToScreen(analyzedFiles, nsiqcppstyle_state, filter):
"""
Report Summary Info into the screen.
"""
fileCount = len(analyzedFiles)
violatedFileCount = len(nsiqcppstyle_state.errorPerFile.keys())
buildQuality = 0
if fileCount != 0:
buildQuality = (fileCount - violatedFileCount) * 100.0 / fileCount
console.Out.Ci("\n")
console.Out.Ci("=================================== Summary Report ===================================")
console.Out.Ci(" ** Total Available Rules : %d" % nsiqcppstyle_rulemanager.ruleManager.availRuleCount)
console.Out.Ci(" ** Total Applied Rules : %d" % len(nsiqcppstyle_state.checkers))
console.Out.Ci(" ** Total Violated Rules : %d" % len(nsiqcppstyle_state.errorPerChecker.keys()))
console.Out.Ci(" ** Total Errors Occurs : %d" % nsiqcppstyle_state.error_count)
console.Out.Ci(" ** Total Analyzed Files : %d" % len(analyzedFiles))
console.Out.Ci(" ** Total Violated Files Count: %d" % violatedFileCount)
console.Out.Ci(f" ** Build Quality : {buildQuality:.2f}%")
if console.IsLevelDisplayed(console.Level.Info):
console.Out.Info("\n================================ Violated Rule Details ===============================")
for checker in nsiqcppstyle_state.errorPerChecker:
console.Out.Info(" - ", checker, "rule violated :", nsiqcppstyle_state.errorPerChecker[checker])
console.Out.Info("\n================================ Violated File Details ===============================")
for eachFile in nsiqcppstyle_state.errorPerFile:
count = 0
for eachRule in nsiqcppstyle_state.errorPerFile[eachFile]:
count += nsiqcppstyle_state.errorPerFile[eachFile][eachRule]
console.Out.Info(" - ", eachFile, " violated in total : ", count)
for eachRule in nsiqcppstyle_state.errorPerFile[eachFile]:
console.Out.Info(" * ", eachRule, " : ", nsiqcppstyle_state.errorPerFile[eachFile][eachRule])
def CloseReport(format):
if format == "xml":
global writer
writer.write("</checkstyle>\n")
writer.close()
##########################################################################
# ruleMap = {}
def IsRuleUsed(ruleName, ruleNames):
if ruleNames.count(ruleName) == 0:
return "false"
return "true"
def ReportRules(availRuleName, ruleNames):
pass
# global ruleMap
# ruleMap = {}
# index = 0
# ===========================================================================
# for eachAvailRuleName in availRuleName :
# ruleMap[eachAvailRuleName] = index
# index += 1
#
# if _nsiqcppstyle_state.output_format == 'xml':
# writer.write("<rules>\n")
# for eachAvailRuleName in availRuleName :
# url = "http://nsiqcppstyle.appspot.com/rule_doc/" + eachAvailRuleName
# writer.write("<rule name='%s' use='%s' index='%d' ruleDoc='%s'/>\n" % (eachAvailRuleName, IsRuleUsed(eachAvailRuleName, ruleNames), ruleMap[eachAvailRuleName], url ))
# writer.write("</rules>\n")
# ===========================================================================
def StartDir(dirname):
if _nsiqcppstyle_state.output_format == "xml":
pass
# writer.write("<dir name='%s'>\n" % (dirname))
def EndDir():
if _nsiqcppstyle_state.output_format == "xml":
pass
# writer.write("</dir>\n")
def StartTarget(targetname):
"""Write Report when each target is analyzed"""
if _nsiqcppstyle_state.output_format == "xml":
global target
target = targetname if isinstance(targetname, str) else str(targetname)
# writer.write("<target name='%s'>\n" % (targetname))
def EndTarget():
"""Write Report when each target is ended"""
if _nsiqcppstyle_state.output_format == "xml":
pass # writer.write("</target>\n")
def StartFile(dirname, filename):
if _nsiqcppstyle_state.output_format == "xml":
writer.write(f"<file name='{os.path.join(target, dirname[1:], filename)}'>\n")
def EndFile():
if _nsiqcppstyle_state.output_format == "xml":
writer.write("</file>\n")
_nsiqcppstyle_state = nsiqcppstyle_state._nsiqcppstyle_state
def __dict_replace(s, d):
"""Replace substrings of a string using a dictionary."""
for key, value in d.items():
s = s.replace(key, value)
return s
def escape(data, entities=None):
"""Escape &, <, and > in a string of data.
You can escape other strings of data by passing a dictionary as
the optional entities parameter. The keys and values must all be
strings; each key will be replaced with its corresponding value.
"""
# must do ampersand first
if entities is None:
entities = {}
data = data.replace("&", "&")
data = data.replace(">", ">")
data = data.replace("<", "<")
if entities:
data = __dict_replace(data, entities)
return data
def ErrorInternal(t, ruleName, message):
"""
Print error
"""
global rule
# Remove the known prefix of "rules." from the path
ruleName = ruleName[6:]
if t is None:
return
if nsiqcppstyle_checker.Search(r"//\s*NS", t.line) is None and not _nsiqcppstyle_state.CheckRuleSuppression(
ruleName,
):
_nsiqcppstyle_state.IncrementErrorCount(ruleName, t.filename)
url = ""
if _nsiqcppstyle_state.showUrl:
url = "http://nsiqcppstyle.appspot.com/rule_doc/" + ruleName
if _nsiqcppstyle_state.output_format == "emacs":
sys.stdout.write(f"{t.filename}:{t.lineno}: {message} [{ruleName}] {url}\n")
elif _nsiqcppstyle_state.output_format == "vs7":
sys.stdout.write(f"{t.filename}({t.lineno}, {t.column}): {message} [{ruleName}] {url}\n")
elif _nsiqcppstyle_state.output_format == "eclipse":
sys.stdout.write(' File "%s", line %d %s (%s)\n' % (t.filename, t.lineno, message, ruleName))
elif _nsiqcppstyle_state.output_format == "csv":
global writer
writer.writerow((t.filename, t.lineno, t.column, message, ruleName, url))
elif _nsiqcppstyle_state.output_format == "xml":
writer.write(
"""<error line='%d' col='%d' severity='warning' message='%s' source='%s'/>\n"""
% (t.lineno, t.column, escape(message).replace("'", '"'), ruleName),
)
Error = ErrorInternal
class DummyToken:
def __init__(self, filename, line, lineno, column):
self.filename = filename
self.line = line
if lineno == 0:
lineno = 1
self.lineno = lineno
self.column = column