Skip to content

armgit / forma

Public Imported from GitHub
0

A 1.2 MB pure-Rust rewrite of headless Blender built for AI agents — 3D B-rep modeling engine, CLI, and MCP server

4.2 KB
Raw Blame
#!/usr/bin/env python3
"""Fail if tracked or staged files contain hardcoded local user-home paths.

Usage:
  python3 scripts/check_local_paths.py           # scan all git-tracked files
  python3 scripts/check_local_paths.py --staged  # scan staged changes (pre-commit)

Optional local-only blocklist (never committed):
  Add one case-insensitive substring per line to `<git-common-dir>/forbidden_strings`.
"""

from __future__ import annotations

import argparse
import os
import re
import subprocess
import sys
from pathlib import Path

PATTERNS: list[tuple[str, re.Pattern[str]]] = [
    (
        "macOS home path",
        re.compile(
            r"(?<![A-Za-z0-9_.-])/Users/"
            r"(?!(?:user|username|yourname|your-user|example|Shared|runner)(?:/|$))"
            r"[A-Za-z0-9][A-Za-z0-9._-]*/"
        ),
    ),
    (
        "Windows home path",
        re.compile(
            r"(?i)(?<![A-Za-z0-9_.-])[A-Z]:\\Users\\"
            r"(?!(?:user|username|yourname|Public|Default)(?:\\|$))"
            r"[A-Za-z0-9][A-Za-z0-9._-]*\\"
        ),
    ),
    (
        "Linux home path",
        re.compile(
            r"(?<![A-Za-z0-9_.-])/home/"
            r"(?!(?:user|username|yourname|pi|runner|ubuntu|ci|dev)(?:/|$))"
            r"[A-Za-z0-9][A-Za-z0-9._-]*/"
        ),
    ),
]

# Files allowed to mention generic regexes/examples in their own source
SELF_PATHS = {"scripts/check_local_paths.py"}


def git_output(args: list[str]) -> bytes:
    return subprocess.check_output(["git", *args])


def load_local_forbidden_strings() -> list[str]:
    try:
        common_dir = Path(git_output(["rev-parse", "--git-common-dir"]).decode().strip())
    except subprocess.CalledProcessError:
        return []
    blocklist = common_dir / "forbidden_strings"
    if not blocklist.is_file():
        return []
    terms: list[str] = []
    for raw in blocklist.read_text(encoding="utf-8", errors="ignore").splitlines():
        term = raw.strip()
        if term and not term.startswith("#"):
            terms.append(term.lower())
    return terms


def list_files(staged: bool) -> list[str]:
    if staged:
        raw = git_output(["diff", "--cached", "--name-only", "--diff-filter=ACMR", "-z"])
    else:
        raw = git_output(["ls-files", "-z"])
    return [p.decode("utf-8", errors="surrogateescape") for p in raw.split(b"\x00") if p]


def read_file_bytes(rel_path: str, staged: bool) -> bytes:
    if staged:
        return git_output(["show", f":{rel_path}"])
    return Path(rel_path).read_bytes()


def main() -> int:
    parser = argparse.ArgumentParser(description="Check repo for hardcoded local user paths.")
    parser.add_argument("--staged", action="store_true", help="Check staged git index contents only.")
    args = parser.parse_args()

    repo_root = Path(git_output(["rev-parse", "--show-toplevel"]).decode().strip())
    os.chdir(repo_root)

    local_terms = load_local_forbidden_strings()
    files = list_files(args.staged)
    violations: list[str] = []

    for rel_path in files:
        if rel_path in SELF_PATHS:
            continue
        try:
            data = read_file_bytes(rel_path, args.staged)
        except (OSError, subprocess.CalledProcessError):
            continue

        text = data.decode("utf-8", errors="ignore")
        for label, regex in PATTERNS:
            for match in regex.finditer(text):
                line_no = text.count("\n", 0, match.start()) + 1
                violations.append(f"{rel_path}:{line_no}: matched {label}")

        if local_terms:
            lower = text.lower()
            for term in local_terms:
                idx = lower.find(term)
                if idx != -1:
                    line_no = text.count("\n", 0, idx) + 1
                    violations.append(f"{rel_path}:{line_no}: matched local forbidden_strings entry")

    if violations:
        print("ERROR: Hardcoded local path or forbidden personal string detected:", file=sys.stderr)
        for v in violations:
            print(f"  - {v}", file=sys.stderr)
        return 1

    scope = "staged files" if args.staged else f"{len(files)} tracked files"
    print(f"OK: no hardcoded local paths found across {scope}.")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())