Skip to content

feat(@codemod-com/codemod-standalone): explore nodejs compat module #1609

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
first draft
  • Loading branch information
AugustinMauroy committed Jul 14, 2025
commit fe9d7b8c0f2f43a1bd3c5cc75cd7e4c6bf956a04
41 changes: 41 additions & 0 deletions packages/codemod-standalone/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
# Codemod Standalone

## Usage

```ts
import { registerCodemod } from "@codemod-com/codemod-standalone";
import type { SgRoot } from "@ast-grep/napi";

// Work with `npx codemod@next`
export default async function transform(root: SgRoot): Promise<string> {
const rootNode = root.root();

const nodes = rootNode.findAll({
rule: {
any: [
{ pattern: "console.log($ARG)" },
{ pattern: "console.debug($ARG)" },
]
},
});

const edits = nodes.map(node => {
const arg = node.getMatch("ARG").text();
return node.replace(`logger.log(${arg})`);
});

const newSource = rootNode.commitEdits(edits);
return newSource;
}

// Register the codemod to use as `node src/transform.ts`
registerCodemod(transform, {
language: 'typescript',
});
```

## Command Line Usage

```bash
node src/transform.ts --input <glob> --exclude <glob>
```
19 changes: 19 additions & 0 deletions packages/codemod-standalone/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"name": "@codemod-com/codemod-standalone",
"author": "Augustin Mauroy",
"version": "0.0.1",
"description": "The utilities used across Codemod.com packages",
"type": "module",
"main": "./dist/index.js",
"module": "./dist/index.js",
"types": "./dist/index.d.ts",
"files": ["./dist", "README.md", "tsconfig.json"],
"scripts": {
"build": "tsc"
},
"license": "Apache-2.0",
"devDependencies": {
"@types/node": "^24.0.0",
"@codemod-com/tsconfig": "workspace:*"
}
}
85 changes: 85 additions & 0 deletions packages/codemod-standalone/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
import fs from "node:fs";
import path from "node:path";
import { parseArgs } from "node:util";
import { isPromise } from "node:util/types";
import { isMainThread } from "node:worker_threads";
import { Lang, parse } from "@ast-grep/napi";
import type { SgRoot } from "@ast-grep/napi";

/**
* Default patterns to exclude from processing.
* These patterns typically include directories like node_modules and .git.
*/
const DEFAULT_EXCLUDE = ["**/node_modules/**", "**/.git/**"];

/**
* Register a codemod transformation.
* This function is intended to be called in the main thread.
* It processes files or directories specified in the command line arguments,
* applies the provided transformation function to the AST of each file,
* and writes the transformed content back to the file.
*
* @param transform Function to transform the AST root.
* It can either return a string or a Promise that resolves to a string.
* @param language
* The programming language of the files to be processed.
*/
export function registerCodemod(
transform: ((root: SgRoot) => Promise<string>) | ((root: SgRoot) => string),
language: string,
) {
if (!isMainThread) return; // break the function if not in the main thread

const astGrepLang = Lang[language as keyof typeof Lang];

if (!astGrepLang) throw new Error(`Unsupported language: ${language}`);

const { values } = parseArgs({
args: process.argv.slice(2),
options: {
// what should we process
input: {
type: "string",
},
// what should we exclude
exclude: {
type: "string",
},
},
allowPositionals: true,
});

if (!values.input)
throw new Error("Input file or directory path is required.");

const files = fs.globSync(values.input, {
exclude: values.exclude ? [values.exclude] : DEFAULT_EXCLUDE,
});

for (const file of files) {
const filePath = path.resolve(file);

if (!fs.existsSync(filePath)) {
console.error(`File not found: ${filePath}`);
continue;
}

const content = fs.readFileSync(filePath, "utf-8");
const root = parse(astGrepLang, content);
const result = transform(root);

if (isPromise(result)) {
result
.then((transformedContent) => {
fs.writeFileSync(filePath, transformedContent, "utf-8");
console.log(`Processed file: ${filePath}`);
})
.catch((err) => {
console.error(`Error processing file ${filePath}:`, err);
});
} else {
fs.writeFileSync(filePath, result, "utf-8");
console.log(`Processed file: ${filePath}`);
}
}
}
7 changes: 7 additions & 0 deletions packages/codemod-standalone/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"extends": "@codemod-com/tsconfig/lib.json",
"compilerOptions": {
"baseUrl": "./src",
"outDir": "./dist"
}
}
Loading
Loading
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy