mirror of
https://github.com/beenuar/AiSOC.git
synced 2026-11-24 08:35:46 +08:00
* Reformat the tree under ruff 0.16, excluding the subtree nobody may edit Mechanical. `ruff format` with no other change, so the diff can be read as "the formatter moved" rather than reviewed line by line: 218 files, 862 insertions against 1075 deletions, almost all of it collapsing calls that 0.4.10 wrapped and 0.16 fits inside the 140-column limit. `plans/` is excluded in `ruff.toml` rather than reformatted. It is the archived prototype subtree that `.github/workflows/codeql.yml` already excludes and `scripts/check_mypy_baseline.py` excludes from every coverage direction, and the project rules forbid editing anything under it -- so formatting it would be a diff nobody may take. 844 lint findings and ~280 unformatted files live there. They are excluded because they cannot be fixed, which is a different statement from saying the code is clean. * Move all fourteen ruff declarations to 0.16, and stop the lint gate at services/ The bump alone reds every open pull request: `ruff format --check` is a hard gate on the required `Python - Lint & Type-check` job and 0.16 formats differently from 0.4.10. The reformat is the previous commit; this one moves the pin, fixes the findings, and answers the scope question. Fourteen declarations now read `>=0.16.8,<0.17` -- seven manifests, three workflows, `.devcontainer/Dockerfile`, and the three `poetry.lock` files that resolve it (now 0.16.9, which is byte-identical to 0.16.8 on both format and lint across this tree). The three findings 0.16 reports on `services/` are fixed, not suppressed: two `C420` comprehensions become `dict.fromkeys` (both values are string literals, so the shared-value hazard does not apply) and one `UP031` percent-format becomes an f-string in a test that counts characters. All three rewrites were asserted equal to the originals before being kept. Scope. `ruff check services/` left `scripts/` -- every CI gate in this repository, the code the rest of its claims are verified by -- linted by nothing. Lint now covers `services/ scripts/ tests/ tools/`, the trees the root `ruff.toml` governs that nothing else lints, and `ruff format --check .` covers everything, because formatting has no semantic content and `.` needs no edit when a tree is added. That surfaced 17 findings outside `services/`, each fixed at the source: two `B007` loops switched to `.values()`, a `B904` re-raise in `security_audit.py` now chains `from exc`, two `E402` imports that genuinely follow a `sys.path` mutation carry a reason next to the marker, and two over-length lines were wrapped. `E501` is ignored for the two detection-spec data modules. Both open their rule table with `# fmt: off`, so the formatter is already opted out of that layout deliberately, and all 199 long lines are single dict or string literals -- 72 positive fixtures, 66 negative, 50 `match_when` clauses, 11 descriptions. Two named files, not `scripts/`. `packages/` and `plugins/` stay outside the lint gate, and the gap is a number rather than a shrug: 91 findings and 2. Two of the five packages are linted by their own workflows under their own configs, and bringing the three published SDKs under this gate means behaviour-touching fixes that belong in a change reviewed as such. * Make packages/aisoc-detections clean under the ruff its own workflow now installs `python-detections.yml` lints `aisoc_detections detections tests` under the pin this PR moved, so the package has to be clean under 0.16 too. Two findings, both fixed at the source rather than silenced: `Callable` moves to `collections.abc`, and a `# noqa: BLE001` that 0.16 correctly reports as unused becomes the sentence it was standing in for -- a detection module is third-party content, so any exception at import is the author's and becomes a DetectionError naming the file. --------- Co-authored-by: Beenu Arora <beenu@MacBook-Pro-3.local>
129 lines
4.7 KiB
Python
129 lines
4.7 KiB
Python
#!/usr/bin/env python3
|
|
"""Gate: one Go version across the repo, and CI installs it.
|
|
|
|
Six ``go.mod`` files declared five different versions — 1.21, 1.22, 1.24,
|
|
1.25.0 and 1.26 — while the CI Go matrix installed 1.25. That is not
|
|
untidiness: ``services/osquery-extensions`` declared 1.26, so it could not be
|
|
built by the toolchain CI provides, and a contributor following the repo
|
|
would install whichever version they happened to read first.
|
|
|
|
Nothing checked, because nothing compared the two. This does.
|
|
|
|
Run: python3 scripts/check_toolchain_versions.py
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import re
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
# `scripts/` is on sys.path when this file is run as a program, but not when a
|
|
# test loads it by path with importlib. gate_toolkit sits beside it either way.
|
|
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
|
|
|
from gate_toolkit import repo_root, self_test_if_requested
|
|
|
|
self_test_if_requested(__file__)
|
|
|
|
REPO_ROOT = repo_root()
|
|
WORKFLOWS = REPO_ROOT / ".github" / "workflows"
|
|
|
|
|
|
def go_modules() -> dict[Path, str]:
|
|
"""Every go.mod and the version it declares."""
|
|
found: dict[Path, str] = {}
|
|
for path in sorted(REPO_ROOT.rglob("go.mod")):
|
|
# Vendored and cached trees are not ours to align.
|
|
if any(part in ("vendor", "node_modules", ".git") for part in path.parts):
|
|
continue
|
|
match = re.search(r"^go (\S+)$", path.read_text(encoding="utf-8"), re.M)
|
|
if match:
|
|
found[path.relative_to(REPO_ROOT)] = match.group(1)
|
|
return found
|
|
|
|
|
|
def workflow_go_versions() -> dict[str, set[str]]:
|
|
"""Every ``go-version:`` a workflow asks setup-go to install."""
|
|
found: dict[str, set[str]] = {}
|
|
for path in sorted(WORKFLOWS.glob("*.yml")):
|
|
versions = set(re.findall(r"go-version:\s*['\"]?([0-9][0-9.x]*)['\"]?", path.read_text(encoding="utf-8")))
|
|
if versions:
|
|
found[path.name] = versions
|
|
return found
|
|
|
|
|
|
def dockerfile_go_images() -> dict[str, str]:
|
|
"""Every ``FROM golang:X.Y`` base image in the repo.
|
|
|
|
Added because the first version of this gate checked go.mod against the
|
|
CI workflows and stopped there. Bumping the modules to 1.26 then broke
|
|
the compose build: three Dockerfiles still pinned golang:1.21, 1.24 and
|
|
1.25, and ``go mod download`` failed inside the image against a module
|
|
requiring a newer toolchain. A gate that covers two of the three places
|
|
a version is written finds the drift it was not looking for.
|
|
"""
|
|
found: dict[str, str] = {}
|
|
for path in sorted(REPO_ROOT.rglob("Dockerfile*")):
|
|
if any(part in ("node_modules", ".git", "plans") for part in path.parts):
|
|
continue
|
|
match = re.search(r"FROM\s+golang:(\d+\.\d+(?:\.\d+)?)", path.read_text(encoding="utf-8"))
|
|
if match:
|
|
found[str(path.relative_to(REPO_ROOT))] = match.group(1)
|
|
return found
|
|
|
|
|
|
def _minor(version: str) -> tuple[int, int]:
|
|
parts = version.split(".")
|
|
return (int(parts[0]), int(parts[1]) if len(parts) > 1 else 0)
|
|
|
|
|
|
def main(argv: list[str] | None = None) -> int:
|
|
argparse.ArgumentParser(description=__doc__).parse_args(argv)
|
|
errors: list[str] = []
|
|
|
|
modules = go_modules()
|
|
if not modules:
|
|
print("toolchain: no go.mod files found", file=sys.stderr)
|
|
return 2
|
|
|
|
declared = set(modules.values())
|
|
if len(declared) > 1:
|
|
detail = "\n".join(f" {p}: {v}" for p, v in sorted(modules.items()))
|
|
errors.append(f"go.mod files declare {len(declared)} different Go versions ({', '.join(sorted(declared))}):\n{detail}")
|
|
|
|
target = max(declared, key=_minor)
|
|
target_minor = _minor(target)
|
|
|
|
for workflow, versions in workflow_go_versions().items():
|
|
for version in versions:
|
|
if version.endswith("x"):
|
|
continue
|
|
if _minor(version) < target_minor:
|
|
errors.append(
|
|
f".github/workflows/{workflow} installs Go {version}, but a module "
|
|
f"declares {target}. That module cannot be built by the toolchain "
|
|
f"CI provides."
|
|
)
|
|
|
|
for dockerfile, version in dockerfile_go_images().items():
|
|
if _minor(version) < target_minor:
|
|
errors.append(
|
|
f"{dockerfile} builds on golang:{version}, but a module declares {target}. `go mod download` fails inside the image."
|
|
)
|
|
|
|
if errors:
|
|
print("TOOLCHAIN VERSION GATE FAILED:", file=sys.stderr)
|
|
for error in errors:
|
|
print(f" - {error}", file=sys.stderr)
|
|
return 1
|
|
|
|
images = dockerfile_go_images()
|
|
print(f"toolchain: OK — {len(modules)} Go modules on {target}; CI and {len(images)} Dockerfile(s) install it")
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|