Skip to main content

scripts-enhance-hooks

#!/usr/bin/env python3 """

title: "Skip check if SKIP_HOOKS environment variable is set" component_type: script version: "1.0.0" audience: contributor status: stable summary: "Enhance hook files with programmatic patterns: " keywords: ['enhance', 'hooks', 'validation'] tokens: ~500 created: 2025-12-22 updated: 2025-12-22 script_name: "enhance-hooks.py" language: python executable: true usage: "python3 scripts/enhance-hooks.py [options]" python_version: "3.10+" dependencies: [] modifies_files: false network_access: false requires_auth: false

Enhance hook files with programmatic patterns:

  • Skip conditions (SKIP_HOOKS environment variable)
  • Performance tracking (execution time logging)
  • Comprehensive error messages
  • Exit code consistency """

import argparse import os from pathlib import Path

HOOKS_DIR = Path(file).parent.parent / "hooks"

HOOKS_TO_ENHANCE = [ "component-validation.sh", "documentation-sync.sh", "production-cleanup-pre-push.sh", "prompt-enhancement.sh", "standards-compliance.sh", ]

SKIP_CHECK_ADDITION = """

Skip check if SKIP_HOOKS environment variable is set

if [ "${SKIP_HOOKS:-0}" = "1" ]; then echo "⏭️ Skipping hook (SKIP_HOOKS=1)" echo '{"continue": true}' exit 0 fi """

TIMING_START = """

Track execution time

START_TIME=$(date +%s) """

TIMING_END = """

Log execution time

END_TIME=$(date +%s) DURATION=$((END_TIME - START_TIME)) echo "⏱️ Hook completed in ${DURATION}s" """

def enhance_hook(hook_file): """Add programmatic enhancements to hook file.""" filepath = HOOKS_DIR / hook_file

if not filepath.exists():
print(f"❌ Not found: {hook_file}")
return False

content = filepath.read_text()

# Check if already enhanced
if "SKIP_HOOKS" in content:
print(f"⏭️ Already enhanced: {hook_file}")
return True

# Find insertion points
lines = content.split("\n")

# Find first line after shebang and comments
insert_idx = 0
for i, line in enumerate(lines):
if line.startswith("#") or line.strip() == "":
insert_idx = i + 1
else:
break

# Insert skip check after header
lines.insert(insert_idx, "")
lines.insert(insert_idx + 1, SKIP_CHECK_ADDITION.strip())
lines.insert(insert_idx + 2, "")

# Insert timing at script start (after skip check)
lines.insert(insert_idx + 3, TIMING_START.strip())
lines.insert(insert_idx + 4, "")

# Find script exit points and add timing before them
enhanced_lines = []
for line in lines:
if line.strip().startswith("exit "):
# Add timing before exit
enhanced_lines.append(TIMING_END.strip())
enhanced_lines.append(line)

filepath.write_text("\n".join(enhanced_lines))
print(f"✅ Enhanced: {hook_file}")
return True

def parse_args(): """Parse command line arguments""" parser = argparse.ArgumentParser( description='Enhance hook files with programmatic patterns.', formatter_class=argparse.RawDescriptionHelpFormatter, epilog=''' Examples: %(prog)s # Enhance all configured hooks %(prog)s --dry-run # Show what would be changed without modifying files %(prog)s --list # List hooks that would be enhanced %(prog)s --hook name.sh # Enhance only a specific hook file

Patterns added to each hook:

  • SKIP_HOOKS environment variable check
  • Execution time tracking
  • Consistent exit codes ''' ) parser.add_argument('--dry-run', action='store_true', help='Show what would be changed without modifying files') parser.add_argument('--list', action='store_true', help='List hooks that would be enhanced') parser.add_argument('--hook', type=str, help='Enhance only a specific hook file') parser.add_argument('--verbose', '-v', action='store_true', help='Verbose output') return parser.parse_args()

def main(): """Enhance all hook files.""" args = parse_args()

# Handle --list
if args.list:
print("Hooks to enhance:")
for hook_file in HOOKS_TO_ENHANCE:
filepath = HOOKS_DIR / hook_file
status = "exists" if filepath.exists() else "NOT FOUND"
print(f" - {hook_file} ({status})")
return

print("🚀 Enhancing hook files with programmatic patterns...\n")

enhanced = 0
skipped = 0

hooks_to_process = HOOKS_TO_ENHANCE
if args.hook:
hooks_to_process = [h for h in HOOKS_TO_ENHANCE if args.hook in h]
if not hooks_to_process:
print(f"No matching hook found for: {args.hook}")
return

for hook_file in hooks_to_process:
if enhance_hook(hook_file):
if "Already enhanced" in str(hook_file):
skipped += 1
else:
enhanced += 1

print(f"\n📊 Summary:")
print(f" ✅ Enhanced: {enhanced}")
print(f" ⏭️ Already done: {skipped}")
print(f" 📝 Total: {enhanced + skipped}")

if name == "main": main()