Skip to content

Instantly share code, notes, and snippets.

@chriscz
Last active September 3, 2024 02:40
Show Gist options
  • Save chriscz/a431e3d2102aa5608bee0aa88e68752a to your computer and use it in GitHub Desktop.
Save chriscz/a431e3d2102aa5608bee0aa88e68752a to your computer and use it in GitHub Desktop.
ast-grep examples

Ruby Example: Prefix second argument

Source

attribute :a, :b, :c, foo, bar

attribute :a, :b, :c, :d

attribute :a, :b

Result

attribute :a, :prefix_b, :c, foo, bar

attribute :a, :prefix_b, :c, :d

attribute :a, :prefix_b

Rule

rule:
  any:
    - pattern: attribute $A, $B, $$$ARGS
    - pattern: attribute $A, $B
fix: attribute $A, $NAME$MAYBE_COMMA$$$ARGS
transform:
  # Idea from https://ast-grep.github.io/guide/rewrite-code.html#add-conditional-text
  MAYBE_COMMA:
    replace:
      by: ', '
      replace: ^.+
      source: $$$ARGS
  NAME:
    replace:
      by: :prefix_$1
      replace: :?(.+)
      source: $B
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment