|
| 1 | +#!/usr/bin/env python3 |
| 2 | +# SPDX-License-Identifier: Apache-2.0 |
| 3 | +# Copyright (c) 2021 Intel Corporation |
| 4 | + |
| 5 | +import os |
| 6 | +import sh |
| 7 | +import argparse |
| 8 | +import re |
| 9 | +from unidiff import PatchSet |
| 10 | + |
| 11 | +if "ZEPHYR_BASE" not in os.environ: |
| 12 | + exit("$ZEPHYR_BASE environment variable undefined.") |
| 13 | + |
| 14 | +repository_path = os.environ['ZEPHYR_BASE'] |
| 15 | + |
| 16 | +sh_special_args = { |
| 17 | + '_tty_out': False, |
| 18 | + '_cwd': repository_path |
| 19 | +} |
| 20 | + |
| 21 | +coccinelle_scripts = ["/scripts/coccinelle/reserved_names.cocci", |
| 22 | + "/scripts/coccinelle/same_identifier.cocci", |
| 23 | + "/scripts/coccinelle/identifier_length.cocci", |
| 24 | + ] |
| 25 | + |
| 26 | + |
| 27 | +def parse_coccinelle(contents: str, violations: dict): |
| 28 | + reg = re.compile("([a-zA-Z0-9/]*\\.[ch]:[0-9]*)(:[0-9\\-]*: )(.*)") |
| 29 | + for line in contents.split("\n"): |
| 30 | + r = reg.match(line) |
| 31 | + if r: |
| 32 | + f = r.group(1) |
| 33 | + if f in violations: |
| 34 | + violations[f].append(r.group(3)) |
| 35 | + else: |
| 36 | + violations[r.group(1)] = [r.group(3)] |
| 37 | + |
| 38 | + |
| 39 | +def parse_args(): |
| 40 | + parser = argparse.ArgumentParser( |
| 41 | + description="Check if change requires full twister") |
| 42 | + parser.add_argument('-c', '--commits', default=None, |
| 43 | + help="Commit range in the form: a..b") |
| 44 | + return parser.parse_args() |
| 45 | + |
| 46 | + |
| 47 | +def main(): |
| 48 | + args = parse_args() |
| 49 | + if not args.commits: |
| 50 | + exit("missing commit range") |
| 51 | + |
| 52 | + commit = sh.git("diff", args.commits, **sh_special_args) |
| 53 | + patch_set = PatchSet(commit) |
| 54 | + zephyr_base = os.getenv("ZEPHYR_BASE") |
| 55 | + violations = {} |
| 56 | + numViolations = 0 |
| 57 | + |
| 58 | + for f in patch_set: |
| 59 | + if not f.path.endswith(".c") and not f.path.endswith(".h") or not os.path.exists(zephyr_base + "/" + f.path): |
| 60 | + continue |
| 61 | + |
| 62 | + for script in coccinelle_scripts: |
| 63 | + script_path = os.getenv("ZEPHYR_BASE") + "/" + script |
| 64 | + cocci = sh.coccicheck( |
| 65 | + "--mode=report", |
| 66 | + "--cocci=" + |
| 67 | + script_path, |
| 68 | + f.path, |
| 69 | + **sh_special_args) |
| 70 | + parse_coccinelle(cocci, violations) |
| 71 | + |
| 72 | + for hunk in f: |
| 73 | + for line in hunk: |
| 74 | + if line.is_added: |
| 75 | + violation = "{}:{}".format(f.path, line.target_line_no) |
| 76 | + if violation in violations: |
| 77 | + numViolations += 1 |
| 78 | + print( |
| 79 | + "{}:{}".format( |
| 80 | + violation, "\t\n".join( |
| 81 | + violations[violation]))) |
| 82 | + |
| 83 | + return numViolations |
| 84 | + |
| 85 | + |
| 86 | +if __name__ == "__main__": |
| 87 | + ret = main() |
| 88 | + exit(ret) |
0 commit comments