surshar / claude-code
Claude Code is an agentic coding tool that lives in your terminal, understands your codebase, and helps you code faster by executing routine tasks, explaining complex code, and handling git workflows - all through natural language commands.
Built by Anthropic · github.com/anthropics
| 1 | #!/usr/bin/env python3 |
| 2 | """PreToolUse hook executor for hookify plugin. |
| 3 | |
| 4 | This script is called by Claude Code before any tool executes. |
| 5 | It reads .claude/hookify.*.local.md files and evaluates rules. |
| 6 | """ |
| 7 | |
| 8 | import os |
| 9 | import sys |
| 10 | import json |
| 11 | |
| 12 | # CRITICAL: Add plugin root to Python path for imports |
| 13 | # We need to add the parent of the plugin directory so Python can find "hookify" package |
| 14 | PLUGIN_ROOT = os.environ.get('CLAUDE_PLUGIN_ROOT') |
| 15 | if PLUGIN_ROOT: |
| 16 | # Add the parent directory of the plugin |
| 17 | parent_dir = os.path.dirname(PLUGIN_ROOT) |
| 18 | if parent_dir not in sys.path: |
| 19 | sys.path.insert(0, parent_dir) |
| 20 | |
| 21 | # Also add PLUGIN_ROOT itself in case we have other scripts |
| 22 | if PLUGIN_ROOT not in sys.path: |
| 23 | sys.path.insert(0, PLUGIN_ROOT) |
| 24 | |
| 25 | try: |
| 26 | from hookify.core.config_loader import load_rules |
| 27 | from hookify.core.rule_engine import RuleEngine |
| 28 | except ImportError as e: |
| 29 | # If imports fail, allow operation and log error |
| 30 | error_msg = {"systemMessage": f"Hookify import error: {e}"} |
| 31 | print(json.dumps(error_msg), file=sys.stdout) |
| 32 | sys.exit(0) |
| 33 | |
| 34 | |
| 35 | def main(): |
| 36 | """Main entry point for PreToolUse hook.""" |
| 37 | try: |
| 38 | # Read input from stdin |
| 39 | input_data = json.load(sys.stdin) |
| 40 | |
| 41 | # Determine event type for filtering |
| 42 | # For PreToolUse, we use tool_name to determine "bash" vs "file" event |
| 43 | tool_name = input_data.get('tool_name', '') |
| 44 | |
| 45 | event = None |
| 46 | if tool_name == 'Bash': |
| 47 | event = 'bash' |
| 48 | elif tool_name in ['Edit', 'Write', 'MultiEdit']: |
| 49 | event = 'file' |
| 50 | |
| 51 | # Load rules |
| 52 | rules = load_rules(event=event) |
| 53 | |
| 54 | # Evaluate rules |
| 55 | engine = RuleEngine() |
| 56 | result = engine.evaluate_rules(rules, input_data) |
| 57 | |
| 58 | # Always output JSON (even if empty) |
| 59 | print(json.dumps(result), file=sys.stdout) |
| 60 | |
| 61 | except Exception as e: |
| 62 | # On any error, allow the operation and log |
| 63 | error_output = { |
| 64 | "systemMessage": f"Hookify error: {str(e)}" |
| 65 | } |
| 66 | print(json.dumps(error_output), file=sys.stdout) |
| 67 | |
| 68 | finally: |
| 69 | # ALWAYS exit 0 - never block operations due to hook errors |
| 70 | sys.exit(0) |
| 71 | |
| 72 | |
| 73 | if __name__ == '__main__': |
| 74 | main() |