Skip to main content
hooksSource-backedReview first Safety Privacy

Go Module Tidy - Hooks

Automatically runs go mod tidy when Go files or go.mod are modified to keep dependencies clean.

by JSONbored·added 2025-09-19·
HarnessClaude Code
Trigger:PostToolUse
Review first review before installing

Open the source and read safety notes before installing.

Citation facts

Source-backed facts for citing this resource, derived directly from the registry — also available as plain text for AI assistants.

Source URLs
https://go.dev/doc/modules/managing-dependencies, https://github.com/JSONbored/awesome-claude/blob/main/content/hooks/go-module-tidy.mdx
Safety notes
Runs automatically on its configured Claude Code hook event and executes shell logic that can read, modify, or delete files in your project (and may run builds, installs, or network calls); review the script and scope it to expected paths before enabling.
Privacy notes
Receives Claude Code hook input (session metadata, file paths, and tool output) and reads local project files; review what the script logs or forwards to external services and keep credentials out of its output.
Author
JSONbored
Claim status
unclaimed
Last verified
2025-09-19

Decision playbook

Review trust signals before you adopt

Signals are present but mixed. Use the checklist below to confirm the source and operational safety for your environment.

Compare context
Selected

0

Current score

78

Baseline

Delta

No baseline selected

No major trust-signal divergence detected in the current selection.

Source and provenance checks

Complete

Confirm ownership and provenance before trusting install instructions.

  • Source link availableRequired

    Open the canonical repository and verify ownership.

    Done
  • Source provenance statusRequired

    Marked as source-backed.

    Done
  • Metadata reviewed

    Registry metadata indicates a reviewed listing.

    Done

Safety and privacy checks

Complete

Validate risk disclosures before installation or API wiring.

  • Safety notes presentRequired

    Review the listed safety guidance before running commands.

    Done
  • Privacy notes presentRequired

    Review data handling notes before connecting accounts or secrets.

    Done
  • Trust level risk gateRequired

    Trust level does not block evaluation.

    Done

Package and install checks

Needs review

Check package metadata and artifact integrity signals.

  • Install payload available

    Install or copy payload is available for review.

    Done
  • Package verification flag

    No package verification flag provided.

    Pending
  • Checksum metadata

    No checksum provided for downloaded artifact.

    Pending

Compare-driven decision checks

Needs review

Use compare context to validate trade-offs before adoption.

  • Compare tray has multiple entries

    Add at least one more entry to compare trust differences.

    Pending
  • Baseline comparison available

    No baseline peer selected yet.

    Pending
  • Diverging trust signals identified

    No major trust-signal divergence found.

    Pending

Setup at a glance

CLI install

Copy-ready — paste the snippet to get started.

Install command

Provided

Config snippet

Provided

Copy snippet

Provided

Prerequisites

None

Platforms

1 listed

Difficulty

0/100

Adoption plan

Balanced adoption plan

Current risk score 16/100. Use staged verification before broader rollout.

Risk 16

Pre-adoption checks

Validate source and review signals before any execution.

  • Confirm source provenanceRequired

    Source URL/provenance metadata is present.

    Done
  • Confirm metadata review state

    Listing has review metadata.

    Done
  • Verify install payload

    Install/config payload exists and can be inspected.

    Done

Security checks

Confirm safety, privacy, and package integrity signals.

  • Review safety notesRequired

    Safety notes are present.

    Done
  • Review privacy notesRequired

    Privacy notes are present.

    Done
  • Verify package integrity metadata

    No package verification/checksum metadata.

    Pending

Rollout

Adopt in controlled steps based on the selected plan.

  • Run in isolated sandbox firstRequired

    Use a constrained sandbox and observe behavior across multiple tasks.

    Pending
  • Roll out graduallyRequired

    Roll out to a small cohort before wider usage.

    Pending
  • Set monitoring and fallback

    Define rollback path and monitor errors after adoption.

    Pending

Evidence readiness

Evidence readiness matrix · balanced

Required evidence gates are covered (5/6 signals complete).

Risk 15

Source provenance

Present

Source repository/provenance is listed.

Required in this preset

Metadata review

Present

Review metadata is present.

Required in this preset

Safety notes

Present

Safety notes are present.

Required in this preset

Privacy notes

Present

Privacy notes are present.

Optional in this preset

Package integrity

Missing

Package integrity metadata is missing.

Optional in this preset

Install payload

Present

Install payload is available.

Required in this preset

Required evidence gates are covered for this preset.

Decision timeline

Decision timeline · balanced

5/6 steps complete with no blocking gaps for this preset.

Risk 14

triage

Confirm source provenanceRequired

Source/provenance metadata is available.

Done

triage

Check metadata review statusRequired

Review metadata is available.

Done

verify

Review safety notesRequired

Safety notes are available.

Done

verify

Review privacy notes

Privacy notes are available.

Done

verify

Validate package integrity metadata

Package integrity metadata is missing.

Pending

rollout

Verify install payload and commandsRequired

Install payload is available.

Done

No required blockers for this timeline preset.

Safety & privacy surface

Safety & privacy surface

1 safety and 1 privacy notes across 2 risk areas. Review closely: credentials & tokens, permissions & scopes.

2 areas
  • SafetyPermissions & scopesRuns automatically on its configured Claude Code hook event and executes shell logic that can read, modify, or delete files in your project (and may run builds, installs, or network calls); review the script and scope it to expected paths before enabling.
  • PrivacyCredentials & tokensReceives Claude Code hook input (session metadata, file paths, and tool output) and reads local project files; review what the script logs or forwards to external services and keep credentials out of its output.

Safety notes

  • Runs automatically on its configured Claude Code hook event and executes shell logic that can read, modify, or delete files in your project (and may run builds, installs, or network calls); review the script and scope it to expected paths before enabling.

Privacy notes

  • Receives Claude Code hook input (session metadata, file paths, and tool output) and reads local project files; review what the script logs or forwards to external services and keep credentials out of its output.

Schema details

Install type
cli
Reading time
1 min
Difficulty score
0
Troubleshooting
Yes
Breaking changes
No
Skill and platform metadata
Retrieval sources
https://go.dev/doc/modules/managing-dependencieshttps://code.claude.com/docs/en/hooks
Runtime and command metadata
Trigger
PostToolUse
Script language
bash
Script body
#!/usr/bin/env bash

# Read the tool input from stdin
INPUT=$(cat)
TOOL_NAME=$(echo "$INPUT" | jq -r '.tool_name')
FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // .tool_input.path // ""')

if [ -z "$FILE_PATH" ]; then
  exit 0
fi

# Check if this is a Go-related file
if [[ "$FILE_PATH" == *.go ]] || [[ "$FILE_PATH" == *go.mod ]] || [[ "$FILE_PATH" == *go.sum ]] || [[ "$FILE_PATH" == *go.work* ]]; then
  echo "🔧 Go Module Maintenance for: $(basename "$FILE_PATH")" >&2
  
  # Find the Go module root
  MODULE_DIR="$(dirname "$FILE_PATH")"
  
  # Walk up the directory tree to find go.mod
  while [ "$MODULE_DIR" != "/" ] && [ ! -f "$MODULE_DIR/go.mod" ]; do
    MODULE_DIR="$(dirname "$MODULE_DIR")"
  done
  
  if [ ! -f "$MODULE_DIR/go.mod" ]; then
    echo "⚠️ No go.mod found - not a Go module" >&2
    exit 0
  fi
  
  echo "📁 Go module root: $MODULE_DIR" >&2
  cd "$MODULE_DIR"
  
  # Check if Go is installed
  if ! command -v go &> /dev/null; then
    echo "❌ Go is not installed or not in PATH" >&2
    exit 1
  fi
  
  GO_VERSION=$(go version | cut -d' ' -f3 2>/dev/null || echo "unknown")
  echo "🐹 Go version: $GO_VERSION" >&2
  
  # Initialize maintenance counters
  ERRORS=0
  WARNINGS=0
  FIXED=0
  
  # Function to report issues
  report_issue() {
    local level="$1"
    local message="$2"
    
    case "$level" in
      "ERROR")
        echo "❌ ERROR: $message" >&2
        ERRORS=$((ERRORS + 1))
        ;;
      "WARNING")
        echo "⚠️ WARNING: $message" >&2
        WARNINGS=$((WARNINGS + 1))
        ;;
      "FIXED")
        echo "✅ FIXED: $message" >&2
        FIXED=$((FIXED + 1))
        ;;
      "INFO")
        echo "ℹ️ INFO: $message" >&2
        ;;
    esac
  }
  
  # 1. Pre-tidy Module Analysis
  echo "📊 Analyzing module state..." >&2
  
  # Check go.mod syntax
  if ! go mod edit -json > /dev/null 2>&1; then
    report_issue "ERROR" "go.mod has syntax errors"
    exit 1
  else
    echo "   ✅ go.mod syntax is valid" >&2
  fi
  
  # Get current dependencies before tidy
  DEPS_BEFORE=$(go list -m all 2>/dev/null | wc -l | xargs || echo "0")
  echo "   📦 Dependencies before tidy: $DEPS_BEFORE" >&2
  
  # Check for any build errors
  if go list ./... > /dev/null 2>&1; then
    echo "   ✅ Module builds successfully" >&2
  else
    report_issue "WARNING" "Module has build issues that may affect dependency resolution"
  fi
  
  # 2. Run go mod tidy
  echo "🧹 Running go mod tidy..." >&2
  
  if go mod tidy; then
    report_issue "FIXED" "go mod tidy completed successfully"
    
    # Check dependencies after tidy
    DEPS_AFTER=$(go list -m all 2>/dev/null | wc -l | xargs || echo "0")
    DEPS_CHANGE=$((DEPS_AFTER - DEPS_BEFORE))
    
    if [ "$DEPS_CHANGE" -gt 0 ]; then
      echo "   📈 Added $DEPS_CHANGE dependencies" >&2
    elif [ "$DEPS_CHANGE" -lt 0 ]; then
      echo "   📉 Removed $((DEPS_CHANGE * -1)) dependencies" >&2
    else
      echo "   📦 No dependency changes" >&2
    fi
    
  else
    report_issue "ERROR" "go mod tidy failed"
  fi
  
  # 3. Verify go.sum integrity
  echo "🔐 Verifying module checksums..." >&2
  
  if go mod verify; then
    echo "   ✅ All module checksums verified" >&2
  else
    report_issue "ERROR" "Module checksum verification failed"
  fi
  
  # 4. Check for vulnerabilities (if govulncheck is available)
  if command -v govulncheck &> /dev/null; then
    echo "🛡️ Scanning for vulnerabilities..." >&2
    
    if govulncheck ./... 2>/dev/null; then
      echo "   ✅ No known vulnerabilities found" >&2
    else
      report_issue "WARNING" "Potential vulnerabilities detected - run 'govulncheck ./...' for details"
    fi
  else
    echo "   💡 Install govulncheck for vulnerability scanning: go install golang.org/x/vuln/cmd/govulncheck@latest" >&2
  fi
  
  # 5. Run go vet for Go source files
  if [[ "$FILE_PATH" == *.go ]]; then
    echo "🔍 Running go vet..." >&2
    
    if go vet ./...; then
      echo "   ✅ go vet passed - no issues found" >&2
    else
      report_issue "WARNING" "go vet found potential issues"
    fi
    
    # Check for common Go issues
    echo "🔍 Additional Go code analysis..." >&2
    
    # Check for gofmt issues
    UNFORMATTED=$(find . -name '*.go' -not -path './vendor/*' -exec gofmt -l {} \; 2>/dev/null)
    if [ -n "$UNFORMATTED" ]; then
      report_issue "WARNING" "Some files are not gofmt formatted"
      echo "$UNFORMATTED" | head -5 | while read file; do
        echo "     $file" >&2
      done
    else
      echo "   ✅ All Go files are properly formatted" >&2
    fi
    
    # Check imports with goimports if available
    if command -v goimports &> /dev/null; then
      IMPORT_ISSUES=$(find . -name '*.go' -not -path './vendor/*' -exec goimports -l {} \; 2>/dev/null)
      if [ -n "$IMPORT_ISSUES" ]; then
        report_issue "WARNING" "Some files have import formatting issues"
      else
        echo "   ✅ All imports are properly formatted" >&2
      fi
    fi
  fi
  
  # 6. Module cleanup suggestions
  echo "🧹 Module optimization check..." >&2
  
  # Check for indirect dependencies that could be direct
  INDIRECT_COUNT=$(go list -m all | grep -c '// indirect' || echo "0")
  if [ "$INDIRECT_COUNT" -gt 0 ]; then
    echo "   📊 Indirect dependencies: $INDIRECT_COUNT" >&2
    echo "   💡 Review if any indirect deps should be direct" >&2
  fi
  
  # Check for replace directives
  REPLACE_COUNT=$(grep -c '^replace ' go.mod 2>/dev/null || echo "0")
  if [ "$REPLACE_COUNT" -gt 0 ]; then
    echo "   🔄 Replace directives: $REPLACE_COUNT" >&2
    echo "   💡 Review replace directives for production readiness" >&2
  fi
  
  # 7. Workspace support
  if [ -f "go.work" ]; then
    echo "🏢 Go workspace detected" >&2
    
    if go work sync; then
      echo "   ✅ Workspace synced successfully" >&2
    else
      report_issue "WARNING" "Workspace sync issues detected"
    fi
  fi
  
  # 8. Module cache suggestions
  if [ "$DEPS_AFTER" -gt 50 ]; then
    echo "💡 Large dependency count - consider 'go clean -modcache' if disk space is low" >&2
  fi
  
  # 9. Generate Summary Report
  echo "" >&2
  echo "📋 Go Module Maintenance Summary:" >&2
  echo "================================" >&2
  echo "   📄 Module: $(basename "$(pwd)")" >&2
  echo "   🐹 Go: $GO_VERSION" >&2
  echo "   📦 Dependencies: $DEPS_AFTER" >&2
  echo "   ✅ Fixed: $FIXED" >&2
  echo "   ⚠️ Warnings: $WARNINGS" >&2
  echo "   ❌ Errors: $ERRORS" >&2
  
  if [ "$ERRORS" -eq 0 ] && [ "$WARNINGS" -eq 0 ]; then
    echo "   🎉 Status: EXCELLENT - Module is clean and optimized" >&2
  elif [ "$ERRORS" -eq 0 ]; then
    echo "   ✅ Status: GOOD - Minor warnings to review" >&2
  else
    echo "   ❌ Status: NEEDS ATTENTION - Errors require fixing" >&2
  fi
  
  echo "" >&2
  echo "💡 Go Module Best Practices:" >&2
  echo "   • Run 'go mod tidy' regularly to keep dependencies clean" >&2
  echo "   • Use 'go mod why <module>' to understand dependency reasons" >&2
  echo "   • Update dependencies with 'go get -u ./...' carefully" >&2
  echo "   • Consider using 'go mod graph' for dependency visualization" >&2
  echo "   • Pin important dependencies to specific versions" >&2
  
  # Exit with error if there are critical issues
  if [ "$ERRORS" -gt 0 ]; then
    echo "⚠️ Go module maintenance completed with errors" >&2
    exit 1
  fi
  
else
  # Not a Go file, exit silently
  exit 0
fi

exit 0
Full copyable content
{
  "hooks": {
    "postToolUse": {
      "script": "./.claude/hooks/go-module-tidy.sh",
      "matchers": [
        "write",
        "edit"
      ]
    }
  }
}

About this resource

Features

  • Automatic go mod tidy execution for Go file and go.mod changes with automatic module root detection by walking up directory tree to find go.mod, dependency cleanup removing unused dependencies and adding missing imports, and dependency change tracking with before/after dependency counts
  • Go vet integration for static analysis and error detection with comprehensive code quality checking including common Go issues detection, error checking, and static analysis warnings with actionable error messages
  • Module dependency validation and inconsistency detection with go.mod syntax validation using go mod edit -json, build verification with go list ./..., and module integrity checking with go mod verify for checksum validation
  • Unused dependency cleanup and missing import resolution with automatic dependency addition for missing imports, dependency removal for unused dependencies, and indirect dependency analysis with recommendations for direct dependencies
  • Go workspace and multi-module project support with go.work file detection, workspace synchronization using go work sync, and multi-module dependency management with workspace-aware operations
  • Dependency vulnerability scanning with go list for dependency analysis and govulncheck integration (when available) for security checking including known vulnerability detection and security recommendations
  • Module cache optimization and cleanup suggestions with dependency count analysis (warnings for large dependency counts), module cache management recommendations (go clean -modcache), and replace directive analysis with production readiness warnings
  • Build constraint and Go version compatibility checking with Go version detection (go version), compatibility validation, and gofmt formatting checks with unformatted file detection and goimports integration for import formatting

Use Cases

  • Automated Go dependency management in development workflows automatically running go mod tidy when Go files or go.mod are modified to maintain clean dependencies and resolve import issues without manual intervention
  • Go module cleanup and optimization in CI/CD pipelines automatically cleaning dependencies, verifying checksums, and checking for vulnerabilities before builds to ensure consistent and secure builds
  • Multi-module workspace maintenance and synchronization automatically detecting Go workspaces (go.work) and synchronizing workspace modules to maintain consistency across multiple modules in monorepo setups
  • Go codebase quality assurance with integrated static analysis automatically running go vet, gofmt checks, and goimports validation to ensure code quality and formatting standards are maintained
  • Dependency security and vulnerability management automatically scanning for known vulnerabilities using govulncheck and providing security recommendations to prevent security issues in production
  • Development workflow integration seamlessly integrating Go module management into development workflows without manual go mod tidy execution or separate dependency management tools

Installation

  1. Create hooks directory: mkdir -p .claude/hooks
  2. Create hook file: touch .claude/hooks/go-module-tidy.sh
  3. Make executable: chmod +x .claude/hooks/go-module-tidy.sh
  4. Add configuration from Hook Configuration section above to .claude/settings.json or ~/.claude/settings.json
  5. Alternative: Use the interactive /hooks command in Claude Code

Config paths

  • Local (not committed): .claude/settings.local.json
  • User settings (global): ~/.claude/settings.json
  • Project-wide (committed): .claude/settings.json

Requirements

  • Claude Code CLI installed
  • Project directory initialized
  • Go 1.16+ installed and in PATH
  • Bash shell available
  • govulncheck (optional, for vulnerability scanning)
  • goimports (optional, for import formatting)

Hook Configuration

{
  "hooks": {
    "postToolUse": {
      "script": "./.claude/hooks/go-module-tidy.sh",
      "matchers": ["write", "edit"]
    }
  }
}

Hook Script

#!/usr/bin/env bash

# Read the tool input from stdin
INPUT=$(cat)
TOOL_NAME=$(echo "$INPUT" | jq -r '.tool_name')
FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // .tool_input.path // ""')

if [ -z "$FILE_PATH" ]; then
  exit 0
fi

# Check if this is a Go-related file
if [[ "$FILE_PATH" == *.go ]] || [[ "$FILE_PATH" == *go.mod ]] || [[ "$FILE_PATH" == *go.sum ]] || [[ "$FILE_PATH" == *go.work* ]]; then
  echo "🔧 Go Module Maintenance for: $(basename "$FILE_PATH")" >&2

  # Find the Go module root
  MODULE_DIR="$(dirname "$FILE_PATH")"

  # Walk up the directory tree to find go.mod
  while [ "$MODULE_DIR" != "/" ] && [ ! -f "$MODULE_DIR/go.mod" ]; do
    MODULE_DIR="$(dirname "$MODULE_DIR")"
  done

  if [ ! -f "$MODULE_DIR/go.mod" ]; then
    echo "⚠️ No go.mod found - not a Go module" >&2
    exit 0
  fi

  echo "📁 Go module root: $MODULE_DIR" >&2
  cd "$MODULE_DIR"

  # Check if Go is installed
  if ! command -v go &> /dev/null; then
    echo "❌ Go is not installed or not in PATH" >&2
    exit 1
  fi

  GO_VERSION=$(go version | cut -d' ' -f3 2>/dev/null || echo "unknown")
  echo "🐹 Go version: $GO_VERSION" >&2

  # Initialize maintenance counters
  ERRORS=0
  WARNINGS=0
  FIXED=0

  # Function to report issues
  report_issue() {
    local level="$1"
    local message="$2"

    case "$level" in
      "ERROR")
        echo "❌ ERROR: $message" >&2
        ERRORS=$((ERRORS + 1))
        ;;
      "WARNING")
        echo "⚠️ WARNING: $message" >&2
        WARNINGS=$((WARNINGS + 1))
        ;;
      "FIXED")
        echo "✅ FIXED: $message" >&2
        FIXED=$((FIXED + 1))
        ;;
      "INFO")
        echo "ℹ️ INFO: $message" >&2
        ;;
    esac
  }

  # 1. Pre-tidy Module Analysis
  echo "📊 Analyzing module state..." >&2

  # Check go.mod syntax
  if ! go mod edit -json > /dev/null 2>&1; then
    report_issue "ERROR" "go.mod has syntax errors"
    exit 1
  else
    echo "   ✅ go.mod syntax is valid" >&2
  fi

  # Get current dependencies before tidy
  DEPS_BEFORE=$(go list -m all 2>/dev/null | wc -l | xargs || echo "0")
  echo "   📦 Dependencies before tidy: $DEPS_BEFORE" >&2

  # Check for any build errors
  if go list ./... > /dev/null 2>&1; then
    echo "   ✅ Module builds successfully" >&2
  else
    report_issue "WARNING" "Module has build issues that may affect dependency resolution"
  fi

  # 2. Run go mod tidy
  echo "🧹 Running go mod tidy..." >&2

  if go mod tidy; then
    report_issue "FIXED" "go mod tidy completed successfully"

    # Check dependencies after tidy
    DEPS_AFTER=$(go list -m all 2>/dev/null | wc -l | xargs || echo "0")
    DEPS_CHANGE=$((DEPS_AFTER - DEPS_BEFORE))

    if [ "$DEPS_CHANGE" -gt 0 ]; then
      echo "   📈 Added $DEPS_CHANGE dependencies" >&2
    elif [ "$DEPS_CHANGE" -lt 0 ]; then
      echo "   📉 Removed $((DEPS_CHANGE * -1)) dependencies" >&2
    else
      echo "   📦 No dependency changes" >&2
    fi

  else
    report_issue "ERROR" "go mod tidy failed"
  fi

  # 3. Verify go.sum integrity
  echo "🔐 Verifying module checksums..." >&2

  if go mod verify; then
    echo "   ✅ All module checksums verified" >&2
  else
    report_issue "ERROR" "Module checksum verification failed"
  fi

  # 4. Check for vulnerabilities (if govulncheck is available)
  if command -v govulncheck &> /dev/null; then
    echo "🛡️ Scanning for vulnerabilities..." >&2

    if govulncheck ./... 2>/dev/null; then
      echo "   ✅ No known vulnerabilities found" >&2
    else
      report_issue "WARNING" "Potential vulnerabilities detected - run 'govulncheck ./...' for details"
    fi
  else
    echo "   💡 Install govulncheck for vulnerability scanning: go install golang.org/x/vuln/cmd/govulncheck@latest" >&2
  fi

  # 5. Run go vet for Go source files
  if [[ "$FILE_PATH" == *.go ]]; then
    echo "🔍 Running go vet..." >&2

    if go vet ./...; then
      echo "   ✅ go vet passed - no issues found" >&2
    else
      report_issue "WARNING" "go vet found potential issues"
    fi

    # Check for common Go issues
    echo "🔍 Additional Go code analysis..." >&2

    # Check for gofmt issues
    UNFORMATTED=$(find . -name '*.go' -not -path './vendor/*' -exec gofmt -l {} \; 2>/dev/null)
    if [ -n "$UNFORMATTED" ]; then
      report_issue "WARNING" "Some files are not gofmt formatted"
      echo "$UNFORMATTED" | head -5 | while read file; do
        echo "     $file" >&2
      done
    else
      echo "   ✅ All Go files are properly formatted" >&2
    fi

    # Check imports with goimports if available
    if command -v goimports &> /dev/null; then
      IMPORT_ISSUES=$(find . -name '*.go' -not -path './vendor/*' -exec goimports -l {} \; 2>/dev/null)
      if [ -n "$IMPORT_ISSUES" ]; then
        report_issue "WARNING" "Some files have import formatting issues"
      else
        echo "   ✅ All imports are properly formatted" >&2
      fi
    fi
  fi

  # 6. Module cleanup suggestions
  echo "🧹 Module optimization check..." >&2

  # Check for indirect dependencies that could be direct
  INDIRECT_COUNT=$(go list -m all | grep -c '// indirect' || echo "0")
  if [ "$INDIRECT_COUNT" -gt 0 ]; then
    echo "   📊 Indirect dependencies: $INDIRECT_COUNT" >&2
    echo "   💡 Review if any indirect deps should be direct" >&2
  fi

  # Check for replace directives
  REPLACE_COUNT=$(grep -c '^replace ' go.mod 2>/dev/null || echo "0")
  if [ "$REPLACE_COUNT" -gt 0 ]; then
    echo "   🔄 Replace directives: $REPLACE_COUNT" >&2
    echo "   💡 Review replace directives for production readiness" >&2
  fi

  # 7. Workspace support
  if [ -f "go.work" ]; then
    echo "🏢 Go workspace detected" >&2

    if go work sync; then
      echo "   ✅ Workspace synced successfully" >&2
    else
      report_issue "WARNING" "Workspace sync issues detected"
    fi
  fi

  # 8. Module cache suggestions
  if [ "$DEPS_AFTER" -gt 50 ]; then
    echo "💡 Large dependency count - consider 'go clean -modcache' if disk space is low" >&2
  fi

  # 9. Generate Summary Report
  echo "" >&2
  echo "📋 Go Module Maintenance Summary:" >&2
  echo "================================" >&2
  echo "   📄 Module: $(basename "$(pwd)")" >&2
  echo "   🐹 Go: $GO_VERSION" >&2
  echo "   📦 Dependencies: $DEPS_AFTER" >&2
  echo "   ✅ Fixed: $FIXED" >&2
  echo "   ⚠️ Warnings: $WARNINGS" >&2
  echo "   ❌ Errors: $ERRORS" >&2

  if [ "$ERRORS" -eq 0 ] && [ "$WARNINGS" -eq 0 ]; then
    echo "   🎉 Status: EXCELLENT - Module is clean and optimized" >&2
  elif [ "$ERRORS" -eq 0 ]; then
    echo "   ✅ Status: GOOD - Minor warnings to review" >&2
  else
    echo "   ❌ Status: NEEDS ATTENTION - Errors require fixing" >&2
  fi

  echo "" >&2
  echo "💡 Go Module Best Practices:" >&2
  echo "   • Run 'go mod tidy' regularly to keep dependencies clean" >&2
  echo "   • Use 'go mod why <module>' to understand dependency reasons" >&2
  echo "   • Update dependencies with 'go get -u ./...' carefully" >&2
  echo "   • Consider using 'go mod graph' for dependency visualization" >&2
  echo "   • Pin important dependencies to specific versions" >&2

  # Exit with error if there are critical issues
  if [ "$ERRORS" -gt 0 ]; then
    echo "⚠️ Go module maintenance completed with errors" >&2
    exit 1
  fi

else
  # Not a Go file, exit silently
  exit 0
fi

exit 0

Examples

Go Module Tidy Hook Script

Complete hook script that performs automatic go mod tidy when Go files are modified

#!/usr/bin/env bash
INPUT=$(cat)
FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // .tool_input.path // ""')
if [ -z "$FILE_PATH" ]; then
  exit 0
fi
if [[ "$FILE_PATH" == *.go ]] || [[ "$FILE_PATH" == *go.mod ]]; then
  MODULE_DIR="$(dirname "$FILE_PATH")"
  while [ "$MODULE_DIR" != "/" ] && [ ! -f "$MODULE_DIR/go.mod" ]; do
    MODULE_DIR="$(dirname "$MODULE_DIR")"
  done
  if [ -f "$MODULE_DIR/go.mod" ]; then
    cd "$MODULE_DIR"
    if command -v go &> /dev/null; then
      go mod tidy
      go mod verify
    fi
  fi
fi
exit 0

Hook Configuration

Complete hook configuration for .claude/settings.json to enable Go module management

{
  "hooks": {
    "postToolUse": {
      "script": "./.claude/hooks/go-module-tidy.sh",
      "matchers": ["write", "edit"]
    }
  }
}

Go Vet and Formatting Checks

Enhanced hook script for Go vet integration and formatting validation

#!/usr/bin/env bash
INPUT=$(cat)
FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // .tool_input.path // ""')
if [[ "$FILE_PATH" == *.go ]]; then
  MODULE_DIR="$(dirname "$FILE_PATH")"
  while [ "$MODULE_DIR" != "/" ] && [ ! -f "$MODULE_DIR/go.mod" ]; do
    MODULE_DIR="$(dirname "$MODULE_DIR")"
  done
  if [ -f "$MODULE_DIR/go.mod" ]; then
    cd "$MODULE_DIR"
    if command -v go &> /dev/null; then
      go vet ./...
      UNFORMATTED=$(find . -name '*.go' -not -path './vendor/*' -exec gofmt -l {} \; 2>/dev/null)
      if [ -n "$UNFORMATTED" ]; then
        echo "⚠️ Some files are not gofmt formatted" >&2
      fi
    fi
  fi
fi
exit 0

Dependency Vulnerability Scanning

Enhanced hook script for dependency vulnerability scanning with govulncheck

#!/usr/bin/env bash
INPUT=$(cat)
FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // .tool_input.path // ""')
if [[ "$FILE_PATH" == *.go ]] || [[ "$FILE_PATH" == *go.mod ]]; then
  MODULE_DIR="$(dirname "$FILE_PATH")"
  while [ "$MODULE_DIR" != "/" ] && [ ! -f "$MODULE_DIR/go.mod" ]; do
    MODULE_DIR="$(dirname "$MODULE_DIR")"
  done
  if [ -f "$MODULE_DIR/go.mod" ]; then
    cd "$MODULE_DIR"
    if command -v govulncheck &> /dev/null; then
      if ! govulncheck ./... 2>/dev/null; then
        echo "⚠️ Potential vulnerabilities detected - run 'govulncheck ./...' for details" >&2
      fi
    else
      echo "💡 Install govulncheck: go install golang.org/x/vuln/cmd/govulncheck@latest" >&2
    fi
  fi
fi
exit 0

Go Workspace Synchronization

Enhanced hook script for Go workspace synchronization with go work sync

#!/usr/bin/env bash
INPUT=$(cat)
FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // .tool_input.path // ""')
if [[ "$FILE_PATH" == *go.work* ]]; then
  MODULE_DIR="$(dirname "$FILE_PATH")"
  while [ "$MODULE_DIR" != "/" ] && [ ! -f "$MODULE_DIR/go.work" ]; do
    MODULE_DIR="$(dirname "$MODULE_DIR")"
  done
  if [ -f "$MODULE_DIR/go.work" ]; then
    cd "$MODULE_DIR"
    if command -v go &> /dev/null; then
      if go work sync; then
        echo "✅ Workspace synced successfully" >&2
      else
        echo "⚠️ Workspace sync issues detected" >&2
      fi
    fi
  fi
fi
exit 0

Troubleshooting

Hook fails to find go.mod in nested module subdirectories

Script walks up directories but may hit root before finding go.mod. Ensure MODULE_DIR search starts from FILE_PATH directory: cd $(dirname "$FILE_PATH") before the while loop to guarantee proper traversal. Verify directory traversal logic. Test with nested module structures.

Go mod tidy hangs when network unavailable for dependency downloads

Add timeout to go commands: timeout 30s go mod tidy to prevent infinite hangs. Set GOPROXY=off to use only local cache, or configure module cache directory with GOMODCACHE for offline operation. Check network connectivity. Use go env GOPROXY to verify proxy settings.

Workspace sync errors when go.work references missing modules

Script runs 'go work sync' without validation. Add existence checks: go work edit -json | jq -r '.Use[].DiskPath' | while read dir; do [ -d "$dir" ] || echo "Missing: $dir"; done before syncing. Verify all workspace modules exist. Check go.work file syntax.

PostToolUse timing causes stale go.sum checksums on rapid changes

Hook runs after each write but go.sum updates may lag. Add explicit go.sum validation: go mod verify before tidy: if verification fails, run go mod tidy -v to refresh checksums and rebuild module graph. Verify go.sum file is up to date. Check for concurrent go mod operations.

Context lost when cd changes directory breaking relative path access

Script changes to MODULE_DIR but hook execution happens per-file. Store original: ORIG_DIR=$(pwd) and restore after: cd "$ORIG_DIR" or use absolute paths: FILE_ABS=$(realpath "$FILE_PATH") throughout script. Verify directory context is preserved. Test with files in different directories.

go vet reports false positives for valid Go code

go vet has known limitations. Review go vet output carefully. Use go vet -v for verbose output. Consider using golangci-lint for more comprehensive analysis. Add go vet skip patterns for known false positives. Verify Go version compatibility with go vet.

govulncheck not found but vulnerability scanning is expected

Install govulncheck: go install golang.org/x/vuln/cmd/govulncheck@latest. Verify installation: command -v govulncheck. Add to PATH if installed but not found. Check Go version compatibility (requires Go 1.18+). Use go install with specific version if needed.

Module cache grows too large consuming disk space

Use go clean -modcache to clean module cache. Set GOMODCACHE environment variable to control cache location. Monitor cache size: du -sh $(go env GOMODCACHE). Consider periodic cache cleanup. Use go mod download -x for verbose download information.

Source citations

Add this badge to your README

Show that Go Module Tidy - Hooks is listed on HeyClaude. Paste this Markdown into your README — it renders the badge and links back to this page.

Listed on HeyClaude
[![Listed on HeyClaude](https://heyclau.de/badge/hooks/go-module-tidy.svg)](https://heyclau.de/entry/hooks/go-module-tidy)

How it compares

Go Module Tidy - Hooks side by side with 3 alternatives on trust, install, platform support, and disclosed safety notes — all from reviewed registry metadata.

Field

Automatically runs go mod tidy when Go files or go.mod are modified to keep dependencies clean.

Open dossier

Detects unused CSS selectors when stylesheets are modified to keep CSS lean using PurgeCSS, PostCSS, and content analysis. This hook runs on CSS/SCSS file write/edit operations and analyzes stylesheets to identify unused selectors, generate optimized output, and report before/after size metrics.

Open dossier

A Stop hook that terminates lingering database connections when a Claude Code session ends — via PostgreSQL pg_terminate_backend, MySQL KILL, Redis CLIENT KILL, and MongoDB connection cleanup.

Open dossier

A Claude Code SessionEnd hook that scans a project for dead code and writes a report to .claude/reports. It runs available tools per language: ESLint and Knip for JS/TS, autoflake or pylint for Python, Knip for unused npm dependencies, ripgrep for unreferenced src files, and jq to flag zero-coverage files.

Open dossier
Next steps
Trust
Review statusReviewedMaintainer reviewedReviewedMaintainer reviewedReviewedMaintainer reviewedReviewedMaintainer reviewed
Package trustPackage not verifiedPackage not verifiedPackage not verifiedPackage not verified
Source provenanceSource-backedSource-backedSource-backedSource-backed
Submitter
Install riskReview firstReview firstReview firstReview first
Notes Safety Privacy Safety Privacy Safety Privacy Safety Privacy
Brand
Categoryhookshookshookshooks
Sourcesource-backedsource-backedsource-backedsource-backed
AuthorJSONboredJSONboredJSONboredJSONbored
Added2025-09-192025-09-192025-09-192025-10-19
Platforms
Claude Code
Claude Code
Claude Code
Claude Code
Source repo
Safety notesRuns automatically on its configured Claude Code hook event and executes shell logic that can read, modify, or delete files in your project (and may run builds, installs, or network calls); review the script and scope it to expected paths before enabling.Runs automatically on its configured Claude Code hook event and executes shell logic that can read, modify, or delete files in your project (and may run builds, installs, or network calls); review the script and scope it to expected paths before enabling.Runs at session end and forcibly terminates database backends/clients (pg_terminate_backend, KILL, CLIENT KILL); pointed at a shared or production database it can drop other users' connections — scope it to local/dev databases and confirm the target before enabling.Registered as a SessionEnd hook, so it runs automatically every time a Claude Code session ends. Invokes external tools via npx (ts-prune, Knip, eslint) and locally installed binaries (autoflake, pylint, vulture, jq, rg), which can trigger package downloads and execute project tooling. Defaults to DRY_RUN=true and only writes a report; setting DRY_RUN=false is intended to enable destructive cleanup, so review the report before changing it. Creates directories under .claude/backups and .claude/reports in the working tree.
Privacy notesReceives Claude Code hook input (session metadata, file paths, and tool output) and reads local project files; review what the script logs or forwards to external services and keep credentials out of its output.Receives Claude Code hook input (session metadata, file paths, and tool output) and reads local project files; review what the script logs or forwards to external services and keep credentials out of its output.Uses locally configured database credentials and connection details to issue termination commands; keep those credentials in environment variables, not in the hook.Writes a dead-code report containing file paths, export names, and dependency names from the project to .claude/reports/dead-code-report.txt and echoes it to stderr. Running tools via npx may fetch packages from the npm registry over the network.
Prerequisites— none listed— none listed— none listed— none listed
Install
mkdir -p .claude/hooks && touch .claude/hooks/go-module-tidy.sh && chmod +x .claude/hooks/go-module-tidy.sh
mkdir -p .claude/hooks && touch .claude/hooks/css-unused-selector-detector.sh && chmod +x .claude/hooks/css-unused-selector-detector.sh
mkdir -p .claude/hooks && touch .claude/hooks/database-connection-cleanup.sh && chmod +x .claude/hooks/database-connection-cleanup.sh
mkdir -p .claude/hooks && touch .claude/hooks/dead-code-eliminator.sh && chmod +x .claude/hooks/dead-code-eliminator.sh
Config
{
  "hooks": {
    "postToolUse": {
      "script": "./.claude/hooks/go-module-tidy.sh",
      "matchers": [
        "write",
        "edit"
      ]
    }
  }
}
{
  "hooks": {
    "postToolUse": {
      "script": "./.claude/hooks/css-unused-selector-detector.sh",
      "matchers": [
        "write",
        "edit"
      ]
    }
  }
}
{
  "hooks": {
    "stop": {
      "script": "./.claude/hooks/database-connection-cleanup.sh"
    }
  }
}
{
  "hooks": {
    "sessionEnd": {
      "script": "./.claude/hooks/dead-code-eliminator.sh"
    }
  }
}
Citations
ClaimUnclaimedUnclaimedUnclaimedUnclaimed
Open 4 picks in the interactive comparison tool

Related guides

Signals

Loading live community signals…

More like this, weekly

A short, calm digest of reviewed Claude resources. Unsubscribe any time.