diff-report.py tool
cover diff-report.py tool
--------------------------------------------------------------------------------
This serie is dependent on this patch:
https://patchwork.kernel.org/project/xen-devel/patch/[email protected]/
--------------------------------------------------------------------------------
Now that we have a tool (xen-analysis.py) that wraps cppcheck to generates reports, we have a generic overview of how many static analysis issues and non compliances to MISRA C we have for a certain revision of the codebase.
This is great and eventually the work to be done should be just having less and less findings in the report until we reach zero.
This is just an ideal trend, because in practice we might have issues that comes from existing code (macro for example) that are not going to be fixed soon for any reason, but we would like to check and see how many issues are introduced by the commits added (ideally zero, but if any is added and the fault resides outside the changed code, maintainers might decide to include it anyway).
So the idea is to check the difference between the reports of the codebase: one called "baseline" which is basically the current codebase, the other one called "new report" that is the codebase after the changes.
To check if any new finding is added, we need to have a look on every finding in the "new report" that is not listed in the "baseline".
It seems very simple, but what can happen to existing findings in the code after a commit is applied?
Basically existing findings can be shifted in position due to changes to unrelated lines, or they can be also deleted or fixed for changes involving the findings line (Michal was the first one to point that out).
So comparing the two report now seems quite difficult, because if we compare them we will have all the new findings plus all the findings that changed position due to the changes applied.
To overcome this, the diff-tool.py is created and it allows to "patch" the "baseline" report, looking into the changes applied to the baseline codebase, described by git diff.
This serie is organised in two patch, I've tried to split the amount of code and to leave a meaning, so in the first patch you have everything you need to import cppcheck reports and do a "raw" diff between reports, this gives you an hint about new findings + old findings that has changed place.
The second patch is adding the "patching" system, having a class that parses the git diff output and later "patching" the baseline before doing the comparison. This last option is activated only when passing the git diff changes to the tool, but everything is described (I hope) in the help.
Some consideration needs to be made, this tool can translate in coordinates (file, line) the findings from the "baseline" to the "new report" using the git diff output as, let me say, a translation matrix.
This doesn't mean it can understand the meaning of the findings and recognise them in the new codebase, so for example, a finding related to a line that is moved to another part of the file won't be recognised as "old finding" and will be just removed from the "baseline patched report", however we will find it in the new report unless it contains a fix for the reported issue.
This means that the tool is not really suited to be a gatekeeper for the merge action, it is more suitable to help the maintainer to understand when a change is introducing new issues without having to check and compare manually two reports of (nowadays) hundreds of finding.
Eventually we could run it in the CI and make the CI reply to the patchwork thread with its output!
The tool has also a debug argument that when applied, generates extra files that can be checked against the original files, for example the reports are imported in the tool, and afterwards the debug code will generate them back from the imported data and they should be the same (if everything works). Another debug check is to export the representation of the parsed git diff output, so that the developer can check how and if the parser interpreted correctly the data.
Future works for this tool might be to parse also Coverity reports and eventually (don't know if it is possible) also eclair text report.
Luca Fancellu (2):
xen/misra: add diff-report.py tool
xen/misra: diff-report.py: add report patching feature
xen/scripts/diff-report.py | 127 +++++++++++ .../xen_analysis/diff_tool/__init__.py | 0 .../xen_analysis/diff_tool/cppcheck_report.py | 41 ++++ xen/scripts/xen_analysis/diff_tool/debug.py | 55 +++++ xen/scripts/xen_analysis/diff_tool/report.py | 198 +++++++++++++++++ .../diff_tool/unified_format_parser.py | 202 ++++++++++++++++++ 6 files changed, 623 insertions(+) create mode 100755 xen/scripts/diff-report.py create mode 100644 xen/scripts/xen_analysis/diff_tool/__init__.py create mode 100644 xen/scripts/xen_analysis/diff_tool/cppcheck_report.py create mode 100644 xen/scripts/xen_analysis/diff_tool/debug.py create mode 100644 xen/scripts/xen_analysis/diff_tool/report.py create mode 100644 xen/scripts/xen_analysis/diff_tool/unified_format_parser.py
Signature · 1 line
2.34.1
PATCH 1/2 xen/misra: add diff-report.py tool
Add a new tool, diff-report.py that can be used to make diff between reports generated by xen-analysis.py tool.
Currently this tool supports the Xen cppcheck text report format in its operations.
The tool prints every finding that is in the report passed with -r (check report) which is not in the report passed with -b (baseline).
--- xen/scripts/diff-report.py | 76 ++++++++++++ .../xen_analysis/diff_tool/__init__.py | 0 .../xen_analysis/diff_tool/cppcheck_report.py | 41 +++++++ xen/scripts/xen_analysis/diff_tool/debug.py | 36 ++++++ xen/scripts/xen_analysis/diff_tool/report.py | 114 ++++++++++++++++++ 5 files changed, 267 insertions(+) create mode 100755 xen/scripts/diff-report.py create mode 100644 xen/scripts/xen_analysis/diff_tool/__init__.py create mode 100644 xen/scripts/xen_analysis/diff_tool/cppcheck_report.py create mode 100644 xen/scripts/xen_analysis/diff_tool/debug.py create mode 100644 xen/scripts/xen_analysis/diff_tool/report.py
xen/scripts/diff-report.py new file +76 -0
@@ -0,0 +1,76 @@ +#!/usr/bin/env python3 + +import os, sys +from argparse import ArgumentParser +from xen_analysis.diff_tool.debug import Debug +from xen_analysis.diff_tool.report import ReportError +from xen_analysis.diff_tool.cppcheck_report import CppcheckReport + + +def log_info(text, end='\n'): + global args + global file_out + + if (args.verbose): + print(text, end=end, file=file_out) + + +def main(argv): + global args + global file_out + + parser = ArgumentParser(prog="diff-report.py") + parser.add_argument("-b", "--baseline", required=True, type=str, + help="Path to the baseline report.") + parser.add_argument("--debug", action='store_true', + help="Produce intermediate reports during operations.") + parser.add_argument("-o", "--out", default="stdout", type=str, + help="Where to print the tool output. Default is " + "stdout") + parser.add_argument("-r", "--report", required=True, type=str, + help="Path to the 'check report', the one checked " + "against the baseline.") + parser.add_argument("-v", "--verbose", action='store_true', + help="Print more informations during the run.") + + args = parser.parse_args() + + if args.out == "stdout": + file_out = sys.stdout + else: + try: + file_out = open(args.out, "wt") + except OSError as e: + print("ERROR: Issue opening file {}: {}".format(args.out, e)) + sys.exit(1) + + debug = Debug(args) + + try: + baseline_path = os.path.realpath(args.baseline) + log_info("Loading baseline report {}".format(baseline_path), "") + baseline = CppcheckReport(baseline_path) + baseline.parse() + debug.debug_print_parsed_report(baseline) + log_info(" [OK]") + new_rep_path = os.path.realpath(args.report) + log_info("Loading check report {}".format(new_rep_path), "") + new_rep = CppcheckReport(new_rep_path) + new_rep.parse() + debug.debug_print_parsed_report(new_rep) + log_info(" [OK]") + except ReportError as e: + print("ERROR: {}".format(e)) + sys.exit(1) + + output = new_rep - baseline + print(output, end="", file=file_out) + + if len(output) > 0: + sys.exit(1) + + sys.exit(0) + + +if __name__ == "__main__": + main(sys.argv[1:])
xen/scripts/xen_analysis/diff_tool/__init__.py new file +0 -0
xen/scripts/xen_analysis/diff_tool/cppcheck_report.py new file +41 -0
41 lines not on this page · raw message
xen/scripts/xen_analysis/diff_tool/debug.py new file +36 -0
@@ -0,0 +1,36 @@ +#!/usr/bin/env python3 + +import os +from .report import Report + + +class Debug: + def __init__(self, args): + self.args = args + + def __get_debug_out_filename(self, path: str, type: str) -> str: + # Take basename + file_name = os.path.basename(path) + # Split in name and extension + file_name = os.path.splitext(file_name) + if self.args.out != "stdout": + out_folder = os.path.dirname(self.args.out) + else: + out_folder = "./" + dbg_report_path = out_folder + file_name[0] + type + file_name[1] + + return dbg_report_path + + def __debug_print_report(self, report: Report, type: str) -> None: + report_name = self.__get_debug_out_filename(report.get_report_path(), + type) + try: + with open(report_name, "wt") as outfile: + print(report, end="", file=outfile) + except OSError as e: + print("ERROR: Issue opening file {}: {}".format(report_name, e)) + + def debug_print_parsed_report(self, report: Report) -> None: + if not self.args.debug: + return + self.__debug_print_report(report, ".parsed")
xen/scripts/xen_analysis/diff_tool/report.py new file +114 -0
114 lines not on this page · raw message
Signature · 1 line
2.34.1
Re: [PATCH 1/2] xen/misra: add diff-report.py tool
Quoted 217 lines · Luca Fancellu
Add a new tool,
diff-report.pythat can be used to make diff between reports generated byxen-analysis.pytool.
Currently this tool supports the Xen cppcheck text report format in its operations.The tool prints every finding that is in the report passed with -r (check report) which is not in the report passed with -b (baseline).
Signed-off-by Luca Fancellu <[email protected]>---
xen/scripts/diff-report.py | 76 ++++++++++++ .../xen_analysis/diff_tool/__init__.py | 0 .../xen_analysis/diff_tool/cppcheck_report.py | 41 +++++++ xen/scripts/xen_analysis/diff_tool/debug.py | 36 ++++++ xen/scripts/xen_analysis/diff_tool/report.py | 114 ++++++++++++++++++ 5 files changed, 267 insertions(+)create mode 100755
xen/scripts/diff-report.py
create mode 100644xen/scripts/xen_analysis/diff_tool/__init__.pycreate mode 100644xen/scripts/xen_analysis/diff_tool/cppcheck_report.pycreate mode 100644xen/scripts/xen_analysis/diff_tool/debug.pycreate mode 100644xen/scripts/xen_analysis/diff_tool/report.pyxen/scripts/diff-report.py new file +76
-0@@ -0,0 +1,76 @@ +#!/usr/bin/env python3 + +import os, sys +from argparse import ArgumentParser +from xen_analysis.diff_tool.debug import Debug +from xen_analysis.diff_tool.report import ReportError +from xen_analysis.diff_tool.cppcheck_report import CppcheckReport + + +def log_info(text, end='\n'): + global args + global file_out + + if (args.verbose): + print(text, end=end, file=file_out) + + +def main(argv): + global args + global file_out + + parser = ArgumentParser(prog="diff-report.py") + parser.add_argument("-b", "--baseline", required=True, type=str, + help="Path to the baseline report.") + parser.add_argument("--debug", action='store_true', + help="Produce intermediate reports during operations.") + parser.add_argument("-o", "--out", default="stdout", type=str, + help="Where to print the tool output. Default is " + "stdout") + parser.add_argument("-r", "--report", required=True, type=str, + help="Path to the 'check report', the one checked " + "against the baseline.") + parser.add_argument("-v", "--verbose", action='store_true', + help="Print more informations during the run.") + + args = parser.parse_args() + + if args.out == "stdout": + file_out = sys.stdout + else: + try: + file_out = open(args.out, "wt") + except OSError as e: + print("ERROR: Issue opening file {}: {}".format(args.out, e)) + sys.exit(1) + + debug = Debug(args) + + try: + baseline_path = os.path.realpath(args.baseline) + log_info("Loading baseline report {}".format(baseline_path), "") + baseline = CppcheckReport(baseline_path) + baseline.parse() + debug.debug_print_parsed_report(baseline) + log_info(" [OK]") + new_rep_path = os.path.realpath(args.report) + log_info("Loading check report {}".format(new_rep_path), "") + new_rep = CppcheckReport(new_rep_path) + new_rep.parse() + debug.debug_print_parsed_report(new_rep) + log_info(" [OK]") + except ReportError as e: + print("ERROR: {}".format(e)) + sys.exit(1) + + output = new_rep - baseline + print(output, end="", file=file_out) + + if len(output) > 0: + sys.exit(1) + + sys.exit(0) + + +if __name__ == "__main__": + main(sys.argv[1:])xen/scripts/xen_analysis/diff_tool/__init__.py new file +0
-0xen/scripts/xen_analysis/diff_tool/cppcheck_report.py new file +41
-0@@ -0,0 +1,41 @@ +#!/usr/bin/env python3 + +import re +from .report import Report, ReportError + + +class CppcheckReport(Report): + def __init__(self, report_path: str) -> None: + super().__init__(report_path) + # This matches a string like: + # path/to/file.c(<line number>,<digits>):<whatever> + # and captures file name path and line number + # the last capture group is used for text substitution in __str__ + self.__report_entry_regex = re.compile(r'^(.*)\((\d+)(,\d+\):.*)$') + + def parse(self) -> None: + report_path = self.get_report_path() + try: + with open(report_path, "rt") as infile: + report_lines = infile.readlines() + except OSError as e: + raise ReportError("Issue with reading file {}: {}" + .format(report_path, e)) + for line in report_lines: + entry = self.__report_entry_regex.match(line) + if entry and entry.group(1) and entry.group(2): + file_path = entry.group(1) + line_number = int(entry.group(2)) + self.add_entry(file_path, line_number, line) + else: + raise ReportError("Malformed report entry in file {}:\n{}" + .format(report_path, line)) + + def __str__(self) -> str: + ret = "" + for entry in self.to_list(): + ret += re.sub(self.__report_entry_regex, + r'{}({}\3'.format(entry.file_path, + entry.line_number), + entry.text) + return retxen/scripts/xen_analysis/diff_tool/debug.py new file +36
-0@@ -0,0 +1,36 @@ +#!/usr/bin/env python3 + +import os +from .report import Report + + +class Debug: + def __init__(self, args): + self.args = args + + def __get_debug_out_filename(self, path: str, type: str) -> str: + # Take basename + file_name = os.path.basename(path) + # Split in name and extension + file_name = os.path.splitext(file_name) + if self.args.out != "stdout": + out_folder = os.path.dirname(self.args.out) + else: + out_folder = "./" + dbg_report_path = out_folder + file_name[0] + type + file_name[1] + + return dbg_report_path + + def __debug_print_report(self, report: Report, type: str) -> None: + report_name = self.__get_debug_out_filename(report.get_report_path(), + type) + try: + with open(report_name, "wt") as outfile: + print(report, end="", file=outfile) + except OSError as e: + print("ERROR: Issue opening file {}: {}".format(report_name, e)) + + def debug_print_parsed_report(self, report: Report) -> None: + if not self.args.debug: + return + self.__debug_print_report(report, ".parsed")xen/scripts/xen_analysis/diff_tool/report.py new file +11
-0@@ -0,0 +1,114 @@ +#!/usr/bin/env python3 + +import os + + +class ReportError(Exception): + pass + + +class Report: + class ReportEntry:
xen/scripts/xen_analysis/diff_tool/report.py line 21
Quoted 10 lines
xen/scripts/xen_analysis/diff_tool/report.py new file +10
-0+ def __init__(self, file_path: str, line_number: int, + entry_text: list, line_id: int) -> None: + if not isinstance(line_number, int) or \ + not isinstance(line_id, int): + raise ReportError("ReportEntry constructor wrong type args") + self.file_path = file_path + self.line_number = line_number + self.text = entry_text + self.line_id = line_id +
I realise now that I had a rebase mistake here, the class ReportEntry should not have these two functions, it was part of another branch, I will fix this in the next version, in the mean time I’ll wait for other possible findings for this patch.
<delete from here>
Quoted 11 lines
xen/scripts/xen_analysis/diff_tool/report.py new file +11
-0+ def __str__(self) -> str: + ret = '' + header = 'File path:Count\n' + + for path in self.stats: + ret += f'{path}: {len(self.stats[path])}\n' + + if ret == '': + ret += 'No new issues introduced\n' + + ret = header + ret
xen/scripts/xen_analysis/diff_tool/report.py line 42
Quoted 10 lines
xen/scripts/xen_analysis/diff_tool/report.py new file +10
-0+ + return ret + + def __len__(self) -> int: + ret = 0 + + for ln_list in self.stats.values(): + ret += len(ln_list) + + return ret
<to here>
Quoted 76 lines
xen/scripts/xen_analysis/diff_tool/report.py new file +72
-0+ + def __init__(self, report_path: str) -> None: + self.__entries = {} + self.__path = report_path + self.__last_line_order = 0 + + def parse(self) -> None: + raise ReportError("Please create a specialised class from 'Report'.") + + def get_report_path(self) -> str: + return self.__path + + def get_report_entries(self) -> dict: + return self.__entries + + def add_entry(self, entry_path: str, entry_line_number: int, + entry_text: list) -> None: + entry = Report.ReportEntry(entry_path, entry_line_number, entry_text, + self.__last_line_order) + if entry_path in self.__entries.keys(): + self.__entries[entry_path].append(entry) + else: + self.__entries[entry_path] = [entry] + self.__last_line_order += 1 + + def to_list(self) -> list: + report_list = [] + for _, entries in self.__entries.items(): + for entry in entries: + report_list.append(entry) + + report_list.sort(key=lambda x: x.line_id) + return report_list + + def __str__(self) -> str: + ret = "" + for entry in self.to_list(): + ret += entry.file_path + ":" + entry.line_number + ":" + entry.text + + return ret + + def __len__(self) -> int: + return len(self.to_list()) + + def __sub__(self, report_b: 'Report') -> 'Report': + if self.__class__ != report_b.__class__: + raise ReportError("Diff of different type of report!") + + filename, file_extension = os.path.splitext(self.__path) + diff_report = self.__class__(filename + ".diff" + file_extension) + # Put in the diff report only records of this report that are not + # present in the report_b. + for file_path, entries in self.__entries.items(): + rep_b_entries = report_b.get_report_entries() + if file_path in rep_b_entries.keys(): + # File path exists in report_b, so check what entries of that + # file path doesn't exist in report_b and add them to the diff + rep_b_entries_num = [ + x.line_number for x in rep_b_entries[file_path] + ] + for entry in entries: + if entry.line_number not in rep_b_entries_num: + diff_report.add_entry(file_path, entry.line_number, + entry.text) + else: + # File path doesn't exist in report_b, so add every entry + # of that file path to the diff + for entry in entries: + diff_report.add_entry(file_path, entry.line_number, + entry.text) + + return diff_reportSignature · 1 line
2.34.1
Re: [PATCH 1/2] xen/misra: add diff-report.py tool
In reply to Luca FancelluQuoted 9 lines · Luca Fancellu
Add a new tool,
diff-report.pythat can be used to make diff between reports generated byxen-analysis.pytool.
Currently this tool supports the Xen cppcheck text report format in its operations.The tool prints every finding that is in the report passed with -r (check report) which is not in the report passed with -b (baseline).
Signed-off-by Luca Fancellu <[email protected]>
Quoted 310 lines
--- xen/scripts/diff-report.py | 76 ++++++++++++ .../xen_analysis/diff_tool/__init__.py | 0 .../xen_analysis/diff_tool/cppcheck_report.py | 41 +++++++ xen/scripts/xen_analysis/diff_tool/debug.py | 36 ++++++ xen/scripts/xen_analysis/diff_tool/report.py | 114 ++++++++++++++++++ 5 files changed, 267 insertions(+) create mode 100755 xen/scripts/diff-report.py create mode 100644 xen/scripts/xen_analysis/diff_tool/__init__.py create mode 100644 xen/scripts/xen_analysis/diff_tool/cppcheck_report.py create mode 100644 xen/scripts/xen_analysis/diff_tool/debug.py create mode 100644 xen/scripts/xen_analysis/diff_tool/report.pyxen/scripts/diff-report.py new file +76
-0@@ -0,0 +1,76 @@ +#!/usr/bin/env python3 + +import os, sys +from argparse import ArgumentParser +from xen_analysis.diff_tool.debug import Debug +from xen_analysis.diff_tool.report import ReportError +from xen_analysis.diff_tool.cppcheck_report import CppcheckReport + + +def log_info(text, end='\n'): + global args + global file_out + + if (args.verbose): + print(text, end=end, file=file_out) + + +def main(argv): + global args + global file_out + + parser = ArgumentParser(prog="diff-report.py") + parser.add_argument("-b", "--baseline", required=True, type=str, + help="Path to the baseline report.") + parser.add_argument("--debug", action='store_true', + help="Produce intermediate reports during operations.") + parser.add_argument("-o", "--out", default="stdout", type=str, + help="Where to print the tool output. Default is " + "stdout") + parser.add_argument("-r", "--report", required=True, type=str, + help="Path to the 'check report', the one checked " + "against the baseline.") + parser.add_argument("-v", "--verbose", action='store_true', + help="Print more informations during the run.") + + args = parser.parse_args() + + if args.out == "stdout": + file_out = sys.stdout + else: + try: + file_out = open(args.out, "wt") + except OSError as e: + print("ERROR: Issue opening file {}: {}".format(args.out, e)) + sys.exit(1) + + debug = Debug(args) + + try: + baseline_path = os.path.realpath(args.baseline) + log_info("Loading baseline report {}".format(baseline_path), "") + baseline = CppcheckReport(baseline_path) + baseline.parse() + debug.debug_print_parsed_report(baseline) + log_info(" [OK]") + new_rep_path = os.path.realpath(args.report) + log_info("Loading check report {}".format(new_rep_path), "") + new_rep = CppcheckReport(new_rep_path) + new_rep.parse() + debug.debug_print_parsed_report(new_rep) + log_info(" [OK]") + except ReportError as e: + print("ERROR: {}".format(e)) + sys.exit(1) + + output = new_rep - baseline + print(output, end="", file=file_out) + + if len(output) > 0: + sys.exit(1) + + sys.exit(0) + + +if __name__ == "__main__": + main(sys.argv[1:])xen/scripts/xen_analysis/diff_tool/__init__.py new file +0
-0xen/scripts/xen_analysis/diff_tool/cppcheck_report.py new file +41
-0@@ -0,0 +1,41 @@ +#!/usr/bin/env python3 + +import re +from .report import Report, ReportError + + +class CppcheckReport(Report): + def __init__(self, report_path: str) -> None: + super().__init__(report_path) + # This matches a string like: + # path/to/file.c(<line number>,<digits>):<whatever> + # and captures file name path and line number + # the last capture group is used for text substitution in __str__ + self.__report_entry_regex = re.compile(r'^(.*)\((\d+)(,\d+\):.*)$') + + def parse(self) -> None: + report_path = self.get_report_path() + try: + with open(report_path, "rt") as infile: + report_lines = infile.readlines() + except OSError as e: + raise ReportError("Issue with reading file {}: {}" + .format(report_path, e)) + for line in report_lines: + entry = self.__report_entry_regex.match(line) + if entry and entry.group(1) and entry.group(2): + file_path = entry.group(1) + line_number = int(entry.group(2)) + self.add_entry(file_path, line_number, line) + else: + raise ReportError("Malformed report entry in file {}:\n{}" + .format(report_path, line)) + + def __str__(self) -> str: + ret = "" + for entry in self.to_list(): + ret += re.sub(self.__report_entry_regex, + r'{}({}\3'.format(entry.file_path, + entry.line_number), + entry.text) + return retxen/scripts/xen_analysis/diff_tool/debug.py new file +36
-0@@ -0,0 +1,36 @@ +#!/usr/bin/env python3 + +import os +from .report import Report + + +class Debug: + def __init__(self, args): + self.args = args + + def __get_debug_out_filename(self, path: str, type: str) -> str: + # Take basename + file_name = os.path.basename(path) + # Split in name and extension + file_name = os.path.splitext(file_name) + if self.args.out != "stdout": + out_folder = os.path.dirname(self.args.out) + else: + out_folder = "./" + dbg_report_path = out_folder + file_name[0] + type + file_name[1] + + return dbg_report_path + + def __debug_print_report(self, report: Report, type: str) -> None: + report_name = self.__get_debug_out_filename(report.get_report_path(), + type) + try: + with open(report_name, "wt") as outfile: + print(report, end="", file=outfile) + except OSError as e: + print("ERROR: Issue opening file {}: {}".format(report_name, e)) + + def debug_print_parsed_report(self, report: Report) -> None: + if not self.args.debug: + return + self.__debug_print_report(report, ".parsed")xen/scripts/xen_analysis/diff_tool/report.py new file +114
-0@@ -0,0 +1,114 @@ +#!/usr/bin/env python3 + +import os + + +class ReportError(Exception): + pass + + +class Report: + class ReportEntry: + def __init__(self, file_path: str, line_number: int, + entry_text: list, line_id: int) -> None: + if not isinstance(line_number, int) or \ + not isinstance(line_id, int): + raise ReportError("ReportEntry constructor wrong type args") + self.file_path = file_path + self.line_number = line_number + self.text = entry_text + self.line_id = line_id + + def __str__(self) -> str: + ret = '' + header = 'File path:Count\n' + + for path in self.stats: + ret += f'{path}: {len(self.stats[path])}\n' + + if ret == '': + ret += 'No new issues introduced\n' + + ret = header + ret + + return ret + + def __len__(self) -> int: + ret = 0 + + for ln_list in self.stats.values(): + ret += len(ln_list) + + return ret + + def __init__(self, report_path: str) -> None: + self.__entries = {} + self.__path = report_path + self.__last_line_order = 0 + + def parse(self) -> None: + raise ReportError("Please create a specialised class from 'Report'.") + + def get_report_path(self) -> str: + return self.__path + + def get_report_entries(self) -> dict: + return self.__entries + + def add_entry(self, entry_path: str, entry_line_number: int, + entry_text: list) -> None: + entry = Report.ReportEntry(entry_path, entry_line_number, entry_text, + self.__last_line_order) + if entry_path in self.__entries.keys(): + self.__entries[entry_path].append(entry) + else: + self.__entries[entry_path] = [entry] + self.__last_line_order += 1 + + def to_list(self) -> list: + report_list = [] + for _, entries in self.__entries.items(): + for entry in entries: + report_list.append(entry) + + report_list.sort(key=lambda x: x.line_id) + return report_list + + def __str__(self) -> str: + ret = "" + for entry in self.to_list(): + ret += entry.file_path + ":" + entry.line_number + ":" + entry.text + + return ret + + def __len__(self) -> int: + return len(self.to_list()) + + def __sub__(self, report_b: 'Report') -> 'Report': + if self.__class__ != report_b.__class__: + raise ReportError("Diff of different type of report!") + + filename, file_extension = os.path.splitext(self.__path) + diff_report = self.__class__(filename + ".diff" + file_extension) + # Put in the diff report only records of this report that are not + # present in the report_b. + for file_path, entries in self.__entries.items(): + rep_b_entries = report_b.get_report_entries() + if file_path in rep_b_entries.keys(): + # File path exists in report_b, so check what entries of that + # file path doesn't exist in report_b and add them to the diff + rep_b_entries_num = [ + x.line_number for x in rep_b_entries[file_path] + ] + for entry in entries: + if entry.line_number not in rep_b_entries_num: + diff_report.add_entry(file_path, entry.line_number, + entry.text) + else: + # File path doesn't exist in report_b, so add every entry + # of that file path to the diff + for entry in entries: + diff_report.add_entry(file_path, entry.line_number, + entry.text) + + return diff_reportSignature · 1 line
2.34.1
Re: [PATCH 1/2] xen/misra: add diff-report.py tool
Quoted 10 lines · Stefano Stabellini
Quoted 5 lines · Luca Fancellu
Add a new tool,
diff-report.pythat can be used to make diff between reports generated byxen-analysis.pytool.
Currently this tool supports the Xen cppcheck text report format in its operations.
Quoted 7 lines
Quoted 4 lines
The tool prints every finding that is in the report passed with -r (check report) which is not in the report passed with -b (baseline).
Signed-off-by Luca Fancellu <[email protected]>Tested-by Stefano Stabellini <[email protected]>
Thank you Stefano for taking the time to review and test it, I will push the new version of the serie with the stale functions removed and I will add your A-by and T-by.
Cheers,
Luca
PATCH 2/2 xen/misra: diff-report.py: add report patching feature
In reply to Luca FancelluAdd a feature to the diff-report.py script that improves the comparison between two analysis report, one from a baseline codebase and the other from the changes applied to the baseline.
The comparison between reports of different codebase is an issue because entries in the baseline could have been moved in position due to addition or deletion of unrelated lines or can disappear because of deletion of the interested line, making the comparison between two revisions of the code harder.
Having a baseline report, a report of the codebase with the changes called "new report" and a git diff format file that describes the changes happened to the code from the baseline, this feature can understand which entries from the baseline report are deleted or shifted in position due to changes to unrelated lines and can modify them as they will appear in the "new report".
Having the "patched baseline" and the "new report", now it's simple to make the diff between them and print only the entry that are new.
--- xen/scripts/diff-report.py | 55 ++++- xen/scripts/xen_analysis/diff_tool/debug.py | 19 ++ xen/scripts/xen_analysis/diff_tool/report.py | 84 ++++++++ .../diff_tool/unified_format_parser.py | 202 ++++++++++++++++++ 4 files changed, 358 insertions(+), 2 deletions(-) create mode 100644 xen/scripts/xen_analysis/diff_tool/unified_format_parser.py
xen/scripts/diff-report.py +53 -2
@@ -5,6 +5,10 @@ from argparse import ArgumentParser from xen_analysis.diff_tool.debug import Debug from xen_analysis.diff_tool.report import ReportError from xen_analysis.diff_tool.cppcheck_report import CppcheckReport +from xen_analysis.diff_tool.unified_format_parser import \ + (UnifiedFormatParser, UnifiedFormatParseError) +from xen_analysis.utils import invoke_command +from xen_analysis.settings import repo_dir def log_info(text, end='\n'):
@@ -32,9 +36,32 @@ def main(argv): "against the baseline.") parser.add_argument("-v", "--verbose", action='store_true', help="Print more informations during the run.") + parser.add_argument("--patch", type=str, + help="The patch file containing the changes to the " + "code, from the baseline analysis result to the " + "'check report' analysis result.\n" + "Do not use with --baseline-rev/--report-rev") + parser.add_argument("--baseline-rev", type=str, + help="Revision or SHA of the codebase analysed to " + "create the baseline report.\n" + "Use together with --report-rev") + parser.add_argument("--report-rev", type=str, + help="Revision or SHA of the codebase analysed to " + "create the 'check report'.\n" + "Use together with --baseline-rev") args = parser.parse_args() + if args.patch and (args.baseline_rev or args.report_rev): + print("ERROR: '--patch' argument can't be used with '--baseline-rev'" + " or '--report-rev'.") + sys.exit(1) + + if bool(args.baseline_rev) != bool(args.report_rev): + print("ERROR: '--baseline-rev' must be used together with " + "'--report-rev'.") + sys.exit(1) + if args.out == "stdout": file_out = sys.stdout else:
@@ -59,11 +86,35 @@ def main(argv): new_rep.parse() debug.debug_print_parsed_report(new_rep) log_info(" [OK]") - except ReportError as e: + diff_source = None + if args.patch: + diff_source = os.path.realpath(args.patch) + elif args.baseline_rev: + git_diff = invoke_command( + "git diff --git-dir={} -C -C {}..{}".format(repo_dir, + args.baseline_rev, + args.report_rev), + True, "Error occured invoking:\n{}\n\n{}" + ) + diff_source = git_diff.splitlines(keepends=True) + if diff_source: + log_info("Parsing changes...", "") + diffs = UnifiedFormatParser(diff_source) + debug.debug_print_parsed_diff(diffs) + log_info(" [OK]") + except (ReportError, UnifiedFormatParseError) as e: print("ERROR: {}".format(e)) sys.exit(1) - output = new_rep - baseline + if args.patch or args.baseline_rev: + log_info("Patching baseline...", "") + baseline_patched = baseline.patch(diffs) + debug.debug_print_patched_report(baseline_patched) + log_info(" [OK]") + output = new_rep - baseline_patched + else: + output = new_rep - baseline + print(output, end="", file=file_out) if len(output) > 0:
xen/scripts/xen_analysis/diff_tool/debug.py +19 -0
@@ -2,6 +2,7 @@ import os from .report import Report +from .unified_format_parser import UnifiedFormatParser class Debug:
@@ -34,3 +35,21 @@ class Debug: if not self.args.debug: return self.__debug_print_report(report, ".parsed") + + def debug_print_patched_report(self, report: Report) -> None: + if not self.args.debug: + return + # The patched report contains already .patched in its name + self.__debug_print_report(report, "") + + def debug_print_parsed_diff(self, diff: UnifiedFormatParser) -> None: + if not self.args.debug: + return + diff_filename = diff.get_diff_path() + out_pathname = self.__get_debug_out_filename(diff_filename, ".parsed") + try: + with open(out_pathname, "wt") as outfile: + for change_obj in diff.get_change_sets().values(): + print(change_obj, end="", file=outfile) + except OSError as e: + print("ERROR: Issue opening file {}: {}".format(out_pathname, e))
xen/scripts/xen_analysis/diff_tool/report.py +84 -0
96 lines not on this page · raw message
xen/scripts/xen_analysis/diff_tool/unified_format_parser.py new file +202 -0
202 lines not on this page · raw message
Signature · 1 line
2.34.1
Re: [PATCH 2/2] xen/misra: diff-report.py: add report patching feature
Quoted 17 lines · Luca Fancellu
Add a feature to the
diff-report.pyscript that improves the comparison between two analysis report, one from a baseline codebase and the other from the changes applied to the baseline.The comparison between reports of different codebase is an issue because entries in the baseline could have been moved in position due to addition or deletion of unrelated lines or can disappear because of deletion of the interested line, making the comparison between two revisions of the code harder.
Having a baseline report, a report of the codebase with the changes called "new report" and a git diff format file that describes the changes happened to the code from the baseline, this feature can understand which entries from the baseline report are deleted or shifted in position due to changes to unrelated lines and can modify them as they will appear in the "new report".
Quoted 4 lines
Having the "patched baseline" and the "new report", now it's simple to make the diff between them and print only the entry that are new.
Signed-off-by Luca Fancellu <[email protected]>
This is an amazing work!! Thanks Luca!
I am having issues trying the new patch feature. After applying this patch I get:
sstabellini@ubuntu-linux-20-04-desktop:/local/repos/xen-upstream/xen$ ./scripts/diff-report.py
Traceback (most recent call last):
File "./scripts/diff-report.py", line 5, in <module>
from xen_analysis.diff_tool.debug import Debug
File "/local/repos/xen-upstream/xen/scripts/xen_analysis/diff_tool/debug.py", line 4, in <module>
from .report import Report
File "/local/repos/xen-upstream/xen/scripts/xen_analysis/diff_tool/report.py", line 4, in <module>
from .unified_format_parser import UnifiedFormatParser, ChangeSet
File "/local/repos/xen-upstream/xen/scripts/xen_analysis/diff_tool/unified_format_parser.py", line 56, in <module>
class UnifiedFormatParser:
File "/local/repos/xen-upstream/xen/scripts/xen_analysis/diff_tool/unified_format_parser.py", line 57, in UnifiedFormatParser
def __init__(self, args: str | list) -> None:
TypeError: unsupported operand type(s) for |: 'type' and 'type'Also got a similar error elsewhere:
sstabellini@ubuntu-linux-20-04-desktop:/local/repos/xen-upstream/xen$ ./scripts/diff-report.py --patch ~/p/1 -b /tmp/1 -r /tmp/1
Traceback (most recent call last):
File "./scripts/diff-report.py", line 127, in <module>
main(sys.argv[1:])
File "./scripts/diff-report.py", line 102, in main
diffs = UnifiedFormatParser(diff_source)
File "/local/repos/xen-upstream/xen/scripts/xen_analysis/diff_tool/unified_format_parser.py", line 79, in __init__
self.__parse()
File "/local/repos/xen-upstream/xen/scripts/xen_analysis/diff_tool/unified_format_parser.py", line 94, in __parse
def parse_diff_header(line: str) -> ChangeSet | None:
TypeError: unsupported operand type(s) for |: 'type' and 'NoneType'My Python is 2.7.18
Am I understanding correctly that one should run the scan for the baseline (saving the result somewhere), then apply the patch, run the scan again. Finally, one should call diff-report.py passing -b baseline-report -r new-report --patch the-patch-applied?
Quoted 441 lines
--- xen/scripts/diff-report.py | 55 ++++- xen/scripts/xen_analysis/diff_tool/debug.py | 19 ++ xen/scripts/xen_analysis/diff_tool/report.py | 84 ++++++++ .../diff_tool/unified_format_parser.py | 202 ++++++++++++++++++ 4 files changed, 358 insertions(+), 2 deletions(-) create mode 100644 xen/scripts/xen_analysis/diff_tool/unified_format_parser.pyxen/scripts/diff-report.py +53
-2@@ -5,6 +5,10 @@ from argparse import ArgumentParser from xen_analysis.diff_tool.debug import Debug from xen_analysis.diff_tool.report import ReportError from xen_analysis.diff_tool.cppcheck_report import CppcheckReport +from xen_analysis.diff_tool.unified_format_parser import \ + (UnifiedFormatParser, UnifiedFormatParseError) +from xen_analysis.utils import invoke_command +from xen_analysis.settings import repo_dir def log_info(text, end='\n'):@@ -32,9 +36,32 @@ def main(argv): "against the baseline.") parser.add_argument("-v", "--verbose", action='store_true', help="Print more informations during the run.") + parser.add_argument("--patch", type=str, + help="The patch file containing the changes to the " + "code, from the baseline analysis result to the " + "'check report' analysis result.\n" + "Do not use with --baseline-rev/--report-rev") + parser.add_argument("--baseline-rev", type=str, + help="Revision or SHA of the codebase analysed to " + "create the baseline report.\n" + "Use together with --report-rev") + parser.add_argument("--report-rev", type=str, + help="Revision or SHA of the codebase analysed to " + "create the 'check report'.\n" + "Use together with --baseline-rev") args = parser.parse_args() + if args.patch and (args.baseline_rev or args.report_rev): + print("ERROR: '--patch' argument can't be used with '--baseline-rev'" + " or '--report-rev'.") + sys.exit(1) + + if bool(args.baseline_rev) != bool(args.report_rev): + print("ERROR: '--baseline-rev' must be used together with " + "'--report-rev'.") + sys.exit(1) + if args.out == "stdout": file_out = sys.stdout else:@@ -59,11 +86,35 @@ def main(argv): new_rep.parse() debug.debug_print_parsed_report(new_rep) log_info(" [OK]") - except ReportError as e: + diff_source = None + if args.patch: + diff_source = os.path.realpath(args.patch) + elif args.baseline_rev: + git_diff = invoke_command( + "git diff --git-dir={} -C -C {}..{}".format(repo_dir, + args.baseline_rev, + args.report_rev), + True, "Error occured invoking:\n{}\n\n{}" + ) + diff_source = git_diff.splitlines(keepends=True) + if diff_source: + log_info("Parsing changes...", "") + diffs = UnifiedFormatParser(diff_source) + debug.debug_print_parsed_diff(diffs) + log_info(" [OK]") + except (ReportError, UnifiedFormatParseError) as e: print("ERROR: {}".format(e)) sys.exit(1) - output = new_rep - baseline + if args.patch or args.baseline_rev: + log_info("Patching baseline...", "") + baseline_patched = baseline.patch(diffs) + debug.debug_print_patched_report(baseline_patched) + log_info(" [OK]") + output = new_rep - baseline_patched + else: + output = new_rep - baseline + print(output, end="", file=file_out) if len(output) > 0:xen/scripts/xen_analysis/diff_tool/debug.py +19
-0@@ -2,6 +2,7 @@ import os from .report import Report +from .unified_format_parser import UnifiedFormatParser class Debug:@@ -34,3 +35,21 @@ class Debug: if not self.args.debug: return self.__debug_print_report(report, ".parsed") + + def debug_print_patched_report(self, report: Report) -> None: + if not self.args.debug: + return + # The patched report contains already .patched in its name + self.__debug_print_report(report, "") + + def debug_print_parsed_diff(self, diff: UnifiedFormatParser) -> None: + if not self.args.debug: + return + diff_filename = diff.get_diff_path() + out_pathname = self.__get_debug_out_filename(diff_filename, ".parsed") + try: + with open(out_pathname, "wt") as outfile: + for change_obj in diff.get_change_sets().values(): + print(change_obj, end="", file=outfile) + except OSError as e: + print("ERROR: Issue opening file {}: {}".format(out_pathname, e))xen/scripts/xen_analysis/diff_tool/report.py +84
-0@@ -1,6 +1,7 @@ #!/usr/bin/env python3 import os +from .unified_format_parser import UnifiedFormatParser, ChangeSet class ReportError(Exception):@@ -65,6 +66,89 @@ class Report: self.__entries[entry_path] = [entry] self.__last_line_order += 1 + def remove_entries(self, entry_file_path: str) -> None: + del self.__entries[entry_file_path] + + def remove_entry(self, entry_path: str, line_id: int) -> None: + if entry_path in self.__entries.keys(): + len_entry_path = len(self.__entries[entry_path]) + if len_entry_path == 1: + del self.__entries[entry_path] + else: + if line_id in self.__entries[entry_path]: + self.__entries[entry_path].remove(line_id) + + def patch(self, diff_obj: UnifiedFormatParser) -> 'Report': + filename, file_extension = os.path.splitext(self.__path) + patched_report = self.__class__(filename + ".patched" + file_extension) + remove_files = [] + rename_files = [] + remove_entry = [] + ChangeMode = ChangeSet.ChangeMode + + # Copy entries from this report to the report we are going to patch + for entries in self.__entries.values(): + for entry in entries: + patched_report.add_entry(entry.file_path, entry.line_number, + entry.text) + + # Patch the output report + patched_rep_entries = patched_report.get_report_entries() + for file_diff, change_obj in diff_obj.get_change_sets().items(): + if change_obj.is_change_mode(ChangeMode.COPY): + # Copy the original entry pointed by change_obj.orig_file into + # a new key in the patched report named change_obj.dst_file, + # that here is file_diff variable content, because this + # change_obj is pushed into the change_sets with the + # change_obj.dst_file key + if change_obj.orig_file in self.__entries.keys(): + for entry in self.__entries[change_obj.orig_file]: + patched_report.add_entry(file_diff, + entry.line_number, + entry.text) + + if file_diff in patched_rep_entries.keys(): + if change_obj.is_change_mode(ChangeMode.DELETE): + # No need to check changes here, just remember to delete + # the file from the report + remove_files.append(file_diff) + continue + elif change_obj.is_change_mode(ChangeMode.RENAME): + # Remember to rename the file entry on this report + rename_files.append(change_obj) + + for line_num, change_type in change_obj.get_change_set(): + len_rep = len(patched_rep_entries[file_diff]) + for i in range(len_rep): + rep_item = patched_rep_entries[file_diff][i] + if change_type == ChangeSet.ChangeType.REMOVE: + if rep_item.line_number == line_num: + # This line is removed with this changes, + # append to the list of entries to be removed + remove_entry.append(rep_item) + elif rep_item.line_number > line_num: + rep_item.line_number -= 1 + elif change_type == ChangeSet.ChangeType.ADD: + if rep_item.line_number >= line_num: + rep_item.line_number += 1 + # Remove deleted entries from the list + if len(remove_entry) > 0: + for entry in remove_entry: + patched_report.remove_entry(entry.file_path, + entry.line_id) + remove_entry.clear() + + if len(remove_files) > 0: + for file_name in remove_files: + patched_report.remove_entries(file_name) + + if len(rename_files) > 0: + for change_obj in rename_files: + patched_rep_entries[change_obj.dst_file] = \ + patched_rep_entries.pop(change_obj.orig_file) + + return patched_report + def to_list(self) -> list: report_list = [] for _, entries in self.__entries.items():xen/scripts/xen_analysis/diff_tool/unified_format_parser.py new file +202
-0@@ -0,0 +1,202 @@ +#!/usr/bin/env python3 + +import re +from enum import Enum +from typing import Tuple + + +class UnifiedFormatParseError(Exception): + pass + + +class ParserState(Enum): + FIND_DIFF_HEADER = 0 + REGISTER_CHANGES = 1 + FIND_HUNK_OR_DIFF_HEADER = 2 + + +class ChangeSet: + class ChangeType(Enum): + REMOVE = 0 + ADD = 1 + + class ChangeMode(Enum): + NONE = 0 + CHANGE = 1 + RENAME = 2 + DELETE = 3 + COPY = 4 + + def __init__(self, a_file: str, b_file: str) -> None: + self.orig_file = a_file + self.dst_file = b_file + self.change_mode = ChangeSet.ChangeMode.NONE + self.__changes = [] + + def __str__(self) -> str: + str_out = "{}: {} -> {}:\n{}\n".format( + str(self.change_mode), self.orig_file, self.dst_file, + str(self.__changes) + ) + return str_out + + def set_change_mode(self, change_mode: ChangeMode) -> None: + self.change_mode = change_mode + + def is_change_mode(self, change_mode: ChangeMode) -> bool: + return self.change_mode == change_mode + + def add_change(self, line_number: int, change_type: ChangeType) -> None: + self.__changes.append((line_number, change_type)) + + def get_change_set(self) -> dict: + return self.__changes + + +class UnifiedFormatParser: + def __init__(self, args: str | list) -> None: + if isinstance(args, str): + self.__diff_file = args + try: + with open(self.__diff_file, "rt") as infile: + self.__diff_lines = infile.readlines() + except OSError as e: + raise UnifiedFormatParseError( + "Issue with reading file {}: {}" + .format(self.__diff_file, e) + ) + elif isinstance(args, list): + self.__diff_file = "git-diff-local.txt" + self.__diff_lines = args + else: + raise UnifiedFormatParseError( + "UnifiedFormatParser constructor called with wrong arguments") + + self.__git_diff_header = re.compile(r'^diff --git a/(.*) b/(.*)$') + self.__git_hunk_header = \ + re.compile(r'^@@ -\d+,(\d+) \+(\d+),(\d+) @@.*$') + self.__diff_set = {} + self.__parse() + + def get_diff_path(self) -> str: + return self.__diff_file + + def add_change_set(self, change_set: ChangeSet) -> None: + if not change_set.is_change_mode(ChangeSet.ChangeMode.NONE): + if change_set.is_change_mode(ChangeSet.ChangeMode.COPY): + # Add copy change mode items using the dst_file key, because + # there might be other changes for the orig_file in this diff + self.__diff_set[change_set.dst_file] = change_set + else: + self.__diff_set[change_set.orig_file] = change_set + + def __parse(self) -> None: + def parse_diff_header(line: str) -> ChangeSet | None: + change_item = None + diff_head = self.__git_diff_header.match(line) + if diff_head and diff_head.group(1) and diff_head.group(2): + change_item = ChangeSet(diff_head.group(1), diff_head.group(2)) + + return change_item + + def parse_hunk_header(line: str) -> Tuple[int, int, int]: + file_linenum = -1 + hunk_a_linemax = -1 + hunk_b_linemax = -1 + hunk_head = self.__git_hunk_header.match(line) + if hunk_head and hunk_head.group(1) and hunk_head.group(2) \ + and hunk_head.group(3): + file_linenum = int(hunk_head.group(2)) + hunk_a_linemax = int(hunk_head.group(1)) + hunk_b_linemax = int(hunk_head.group(3)) + + return (file_linenum, hunk_a_linemax, hunk_b_linemax) + + file_linenum = 0 + hunk_a_linemax = 0 + hunk_b_linemax = 0 + diff_elem = None + parse_state = ParserState.FIND_DIFF_HEADER + ChangeMode = ChangeSet.ChangeMode + ChangeType = ChangeSet.ChangeType + + for line in self.__diff_lines: + if parse_state == ParserState.FIND_DIFF_HEADER: + diff_elem = parse_diff_header(line) + if diff_elem: + # Found the diff header, go to the next stage + parse_state = ParserState.FIND_HUNK_OR_DIFF_HEADER + elif parse_state == ParserState.FIND_HUNK_OR_DIFF_HEADER: + # Here only these change modalities will be registered: + # deleted file mode <mode> + # rename from <path> + # rename to <path> + # copy from <path> + # copy to <path> + # + # These will be ignored: + # old mode <mode> + # new mode <mode> + # new file mode <mode> + # + # Also these info will be ignored + # similarity index <number> + # dissimilarity index <number> + # index <hash>..<hash> <mode> + if line.startswith("deleted file"): + # If the file is deleted, register it but don't go through + # the changes that will be only a set of lines removed + diff_elem.set_change_mode(ChangeMode.DELETE) + parse_state = ParserState.FIND_DIFF_HEADER + elif line.startswith("new file"): + # If the file is new, skip it, as it doesn't give any + # useful information on the report translation + parse_state = ParserState.FIND_DIFF_HEADER + elif line.startswith("rename to"): + # Renaming operation can be a pure renaming or a rename + # and a set of change, so keep looking for the hunk + # header + diff_elem.set_change_mode(ChangeMode.RENAME) + elif line.startswith("copy to"): + # This is a copy operation, mark it + diff_elem.set_change_mode(ChangeMode.COPY) + else: + # Look for the hunk header + (file_linenum, hunk_a_linemax, hunk_b_linemax) = \ + parse_hunk_header(line) + if file_linenum >= 0: + if diff_elem.is_change_mode(ChangeMode.NONE): + # The file has only changes + diff_elem.set_change_mode(ChangeMode.CHANGE) + parse_state = ParserState.REGISTER_CHANGES + else: + # ... or there could be a diff header + new_diff_elem = parse_diff_header(line) + if new_diff_elem: + # Found a diff header, register the last change + # item + self.add_change_set(diff_elem) + diff_elem = new_diff_elem + elif parse_state == ParserState.REGISTER_CHANGES: + if (hunk_b_linemax > 0) and line.startswith("+"): + diff_elem.add_change(file_linenum, ChangeType.ADD) + hunk_b_linemax -= 1 + elif (hunk_a_linemax > 0) and line.startswith("-"): + diff_elem.add_change(file_linenum, ChangeType.REMOVE) + hunk_a_linemax -= 1 + file_linenum -= 1 + elif ((hunk_a_linemax + hunk_b_linemax) > 0) and \ + line.startswith(" "): + hunk_a_linemax -= 1 if (hunk_a_linemax > 0) else 0 + hunk_b_linemax -= 1 if (hunk_b_linemax > 0) else 0 + + if (hunk_a_linemax + hunk_b_linemax) <= 0: + parse_state = ParserState.FIND_HUNK_OR_DIFF_HEADER + + file_linenum += 1 + + if diff_elem is not None: + self.add_change_set(diff_elem) + + def get_change_sets(self) -> dict: + return self.__diff_setSignature · 1 line
2.34.1
Re: [PATCH 2/2] xen/misra: diff-report.py: add report patching feature
Quoted 60 lines · Stefano Stabellini
Quoted 17 lines · Luca Fancellu
Add a feature to the
diff-report.pyscript that improves the comparison between two analysis report, one from a baseline codebase and the other from the changes applied to the baseline.The comparison between reports of different codebase is an issue because entries in the baseline could have been moved in position due to addition or deletion of unrelated lines or can disappear because of deletion of the interested line, making the comparison between two revisions of the code harder.
Having a baseline report, a report of the codebase with the changes called "new report" and a git diff format file that describes the changes happened to the code from the baseline, this feature can understand which entries from the baseline report are deleted or shifted in position due to changes to unrelated lines and can modify them as they will appear in the "new report".
Quoted 4 lines
Having the "patched baseline" and the "new report", now it's simple to make the diff between them and print only the entry that are new.
Signed-off-by Luca Fancellu <[email protected]>This is an amazing work!! Thanks Luca!
I am having issues trying the new patch feature. After applying this patch I get:
sstabellini@ubuntu-linux-20-04-desktop:/local/repos/xen-upstream/xen$ ./scripts/diff-report.py Traceback (most recent call last): File "./scripts/diff-report.py", line 5, in <module> from xen_analysis.diff_tool.debug import Debug File "/local/repos/xen-upstream/xen/scripts/xen_analysis/diff_tool/debug.py", line 4, in <module> from .report import Report File "/local/repos/xen-upstream/xen/scripts/xen_analysis/diff_tool/report.py", line 4, in <module> from .unified_format_parser import UnifiedFormatParser, ChangeSet File "/local/repos/xen-upstream/xen/scripts/xen_analysis/diff_tool/unified_format_parser.py", line 56, in <module> class UnifiedFormatParser: File "/local/repos/xen-upstream/xen/scripts/xen_analysis/diff_tool/unified_format_parser.py", line 57, in UnifiedFormatParser def __init__(self, args: str | list) -> None: TypeError: unsupported operand type(s) for |: 'type' and 'type'Also got a similar error elsewhere:
sstabellini@ubuntu-linux-20-04-desktop:/local/repos/xen-upstream/xen$ ./scripts/diff-report.py --patch ~/p/1 -b /tmp/1 -r /tmp/1 Traceback (most recent call last): File "./scripts/diff-report.py", line 127, in <module> main(sys.argv[1:]) File "./scripts/diff-report.py", line 102, in main diffs = UnifiedFormatParser(diff_source) File "/local/repos/xen-upstream/xen/scripts/xen_analysis/diff_tool/unified_format_parser.py", line 79, in __init__ self.__parse() File "/local/repos/xen-upstream/xen/scripts/xen_analysis/diff_tool/unified_format_parser.py", line 94, in __parse def parse_diff_header(line: str) -> ChangeSet | None: TypeError: unsupported operand type(s) for |: 'type' and 'NoneType'
Quoted 7 lines
My Python is 2.7.18
Am I understanding correctly that one should run the scan for the baseline (saving the result somewhere), then apply the patch, run the scan again. Finally, one should call
diff-report.pypassing -b baseline-report -r new-report --patch the-patch-applied?
Hi Stefano,
Yes indeed, that procedure is correct, I think the error you are seeing comes from the python version, I am using python 3, version 3.10.6.
The error seems to come from python annotations, I’m surprised you didn’t hit it when testing the first patch, did you use python2 for that?
Is it a problem if I developed the tool having in mind its usage with python3?
Cheers,
Luca
Re: [PATCH 2/2] xen/misra: diff-report.py: add report patching feature
Quoted 68 lines · Luca Fancellu
Quoted 58 lines · Stefano Stabellini
Quoted 17 lines · Luca Fancellu
Add a feature to the
diff-report.pyscript that improves the comparison between two analysis report, one from a baseline codebase and the other from the changes applied to the baseline.The comparison between reports of different codebase is an issue because entries in the baseline could have been moved in position due to addition or deletion of unrelated lines or can disappear because of deletion of the interested line, making the comparison between two revisions of the code harder.
Having a baseline report, a report of the codebase with the changes called "new report" and a git diff format file that describes the changes happened to the code from the baseline, this feature can understand which entries from the baseline report are deleted or shifted in position due to changes to unrelated lines and can modify them as they will appear in the "new report".
Quoted 4 lines
Having the "patched baseline" and the "new report", now it's simple to make the diff between them and print only the entry that are new.
Signed-off-by Luca Fancellu <[email protected]>This is an amazing work!! Thanks Luca!
I am having issues trying the new patch feature. After applying this patch I get:
sstabellini@ubuntu-linux-20-04-desktop:/local/repos/xen-upstream/xen$ ./scripts/diff-report.py Traceback (most recent call last): File "./scripts/diff-report.py", line 5, in <module> from xen_analysis.diff_tool.debug import Debug File "/local/repos/xen-upstream/xen/scripts/xen_analysis/diff_tool/debug.py", line 4, in <module> from .report import Report File "/local/repos/xen-upstream/xen/scripts/xen_analysis/diff_tool/report.py", line 4, in <module> from .unified_format_parser import UnifiedFormatParser, ChangeSet File "/local/repos/xen-upstream/xen/scripts/xen_analysis/diff_tool/unified_format_parser.py", line 56, in <module> class UnifiedFormatParser: File "/local/repos/xen-upstream/xen/scripts/xen_analysis/diff_tool/unified_format_parser.py", line 57, in UnifiedFormatParser def __init__(self, args: str | list) -> None: TypeError: unsupported operand type(s) for |: 'type' and 'type'Also got a similar error elsewhere:
sstabellini@ubuntu-linux-20-04-desktop:/local/repos/xen-upstream/xen$ ./scripts/diff-report.py --patch ~/p/1 -b /tmp/1 -r /tmp/1 Traceback (most recent call last): File "./scripts/diff-report.py", line 127, in <module> main(sys.argv[1:]) File "./scripts/diff-report.py", line 102, in main diffs = UnifiedFormatParser(diff_source) File "/local/repos/xen-upstream/xen/scripts/xen_analysis/diff_tool/unified_format_parser.py", line 79, in __init__ self.__parse() File "/local/repos/xen-upstream/xen/scripts/xen_analysis/diff_tool/unified_format_parser.py", line 94, in __parse def parse_diff_header(line: str) -> ChangeSet | None: TypeError: unsupported operand type(s) for |: 'type' and 'NoneType'Quoted 7 lines
My Python is 2.7.18
Am I understanding correctly that one should run the scan for the baseline (saving the result somewhere), then apply the patch, run the scan again. Finally, one should call
diff-report.pypassing -b baseline-report -r new-report --patch the-patch-applied?Hi Stefano,
Quoted 7 lines
Yes indeed, that procedure is correct, I think the error you are seeing comes from the python version, I am using python 3, version 3.10.6.
The error seems to come from python annotations, I’m surprised you didn’t hit it when testing the first patch, did you use python2 for that?
Is it a problem if I developed the tool having in mind its usage with python3?
Hi Luca,
It is not a problem per se if the script requires python3 but then we should check for the python version at the beginning of the script to fail explictly with a nice error message if python < 3.
I am fine if you want to proceed that way, but if the only issue are the annotations, I suggest it might be easier to remove them and then you also get the benefit of python2 compatibility. I'll leave the choice to you.
Either way, if you are OK with it, I think you should add a new entry to the MAINTAINERS file to cover the xen analysis scripts if you are OK with it:
xen/scripts/xen_analysisxen/scripts/xen-analysis.pyxen/scripts/diff-report.py