astGrep(pattern, callback)

Search part of the code (single AST node) using ast-grep and iterate over found nodes in the callback or returned commands. Creates separate context for each found node, which could be reused later.

callback
import { git } from '@codemod.com/workflow'

await git
  .clone('repository-to-clone')
  .files('**/*.{jsx,tsx}')
  .jsFam()
  /**
   * For string patterns, by default
   * strictness `relaxed` is used,
   * so comments and non-significant
   * syntax constructs will be ignored.
   * Possible matches:
   * - import React from 'react'
   * - import React from "react"
   */
  .astGrep('import React from "react"', async ({ replace, map }) => {
    // remove import statement
    await replace('')
    const foundCode = await map(({ getNode }) => getNode().text())
    console.log(`Found code:\n${foundCode.join('\n')}`)
})

Parameters

pattern
string | readonly string[] | NapiConfig | AstGrepAPI
required
interface NapiConfig {
  rule: object
  constraints?: object
  language?: FrontEndLanguage
  transform?: object
  utils?: object
}
interface AstGrepAPI {
  id: string
  language: FrontEndLanguage
  rule: object
  utils?: any
  fix?: any
}

There are multiple ways to define a pattern:

  • String pattern, e.g. console.log($$$A); by default relaxed strictness algorithm is used, meaning that comments and non-significant syntax constructs (like single and double quotes for JavaScript) will be ignored.
  • Object pattern, using NapiConfig, which will be passed as is to ast-grep engine.
  • Template literal, using YAML format inside. It is a syntax sugar for NapiConfig object, so you can copy rules from ast-grep playground and paste them here.
  • Object pattern, using AstGrepAPI. In this case request is sent to ast-grep CLI and you can use all its features, like fix. But there is no programmatic access to the results, it is one-way operation. It has similar syntax to NapiConfig, but with additional id field.
callback
(subcommands: Subcommands) => Promise<void> | void

A callback which will be executed for each repository. First argument is an object with subcommands. It can be destructured to get access to subcommands.

Returns

Learn more