Skip to content

Commit

Permalink
WB-1660: Create wb-codemod package (#2171)
Browse files Browse the repository at this point in the history
## Summary:

This PR creates a new package `wb-codemod` that will be used to run code
migrations using codemods. The package is a wrapper around `jscodeshift` that
provides a CLI to run WB codemods from different packages/locations.

This will be useful now that Web Wonder Blocks is being actively used in the
main repo and in Perseus as well.

The goal/motivation is for anyone to run a particular codemod without having to
install jscodeshift or the codemod package itself locally.

```
npx @khanacademy/wb-codemod -t <transform-file-name> <path>
```

e.g.
```
npx @khanacademy/wb-codemod -t "template" src/
```

Issue: WB-1660

## Test plan:

Verify that unit tests pass and that the package can be used to run codemods.

If you want to run this locally while the package is not published yet, you can
use the following command:

```
cd wb-codemod
npx . -t "template" ../packages/wonder-blocks-button/
```
![Uploading Screenshot 2024-01-31 at 6.04.15 PM.png…]()

Author: jandrade

Reviewers: jeresig, jandrade

Required Reviewers:

Approved By: jeresig

Checks: ✅ codecov/project, ✅ Chromatic - Get results on regular PRs (ubuntu-latest, 20.x), ✅ Test (ubuntu-latest, 20.x, 2/2), ✅ Check build sizes (ubuntu-latest, 20.x), ✅ Test (ubuntu-latest, 20.x, 1/2), ✅ Lint (ubuntu-latest, 20.x), ✅ Chromatic - Build on regular PRs / chromatic (ubuntu-latest, 20.x), ✅ Publish npm snapshot (ubuntu-latest, 20.x), ✅ Prime node_modules cache for primary configuration (ubuntu-latest, 20.x), ⏭️  Chromatic - Skip on Release PR (changesets), ✅ Check for .changeset entries for all changed files (ubuntu-latest, 20.x), ✅ gerald, ⏭️  dependabot

Pull Request URL: #2171
  • Loading branch information
jandrade authored Feb 1, 2024
1 parent 0c32956 commit 95a4bb6
Show file tree
Hide file tree
Showing 9 changed files with 566 additions and 2 deletions.
5 changes: 5 additions & 0 deletions .changeset/smart-terms-own.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@khanacademy/wb-codemod": major
---

Create wb-codemod package to run code migrations
5 changes: 4 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@
"@testing-library/react-hooks": "^8.0.1",
"@testing-library/user-event": "^13.5.0",
"@types/jest": "29",
"@types/jscodeshift": "^0.11.11",
"@types/node": "^18.14.1",
"@types/react": "16",
"@types/react-dom": "16",
Expand Down Expand Up @@ -102,6 +103,7 @@
"jest-date-mock": "^1.0.8",
"jest-environment-jsdom": "^28.1.2",
"jest-extended": "^3.2.4",
"jscodeshift": "^0.15.1",
"npm-package-json-lint": "^6.4.0",
"prettier": "^2.8.1",
"react-refresh": "^0.14.0",
Expand Down Expand Up @@ -133,7 +135,8 @@
},
"workspaces": [
"packages/*",
"build-settings"
"build-settings",
"wb-codemod"
],
"resolutions": {
"@types/react": "16",
Expand Down
33 changes: 33 additions & 0 deletions wb-codemod/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
# @khanacademy/wb-codemod

This package is a wrapper around
[jscodeshift](https://github.com/facebook/jscodeshift/) to make it easier to
run Wonder Blocks codemods on the Khan Academy's codebase.

## Usage

To run a codemod, you can use the `wb-codemod` command line tool. For example:

```sh
npx @khanacademy/wb-codemod -t template path/to/files
```

This will run the `template` codemod on the files in `path/to/files`. This
`template` codemod is a file in the `transforms` directory of this package.

## Writing a codemod

To write a codemod, you can create a new file in the `transforms` directory of
this package. The file should export a function that takes a `file` argument, an
`api` argument, and an optional options argument.

You can take a look at the existing codemods in the `transforms/template.ts`
file for an example of how to write a codemod.

### Unit testing

To write unit tests for your codemod, you can create a new file in the
`transforms/__test__` directory of this package.

See https://github.com/facebook/jscodeshift?tab=readme-ov-file#unit-testing for
more information on how to write unit tests for your codemod.
51 changes: 51 additions & 0 deletions wb-codemod/bin/cli.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
#!/usr/bin/env -S node -r @swc-node/register
/* eslint-disable @typescript-eslint/no-var-requires */
/* eslint-disable import/no-commonjs */
const {parseArgs} = require("node:util");
const {run} = require("../src/wb-codemod");

const HELP_TEXT = `
Usage: wb-codemod [options] <files>
Options:
-t, --transform-file The path to the transform file to use.
-d, --dry-run Whether to run the codemod without making any changes.
-p, --print Whether to print the transformed code to stdout.
-h, --help Show this help message.
`;

const {
values: {help, transformFile, dryRun, print},
positionals: [files],
} = parseArgs({
options: {
transformFile: {
type: "string",
short: "t",
},
dryRun: {
type: "boolean",
short: "d",
},
print: {
type: "boolean",
short: "p",
},
help: {
type: "boolean",
short: "h",
},
},
allowPositionals: true,
});

if (help) {
// eslint-disable-next-line no-console
console.log(HELP_TEXT);
process.exit(0);
}

run(transformFile, [files], {
dryRun,
print,
});
13 changes: 13 additions & 0 deletions wb-codemod/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"name": "@khanacademy/wb-codemod",
"version": "0.1.0",
"license": "MIT",
"dependencies": {
"@swc-node/register": "^1.6.5",
"jscodeshift": "^0.15.1"
},
"devDependencies": {
"@types/jscodeshift": "^0.11.11"
},
"bin": "bin/cli.js"
}
60 changes: 60 additions & 0 deletions wb-codemod/src/wb-codemod.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
/* eslint-disable no-console */
import path from "path";
import chalk from "chalk";
import jscodeshift from "jscodeshift/src/Runner";

type RunOptions = {
/**
* Whether to dry run the codemod.
*
* If true, the codemod will not be applied in the files, but the
* transformed code will be printed.
*/
dryRun?: boolean;
/**
* Whether to print the output of the codemod.
*/
print?: boolean;
};

/**
* Runs jscodeshift on the given transform file (codemod) and file paths.
*/
export async function run(
transformFileName: string,
filePaths: Array<string>,
options: RunOptions,
) {
const jsCodemodsDir = path.resolve(__dirname, "../transforms");
// Transform path
const transformFile = path.join(jsCodemodsDir, transformFileName + ".ts");

console.log(
chalk.cyan(`Transforming ${transformFileName} in: ${filePaths}...`),
);

try {
const result = await jscodeshift.run(transformFile, filePaths, {
dry: options.dryRun || false,
print: options.print || false,
verbose: 2,
babel: true,
extensions: "js,jsx,ts,tsx",
parser: "tsx",
runInBand: !!options.dryRun,
silent: false,
ignorePattern: ["**/node_modules/**", "**/dist/**"],
// Allows to format the transformed code.
printOptions: {
objectCurlySpacing: false,
quote: "double",
trailingComma: true,
},
});

console.log(result);
} catch (e) {
console.error(e);
process.exit(1);
}
}
20 changes: 20 additions & 0 deletions wb-codemod/transforms/__tests__/template.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import transform from "../template";

// eslint-disable-next-line import/no-commonjs, @typescript-eslint/no-var-requires
const defineInlineTest = require("jscodeshift/dist/testUtils").defineInlineTest;

const transformOptions = {
printOptions: {
objectCurlySpacing: false,
},
};

describe("template", () => {
defineInlineTest(
transform,
transformOptions,
`const foo = true;`,
`const bar = true;`,
"should replace foo with bar",
);
});
19 changes: 19 additions & 0 deletions wb-codemod/transforms/template.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import {API, FileInfo, Options} from "jscodeshift";

/**
* Transforms:
* const foo = true;
*
* to:
* const bar = true;
*/
export default function transform(file: FileInfo, api: API, options: Options) {
const j = api.jscodeshift;
const root = j(file.source);

root.find(j.Identifier, {name: "foo"}).forEach((path) => {
j(path).replaceWith(j.identifier("bar"));
});

return root.toSource(options.printOptions);
}
Loading

0 comments on commit 95a4bb6

Please sign in to comment.