### Installation Source: https://github.com/ast-grep/ast-grep.github.io/blob/main/website/guide/api-usage/js-api.md Install the ast-grep napi package using npm or pnpm. ```APIDOC ## Installation First, install ast-grep's napi package. ::: code-group ```bash[npm] npm install --save @ast-grep/napi ``` ```bash[pnpm] pnpm add @ast-grep/napi ``` ::: Now let's explore ast-grep's API! ``` -------------------------------- ### Install ast-grep Source: https://github.com/ast-grep/ast-grep.github.io/blob/main/website/blog/migrate-bevy.md Install the ast-grep binary using either cargo or Homebrew. ```shell # install the binary `ast-grep` cargo install ast-grep # or use brew brew install ast-grep ``` -------------------------------- ### Install ast-grep via Homebrew Source: https://github.com/ast-grep/ast-grep.github.io/blob/main/website/guide/quick-start.md Install the ast-grep CLI using Homebrew. ```shell # install via homebrew brew install ast-grep ``` -------------------------------- ### Install ast-grep napi package Source: https://github.com/ast-grep/ast-grep.github.io/blob/main/website/guide/api-usage/js-api.md Install the required package using npm or pnpm. ```bash npm install --save @ast-grep/napi ``` ```bash pnpm add @ast-grep/napi ``` -------------------------------- ### Install Rust and Git Hooks Source: https://github.com/ast-grep/ast-grep.github.io/blob/main/website/contributing/development.md Commands to initialize the development environment by installing the Rust toolchain and setting up git hooks. ```bash rustup install stable ``` ```bash prek install ``` -------------------------------- ### Verify Installation Source: https://github.com/ast-grep/ast-grep.github.io/blob/main/website/guide/quick-start.md Check if the ast-grep binary is installed and accessible by running it with the --help flag. Use 'ast-grep' or 'sg' depending on your OS. ```shell ast-grep --help # if you are not on Linux sg --help ``` -------------------------------- ### Start Language Server Source: https://github.com/ast-grep/ast-grep.github.io/blob/main/website/reference/cli.md Starts the ast-grep language server for editor integration and diagnostics reporting. ```shell ast-grep lsp ``` -------------------------------- ### Project Inspection Output Example Source: https://github.com/ast-grep/ast-grep.github.io/blob/main/website/guide/project/project-config.md Example output from `ast-grep scan --inspect summary` showing project details. ```text sg: summary|project: isProject=true,projectDir=/path/to/project ``` -------------------------------- ### Install ast-grep via Pip Source: https://github.com/ast-grep/ast-grep.github.io/blob/main/website/guide/quick-start.md Install the ast-grep CLI using pip, the Python package installer. ```shell # install via pip pip install ast-grep-cli ``` -------------------------------- ### Method Definition Rule Configuration Source: https://github.com/ast-grep/ast-grep.github.io/blob/main/website/advanced/pattern-parse.md Use this YAML configuration to match method definitions that start with 'get' or 'set' using a regex rule. ```yaml rule: kind: method_definition regex: '^get|set\s' ``` -------------------------------- ### Install flamegraph Source: https://github.com/ast-grep/ast-grep.github.io/blob/main/website/blog/optimize-ast-grep.md Install the flamegraph profiling tool via cargo. ```bash cargo install flamegraph ``` -------------------------------- ### Install ast-grep Python library Source: https://github.com/ast-grep/ast-grep.github.io/blob/main/website/guide/api-usage/py-api.md Use pip to install the ast-grep-py package. ```bash pip install ast-grep-py ``` -------------------------------- ### Install ast-grep via MacPorts Source: https://github.com/ast-grep/ast-grep.github.io/blob/main/website/guide/quick-start.md Install the ast-grep CLI using MacPorts. ```shell # install via MacPorts sudo port install ast-grep ``` -------------------------------- ### Define Rule Example Source: https://github.com/ast-grep/ast-grep.github.io/blob/main/website/catalog/rule-template.md Example of code to be matched by the rule. ```js var a = 123 ``` -------------------------------- ### Initialize ast-grep Project Source: https://github.com/ast-grep/ast-grep.github.io/blob/main/website/guide/scan-project.md Interactive setup process for creating the necessary configuration and directory structure. ```markdown No sgconfig.yml found. Creating a new ast-grep project... > Where do you want to have your rules? rules > Do you want to create rule tests? Yes > Where do you want to have your tests? rule-tests > Do you want to create folder for utility rules? Yes > Where do you want to have your utilities? utils Your new ast-grep project has been created! ``` -------------------------------- ### CaseChange separator examples Source: https://github.com/ast-grep/ast-grep.github.io/blob/main/website/reference/yaml/transformation.md Examples demonstrating how the CaseChange separator splits strings based on character case transitions. ```text RegExp -> [Reg, Exp] XMLHttpRequest -> [XML, Http, Request] regExp -> [reg, Exp] writeHTML -> [write, HTML] ``` -------------------------------- ### Example component to refactor Source: https://github.com/ast-grep/ast-grep.github.io/blob/main/website/catalog/tsx/rewrite-mobx-component.md A concrete example of a MobX observer component before applying the refactor. ```js export const Example = observer(() => { return
Hello World
}) ``` -------------------------------- ### Get node text Source: https://github.com/ast-grep/ast-grep.github.io/blob/main/website/guide/api-usage/py-api.md Example of retrieving the source text of a node. ```python root = SgRoot("print('hello world')", "python") node = root.root() node.text() # will return "print('hello world')" ``` -------------------------------- ### Golang JWT Library Detection Example Source: https://github.com/ast-grep/ast-grep.github.io/blob/main/website/catalog/go/match-package-import.md This Go code example demonstrates the usage of the JWT library, which can be detected by the ast-grep rule. It shows how to create, add claims to, and sign a JWT token. ```go package main import ( "fmt" "github.com/golang-jwt/jwt" // This matches the AST rule ) func main() { token := jwt.New(jwt.SigningMethodHS256) // Create a new token // Add some claims token.Claims = jwt.MapClaims{"user": "alice", "role": "admin"} tokenString, err := token.SignedString([]byte("my-secret")) // Sign the token if err != nil { fmt.Printf("Error signing token: %v\n", err) return } fmt.Printf("Generated token: %s\n", tokenString) } ``` -------------------------------- ### Install ast-grep via NPM Source: https://github.com/ast-grep/ast-grep.github.io/blob/main/website/guide/quick-start.md Install the ast-grep CLI globally using npm. Note: pnpm users may need to manually approve the postinstall script. ```shell # install via npm npm i @ast-grep/cli -g # note, for pnpm, you may need manually approve postinstall script # pnpm approve-builds ``` -------------------------------- ### Kotlin Playground Example Source: https://github.com/ast-grep/ast-grep.github.io/blob/main/website/blog/stars-5000.md Demonstrates pattern matching and rewriting in Kotlin using ast-grep's playground. This example shows how to match a variable declaration and rewrite it. ```kotlin fun minami() { val kotlin = "Kotlin" } ``` -------------------------------- ### Install Tree-sitter CLI Source: https://github.com/ast-grep/ast-grep.github.io/blob/main/website/advanced/custom-language.md Install the Tree-sitter CLI tool globally using npm. This is required for compiling parsers. ```bash npm install -g tree-sitter-cli ``` -------------------------------- ### System Stage Migration Diff Source: https://github.com/ast-grep/ast-grep.github.io/blob/main/website/blog/migrate-bevy.md Example diff showing the transition from add_system_to_stage to in_base_set. ```diff --- a/src/lib.rs +++ b/src/lib.rs @@ -243,7 +243,7 @@ impl Plugin for BigBrainPlugin { - app.add_system_to_stage(BigBrainStage::Thinkers, thinker::thinker_system); + app.add_system(thinker::thinker_system.in_base_set(BigBrainStage::Thinkers)); ``` -------------------------------- ### Install ast-grep via Cargo Source: https://github.com/ast-grep/ast-grep.github.io/blob/main/website/guide/quick-start.md Install the ast-grep CLI using Cargo, Rust's package manager. ```shell # install via cargo cargo install ast-grep --locked ``` -------------------------------- ### Target HTML template for migration Source: https://github.com/ast-grep/ast-grep.github.io/blob/main/website/catalog/html/upgrade-ant-design-vue.md Example template showing components that should be updated and those that should remain unchanged. ```html ``` -------------------------------- ### Apply String Style Transformations Source: https://github.com/ast-grep/ast-grep.github.io/blob/main/website/guide/rewrite/transform.md Examples of using substring, case conversion, and regex replacement transformations. ```yaml transform: LIST: substring($GEN, startChar=1, endChar=-1) KEBABED: convert($OLD_FN, toCase=kebabCase) MAYBE_COMMA: replace($$$ARGS, replace='^.+', by=', ') ``` -------------------------------- ### SQLAlchemy Code Examples Source: https://github.com/ast-grep/ast-grep.github.io/blob/main/website/catalog/python/rewrite-sqlalchemy-mapped-column.md Python code demonstrating various mapped_column configurations, including those that should and should not be transformed. ```python message = mapped_column(String, default="hello", nullable=True) message = mapped_column(String, nullable=True) _message = mapped_column("message", String, nullable=True) message = mapped_column(String, nullable=True, unique=True) message = mapped_column( String, index=True, nullable=True, unique=True) # Should not be transformed message = mapped_column(String, default="hello") message = mapped_column(String, default="hello", nullable=False) message = mapped_column(Integer, default="hello") ``` -------------------------------- ### Example: Chai `should` to `expect` migration Source: https://github.com/ast-grep/ast-grep.github.io/blob/main/website/catalog/typescript/switch-from-should-to-expect.md This JavaScript example demonstrates the migration of Chai `should` style assertions to `expect` style. It covers converting `should.be.an.instanceof` and `should.be.a` assertions. ```javascript it('should produce an instance of chokidar.FSWatcher', () => { watcher.should.be.an.instanceof(chokidar.FSWatcher); }); it('should expose public API methods', () => { watcher.on.should.be.a('function'); watcher.emit.should.be.a('function'); watcher.add.should.be.a('function'); watcher.close.should.be.a('function'); watcher.getWatched.should.be.a('function'); }); ``` ```javascript it('should produce an instance of chokidar.FSWatcher', () => { expect(watcher).instanceOf(chokidar.FSWatcher); }); it('should expose public API methods', () => { expect(watcher.on).to.be.a('function'); expect(watcher.emit).to.be.a('function'); expect(watcher.add).to.be.a('function'); expect(watcher.close).to.be.a('function'); expect(watcher.getWatched).to.be.a('function'); }); ``` -------------------------------- ### Barrel Import Example Source: https://github.com/ast-grep/ast-grep.github.io/blob/main/website/advanced/find-n-patch.md An example of a barrel import statement that consolidates multiple module exports. ```js import {a, b, c} from './barrel'; ``` -------------------------------- ### Example JavaScript with GraphQL Source: https://github.com/ast-grep/ast-grep.github.io/blob/main/website/advanced/language-injection.md A sample JavaScript file using the Relay framework's graphql tag. ```js import React from "react" import { graphql } from "react-relay" const artistsQuery = graphql` query ArtistQuery($artistID: String!) { artist(id: $artistID) { name ...ArtistDescription_artist } } ` ``` -------------------------------- ### XState v4 Example Code Source: https://github.com/ast-grep/ast-grep.github.io/blob/main/website/catalog/typescript/migrate-xstate-v5.md Sample XState v4 code structure targeted for migration. ```js import { Machine, interpret } from 'xstate'; const machine = Machine({ /*...*/}); const specificMachine = machine.withConfig({ actions: { /* ... */ }, guards: { /* ... */ }, services: { /* ... */ }, }); const actor = interpret(specificMachine, { /* actor options */ }); ``` -------------------------------- ### Install ast-grep via Nix Shell Source: https://github.com/ast-grep/ast-grep.github.io/blob/main/website/guide/quick-start.md Try ast-grep within a Nix shell environment. ```shell # try ast-grep in nix-shell nix-shell -p ast-grep ``` -------------------------------- ### Define configuration-based search rules Source: https://github.com/ast-grep/ast-grep.github.io/blob/main/website/blog/code-search-design-space.md Examples of YAML-based configuration rules for ast-grep and Semgrep. ```yaml id: match-function-call language: c rule: pattern: context: $M($$$); selector: call_expression ``` ```yaml rules: - id: my-pattern-name pattern: | TODO message: "Some message to display to the user" languages: [python] severity: ERROR ``` -------------------------------- ### JavaScript Code Example Source: https://github.com/ast-grep/ast-grep.github.io/blob/main/website/advanced/pattern-parse.md JavaScript code used to demonstrate selector usage. ```js console.log("Hello") console.log("World"); ``` -------------------------------- ### Example JSX with Styled Components Source: https://github.com/ast-grep/ast-grep.github.io/blob/main/website/advanced/language-injection.md A sample JavaScript file containing styled-components that can be targeted by the injection configuration. ```js import styled from 'styled-components'; const Button = styled.button` background: red; color: white; padding: 10px 20px; border-radius: 3px; ` export default function App() { return } ``` -------------------------------- ### Example Markdown ATX Headings Source: https://github.com/ast-grep/ast-grep.github.io/blob/main/website/blog/new-ver-43.md Illustrates the structure of ATX headings in Markdown that can be matched by ast-grep. ```md # ast-grep ## Installation ### Use with npm ``` -------------------------------- ### Target Configuration Example Source: https://github.com/ast-grep/ast-grep.github.io/blob/main/website/catalog/yaml/find-key-value.md A sample configuration file demonstrating the lines that would be matched by the host and port detection rule. ```yaml db: username: root password: root server: host: 127.0.0.1 port: 8001 ``` -------------------------------- ### Example source code for relational matching Source: https://github.com/ast-grep/ast-grep.github.io/blob/main/website/guide/rule-config/relational-rule.md Source code demonstrating which console.log statements match the follows rule. ```javascript console.log('hello'); // does not match console.log('world'); console.log('hello'); // matches!! ``` -------------------------------- ### Search with Matchers Source: https://github.com/ast-grep/ast-grep.github.io/blob/main/website/guide/api-usage/js-api.md Examples of searching using patterns, kind IDs, and configuration objects. ```typescript // basic find example root.find('console.log($A)') // returns SgNode of call_expression let l = Lang.JavaScript // calling kind function requires Lang const kind = kind(l, 'string') // convert kind name to kind id number root.find(kind) // returns SgNode of string root.find('notExist') // returns null if not found // basic find all example const nodes = root.findAll('function $A($$$) {$$$}') Array.isArray(nodes) // true, findAll returns SgNode nodes.map(n => n.text()) // string array of function source const empty = root.findAll('not exist') // returns [] empty.length === 0 // true // find i.e. `console.log("hello world")` using a NapiConfig const node = root.find({ rule: { pattern: "console.log($A)" }, constraints: { A: { regex: "hello" } } }) ``` -------------------------------- ### Tree-sitter Grammar Rules for Named and Unnamed Nodes Source: https://github.com/ast-grep/ast-grep.github.io/blob/main/website/advanced/core-concepts.md This JavaScript example from Tree-sitter's guide demonstrates the definition of named nodes (like 'identifier') and unnamed nodes (like the '+' operator in 'binary_expression'). ```javascript rules: { // named nodes are defined with the format `kind: parseRule` identifier: $ => /[a-z]+/, // binary_expression is also a named node, // the `+` operator is defined with a string literal, so it is an unnamed node binary_expression: $ => seq($.identifier, '+', $.identifier) // ↑ unnamed node } ``` -------------------------------- ### Define Rule Configuration Source: https://github.com/ast-grep/ast-grep.github.io/blob/main/website/guide/test-rule.md Example rule configuration for detecting await statements inside loops. ```yaml id: no-await-in-loop message: Don't use await inside of loops severity: warning language: TypeScript rule: all: - inside: any: - kind: for_in_statement - kind: while_statement stopBy: end - pattern: await $_ ``` -------------------------------- ### Install coc-ast-grep for coc.nvim Source: https://github.com/ast-grep/ast-grep.github.io/blob/main/website/guide/tools/editors.md Add the coc-ast-grep plugin to your vim-plug configuration. This requires running `yarn install --frozen-lockfile` after installation to set up the necessary Node.js dependencies. ```vim Plug 'yaegassy/coc-ast-grep', {'do': 'yarn install --frozen-lockfile'} ``` -------------------------------- ### Project Configuration for Utility Rules Source: https://github.com/ast-grep/ast-grep.github.io/blob/main/website/guide/rule-config/utility-rule.md This `sgconfig.yml` example specifies the directories for regular rules ('rules') and utility rules ('utils'), enabling ast-grep to find global utility definitions. ```yaml ruleDirs: - rules utilDirs: - utils ``` -------------------------------- ### Install Claude Code Skill Source: https://github.com/ast-grep/ast-grep.github.io/blob/main/website/advanced/prompting.md Copy the ast-grep skill directory to your local Claude Code configuration path. ```bash # If you have a skills directory configured cp -r ast-grep ~/.claude/skills/ # Or place it wherever your Claude Code skills are located ``` -------------------------------- ### Match a node following another Source: https://github.com/ast-grep/ast-grep.github.io/blob/main/website/guide/rule-config/relational-rule.md Example rule configuration to match a console.log('hello') that follows a console.log('world'). ```yaml pattern: console.log('hello'); follows: pattern: console.log('world'); ``` -------------------------------- ### Run ast-grep with StdIn Source: https://github.com/ast-grep/ast-grep.github.io/blob/main/website/guide/tooling-overview.md Examples of running ast-grep on piped input for code execution and scanning. ```bash echo "print('Hello world')" | ast-grep run --lang python ``` ```bash echo "print('Hello world')" | ast-grep scan --rule "python-rule.yml" ``` -------------------------------- ### Main Thread Channel and Printer Thread Setup Source: https://github.com/ast-grep/ast-grep.github.io/blob/main/website/blog/fearless-concurrency.md Demonstrates setting up an mpsc channel and spawning a dedicated printer thread that receives results and prints them sequentially. ```rust fn main() { let (sender, receiver) = mpsc::channel(); let mut printer = StdoutPrinter::new(); let printer_thread = thread::spawn(move || { for result in receiver { printer.print(result); } }); // spawn worker threads } ``` -------------------------------- ### Target C++ Struct Example Source: https://github.com/ast-grep/ast-grep.github.io/blob/main/website/catalog/cpp/find-struct-inheritance.md Example of C++ code that matches the struct inheritance pattern. ```cpp struct Bar: Baz { int a, b; } ``` -------------------------------- ### Example Markdown with Headings and Code Source: https://github.com/ast-grep/ast-grep.github.io/blob/main/website/blog/new-ver-43.md A sample Markdown snippet demonstrating ATX headings, list items, and a fenced code block. ```md # Agent Handoff ## Current Goal - Update the parser docs. - Add examples for Markdown search. ## Relevant Commands ```bash ast-grep run -k 'atx_heading' -l md ``` ``` -------------------------------- ### TypeScript Function Declaration Example Source: https://github.com/ast-grep/ast-grep.github.io/blob/main/website/advanced/faq.md This is an example of TypeScript code used in the playground to demonstrate pattern matching. ```typescript function test(a) {} ``` -------------------------------- ### Inspect Project Summary Source: https://github.com/ast-grep/ast-grep.github.io/blob/main/website/guide/project/project-config.md Use the `--inspect summary` flag with `ast-grep scan` to view the project directory and configuration file path being used. ```bash ast-grep scan --inspect summary ``` -------------------------------- ### JavaScript Function Declaration Example Source: https://github.com/ast-grep/ast-grep.github.io/blob/main/website/advanced/faq.md This is an example of JavaScript code used in the playground to demonstrate pattern matching. ```javascript function ReactComponent() { const data = notHoo() const [foo, setFoo] = useState('s') } ``` -------------------------------- ### Automate System Set Migration with ast-grep Source: https://github.com/ast-grep/ast-grep.github.io/blob/main/website/blog/migrate-bevy.md Uses ast-grep to migrate add_system_set_to_stage to add_systems with in_set. ```sh ast-grep \ -p '$APP.add_system_set_to_stage($STAGE, $SYS,)' \ -r '$APP.add_systems($SYS.in_set($STAGE))' -i ``` -------------------------------- ### Configure ast-grep LSP server via command line Source: https://github.com/ast-grep/ast-grep.github.io/blob/main/website/guide/tools/editors.md Start the ast-grep LSP server and specify a custom configuration file path using the `-c` flag. This allows overriding the default `sgconfig.yml` or `sgconfig.yaml` lookup. ```bash ast-grep lsp -c ``` -------------------------------- ### Test cases for dash-prefixed JSON tags Source: https://github.com/ast-grep/ast-grep.github.io/blob/main/website/catalog/go/unmarshal-tag-is-dash.md Example Go structs demonstrating valid and invalid JSON tag configurations. ```go package main type TestStruct1 struct { A string `json:"id"` // ok } type TestStruct2 struct { B string `json:"-,omitempty"` // wrong } type TestStruct3 struct { C string `json:"-,123"` // wrong } type TestStruct4 struct { D string `json:"-,"` // wrong } ``` -------------------------------- ### Redundant Unsafe Function Examples Source: https://github.com/ast-grep/ast-grep.github.io/blob/main/website/catalog/rust/redundant-unsafe-function.md Rust code examples demonstrating functions that trigger the rule and those that are correctly implemented with unsafe blocks. ```rs // Should match - unsafe function without unsafe block (no return type) unsafe fn redundant_unsafe() { println!("No unsafe operations here"); } // Should match - unsafe function with return type, no unsafe block unsafe fn redundant_with_return() -> i32 { let x = 5; x + 10 } // Should match - unsafe function with complex return type unsafe fn redundant_complex_return() -> Result { Ok(String::from("safe operation")) } // Should NOT match - unsafe function with unsafe block unsafe fn proper_unsafe() -> *const i32 { unsafe { let ptr = 0x1234 as *const i32; ptr } } // Should match - unsafe async function without unsafe block unsafe async fn async_redundant() -> i32 { 42 } // Should match - unsafe const function unsafe const fn const_redundant() -> i32 { 100 } // Should NOT match - regular function fn regular_function() -> i32 { 42 } ``` -------------------------------- ### TypeScript TypeMap Example Source: https://github.com/ast-grep/ast-grep.github.io/blob/main/website/blog/typed-napi.md A concrete example of a TypeMap entry for a 'function_declaration' in TypeScript, illustrating node type, naming, and field structure. ```typescript type TypeScript = { // AST node type definition function_declaration: { type: "function_declaration", // kind named: true, // is named fields: { body: { types: [ { type: "statement_block", named: true } ] }, } }, ... } ``` -------------------------------- ### Get Digit Count in usize Rust Source: https://github.com/ast-grep/ast-grep.github.io/blob/main/website/catalog/rust/index.md Checks for inefficient methods of getting the digit count of a usize in Rust and suggests alternatives. ```yaml id: get-digit-count-in-usize rule: pattern: | $X.to_string().len() message: Prefer using integer arithmetic to calculate digit count for usize. ``` -------------------------------- ### Parse and Find Example Source: https://github.com/ast-grep/ast-grep.github.io/blob/main/website/reference/api.md Demonstrates parsing JavaScript source code and finding a specific pattern like 'console.log' using the ast-grep NAPI. ```typescript import { parse, Lang } from '@ast-grep/napi' const ast = parse(Lang.JavaScript, source) const root = ast.root() root.find("console.log") ``` -------------------------------- ### Example TypeScript File Source: https://github.com/ast-grep/ast-grep.github.io/blob/main/website/blog/new-ver-43.md A sample TypeScript file demonstrating various declarations including imports, exports, functions, and classes. ```typescript import { readFile } from "node:fs/promises"; export const model = "gpt"; export async function summarize(path: string) { const text = await readFile(path, "utf8"); return text.slice(0, 120); } class Planner { next() { return "inspect"; } } export default Planner; ``` -------------------------------- ### TypeMap Subtype Alias Example Source: https://github.com/ast-grep/ast-grep.github.io/blob/main/website/blog/typed-napi.md An example demonstrating how 'subtypes' in TypeMap can be used to create aliases for multiple node kinds, reducing redundancy. ```typescript type TypeScript = { // node type alias declaration: { type: "declaration", subtypes: [ { type: "class_declaration", named: true }, { type: "function_declaration", named: true }, ] }, ... } ``` -------------------------------- ### Rust nested if to let-chain example Source: https://github.com/ast-grep/ast-grep.github.io/blob/main/website/catalog/rust/rust-2024-let-chain-candidate.md Demonstrates a Rust function with nested if statements that can be refactored into let-chains. Includes examples of valid refactorings and cases that are not suitable. ```Rust fn handle_request(user: Option, cfg: Config) { if let Some(user) = user { if user.is_active() { grant_access(user); } } if cfg!(debug_assertions) { if let Some(path) = cfg.log_path() { enable_file_logging(path); } } // OK: the inner if is not the only statement in the block. if let Some(user) = current_user() { audit(&user); if user.is_admin() { grant_admin(user); } } // OK: this has an else branch. if let Some(path) = cfg.cache_path() { if path.exists() { load_cache(path); } } else { rebuild_cache(); } } ``` -------------------------------- ### Display Help Summary Source: https://github.com/ast-grep/ast-grep.github.io/blob/main/website/reference/cli/new.md Use the `-h` option to print a summary of the help information for the command. ```shell -h, --help ``` -------------------------------- ### Example of Optional[int] type hint Source: https://github.com/ast-grep/ast-grep.github.io/blob/main/website/catalog/python/optional-to-none-union.md This is an example of the code structure that the rule targets. It shows a function argument with an Optional[int] type hint. ```python def a(arg: Optional[int]): pass ``` -------------------------------- ### System Set Migration Pattern Source: https://github.com/ast-grep/ast-grep.github.io/blob/main/website/blog/migrate-bevy.md Shows the migration from SystemSet::new() to the new add_systems syntax. ```rust // Before: app.add_system_set( SystemSet::new() .with_system(a) .with_system(b) .with_run_criteria(my_run_criteria) ); // After: app.add_systems((a, b).run_if(my_run_condition)); ``` -------------------------------- ### Initialize SgRoot and get root node Source: https://github.com/ast-grep/ast-grep.github.io/blob/main/website/guide/api-usage/py-api.md Parsing source code into a syntax tree and accessing the root node. ```python class SgRoot: def __init__(self, src: str, language: str) -> None: ... def root(self) -> SgNode: ... ``` ```python root = SgRoot("print('hello world')", "python") # 1. parse node = root.root() # 2. get root ``` -------------------------------- ### Examples of await inside loops Source: https://github.com/ast-grep/ast-grep.github.io/blob/main/website/guide/rule-config/relational-rule.md These JavaScript code examples demonstrate various loop structures containing 'await' calls, which would be matched by the preceding 'inside' rule. ```javascript while (foo) { await bar() } for (let i = 0; i < 10; i++) { await bar() } for (let key in obj) { await bar() } do { await bar() } while (condition) ``` -------------------------------- ### Python List Comprehension to Generator Expression Example Source: https://github.com/ast-grep/ast-grep.github.io/blob/main/website/catalog/python/prefer-generator-expressions.md This example demonstrates the transformation of a Python list comprehension within the `any()` function to a generator expression. This is safe because `any()` accepts iterables. ```python any([x for x in range(10)]) ``` -------------------------------- ### YAML Rule Kind Example (YAML) Source: https://github.com/ast-grep/ast-grep.github.io/blob/main/website/blog/new-ver-43.md Shows how to use ESQuery-style selectors within a YAML rule definition for ast-grep. This example targets exported function declarations in TypeScript. ```yaml id: exported-function language: TypeScript rule: kind: export_statement > function_declaration ``` -------------------------------- ### Create New ast-grep Project Source: https://github.com/ast-grep/ast-grep.github.io/blob/main/website/reference/cli/new.md Use the `project` subcommand to create a new ast-grep project. This scaffolds a root config file, rule folder, test case folder, and utility rule folder. ```shell ast-grep new project ``` -------------------------------- ### Project Directory Structure Source: https://github.com/ast-grep/ast-grep.github.io/blob/main/website/guide/scan-project.md The standard file layout generated after initializing an ast-grep project. ```bash my-awesome-project |- rules # where rules go |- rule-tests # test cases for rules |- utils # global utility rules for reusing |- sgconfig.yml # root configuration file ``` -------------------------------- ### Local Utility Rule Definition Example Source: https://github.com/ast-grep/ast-grep.github.io/blob/main/website/guide/rule-config/utility-rule.md A concise example of defining a local utility rule 'is-literal' within the 'utils' field of a config file and applying it in the 'rule' section. ```yaml utils: is-literal: any: - kind: 'false' - kind: undefined - kind: 'null' - kind: 'true' - kind: regex - kind: number - kind: string rule: matches: is-literal ``` -------------------------------- ### Example of Repetitive Rule Definition Source: https://github.com/ast-grep/ast-grep.github.io/blob/main/website/guide/rule-config/utility-rule.md This example demonstrates the need for rule reuse by showing how literal values and arrays of literal values would be defined repetitively without utilities. ```yaml rule: any: - kind: 'false' - kind: undefined # more literal kinds omitted # ... - kind: array has: any: - kind: 'false' - kind: undefined # more literal kinds omitted # ... ``` -------------------------------- ### Run Interactive Snapshot Update Source: https://github.com/ast-grep/ast-grep.github.io/blob/main/website/guide/test-rule.md Launch the interactive session to review and accept snapshot changes. ```bash ast-grep test --interactive ``` -------------------------------- ### Example Ruby on Rails Controller Before Filter Migration Source: https://github.com/ast-grep/ast-grep.github.io/blob/main/website/catalog/ruby/migrate-action-filter.md This example demonstrates the original code in a Rails controller that uses `before_filter`, `around_filter`, and `after_filter`. These methods are deprecated in Rails 5.0 and later. ```ruby class TodosController < ApplicationController before_filter :authenticate around_filter :wrap_in_transaction, only: :show after_filter do |controller| flash[:error] = "You must be logged in" end def index @todos = Todo.all end end ``` -------------------------------- ### C Code Example for Yoda Condition Source: https://github.com/ast-grep/ast-grep.github.io/blob/main/website/catalog/c/yoda-condition.md This C code snippet shows an example of an `if` statement that will be matched by the ast-grep rule. The rule targets comparisons like `myNumber == 42`. ```c if (myNumber == 42) { /* ... */} if (notMatch == another) { /* ... */} if (notMatch) { /* ... */} ``` -------------------------------- ### Example of disallowed console.debug and console.log Source: https://github.com/ast-grep/ast-grep.github.io/blob/main/website/catalog/typescript/no-console-except-catch.md This TypeScript example demonstrates code that violates the `no-console-except-error` rule by using `console.debug` and `console.log` outside of a catch block. The `console.error` within the catch block is permitted. ```typescript console.debug('') try { console.log('hello') } catch (e) { console.error(e) // OK } ``` -------------------------------- ### Match Function Calls Starting with a Prefix Source: https://github.com/ast-grep/ast-grep.github.io/blob/main/website/advanced/faq.md Use `constraints` with a `regex` to match function names that begin with a specific string. This is useful for enforcing naming conventions like React Hooks starting with 'use'. ```yaml rule: pattern: $HOOK($$$ARGS) constraints: HOOK: { regex: '^use' } ``` -------------------------------- ### Execute Rule Tests Source: https://github.com/ast-grep/ast-grep.github.io/blob/main/website/guide/test-rule.md Run the test suite using the CLI, optionally skipping snapshot verification. ```bash $ ast-grep test --skip-snapshot-tests Running 1 tests PASS no-await-in-loop ......................... test result: ok. 1 passed; 0 failed; ``` -------------------------------- ### Java Code Example for String Field Declarations Source: https://github.com/ast-grep/ast-grep.github.io/blob/main/website/catalog/java/find-field-with-type.md This Java code demonstrates various ways String fields can be declared, including with annotations and multiple modifiers. It serves as an example input for the ast-grep rule designed to find all such fields. ```java @Component class ABC extends Object{ @Resource private final String with_anno; private final String with_multi_mod; public String simple; } ``` -------------------------------- ### Install ast-grep.el with Doom Emacs Source: https://github.com/ast-grep/ast-grep.github.io/blob/main/website/guide/tools/editors.md Configure Doom Emacs to use the ast-grep package by adding it to your `packages.el` file with the correct recipe pointing to its GitHub repository. ```elisp (package! ast-grep :recipe (:host github :repo "SunskyXH/ast-grep.el")) ``` -------------------------------- ### Get root SgNode Source: https://github.com/ast-grep/ast-grep.github.io/blob/main/website/guide/api-usage/js-api.md Retrieve the root node from an SgRoot instance. ```javascript const root = ast.root() // root is an instance of SgNode ``` -------------------------------- ### ast-grep Help Command Source: https://github.com/ast-grep/ast-grep.github.io/blob/main/website/reference/cli.md Display all available command line options and their descriptions. This is useful for quickly referencing available commands and flags. ```shell ast-grep --help ``` -------------------------------- ### JSON Output of Author List Source: https://github.com/ast-grep/ast-grep.github.io/blob/main/website/guide/tooling-overview.md Example output generated by the web crawler command. ```json "Ben Blaiszik" "Qiming Sun" "Max Jones" "Thomas J. Fan" "Sebastian Bichelmaier" "Cliff Kerr" ... ``` -------------------------------- ### Filter nodes with matches Source: https://github.com/ast-grep/ast-grep.github.io/blob/main/website/guide/api-usage/py-api.md Example of using the matches method to refine node selection. ```python node = root.find(pattern="print($A)") if node["A"].matches(kind="string"): print("A is a string") ``` -------------------------------- ### JSON Output Format Example Source: https://github.com/ast-grep/ast-grep.github.io/blob/main/website/guide/tooling-overview.md Represents the structure of the JSON array returned by ast-grep. ```json [ { "text": "import", "range": { "byteOffset": { "start": 66, "end": 72 }, "start": { "line": 3, "column": 2 }, "end": { "line": 3, "column": 8 } }, "file": "website/src/vite-env.d.ts", "replacement": "require", "language": "TypeScript" } ] ``` -------------------------------- ### Python example code Source: https://github.com/ast-grep/ast-grep.github.io/blob/main/website/catalog/python/use-walrus-operator-in-if.md Original Python code snippet before applying the refactoring rules. ```python a = foo() if a: do_bar() ``` -------------------------------- ### Migrate add_stage_after to configure_set using ast-grep Source: https://github.com/ast-grep/ast-grep.github.io/blob/main/website/blog/migrate-bevy.md This ast-grep command migrates `app.add_stage_after` calls to `app.configure_set` using meta-variables for flexibility. It handles cases without a trailing comma. ```bash ast-grep \ -p '$APP.add_stage_after($STAGE, $OWN_STAGE, SystemStage::parallel())' \ -r '$APP.configure_set($OWN_STAGE.after($STAGE))' -i ``` -------------------------------- ### Java Unused Variable Example Source: https://github.com/ast-grep/ast-grep.github.io/blob/main/website/catalog/java/no-unused-vars.md Demonstrates the removal of an unused string variable declaration. ```java String unused = "unused"; // [!code --] String used = "used"; System.out.println(used); ``` -------------------------------- ### Call Parameterized Utility with Arguments Source: https://github.com/ast-grep/ast-grep.github.io/blob/main/website/blog/new-ver-42.md Demonstrates calling a parameterized global utility by passing arguments via 'matches'. Each argument is a rule, allowing for flexible customization of the utility's behavior. ```yaml # rules/audit-logging.yml id: no-console-string-args language: TypeScript matches: - '@audit-log-call': logger-rule: "console" rule: pattern: $OBJ.$METHOD($$$ARGS) all: - has: kind: member_expression has: field: object matches: $logger-rule - has: field: arguments has: kind: string --- id: no-hardcoded-logger-args language: TypeScript matches: - '@audit-log-call': logger-rule: "logger" rule: pattern: $OBJ.$METHOD($$$ARGS) all: - has: kind: member_expression has: field: object matches: $logger-rule - has: field: arguments has: kind: string ``` -------------------------------- ### Compile Mojo Parser Manually with GCC Source: https://github.com/ast-grep/ast-grep.github.io/blob/main/website/advanced/custom-language.md Example of manually compiling the Mojo parser using GCC, specifying the 'src' directory for headers and source files, and outputting 'mojo.so'. ```bash gcc -shared -fPIC -fno-exceptions -g -I 'src' -o mojo.so -O2 src/scanner.cc -xc src/parser.c -lstdc++ ``` -------------------------------- ### Access node range information Source: https://github.com/ast-grep/ast-grep.github.io/blob/main/website/guide/api-usage/py-api.md Retrieving start and end positions for a node, which are 0-indexed. ```python rng = node.range() pos = rng.start # or rng.end, both are `Pos` objects pos.line # 0, line starts with 0 pos.column # 0, column starts with 0 rng.end.index # 17, index starts with 0 ``` -------------------------------- ### Run Benchmarks Source: https://github.com/ast-grep/ast-grep.github.io/blob/main/website/contributing/development.md Execute performance benchmarks located in the benches directory. ```bash cd benches cargo bench ```