1#!/usr/bin/env python3
2# coding: utf-8
3#
4# © 2023 Qualcomm Innovation Center, Inc. All rights reserved.
5#
6# SPDX-License-Identifier: BSD-3-Clause
7
8"""
9Run as a part of gitlab CI, after Klocwork reports have been generated.
10
11This script converts the Klocwork JSON-format report to a Code Climate
12compatible json file, that gitlab code quality can interpret.
13"""
14
15import json
16import argparse
17import sys
18import os
19import hashlib
20
21argparser = argparse.ArgumentParser(
22    description="Convert Klocwork JSON to Code Climate JSON")
23argparser.add_argument('input', type=argparse.FileType('r'), nargs='?',
24                       default=sys.stdin, help="the Klocwork JSON input")
25argparser.add_argument('--output', '-o', type=argparse.FileType('w'),
26                       default=sys.stdout, help="the Code Climate JSON output")
27args = argparser.parse_args()
28
29json_input_file = ""
30
31kw_violations = []
32issue = {}
33
34severity_map = {
35    1: "blocker",
36    2: "critical",
37    3: "major",
38    4: "minor",
39    5: "info",
40}
41
42
43def get_severity(v):
44    if (v > 5):
45        return severity_map[5]
46    else:
47        return severity_map[v]
48
49
50with open(args.input.name, 'r') as json_file:
51    json_input_file = json.load(json_file)
52
53for v in range(len(json_input_file)):
54    # print(json_input_file[v])
55    issue["type"] = "issue"
56    issue["categories"] = ["Bug Risk"]
57    issue["severity"] = get_severity(
58        int(json_input_file[v]['severityCode']))
59    issue["check_name"] = json_input_file[v]['code']
60    issue["description"] = json_input_file[v]['message'] + '. ' + \
61        json_input_file[v]['severity'] + \
62        '. (' + json_input_file[v]['code'] + ')'
63    issue["location"] = {}
64    issue["location"]["path"] = os.path.relpath(json_input_file[v]['file'])
65    issue["location"]["lines"] = {}
66    issue["location"]["lines"]["begin"] = int(json_input_file[v]['line'])
67    issue["location"]["lines"]["end"] = int(json_input_file[v]['line'])
68    dump_issue = json.dumps(issue)
69    issue["fingerprint"] = hashlib.md5(dump_issue.encode('utf-8')).hexdigest()
70    # print(issue)
71    kw_violations.append(issue)
72    issue = {}  # was getting wired result without clearing it
73args.output.write(json.dumps(kw_violations))
74