|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Run CodeQL tests with appropriate configuration. |
| 3 | +
|
| 4 | +Called from just recipes as: |
| 5 | + python3 codeql_test_run.py LANGUAGE [ARG...] |
| 6 | +
|
| 7 | +Arguments are already split by `just` (see `set lists`), so each one is taken verbatim. |
| 8 | +`--all-checks=FLAG` contributes FLAG to the set of extra checks that `--all-checks` (or |
| 9 | +its `+` abbreviation) turns on. |
| 10 | +""" |
| 11 | + |
| 12 | +import os |
| 13 | +import re |
| 14 | +import subprocess |
| 15 | +import sys |
| 16 | +from pathlib import Path |
| 17 | + |
| 18 | +JUST = os.environ.get("JUST_EXECUTABLE", "just") |
| 19 | +ERROR = os.environ.get("JUST_ERROR", "error: ") |
| 20 | +CMD_BEGIN = os.environ.get("CMD_BEGIN", "") |
| 21 | +CMD_END = os.environ.get("CMD_END", "") |
| 22 | +SEMMLE_CODE = os.environ.get("SEMMLE_CODE") |
| 23 | + |
| 24 | +ALL_CHECKS_PREFIX = "--all-checks=" |
| 25 | +ENV_RE = re.compile(r"^[A-Z_][A-Z_0-9]*=.*$") |
| 26 | + |
| 27 | + |
| 28 | +def invoke(invocation, *, cwd=None, log_prefix=""): |
| 29 | + prefix = f"{log_prefix} " if log_prefix else "" |
| 30 | + print(f"{CMD_BEGIN}{prefix}{' '.join(invocation)}{CMD_END}") |
| 31 | + try: |
| 32 | + subprocess.run(invocation, check=True, cwd=cwd) |
| 33 | + except subprocess.CalledProcessError as e: |
| 34 | + return e.returncode |
| 35 | + return 0 |
| 36 | + |
| 37 | + |
| 38 | +def error(message): |
| 39 | + print(f"{ERROR}{message}", file=sys.stderr) |
| 40 | + |
| 41 | + |
| 42 | +def parse_args(args, argv): |
| 43 | + """Sort arguments into tests, flags and environment assignments.""" |
| 44 | + for arg in argv: |
| 45 | + if not arg: |
| 46 | + # an empty argument can come from a caller interpolating an unset variable |
| 47 | + continue |
| 48 | + if arg.startswith(ALL_CHECKS_PREFIX): |
| 49 | + args["all_checks"].append(arg[len(ALL_CHECKS_PREFIX) :]) |
| 50 | + elif arg.startswith("--codeql="): |
| 51 | + args["codeql"] = arg.split("=", 1)[1] |
| 52 | + elif arg in ("+", "--all-checks"): |
| 53 | + args["all"] = True |
| 54 | + elif arg.startswith("-"): |
| 55 | + args["flags"].append(arg) |
| 56 | + elif ENV_RE.match(arg): |
| 57 | + args["env"].append(arg) |
| 58 | + else: |
| 59 | + args["tests"].append(arg) |
| 60 | + |
| 61 | + |
| 62 | +def env_value(args, name, default): |
| 63 | + """Resolve a setting from test arguments, then the environment, then a default.""" |
| 64 | + for assignment in reversed(args["env"]): |
| 65 | + key, _, value = assignment.partition("=") |
| 66 | + if key == name and value: |
| 67 | + return value |
| 68 | + return os.environ.get(name) or default |
| 69 | + |
| 70 | + |
| 71 | +def main(): |
| 72 | + argv = sys.argv[1:] |
| 73 | + if not argv: |
| 74 | + error("Usage: codeql_test_run.py LANGUAGE [ARG...]") |
| 75 | + return 1 |
| 76 | + |
| 77 | + language, *rest = argv |
| 78 | + |
| 79 | + args = { |
| 80 | + "tests": [], |
| 81 | + "flags": [], |
| 82 | + "env": [], |
| 83 | + "all_checks": [], |
| 84 | + "codeql": "build" if SEMMLE_CODE else "host", |
| 85 | + "all": False, |
| 86 | + } |
| 87 | + parse_args(args, rest) |
| 88 | + if args["all"]: |
| 89 | + parse_args(args, args["all_checks"]) |
| 90 | + |
| 91 | + if not SEMMLE_CODE and args["codeql"] in ("build", "built"): |
| 92 | + error( |
| 93 | + "Using `--codeql=build` or `--codeql=built` requires working " |
| 94 | + "with the internal repository" |
| 95 | + ) |
| 96 | + return 1 |
| 97 | + |
| 98 | + if not args["tests"]: |
| 99 | + args["tests"].append(".") |
| 100 | + |
| 101 | + # Resolve these only once all arguments are known, so that a `RAM_PER_THREAD=` test |
| 102 | + # argument can lower the default on memory-heavy suites. |
| 103 | + default_ram = 3000 if sys.platform == "linux" else 2048 |
| 104 | + ram_per_thread = int(env_value(args, "RAM_PER_THREAD", default_ram)) |
| 105 | + cpus = int(env_value(args, "CPUS", os.cpu_count() or 1)) |
| 106 | + args["flags"][:0] = [f"--ram={ram_per_thread * cpus}", f"-j{cpus}"] |
| 107 | + |
| 108 | + if args["codeql"] == "build": |
| 109 | + if invoke([JUST, language, "build"], cwd=SEMMLE_CODE) != 0: |
| 110 | + return 1 |
| 111 | + |
| 112 | + if args["codeql"] != "host": |
| 113 | + # Disable the default implicit config file, but keep an explicit one. |
| 114 | + # Same behavior wrt --codeql as the integration test runner. |
| 115 | + os.environ.setdefault("CODEQL_CONFIG_FILE", ".") |
| 116 | + |
| 117 | + for env_var in args["env"]: |
| 118 | + key, _, value = env_var.partition("=") |
| 119 | + if not key: |
| 120 | + error(f"Invalid environment variable assignment: {env_var}") |
| 121 | + return 1 |
| 122 | + os.environ[key] = value |
| 123 | + |
| 124 | + # Resolve codeql executable |
| 125 | + if args["codeql"] in ("built", "build"): |
| 126 | + codeql = Path(SEMMLE_CODE, "target", "intree", f"codeql-{language}", "codeql") |
| 127 | + elif args["codeql"] == "host": |
| 128 | + codeql = Path("codeql") |
| 129 | + else: |
| 130 | + codeql = Path(args["codeql"]) |
| 131 | + |
| 132 | + if codeql.is_dir(): |
| 133 | + codeql = codeql / "codeql" |
| 134 | + |
| 135 | + # On Windows, prefer codeql.exe over the Unix shell wrapper |
| 136 | + if sys.platform == "win32" and codeql.suffix != ".exe": |
| 137 | + exe = codeql.with_suffix(".exe") |
| 138 | + if exe.exists(): |
| 139 | + codeql = exe |
| 140 | + |
| 141 | + if args["codeql"] != "host" and not codeql.exists(): |
| 142 | + error(f"CodeQL executable not found: {codeql}") |
| 143 | + return 1 |
| 144 | + |
| 145 | + return invoke( |
| 146 | + [str(codeql), "test", "run", *args["flags"], "--", *args["tests"]], |
| 147 | + log_prefix=" ".join(args["env"]), |
| 148 | + ) |
| 149 | + |
| 150 | + |
| 151 | +if __name__ == "__main__": |
| 152 | + try: |
| 153 | + sys.exit(main()) |
| 154 | + except KeyboardInterrupt: |
| 155 | + sys.exit(128 + 2) |
0 commit comments