main

ast-grep Quick Reference

Setup

cd ~/src/home  # Must be in repo root

Common Commands

# Full scan
ast-grep scan

# Scan specific directory
ast-grep scan systems/

# Show only errors
ast-grep scan --json 2>/dev/null | jq -r '.[] | select(.severity == "error")'

# Get statistics
ast-grep scan --json 2>/dev/null | jq -s 'group_by(.severity) | map({severity: .[0].severity, count: length})'

Search Patterns

# Find NixOS module patterns
ast-grep -p 'mkHost { $$$ }' -l nix flake.nix
ast-grep -p 'mkOption { $$$ }' -l nix modules/

# Find bash functions
ast-grep -p '$NAME() { $$$ }' -l bash tools/

# Find Go error handling
ast-grep -p 'if err != nil { $$$ }' -l go

Interactive Refactoring

# Replace pattern with review
ast-grep -p 'oldPattern' --rewrite 'newPattern' --interactive

# Example: Update API versions
ast-grep -p 'apiVersion: tekton.dev/v1beta1' \
  --rewrite 'apiVersion: tekton.dev/v1' \
  --interactive -l yaml

Current Rules

Rule ID Severity What It Finds
nix-prefer-inherit info Use inherit instead of x = x
nix-explicit-option-types warning mkOption without type = ...
nix-prefer-optional info Use lib.optional for conditionals
nix-boolean-comparison warning Comparing x == true
bash-require-strict-mode error Missing set -euo pipefail
bash-unsafe-rm-rf error rm -rf without checks
bash-use-command-over-which warning Use command -v not which
bash-prefer-dollar-parens info Use $() not backticks
security-unsafe-curl-pipe-sh error curl ... | sh pattern

Pattern Syntax

  • $VAR - Match single AST node (like .* in regex)
  • $$$ARGS - Match zero or more nodes (like .* in regex)
  • if $COND then $TRUE else $FALSE - Match structure

Performance

  • ~0.025s for 415 files (~16,000 files/sec)
  • Compare: ripgrep (~0.005s), semgrep (~30s)

Documentation

Troubleshooting

Error: “No ast-grep project configuration is found”

  • Make sure you’re in ~/src/home (repo root)
  • Check that sgconfig.yml exists in repo root

No results from scan

  • Verify rules exist in .ast-grep/rules/
  • Check rule syntax in YAML files
  • Try with -p pattern search first

Too many false positives

  • Refine pattern in playground first
  • Add not: clause to exclude cases
  • Use where: for metavariable constraints

Tips

  1. Always run from repo root (cd ~/src/home)
  2. Test patterns in playground before creating rules
  3. Use interactive mode for refactoring (--interactive)
  4. Review findings - not all matches are bugs
  5. Layer with other tools (statix, shellcheck, etc.)

Next Actions

# See what's wrong
cd ~/src/home && ast-grep scan

# Fix bash scripts (10 errors)
# Add "set -euo pipefail" after shebang in flagged files

# Review unsafe rm -rf (5 errors)
# Check if variables have safety guards

# Add types to options (137 warnings)
# Add "type = types.<type>" to mkOption calls