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 all commits
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
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ target/

# Testing
coverage/
coverage.lcov

# CLI package
apps/cli/package/
1 change: 1 addition & 0 deletions biome.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
"*.d.ts",
"*.js",
"dist",
"fixtures",
"cdmd_dist",
"build",
"pnpm-lock.yaml",
Expand Down
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`

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

## Command Line Usage

```bash
node src/transform.ts --input <glob> --exclude <glob>
```
21 changes: 21 additions & 0 deletions packages/codemod-standalone/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
{
"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",
"test": "node --experimental-strip-types --test tests/**/*.test.ts",
"test:coverage": "node --experimental-strip-types --experimental-test-coverage --test --test-reporter=lcov --test-reporter-destination=./coverage.lcov --test-reporter=spec --test-reporter-destination=stdout --test-coverage-include='src/**/*' tests/**/*.test.ts"
},
"license": "Apache-2.0",
"devDependencies": {
"@types/node": "^24.0.0",
"@codemod-com/tsconfig": "workspace:*"
}
}
85 changes: 85 additions & 0 deletions packages/codemod-standalone/src/mod.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,
});

if (files.length === 0) {
console.error("No files found to process.");
return;
}

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

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}`);
}
}
}
23 changes: 23 additions & 0 deletions packages/codemod-standalone/tests/fixtures/expected.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
function example() {
logger.log("Hello world");
logger.log("Debug message");
logger.log(42);
logger.log(variable);

// These should not be transformed
console.error("Error message");
console.warn("Warning");

// Nested cases
if (condition) {
logger.log("Nested log");
logger.log("Nested debug");
}
}

const data = {
value: 123
};

logger.log(data);
console.debug("Processing data:", data.value);
23 changes: 23 additions & 0 deletions packages/codemod-standalone/tests/fixtures/input.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
function example() {
console.log("Hello world");
console.log("Debug message");
console.log(42);
console.log(variable);

// These should not be transformed
console.error("Error message");
console.warn("Warning");

// Nested cases
if (condition) {
console.log("Nested log");
console.log("Nested debug");
}
}

const data = {
value: 123
};

console.log(data);
console.debug("Processing data:", data.value);
27 changes: 27 additions & 0 deletions packages/codemod-standalone/tests/fixtures/workflow-sync.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import type { SgRoot } from "@ast-grep/napi";
import { registerCodemod } from "../../src/mod.ts";

// Work with `npx codemod@next`
export default function transform(root: SgRoot): 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, "TypeScript");
10 changes: 10 additions & 0 deletions packages/codemod-standalone/tests/fixtures/workflow-with-error.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import type { SgRoot } from "@ast-grep/napi";
import { registerCodemod } from "../../src/mod.ts";

// Work with `npx codemod@next`
export default async function transform(root: SgRoot): Promise<string> {
if (true) throw new Error("This is a test error in the workflow codemod");
}

// Register the codemod to use as `node src/transform.ts`
registerCodemod(transform, "TypeScript");
27 changes: 27 additions & 0 deletions packages/codemod-standalone/tests/fixtures/workflow-wrong-lang.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import type { SgRoot } from "@ast-grep/napi";
import { registerCodemod } from "../../src/mod.ts";

// 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, "invalid-language");
27 changes: 27 additions & 0 deletions packages/codemod-standalone/tests/fixtures/workflow.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import type { SgRoot } from "@ast-grep/napi";
import { registerCodemod } from "../../src/mod.ts";

// 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, "TypeScript");
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