Cotton code
219 lines · 9.0 KB · PythonRaw
#!/usr/bin/env python3"""Run the registered source guards independently of changed-package selection."""import argparsefrom collections import defaultdictimport jsonfrom pathlib import Pathimport reimport subprocessimport sysROOT = Path(__file__).resolve().parents[2]REGISTRY = ROOT / "scripts/ci/rust-source-guards.json"RAW = re.compile(r'(?:br|r)(#*)"')CHAR = re.compile("'(?:\\\\.|[^'\\\\\\n])'")def mask(source, strings=True):    """Keep offsets while blanking Rust comments and optionally string bodies."""    result = list(source)    at = 0    while at < len(source):        end = at        if source.startswith("//", at):            end = source.find("\n", at)            if end < 0:                end = len(source)        elif source.startswith("/*", at):            end, depth = at + 2, 1            while end < len(source) and depth:                if source.startswith("/*", end):                    depth += 1; end += 2                elif source.startswith("*/", end):                    depth -= 1; end += 2                else:                    end += 1        else:            raw = RAW.match(source, at) if source[at] in "br" else None            if raw and (at == 0 or not (source[at - 1].isalnum() or source[at - 1] == "_")):                close = '"' + raw[1]                found = source.find(close, at + len(raw[0]))                end = len(source) if found < 0 else found + len(close)            elif source[at] == '"':                end = at + 1                while end < len(source):                    if source[end] == "\\":                        end += 2                    elif source[end] == '"':                        end += 1; break                    else:                        end += 1            elif source[at] == "'":                char = CHAR.match(source, at)                if char:                    end = at + len(char[0])            if end > at and not strings:                at = end                continue        if end > at:            for index in range(at, end):                if result[index] != "\n":                    result[index] = " "            at = end        else:            at += 1    return "".join(result)def functions(source):    code = mask(source)    clean = mask(source, strings=False)    found = []    previous_end = 0    for match in re.finditer(r"\bfn\s+(\w+)\s*(?:<[^;{]*>)?\s*\([^;{]*\)[^;{]*\{", code):        begin = match.end()        end, depth = begin, 1        while end < len(code) and depth:            depth += (code[end] == "{") - (code[end] == "}")            end += 1        prefix = code[previous_end:match.start()] if previous_end <= match.start() else ""        tested = bool(re.search(r"#\[\s*(?:\w+::)*test\b", prefix))        found.append(dict(name=match[1], body=clean[begin:end - 1], test=tested))        previous_end = max(previous_end, end)    return founddef scanners(source_path, source):    if not any(token in source for token in ["manifest_dir", "CARGO_MANIFEST_DIR", "include_str!", "Path::new", "PathBuf::from"]):        return []    clean = mask(source, strings=False)    crate = Path(*source_path.parts[:2])    rust_read = bool(re.search(r'read_to_string|read_dir|WalkDir', clean) and re.search(r'"(?:[^"\n]*\.rs|rs)"', clean))    def outward(body):        if rust_read and ("manifest_dir" in body or "CARGO_MANIFEST_DIR" in body):            if re.search(r'\.join\(\s*"\.\.|\.parent\(\)', body):                return True        if rust_read and re.search(r'Path(?:Buf)?::(?:new|from)\(\s*"(?:\.\.|crates)', body):            return True        for relative in re.findall(r'include_str!\s*\(\s*"([^"]+\.rs)"', body):            if not (ROOT / source_path.parent / relative).resolve().is_relative_to((ROOT / crate).resolve()):                return True        return False    if not rust_read and not re.search(r'include_str!\s*\(\s*"[^"]+\.rs"', clean):        return []    methods = functions(source)    global_functions = {f["name"] for f in methods if outward(f["body"])}    # A scanner may put root discovery in a helper and call it from a test.    while True:        callers = {f["name"] for f in methods if any(re.search(r"\b" + re.escape(name) + r"\s*\(", f["body"]) for name in global_functions)}        enlarged = global_functions | callers        if enlarged == global_functions:            break        global_functions = enlarged    return sorted({f["name"] for f in methods if f["test"] and f["name"] in global_functions})def inventory(root=ROOT):    result = {}    for path in (root / "crates").rglob("*.rs"):        if "target" in path.relative_to(root).parts:            continue        names = scanners(path.relative_to(root), path.read_text())        if names:            result[path.relative_to(root).as_posix()] = names    return resultdef registrations(root=ROOT):    # The only always-run list. Selection and workflow code never copy it.    entries = json.loads((root / REGISTRY.relative_to(ROOT)).read_text())    if not entries:        raise ValueError("always-run source guard registry is empty")    for source, entry in entries.items():        if not source.startswith("crates/") or ".." in Path(source).parts:            raise ValueError("source guard must name a repository source")        actual = {f["name"] for f in functions((root / source).read_text()) if f["test"]}        if not entry["tests"] or not set(entry["tests"]) <= actual:            raise ValueError("missing or stale source guard tests: " + source)        parts = Path(source).parts        target = "lib" if parts[2] == "src" else "test:" + Path(parts[3]).stem        if entry["target"] != target:            raise ValueError("guard target does not own its source: " + source)    return entriesdef check(root=ROOT):    entries = registrations(root)    missing = {source: sorted(set(names) - set(entries.get(source, {}).get("tests", [])))               for source, names in inventory(root).items()}    missing = {source: names for source, names in missing.items() if names}    if missing:        raise ValueError("cross-crate source scanners missing from " + str(REGISTRY.relative_to(ROOT)) + ": " + json.dumps(missing, sort_keys=True))    return entriesdef commands(entries, root=ROOT):    grouped = defaultdict(list)    for source, entry in entries.items():        grouped[Path(source).parts[1]].append(entry)    result = []    for directory, guards in sorted(grouped.items()):        import tomllib        package = tomllib.loads((root / "crates" / directory / "Cargo.toml").read_text())["package"]["name"]        targets = sorted({e["target"] for e in guards})        args = ["-p", package]        for target in targets:            args += ["--lib"] if target == "lib" else ["--test", target[5:]]        expressions = []        expected = []        for entry in guards:            binary = package if entry["target"] == "lib" else package + "::" + entry["target"][5:]            names = "|".join(re.escape(name) for name in entry["tests"])            expressions.append(f"(binary_id(={binary}) & test(/(^|::)({names})$/))")            expected += [(binary, name) for name in entry["tests"]]        result.append((package, args, " | ".join(expressions), expected))    return resultdef missing_runnable(suites, expected):    return [(binary, name) for binary, name in expected            if not any(test.split("::")[-1] == name and not details.get("ignored", False)                       and details.get("filter-match", {}).get("status") == "matches"                       for test, details in suites.get(binary, {}).get("testcases", {}).items())]def run(root=ROOT):    failed = False    for package, args, expression, expected in commands(check(root), root):        base = ["cargo", "nextest"]        options = ["--manifest-path", str(root / "crates/Cargo.toml"), "--profile", "fast", "--ignore-default-filter", *args, "-E", expression]        listing = subprocess.run([*base, "list", *options, "--message-format", "json"], text=True, stdout=subprocess.PIPE)        if listing.returncode:            failed = True            continue        suites = json.loads(listing.stdout)["rust-suites"]        missing = missing_runnable(suites, expected)        if missing:            raise ValueError("registered source guards did not become runnable: " + repr(missing))        print("Always-run source guards: " + package, flush=True)        result = subprocess.run([*base, "run", *options, "--no-fail-fast"])        failed |= result.returncode != 0    return int(failed)def main():    parser = argparse.ArgumentParser(description=__doc__)    parser.add_argument("--inventory", action="store_true")    parser.add_argument("--check", action="store_true")    args = parser.parse_args()    if args.inventory:        print(json.dumps(inventory(), indent=2, sort_keys=True))    elif args.check:        entries = check()        print(f"Always-run source guards: {sum(len(e['tests']) for e in entries.values())} tests registered")    else:        sys.exit(run())if __name__ == "__main__":    main()