From 2c3ca3c0eb564a4adf9259f70a44798a6e0e13b2 Mon Sep 17 00:00:00 2001 From: Michael Hohn Date: Mon, 6 Dec 2021 11:27:39 -0800 Subject: [PATCH] Fix for KeyError: 'region', caused by `result` without `region` Region / line / column information are present in most messages. The one that caused this error refers to the whole file: ipdb> p sarif_struct {'ruleId': 'com.lgtm/cpp-queries:cpp/missing-header-guard', 'ruleIndex': 12, 'message': {'text': 'This header file should contain a header guard to prevent multiple inclusion.'}, 'locations': [{'physicalLocation': {'artifactLocation': {'uri': 'diff/cmpbuf.h', 'uriBaseId': '%SRCROOT%', 'index': 13}}}], 'partialFingerprints': {'primaryLocationLineHash': 'd04cb834fa64727d:1', 'primaryLocationStartColumnFingerprint': '0'}} The goal is fixed-structure output formatting, so whole-file output uses -1,-1,-1,-1 for line, column information. --- bin/sarif-results-summary | 8 ++++++-- sarif_cli/__init__.py | 10 +++++++++- 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/bin/sarif-results-summary b/bin/sarif-results-summary index cfb1269..833459d 100755 --- a/bin/sarif-results-summary +++ b/bin/sarif-results-summary @@ -33,13 +33,17 @@ for runi in S.indices(sarif_struct, 'runs'): # Non-path problems # TODO: just pull out the uri, not the artifact message, artifact, region = S.get_location_message_info(result) - l1, c1, l2, c2 = S.lineinfo(region) + if region == S.WholeFile: + l1, c1, l2, c2 = -1, -1, -1, -1 + else: + l1, c1, l2, c2 = S.lineinfo(region) filepath = "%s:%d:%d:%d:%d" % (artifact['uri'], l1, c1, l2, c2) if args.csv: S.write_csv(cw, "result", artifact['uri'], l1, c1, l2, c2, message) else: S.msg("RESULT: %s: %s\n\n" % (filepath, message)) - if args.list_source: + + if region != S.WholeFile and args.list_source: lines = S.load_lines(args.list_source, artifact['uri'], l1, l2) if args.csv: pass diff --git a/sarif_cli/__init__.py b/sarif_cli/__init__.py index ec694ef..913c682 100644 --- a/sarif_cli/__init__.py +++ b/sarif_cli/__init__.py @@ -33,14 +33,22 @@ def get_relatedlocation_message_info(related_location): region = get(related_location, 'physicalLocation', 'region') return message, artifact, region +class WholeFile: + pass + def get_location_message_info(result): """ Given one of the results, extract message information. The `result` typically starts from get(sarif_struct, 'runs', run_index, 'results', res_index) + + Returns: (message, artifact, region) + For an empty 'region' key, returns (message, artifact, sarif_cli.WholeFile) + """ message = get(result, 'message', 'text') artifact = get(result, 'locations', 0, 'physicalLocation', 'artifactLocation') - region = get(result, 'locations', 0, 'physicalLocation', 'region') + # If there is no 'region' key, use the whole file + region = get(result, 'locations', 0, 'physicalLocation').get('region', WholeFile) return (message, artifact, region) def display_underlined(l1, c1, l2, c2, line, line_num):