← See all TILs

ast-grep

Published: June 21, 2025

ast-grep is a blazingly fast syntax-aware tool for searching, linting, and rewriting code.

Most recently, I used it to find all instances of early exit statements inside ActiveRecord transactions1.

sg scan --inline-rules "
id: early-exit-inside-transaction
language: Ruby
rule:
  any:
    - pattern: return
    - pattern: break
    - pattern: throw
  inside:
    any:
      - kind: block
      - kind: do_block
    follows:
      kind: identifier
      regex: '^transaction|with_lock|with_asynchronous_commits|long_running_connection$'
    stopBy: end
" --globs '**/*.rb' --report-style rich --context 20
  1. There’s a RuboCop rule for this, but I wanted a reason to play around with ast-grep and needed to support more transaction methods.