|
| 1 | +#!/usr/bin/env python3 |
| 2 | +""" |
| 3 | +PreToolUse hook: Block edits containing BookStore banned patterns. |
| 4 | +
|
| 5 | +Scans .cs files in edit tool calls and denies the operation when |
| 6 | +any AGENTS.md code rule violation is detected. |
| 7 | +
|
| 8 | +Input (stdin): VS Code PreToolUse JSON payload |
| 9 | +Output (stdout): JSON deny decision, or nothing on success |
| 10 | +""" |
| 11 | + |
| 12 | +import json |
| 13 | +import re |
| 14 | +import sys |
| 15 | + |
| 16 | +# (regex_pattern, human-readable fix message) |
| 17 | +RULES: list[tuple[str, str]] = [ |
| 18 | + ( |
| 19 | + r"\bGuid\.NewGuid\(\)", |
| 20 | + "Use Guid.CreateVersion7() instead of Guid.NewGuid()", |
| 21 | + ), |
| 22 | + ( |
| 23 | + r"\bDateTime\.Now\b", |
| 24 | + "Use DateTimeOffset.UtcNow instead of DateTime.Now", |
| 25 | + ), |
| 26 | + ( |
| 27 | + r"\b_logger\.Log(?:Information|Warning|Error|Debug|Critical|Trace)\s*\(", |
| 28 | + "Use [LoggerMessage] source generator — never call _logger.Log*() directly", |
| 29 | + ), |
| 30 | + ( |
| 31 | + r"namespace\s+[\w.]+\s*\{", |
| 32 | + "Use file-scoped namespaces: 'namespace BookStore.X;' not 'namespace BookStore.X { }'", |
| 33 | + ), |
| 34 | + ( |
| 35 | + r'"(?:\*DEFAULT\*|default)"', |
| 36 | + 'Use MultiTenancyConstants.* instead of hardcoded tenant strings "*DEFAULT*" or "default"', |
| 37 | + ), |
| 38 | +] |
| 39 | + |
| 40 | + |
| 41 | +def check_content(content: str) -> list[str]: |
| 42 | + return [msg for pattern, msg in RULES if re.search(pattern, content)] |
| 43 | + |
| 44 | + |
| 45 | +def extract_cs_files(tool_input: dict) -> list[tuple[str, str]]: |
| 46 | + """Return (path, content) pairs for .cs files, handling multiple tool input shapes.""" |
| 47 | + results: list[tuple[str, str]] = [] |
| 48 | + |
| 49 | + # editFiles / createFile shape: { files: [{filePath, content}] } |
| 50 | + for f in tool_input.get("files", []): |
| 51 | + if isinstance(f, dict): |
| 52 | + path = f.get("filePath", f.get("path", "")) |
| 53 | + content = f.get("content", f.get("newContent", "")) |
| 54 | + else: |
| 55 | + path, content = str(f), "" |
| 56 | + if path.endswith(".cs") and content: |
| 57 | + results.append((path, content)) |
| 58 | + |
| 59 | + # replaceStringInFile shape: { filePath, newString } |
| 60 | + fp = tool_input.get("filePath", "") |
| 61 | + if fp.endswith(".cs"): |
| 62 | + new_str = tool_input.get("newString", "") |
| 63 | + if new_str: |
| 64 | + results.append((fp, new_str)) |
| 65 | + |
| 66 | + return results |
| 67 | + |
| 68 | + |
| 69 | +def deny(reason: str) -> None: |
| 70 | + output = { |
| 71 | + "hookSpecificOutput": { |
| 72 | + "hookEventName": "PreToolUse", |
| 73 | + "permissionDecision": "deny", |
| 74 | + "permissionDecisionReason": reason, |
| 75 | + } |
| 76 | + } |
| 77 | + print(json.dumps(output)) |
| 78 | + sys.exit(0) |
| 79 | + |
| 80 | + |
| 81 | +def main() -> None: |
| 82 | + try: |
| 83 | + data = json.load(sys.stdin) |
| 84 | + except Exception: |
| 85 | + sys.exit(0) |
| 86 | + |
| 87 | + cs_files = extract_cs_files(data.get("tool_input", {})) |
| 88 | + if not cs_files: |
| 89 | + sys.exit(0) |
| 90 | + |
| 91 | + all_violations: list[str] = [] |
| 92 | + for path, content in cs_files: |
| 93 | + for violation in check_content(content): |
| 94 | + all_violations.append(f" • {path}: {violation}") |
| 95 | + |
| 96 | + if all_violations: |
| 97 | + deny("BookStore code rule violations:\n" + "\n".join(all_violations)) |
| 98 | + |
| 99 | + |
| 100 | +if __name__ == "__main__": |
| 101 | + main() |
0 commit comments