### Install Grit CLI via npm Source: https://docs.grit.io/cli/quickstart Installs the Grit command-line interface globally using npm, making it available from any directory. ```bash npm install --location=global @getgrit/cli ``` -------------------------------- ### Apply Various GritQL Patterns Source: https://docs.grit.io/cli/quickstart Examples of using `grit apply` to run different GritQL patterns, including showing declarations, removing `console.log` statements, converting `if-else` to ternary operators, and converting Cypress tests to Playwright tests. ```bash grit apply "const" # Simply shows all const declarations grit apply no_console_log # Removes console.log statements from JavaScript grit apply ternary_op # Converts if-else statements to ternary operators in Python grit apply cypress_to_playwright # Converts Cypress tests to Playwright tests ``` -------------------------------- ### Install Grit CLI via Installation Script Source: https://docs.grit.io/cli/quickstart Installs the Grit command-line interface using a shell script downloaded via curl, providing an alternative installation method. ```bash curl -fsSL https://docs.grit.io/install | bash ``` -------------------------------- ### Grit CLI Installation: Install Supporting Binaries Source: https://docs.grit.io/cli/reference Installs necessary supporting binaries for Grit. You can specify whether to look for updates or install a specific application. ```APIDOC grit install: Description: Install supporting binaries Usage: grit install [OPTIONS] Options: --update: Description: Look for updates and install them Possible values: true, false --app : Description: Specify a specific app to install Possible values: grit, gouda, workflow-runner ``` -------------------------------- ### List All Available Grit Patterns Source: https://docs.grit.io/cli/quickstart Command to view the full list of available patterns in the Grit standard library, useful for discovering pre-built transformations. ```bash grit list ``` -------------------------------- ### Grit CLI Initialization: Install Modules Source: https://docs.grit.io/cli/reference Installs Grit modules. This command can also be used to update global Grit modules. ```APIDOC grit init: Description: Install grit modules Usage: grit init [OPTIONS] Options: --global: Description: Update global grit modules Default value: false Possible values: true, false ``` -------------------------------- ### Apply GritQL Pattern with Parameters Source: https://docs.grit.io/cli/quickstart Shows how to pass parameters to a GritQL pattern, specifically demonstrating how to remove all import statements from 'react'. ```bash grit apply 'remove_import(from=`"react"`)' ``` -------------------------------- ### Apply Standard Library Pattern for React Hooks Source: https://docs.grit.io/cli/quickstart Demonstrates applying a standard Grit pattern from the standard library to automatically upgrade React Class Components to hooks. ```bash grit apply react_to_hooks ``` -------------------------------- ### Grit Repository Structure Example Source: https://docs.grit.io/guides/config Illustrates the typical directory structure for a Grit project, showing the location of the `.grit/grit.yaml` configuration file. ```shell /repo ├── .grit │ └── grit.yaml ├── foobar | └── baz ├── src └── etc ``` -------------------------------- ### Example: GritQL Pattern Definition in Markdown Source: https://docs.grit.io/guides/testing This example illustrates a complete Markdown file used to define a GritQL pattern. It includes YAML front matter for metadata, the GritQL pattern body, and TypeScript code snippets demonstrating input and expected output for testing. ```markdown --- tags: [optional, tags, here] --- # Remove console.log Remove console.log in production code. ```grit `console.log($_)` => . ``` ## Test case one This is the first test case. You can include an explanation of the case here. ```typescript console.error("keep this"); console.log('remove this!'); ``` It is fine to include additional descriptive text around the test cases. This is often used to explain the context of the test case, or to explain a convention. ```typescript console.error("keep this"); ``` ``` -------------------------------- ### GritQL Code Rewrite with Metavariable Source: https://docs.grit.io/tutorials/gritql Shows how to perform code rewrites in GritQL using the `=>` operator. This example replaces `console.log` calls with `winston.info`, demonstrating how metavariables can be carried over to the replacement code to preserve dynamic parts. ```GritQL `console.log($my_message)` => `winston.info($my_message)` ``` -------------------------------- ### JavaScript Console Logging Example Source: https://docs.grit.io/language/idioms A straightforward JavaScript code snippet demonstrating multiple `console.log` statements. This file is named 'stuff.js', which aligns with the filename matching criteria specified in the accompanying GritQL pattern. ```JavaScript // @filename: stuff.js console.log("hello"); console.log("goodbye"); console.log("wow"); console.log("multiline"); ``` -------------------------------- ### GritQL Pattern for Creating New Files Source: https://docs.grit.io/language/idioms Illustrates the use of the `$new_files` metavariable in GritQL to create new files as a side-effect of a pattern. The example shows how to move functions starting with 'test' to a separate `.test.js` file. Users should be aware that this does not consider existing files and can overwrite them. ```GritQL `function $functionName($_) {$_}` as $f where { $functionName <: r"test.*", $f => ., $new_file_name = `$functionName.test.js`, $new_files += file(name = $new_file_name, body = $f) } ``` ```JavaScript function doStuff() {} function testStuff() {} ``` ```JavaScript // stuff.js function doStuff() {} // testStuff.test.js function testStuff() {} ``` -------------------------------- ### Example Grit Configuration with Custom Pattern Source: https://docs.grit.io/guides/config Demonstrates a complete `.grit/grit.yaml` file, including version, and a custom pattern definition (`avoid_only`) with its body, description, and sample input/output. This pattern helps identify and remove `.only` calls often left over from debugging. ```yaml version: 0.0.1 patterns: - name: avoid_only tags: ["style", "debugging"] level: error body: |\n \`$testlike.only\` => \`$testlike\` where {\n \`$testlike\` <: or {\n \`describe\`\n \`it\`\n \`test\`\n }\n } description: |\n .only is usually a mistake left over from local debugging. Pushing it to\n main risks false negatives on CI. samples: - input: |\n describe.only('this is a test', () => {\n // ...\n }); output: |\n describe('this is a test', () => {\n // ...\n }); - name: disabled_pattern level: none # This pattern is disabled body: |\n \`something\` => \`somewhere\` - file: ../other/doc/file.md ``` -------------------------------- ### Grit Markdown Pattern Example: Remove console.log Source: https://docs.grit.io/guides/config An example of a Grit pattern defined in a Markdown file. It includes front matter for tags, a title, a description, and the GritQL body to remove `console.log` statements. ```markdown --- tags: [optional, tags, here] --- # Remove console.log Remove console.log in production code. ```grit `console.log($_)` => . ``` ``` -------------------------------- ### Grit.io: String Primitive Literal Example Source: https://docs.grit.io/language/patterns Demonstrates the syntax for a Grit string primitive, enclosed in double quotes. This shows how Grit handles language-agnostic string literals, which can be used for matching exact strings rather than AST-aware code snippets. ```Grit "Hello, world!" // string ``` -------------------------------- ### Gritignore File Example for JavaScript Exclusion Source: https://docs.grit.io/guides/config Illustrates how to configure a `.gritignore` file to exclude specific file types from Grit's analysis. This example shows how to ignore all JavaScript files using a glob pattern. ```text **/*.js ``` -------------------------------- ### Example Code Transformation using GritQL text() Function Source: https://docs.grit.io/guides/duplicating This example illustrates the effect of the GritQL pattern using the `text()` function. It shows an initial JavaScript-like code snippet and its transformed output, where the original block is duplicated and the new block is modified. ```JavaScript const a = { something: foo } ``` ```JavaScript const a = { something: foo } const b = { something: bar } ``` -------------------------------- ### Grit.io: Matching 'augmented_assignment_expression' AST Node Source: https://docs.grit.io/language/patterns Demonstrates how to match against specific Abstract Syntax Tree (AST) nodes in Grit. This example targets `augmented_assignment_expression` nodes, showing how to capture operator, left, and right operands using metavariables. Includes TypeScript examples to illustrate the matched code. ```Grit augmented_assignment_expression(operator = $op, left = $x, right = $v) ``` ```TypeScript x = 1; x += 5; ``` -------------------------------- ### Grit.io: 'string' AST Node Structure Example Source: https://docs.grit.io/language/patterns Explains the structure of a `string` AST node in Grit.io, showing how it captures the literal fragment. This highlights how primitive values like strings are represented as nodes with specific fields for detailed matching. ```Grit string(fragment = "foo") ``` -------------------------------- ### GritQL Pattern with Metavariable Source: https://docs.grit.io/tutorials/gritql Illustrates the use of metavariables (identifiers starting with `$`) in GritQL patterns to match similar but not identical code structures. This pattern finds all `console.log` calls regardless of their message content, allowing for flexible searches. ```GritQL `console.log($my_message)` ``` -------------------------------- ### Example Grit Pattern Markdown File Source: https://docs.grit.io/guides/authoring Demonstrates the complete structure of a Grit pattern defined within a Markdown file. This includes YAML frontmatter for pattern metadata (like tags), the GritQL pattern body, and TypeScript code blocks used to define input and expected output for test cases. ```Markdown --- tags: [optional, tags, here] --- # Remove console.log Remove console.log in production code. ```grit `console.log($_)` => . ``` ## Test case one This is the first test case. You can include an explanation of the case here. ```typescript console.error("keep this"); console.log('remove this!'); ``` It is fine to include additional descriptive text around the test cases. This is often used to explain the context of the test case, or to explain a convention. ```typescript console.error("keep this"); ``` ``` -------------------------------- ### Grit CLI Troubleshooting Commands Source: https://docs.grit.io/guides/vscode Command-line interface commands used for verifying and updating the Grit CLI installation, which is a prerequisite for the VS Code extension. These commands are crucial for troubleshooting connectivity issues with the language server. ```Shell grit version ``` ```Shell grit install --update ``` -------------------------------- ### Grit CLI Authentication: Get Token Source: https://docs.grit.io/cli/reference Retrieves your authentication token for grit.io. This command is used to obtain the necessary credentials for interacting with the Grit.io platform. ```APIDOC grit auth get-token: Description: Get your grit.io token Usage: grit auth get-token ``` -------------------------------- ### Grit Sequential Pattern for Chained Rewrites (JavaScript) Source: https://docs.grit.io/language/patterns Illustrates the use of the `sequential` top-level clause in Grit, which allows multiple patterns to be processed in a defined order. This example demonstrates a chained rewrite where `console.log` becomes `console.warn`, and then `console.warn` becomes `console.info`. ```grit language js sequential { bubble file($body) where $body <: contains `console.log($message)` => `console.warn($message)`, bubble file($body) where $body <: contains `console.warn($message)` => `console.info($message)` } ``` -------------------------------- ### GritQL Non-Specific Rewrite Example Source: https://docs.grit.io/language/idioms Illustrates a non-specific GritQL rewrite where the entire matched pattern is rewritten. This approach can inadvertently remove important syntactic and semantic details, such as `async` keywords or comments, from the original code. ```GritQL `function foo($args) { $body }` => `function bar($args) {$body} ` ``` ```JavaScript async function foo(/* no args */) { console.log('Hello, world!'); } ``` ```JavaScript function bar() { console.log('Hello, world!'); } ``` -------------------------------- ### GritQL Rewrite with `where` Clause and Negation Source: https://docs.grit.io/tutorials/gritql Illustrates using negation (`!`) within a GritQL `where` clause to exclude matches that satisfy a certain condition. This example prevents `console.log` calls containing 'user-facing' from being rewritten to `winston.info` by using a regular expression. ```GritQL `console.log($my_message)` => `winston.info($my_message)` where { !$my_message <: r".+user-facing.+" } ``` -------------------------------- ### Call GritQL Standard Library Literal Pattern for JavaScript Values Source: https://docs.grit.io/tutorials/gritql Shows how to reuse common patterns by 'calling' them, similar to functions, and passing named arguments. This example uses the built-in `literal` pattern from the Grit standard library to match JavaScript literals with a specific value (e.g., '42'). ```GritQL `console.log($my_message)` => `winston.info($my_message)` where { $my_message <: literal(value="42") } ``` -------------------------------- ### Grit.io: Number Primitive and Arithmetic Transformation Source: https://docs.grit.io/language/patterns Illustrates the use of Grit number primitives and how they can be used in arithmetic operations within patterns. This example shows a transformation that multiplies a variable `$x` by 2 and then rewrites `$x` to the calculated result `$y`. ```Grit js"multiply($x)" where { $y = $x * 2, $x => $y } ``` -------------------------------- ### GritQL Compound Pattern with `or` Operator Source: https://docs.grit.io/tutorials/gritql Demonstrates combining multiple patterns using the `or` boolean operator within a single GritQL query. This example matches either `console.log` or `console.error` calls and rewrites both to `winston.info`, showcasing how to apply a single rewrite to multiple source patterns. ```GritQL or { `console.log($my_message)`, `console.error($my_message)` } => `winston.info($my_message)` ``` -------------------------------- ### Example Grit Pattern for .grit File Source: https://docs.grit.io/guides/patterns Provides a sample Grit pattern, `replace_console_log`, intended for placement in a `.grit` file within the `.grit/patterns` directory. This pattern transforms `console.log` calls to `console.error`, demonstrating a common refactoring use case. ```Grit pattern replace_console_log() { `console.log($args)` => `console.error($args)` } ``` -------------------------------- ### GritQL Specific Rewrite Example Source: https://docs.grit.io/language/idioms Demonstrates a specific GritQL rewrite where only particular metavariables are changed within a `where` clause. This method is preferred as it preserves the original code's syntactic and semantic details, such as `async` modifiers and comments, by avoiding full pattern replacement. ```GritQL `function $name($args) { $body }` where { $name <: `foo` => `bar` } ``` ```JavaScript async function foo(/* no args */) { console.log('Hello, world!'); } ``` ```JavaScript async function bar(/* no args */) { console.log('Hello, world!'); } ``` -------------------------------- ### Grit.io: Matching a Rewrite within a Pattern for 'test.only' Source: https://docs.grit.io/language/patterns Shows an advanced Grit.io pattern where a rewrite itself is matched and applied within a `where` clause. This example transforms `test.only` calls to `test` within a JavaScript context, demonstrating how rewrites can be nested or used as sub-patterns for concise GritQL. ```Grit engine marzano(0.1) language js `$test($_)` where { $test <: js"test.only" => js"test" } ``` ```Diff test.only(() => { expect(true).toEqual(true); }); ``` ```Diff test(() => { expect(true).toEqual(true); }); ``` -------------------------------- ### TypeScript Console Logging Test Cases Source: https://docs.grit.io/guides/config Demonstrates basic console logging in TypeScript for test cases. The first example shows both `console.error` and `console.log`, while the second highlights a common convention of retaining `console.error` while `console.log` might be removed or ignored. ```typescript console.error("keep this"); console.log('remove this!'); ``` ```typescript console.error("keep this"); ``` -------------------------------- ### Define and Use Custom GritQL Functions Source: https://docs.grit.io/language/functions Demonstrates how to define custom functions (`lines`, `my_todo`) using the `function` keyword in GritQL. It showcases parameter handling, conditional logic, and string manipulation within functions, along with an example of applying `my_todo` in a rewrite operation. ```pattern // define a lines function function lines($string) { return split($string, separator=`\n`) } // Define a my_todo function function my_todo($target, $message) { if($message <: undefined) { $message = "This requires manual intervention." }, $lines = lines(string = $message), $lines <: some bubble($result) $x where { if ($result <: undefined) { $result = `// TODO: $x` } else { $result += `\n// $x` } }, $target_lines = lines(string = $target), $target_lines <: some bubble($result) $x where { $result += `\n// $x` }, return $result, } // Use the my_todo function `module.exports = $_` as $x => my_todo(target=$x, message=`Fix this\nAnd that`) ``` ```diff module.exports = { king, queen: '8', }; ``` ```diff // TODO: Fix this // And that // module.exports = { // king, // queen: '8', // }; ``` -------------------------------- ### Illustrative Diff for TypeScript Type Renaming Source: https://docs.grit.io/language/patterns Shows a practical example of how a type renaming operation would appear in a `diff` format. It highlights the change from `Props` to `NewProps` in a definition file and the corresponding updates in files that import and use this type, demonstrating a common refactoring scenario. ```js // file1.js type Props = { name: string; }; // file2.js type Props = { age: string; }; // file3.js import { Props } from './file1.js'; const foo: Props = { name: 'foo', }; // file4.js import { Props } from './file2.js'; const foo: Props = { age: 'foo', }; ``` ```js // file1.js type NewProps = { name: string; }; // file2.js type Props = { age: string; }; // file3.js import { NewProps } from './file1.js'; const foo: NewProps = { name: 'foo', }; // file4.js import { Props } from './file2.js'; const foo: Props = { age: 'foo', }; ``` -------------------------------- ### Basic Metavariable Usage in Grit Source: https://docs.grit.io/language/patterns Illustrates the fundamental use of metavariables (e.g., `$foo`) in Grit patterns to bind to specific parts of the syntax tree. Metavariables are alphanumeric, start with a letter, and typically use `$lowercase_snake_case`. ```grit `console.log($foo)` ``` ```typescript console.log('Hello, world!') ``` -------------------------------- ### Grit Multifile Pattern for Cross-File Refactoring (JavaScript) Source: https://docs.grit.io/language/patterns Demonstrates the `multifile` pattern, which allows a Grit program to evaluate against multiple files while maintaining a single global state. This example finds and renames a 'Prop' type in one file and then applies that rename across all other relevant files. ```grit language js multifile { // Since multifile has a single global state, // we need to use `bubble` to restrict the scope of $body bubble($prop, $source_file, $new_prop) file($body) where $body <: contains `type $prop = $_` where { // If we already have found a specific $source_file, // we don't want to keep looking for new props $source_file <: undefined, $prop <: `Props`, $new_prop = `New$prop`, // Rename the prop in this file $prop => $new_prop, } ``` -------------------------------- ### Match Console Log within Try/Catch Block using GritQL `within` Modifier Source: https://docs.grit.io/tutorials/gritql Illustrates the use of the `within` pattern modifier in GritQL to match `console.log` statements only when they are nested inside a `try/catch` block. This example also introduces the anonymous `$_` metavariable for matching any pattern as a placeholder. ```GritQL `console.log($my_message)` => `winston.error($my_message)` where { $my_message <: within `try { $_ } catch($_) { $_ }` } ``` -------------------------------- ### Grit Inline Suppression Diff Example Source: https://docs.grit.io/guides/config Demonstrates inline suppression using `grit-ignore` in a diff format. The first block shows the original code with a `console.log` statement suppressed. The second block shows the result after a GritQL pattern has been applied, where the unsuppressed `console.log` is rewritten to `console.info`, while the suppressed line remains unchanged. ```javascript console.log("Hello, world!"); // grit-ignore console.log("Can you hear me?"); ``` ```javascript console.info("Hello, world!"); // grit-ignore console.log("Can you hear me?"); ``` -------------------------------- ### GritQL Pattern: Ensure Import from Source Source: https://docs.grit.io/guides/imports This GritQL pattern ensures that a specified value (e.g., a component) is imported from a given source. It automatically adds the import statement if it does not already exist. The example demonstrates how to ensure the 'Component' class is imported from 'React' for a class extending it. ```GritQL Pattern `class $_ extends $comp { $_ }` where { $comp <: `Component`, $source = `"React"`, $comp <: ensure_import_from($source) } ``` ```JavaScript (Before Transformation) class Button extends Component { // ... } ``` ```JavaScript (After Transformation) import { Component } from 'React'; class Button extends Component { // ... } ``` -------------------------------- ### Grit CLI: grit apply Command Options Source: https://docs.grit.io/cli/reference Reference for all available options when using the `grit apply` command, including input parameters, remote execution settings, output formats, and language specification. ```APIDOC grit apply options: --input : type: string description: JSON input parameter to pass to the workflow --remote: type: boolean description: Run the workflow remotely on Grit Cloud possible_values: true, false --workflow-id : type: string description: Workflow ID to set, only applicable when running remotely --watch: type: boolean description: Watch the workflow for updates (only applicable when running remotely) possible_values: true, false --verbose: type: boolean description: Print verbose output possible_values: true, false --output : type: string description: Output format default: standard possible_values: none, standard, compact -m, --limit : type: integer description: Limit the number of changes applied --dry-run: type: boolean description: Show a dry-run of the changes that would be applied default: false possible_values: true, false --force: type: boolean description: Force apply, even if there are uncommitted changes default: false possible_values: true, false -i, --interactive: type: boolean description: Selectively apply changes interactively default: false possible_values: true, false --output-file : type: string description: Path to a file to write the results to, defaults to stdout --stdin: type: boolean description: Use this option when you want to transform code piped from stdin, and print the output to stdout. If used, you must specify a file path to allow Grit to determine the language of the code. possible_values: true, false --cache: type: boolean description: Use cache possible_values: true, false --refresh-cache: type: boolean description: Clear cache before running apply possible_values: true, false --ai: type: boolean description: Interpret the request as a natural language request possible_values: true, false --language : type: string description: Change the default language to use for the pattern (if unset, JavaScript is used by default) possible_values: js, html, css, json, java, kotlin, csharp, python, markdown, go, rust, ruby, elixir, solidity, hcl, yaml, sql, vue, toml, php --only-in-json : type: string description: Only analyze ranges inside a provided eslint-style JSON string. The JSON should be an array of objects formatted as [{"filePath": "path/to/file", "messages": [{"line": 1, "column": 1, "endLine": 1, "endColumn": 1}]}]. ``` -------------------------------- ### Grit CLI Patterns: Manage Patterns Source: https://docs.grit.io/cli/reference Provides commands for managing Grit patterns. This includes listing, testing, editing, and describing patterns. ```APIDOC grit patterns: Description: Patterns commands, run grit patterns --help for more information Usage: grit patterns Subcommands: list: Description: List all available named patterns test: Description: Test patterns against expected output edit: Description: Open a pattern in the studio describe: Description: Describe a pattern ``` -------------------------------- ### Refactor Console Logging to Winston with Method Mapping in GritQL Source: https://docs.grit.io/tutorials/gritql Demonstrates how to refactor `console` logging calls to `winston` calls in GritQL, mapping specific `console` methods (`log`, `error`) to `winston` methods (`debug`, `warn`) using a `where` clause and an `or` pattern. ```GritQL `console.$method($my_message)` => `winston.$method($my_message)` where { $method <: or { `log` => `debug`, `error` => `warn` } } ``` -------------------------------- ### Run GritQL Pattern Tests via CLI Source: https://docs.grit.io/guides/testing This snippet demonstrates how to execute GritQL pattern tests from the command line. It shows the basic `grit patterns test` command and how to use the `--filter` option to run a specific subset of patterns. ```shell grit patterns test --filter=pattern_to_test ``` -------------------------------- ### GritQL Basic Pattern Matching Source: https://docs.grit.io/tutorials/gritql Demonstrates a basic GritQL pattern to find exact string matches within `console.log` calls. It highlights GritQL's structural matching capabilities, which can handle variations in quotes or line breaks, unlike simple string matching. ```GritQL `console.log("Hello world!")` ``` -------------------------------- ### Get Length of List or String with Length Function (Grit) Source: https://docs.grit.io/language/functions The `length` function returns the number of elements in a target list or the number of characters in a target string. It provides a way to determine the size of collections or text. ```grit length(target=[7, 8, 9]) // returns 3 length(target="hello") // returns 5 ``` -------------------------------- ### Grit CLI Workflows: List Available Workflows Source: https://docs.grit.io/cli/reference Lists all workflows that are currently available in your Grit environment. ```APIDOC grit workflows list: Description: List all available workflows Usage: grit workflows list ``` -------------------------------- ### Grit CLI: grit blueprints list Command Source: https://docs.grit.io/cli/reference Documentation for the `grit blueprints list` subcommand, used to display all available blueprints. ```APIDOC grit blueprints list: description: List available blueprints usage: grit blueprints list ``` -------------------------------- ### Grit CLI Workflows: Manage Workflows Source: https://docs.grit.io/cli/reference Provides commands for managing Grit workflows. Use subcommands like 'list' to view available workflows or 'upload' to add new ones. ```APIDOC grit workflows: Description: Workflow commands, run grit workflows --help for more information Usage: grit workflows Subcommands: list: Description: List all available workflows upload: Description: Upload a workflow ``` -------------------------------- ### Define a Sample Grit Workflow Source: https://docs.grit.io/workflows/overview This TypeScript code defines a simple Grit workflow. It imports the standard library, exports an async `execute` function as the entry point, and applies a GritQL pattern to swap arguments in a `sum` function. Workflows are placed in `.grit/workflows` and are invoked via `grit apply`. ```typescript import { stdlib } from '@getgrit/api'; export async function execute() { await stdlib.apply({ query: '`sum($a, $b)` => `sum($b, $a)`' }, {}); return { success: true, message: 'Migration complete' }; } ``` -------------------------------- ### Capture Node Text with Text Function (Grit) Source: https://docs.grit.io/language/functions The `text` function captures the current textual representation of a target node as a string. This is particularly useful for preserving the original text of a node before it is modified, for example, when duplicating code. ```grit `console.log($msg)` where { $clone = text($msg), // keep a clone of $msg, since we are about to modify it $msg => `"log", $clone` } ``` -------------------------------- ### Define and Apply a Basic Grit Pattern Source: https://docs.grit.io/guides/patterns Illustrates the fundamental syntax for defining a Grit pattern using the `pattern` keyword. The `console_method_to_info` pattern transforms `console.$method($message)` calls to `console.info($message)`. This snippet also shows how to apply the pattern by explicitly naming the parameter. ```Grit pattern console_method_to_info($method) { `console.$method($message)` => `console.info($message)` } console_method_to_info(method = `log`) ``` ```diff console.log('Hello, world!'); console.warn('Can you hear me?'); ``` ```diff console.info('Hello, world!'); console.warn('Can you hear me?'); ``` -------------------------------- ### Grit CLI: grit auth login Command Source: https://docs.grit.io/cli/reference Documentation for the `grit auth login` subcommand, used to authenticate and log in with Grit.io. ```APIDOC grit auth login: description: Log in with grit.io usage: grit auth login ``` -------------------------------- ### Grit CLI Base Command Source: https://docs.grit.io/cli/reference The main entry point for the Grit CLI, providing an overview of available subcommands and global options for software maintenance on autopilot. ```APIDOC grit: Description: Software maintenance on autopilot, from grit.io Usage: grit [OPTIONS] Help: For help with a specific command, run `grit help `. Subcommands: check: Check the current directory for pattern violations list: List everything that can be applied to the current directory apply: Apply a pattern or migration to a set of files doctor: Print diagnostic information about the current environment blueprints: Manage blueprints for the Grit Agent auth: Authentication commands, run `grit auth --help` for more information install: Install supporting binaries init: Install grit modules workflows: Workflow commands, run `grit workflows --help` for more information patterns: Patterns commands, run `grit patterns --help` for more information version: Display version information about the CLI and agents format: Format grit files under current directory Options: --json: Enable JSON output, only supported on some commands (Possible values: true, false) --jsonl: Enable JSONL output, only supported on some commands (Possible values: true, false) --log-level : Override the default log level (info) --grit-dir : Override the default .grit directory location ``` -------------------------------- ### Grit CLI Apply Command Source: https://docs.grit.io/cli/reference Applies a specified pattern or migration to a set of files. The pattern can be provided by its name or as an inline pattern string. ```APIDOC grit apply: Description: Apply a pattern or migration to a set of files Usage: grit apply [OPTIONS] [PATHS]... Arguments: : The pattern to apply, in a few forms: A pattern name (ex. `raw_no_console_log`) A pattern by itself (ex. `'`console.log` => `console.error`'`) ``` -------------------------------- ### Grit Configuration: Importing All Patterns from a Remote Module Source: https://docs.grit.io/guides/config Demonstrates how to enable all patterns from a remote Grit module (e.g., `stdlib`) by using a wildcard (`*`) for the pattern name, prefixed with the module name and a `#`, within the `grit.yaml` file. ```yaml patterns: - name: github.com/getgrit/stdlib#* ``` -------------------------------- ### Grit CLI: grit blueprints push Command Source: https://docs.grit.io/cli/reference Documentation for the `grit blueprints push` subcommand, used to upload a blueprint by its workflow ID, with an option to specify the input file. ```APIDOC grit blueprints push: description: Push a blueprint by workflow ID usage: grit blueprints push [OPTIONS] --workflow-id options: - --workflow-id : type: string description: The workflow ID of the blueprint to push - --file : type: string description: File containing the blueprint default: blueprint.md ``` -------------------------------- ### Grit CLI: grit auth Command Source: https://docs.grit.io/cli/reference Documentation for the `grit auth` command, which handles authentication-related operations for Grit.io, including login, logout, token retrieval, and refresh. ```APIDOC grit auth: description: Authentication commands usage: grit auth subcommands: - login: Log in with grit.io - logout: Remove your grit.io credentials - get-token: Get your grit.io token - refresh: Refresh your grit.io auth ``` -------------------------------- ### Grit.io: Basic Rewrite Operator for 'println' to 'console.log' Source: https://docs.grit.io/language/patterns Demonstrates the fundamental usage of the Grit.io rewrite operator (`=>`) to transform a `println` function call into `console.log`. It shows the `pattern` definition and the resulting `diff` illustrating the change. ```Grit `println` => `console.log` ``` ```Diff println("Hello, world!"); ``` ```Diff console.log("Hello, world!"); ``` -------------------------------- ### Match Any Pattern with Grit `or` Clause Source: https://docs.grit.io/language/modifiers The `or` clause in Grit matches if any of its comma-separated patterns are true. It is short-circuited, meaning the first matching pattern will be the one that is used for transformation. This example shows how to use `or` to conditionally rewrite React hooks based on which one is found first. ```Grit arrow_function($body) where $body <: or { contains js"React.useState" => js"useState", contains js"React.useMemo" => js"useMemo", } ``` ```JavaScript const someComponent = () => { const [count, setCount] = React.useState(0); }; const anotherComponent = () => { const [count, setCount] = React.useState(0); const math = React.useMemo(() => count + 5, [count]); }; ``` ```JavaScript const someComponent = () => { const [count, setCount] = useState(0); }; const anotherComponent = () => { const [count, setCount] = useState(0); const math = React.useMemo(() => count + 5, [count]); }; ``` -------------------------------- ### Grit CLI: grit blueprints Command Source: https://docs.grit.io/cli/reference Documentation for the `grit blueprints` command, which manages blueprints for the Grit Agent, including subcommands for listing, pulling, and pushing blueprints. ```APIDOC grit blueprints: description: Manage blueprints for the Grit Agent usage: grit blueprints subcommands: - list: List available blueprints - pull: Pull a blueprint by workflow ID - push: Push a blueprint by workflow ID ``` -------------------------------- ### Grit CLI Patterns: Describe a Pattern Source: https://docs.grit.io/cli/reference Provides a description of a specified pattern. Requires the name of the pattern. ```APIDOC grit patterns describe: Description: Describe a pattern Usage: grit patterns describe Arguments: : Description: The pattern name to describe ``` -------------------------------- ### Grit.io: Omitting Fields in AST Node Matching Patterns Source: https://docs.grit.io/language/patterns Illustrates that fields not relevant to the match can be omitted in Grit.io AST node patterns. This example shows two equivalent patterns for `augmented_assignment_expression` where the `left` and `right` fields are implicitly ignored or explicitly represented by `$_`. ```Grit augmented_assignment_expression(operator = $op) // same as augmented_assignment_expression(operator = $op, left = $_, right = $_) ``` -------------------------------- ### Grit.io List Pattern Matching Source: https://docs.grit.io/language/modifiers The list pattern in Grit.io matches if all specified terms in the list match in the exact order. This example demonstrates transforming a variable assignment with a generic number list into one with specific prime numbers by matching an ordered list. ```Grit.io Pattern `var $x = [$numbers]` => `var firstPrimes = [$numbers]` where { $numbers <: [ `2`, `3`, `5` ] } ``` ```JavaScript var someNumbers = [2, 3, 5]; ``` ```JavaScript var firstPrimes = [2, 3, 5]; ``` -------------------------------- ### Negate Pattern Matching with Grit `not` Clause Source: https://docs.grit.io/language/modifiers The `not` clause in Grit negates a pattern, matching only if the specified pattern does *not* match. This is useful for excluding specific cases from a broader pattern. This example demonstrates how to rewrite `console` method calls to `console.warn` while explicitly preventing `console.error` from being transformed. ```Grit `$method($message)` => `console.warn($message)` where { $method <: not `console.error` } ``` ```JavaScript console.log("Hello, world!"); console.error("Hello, world!"); ``` ```JavaScript console.warn("Hello, world!"); console.error("Hello, world!"); ``` -------------------------------- ### Grit CLI Patterns: List Named Patterns Source: https://docs.grit.io/cli/reference Lists all available named patterns. You can filter patterns by enforcement level, source, or target language. ```APIDOC grit patterns list: Description: List all available named patterns Usage: grit patterns list [OPTIONS] Options: --level : Description: List only at or above an enforcement level --source : Description: List items from a specific source Default value: all Possible values: all, local, user --language : Description: List only items targeting a specific language Possible values: js, html, css, json, java, kotlin, csharp, python, markdown, go, rust, ruby, elixir, solidity, hcl, yaml, sql, vue, toml, php ``` -------------------------------- ### Combine Multiple Patterns with Grit `and` Clause Source: https://docs.grit.io/language/modifiers The `and` clause in Grit combines multiple comma-separated patterns, matching only if all specified patterns are true. This example demonstrates its use with a `where` clause to rewrite two types of React hooks simultaneously, ensuring both conditions are met before applying the transformation. ```Grit arrow_function($body) where $body <: and { contains js"React.useState" => js"useState", contains js"React.useMemo" => js"useMemo", } ``` ```JavaScript const someComponent = () => { const [count, setCount] = React.useState(0); }; const anotherComponent = () => { const [count, setCount] = React.useState(0); const math = React.useMemo(() => count + 5, [count]); }; ``` ```JavaScript const someComponent = () => { const [count, setCount] = React.useState(0); }; const anotherComponent = () => { const [count, setCount] = useState(0); const math = useMemo(() => count + 5, [count]); }; ``` -------------------------------- ### Grit CLI List Command Source: https://docs.grit.io/cli/reference Lists everything that can be applied to the current directory. This command supports filtering items by enforcement level, source (all, local, user), and target programming language. ```APIDOC grit list: Description: List everything that can be applied to the current directory Usage: grit list [OPTIONS] Options: --level : List only at or above an enforcement level --source : List items from a specific source (Default value: all) Possible values: all: All patterns local: Only patterns from the local repo user: Only patterns from the user config --language : List only items targeting a specific language Possible values: js, html, css, json, java, kotlin, csharp, python, markdown, go, rust, ruby, elixir, solidity, hcl, yaml, sql, vue, toml, php ``` -------------------------------- ### Grit CLI Workflows: Upload a Workflow Source: https://docs.grit.io/cli/reference Uploads a new workflow to Grit. Requires the path to the workflow file and a unique workflow ID. ```APIDOC grit workflows upload: Description: Upload a workflow Usage: grit workflows upload Arguments: : : ``` -------------------------------- ### Grit VS Code Extension Command Palette Actions Source: https://docs.grit.io/guides/vscode Key commands available through the Visual Studio Code Command Palette for interacting with the Grit extension, enabling users to apply patterns, fix files, and perform GritQL searches directly within the editor. ```APIDOC Command: Grit: Apply Pattern Description: Applies any configured pattern to the current file. Usage: Accessible via the VS Code Command Palette. ``` ```APIDOC Command: Grit: Fix File Description: Applies all configured patterns to the current file at once. Usage: Accessible via the VS Code Command Palette. ``` ```APIDOC Command: Grit: Search with GritQL Description: Opens a search file allowing users to scan for GritQL matches directly in the editor. Accepts any valid GritQL query and highlights matches in the codebase. Usage: Accessible via the VS Code Command Palette. ``` -------------------------------- ### Grit CLI: grit blueprints pull Command Source: https://docs.grit.io/cli/reference Documentation for the `grit blueprints pull` subcommand, used to download a blueprint by its workflow ID, with options for force pulling and specifying an output file. ```APIDOC grit blueprints pull: description: Pull a blueprint by workflow ID usage: grit blueprints pull [OPTIONS] --workflow-id options: - --workflow-id : type: string description: The workflow ID of the blueprint to pull - -f, --force: type: boolean description: Force pull even if the blueprint already exists possible_values: true, false - --file : type: string description: File to save the blueprint to default: blueprint.md ``` -------------------------------- ### Grit CLI Utility: Display Version Information Source: https://docs.grit.io/cli/reference Displays version information for both the Grit CLI and its associated agents. ```APIDOC grit version: Description: Display version information about the CLI and agents Usage: grit version ``` -------------------------------- ### Restricting Grit.io Pattern Matches with `within` Clause Source: https://docs.grit.io/language/modifiers The `within` clause restricts a Grit.io pattern to only match if the target node appears inside code that matches another specified pattern. This ensures context-aware matching, for example, only matching `console.log` statements that are nested within an `if (DEBUG)` block. ```grit `console.log($arg)` where { $arg <: within `if (DEBUG) { $_ }` } ``` ```typescript console.log('Hello, world!'); if (DEBUG) { console.log('Hello, world!'); } ``` -------------------------------- ### Grit Configuration: Importing a Single Remote Pattern Source: https://docs.grit.io/guides/config Illustrates how to enable a specific pattern from a remote Grit module (e.g., `stdlib`) by referencing its full name, prefixed with the module name and a `#`, in the `grit.yaml` file. ```yaml patterns: - name: github.com/getgrit/stdlib#no_console_log ``` -------------------------------- ### Matching All List Elements with Grit.io `every` Clause Source: https://docs.grit.io/language/modifiers The `every` clause in Grit.io matches a pattern against every element of a list, succeeding only if all elements match the specified pattern. This ensures that all items in a collection conform to a certain condition before a transformation is applied, for example, renaming a variable only if all names in a list are 'andrew' or 'alex'. ```pattern `var $x = [$names]` => `var coolPeople = [$names]` where { $names <: every or {`"andrew"`, `"alex"`} } ``` ```diff var people = ["alex", "andrew", "alex"]; var peopleTwo = ["alex", "max", "right"]; var nobody = ["sam", "susan"]; ``` ```diff var coolPeople = ["alex", "andrew", "susan"]; var peopleTwo = ["alex", "max", "right"]; var nobody = ["sam", "susan"]; ``` -------------------------------- ### GritQL Comments Syntax Source: https://docs.grit.io/language/idioms Explains that GritQL supports single-line comments. Any line beginning with `//` is treated as a comment and is ignored by the GritQL parser. ```GritQL `console.log($message)` => . where { // This is a comment $message <: js"'Hello, world!'" } ``` -------------------------------- ### Grit.io Limit Clause for Query Result Control Source: https://docs.grit.io/language/modifiers The `limit` clause can be appended to any root pattern in Grit.io to restrict the total number of matches returned. This clause is enforced globally across all queried files and is typically used to control the scope of transformations or analyses. The example shows limiting a `console.log` to `console.warn` transformation to only 2 files. ```Grit.io Pattern `console.$method($message)` => `console.warn($message)` where { $method <: not `error` } limit 2 // Only find 2 files ``` ```JavaScript // @filename: file.tsx console.log("Hello, world!"); console.log("Hello, world 2!"); // @filename: file2 console.log("This is another file"); // @filename: file3 console.log("This is a third file"); ``` ```JavaScript // @filename: file.tsx console.warn("Hello, world!"); console.warn("Hello, world 2!"); // @filename: file2 console.warn("This is another file"); // @filename: file3 console.log("This is a third file"); ``` -------------------------------- ### Match Nodes Containing a Pattern with Grit `contains` Operator Source: https://docs.grit.io/language/modifiers The `contains` operator in Grit modifies a pattern to match any node that contains a specific sub-pattern by traversing downwards through the syntax tree. This allows for flexible matching based on the presence of a particular element within a larger structure. This example shows how to find functions whose arguments contain the variable `x`. ```Grit `function ($args) { $body }` where { $args <: contains `x` } ``` -------------------------------- ### Apply Grit Pattern from Stdin with JavaScript Source: https://docs.grit.io/cli/reference Demonstrates how to pipe JavaScript code to `grit apply` via `stdin` and transform it using a Grit pattern, printing the output to `stdout`. This requires specifying a file path to allow Grit to determine the language of the code. ```Shell echo 'console.log(hello)' | grit apply '`hello`=>`goodbye`' file.js --stdin ```