187 lines
4.7 KiB
Python
187 lines
4.7 KiB
Python
#!/usr/bin/env python3
|
|
# -*- coding: utf-8 -*-
|
|
"""Lane/domain guardrail with baseline support.
|
|
|
|
Purpose:
|
|
- Keep .com/.cn/hackrobot lane references from drifting over time.
|
|
- Do not force immediate cleanup of historical violations.
|
|
- Block only *new* violations by default.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import re
|
|
import subprocess
|
|
import sys
|
|
from dataclasses import dataclass
|
|
from pathlib import Path
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
BASELINE_PATH = ROOT / "scripts" / "lane_guard_baseline.json"
|
|
|
|
ALLOWED_SUFFIXES = {
|
|
".ts",
|
|
".tsx",
|
|
".js",
|
|
".jsx",
|
|
".mjs",
|
|
".cjs",
|
|
".py",
|
|
".sh",
|
|
".ps1",
|
|
".json",
|
|
".yaml",
|
|
".yml",
|
|
".md",
|
|
".conf",
|
|
".env",
|
|
".txt",
|
|
}
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class Rule:
|
|
scope_name: str
|
|
path_prefixes: tuple[str, ...]
|
|
forbidden_regexes: tuple[str, ...]
|
|
|
|
|
|
RULES: tuple[Rule, ...] = (
|
|
Rule(
|
|
scope_name="com_scope_forbid_cn_domains",
|
|
path_prefixes=("apps/com/",),
|
|
forbidden_regexes=(
|
|
r"\bnomadro\.cn\b",
|
|
r"\bapi\.nomadro\.cn\b",
|
|
r"\badmin\.nomadro\.cn\b",
|
|
),
|
|
),
|
|
Rule(
|
|
scope_name="cn_scope_forbid_com_domains",
|
|
path_prefixes=("apps/miniprogram/", "apps/admin/"),
|
|
forbidden_regexes=(
|
|
r"\bnomadro\.com\b",
|
|
r"\bapi\.nomadro\.com\b",
|
|
r"\badmin\.nomadro\.com\b",
|
|
),
|
|
),
|
|
Rule(
|
|
scope_name="hackrobot_scope_forbid_nomadro_domains",
|
|
path_prefixes=("apps/hackrobot/",),
|
|
forbidden_regexes=(
|
|
r"\bnomadro\.com\b",
|
|
r"\bnomadro\.cn\b",
|
|
r"\badmin\.nomadro\.com\b",
|
|
r"\badmin\.nomadro\.cn\b",
|
|
),
|
|
),
|
|
)
|
|
|
|
|
|
def git_tracked_files() -> list[str]:
|
|
output = subprocess.check_output(
|
|
["git", "ls-files"],
|
|
cwd=ROOT,
|
|
text=True,
|
|
encoding="utf-8",
|
|
)
|
|
return [line.strip() for line in output.splitlines() if line.strip()]
|
|
|
|
|
|
def is_scannable(path: str) -> bool:
|
|
suffix = Path(path).suffix.lower()
|
|
if suffix and suffix not in ALLOWED_SUFFIXES:
|
|
return False
|
|
# Skip likely binaries/minified assets checked into repo.
|
|
lowered = path.lower()
|
|
if "/dist/" in lowered or "/.next/" in lowered:
|
|
return False
|
|
return True
|
|
|
|
|
|
def scan_violations() -> dict[str, list[str]]:
|
|
files = git_tracked_files()
|
|
violations: dict[str, list[str]] = {}
|
|
|
|
compiled_rules = [
|
|
(
|
|
rule,
|
|
tuple(re.compile(pattern, flags=re.IGNORECASE) for pattern in rule.forbidden_regexes),
|
|
)
|
|
for rule in RULES
|
|
]
|
|
|
|
for rel in files:
|
|
if not is_scannable(rel):
|
|
continue
|
|
abs_path = ROOT / rel
|
|
try:
|
|
text = abs_path.read_text(encoding="utf-8", errors="ignore")
|
|
except OSError:
|
|
continue
|
|
|
|
for rule, patterns in compiled_rules:
|
|
if not any(rel.startswith(prefix) for prefix in rule.path_prefixes):
|
|
continue
|
|
|
|
for idx, line in enumerate(text.splitlines(), start=1):
|
|
for pattern in patterns:
|
|
if pattern.search(line):
|
|
key = f"{rel}:{idx}:{rule.scope_name}"
|
|
violations[key] = [line.strip(), pattern.pattern]
|
|
|
|
return violations
|
|
|
|
|
|
def load_baseline() -> dict[str, list[str]]:
|
|
if not BASELINE_PATH.exists():
|
|
return {}
|
|
data = json.loads(BASELINE_PATH.read_text(encoding="utf-8"))
|
|
return data.get("violations", {})
|
|
|
|
|
|
def write_baseline(violations: dict[str, list[str]]) -> None:
|
|
payload = {
|
|
"version": 1,
|
|
"generatedBy": "scripts/lane_guard.py",
|
|
"violations": dict(sorted(violations.items())),
|
|
}
|
|
BASELINE_PATH.write_text(
|
|
json.dumps(payload, ensure_ascii=False, indent=2) + "\n",
|
|
encoding="utf-8",
|
|
)
|
|
|
|
|
|
def main() -> int:
|
|
update = "--update-baseline" in sys.argv
|
|
current = scan_violations()
|
|
|
|
if update:
|
|
write_baseline(current)
|
|
print(f"lane guard baseline updated: {len(current)} entries")
|
|
return 0
|
|
|
|
baseline = load_baseline()
|
|
new_keys = sorted(set(current) - set(baseline))
|
|
|
|
if not new_keys:
|
|
print(f"lane guard passed (baseline={len(baseline)}, current={len(current)})")
|
|
return 0
|
|
|
|
print("lane guard failed: new cross-lane references detected")
|
|
for key in new_keys[:80]:
|
|
line, pattern = current[key]
|
|
print(f"- {key}")
|
|
print(f" pattern: {pattern}")
|
|
print(f" line: {line[:220]}")
|
|
remaining = len(new_keys) - 80
|
|
if remaining > 0:
|
|
print(f"... and {remaining} more")
|
|
print("\nIf intentional, run: python scripts/lane_guard.py --update-baseline")
|
|
return 1
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|