Skip to content
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

cli #9

Merged
merged 8 commits into from
Dec 1, 2019
Merged
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
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -29,3 +29,5 @@ yarn.lock
package-lock.json
coverage/
.doc

cli_fixtures/
9 changes: 9 additions & 0 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,15 @@
"windows": {
"program": "${workspaceFolder}/node_modules/jest/bin/jest"
}
},
{
"type": "node",
"request": "launch",
"name": "Launch cli",
"program": "${workspaceFolder}/bin/antd-codemod.js",
"cwd": "${workspaceFolder}/lib",
"args": ["run", "--path", "*.js"],
"skipFiles": ["<node_internals>/**"]
}
]
}
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,14 @@ npx jscodeshift -t antd-codemod/transforms/v3-Icon-to-v4-Icon.js src/**/*.js --p
npx jscodeshift -t antd-codemod/transforms/v3-Component-to-compatible.js src/**/*.js --parser=babylon # for Form and Mention
npx jscodeshift -t antd-codemod/transforms/v3-LocaleProvider-to-v4-ConfigProvider.js src/**/*.js --parser=babylon
npx jscodeshift -t antd-codemod/transforms/v4-Icon-Outlined.js src/**/*.js --parser=babylon

node bin/antd-codemod.js run --path=es/*.js
```

## Development

```shell
npx jscodeshift -t transforms/v3-Icon-to-v4-Icon.js cli_fixtures --parser=babylon
```

**tips**
Expand Down
123 changes: 112 additions & 11 deletions bin/antd-codemod.js
Original file line number Diff line number Diff line change
@@ -1,21 +1,122 @@
const minimist = require('minimist');
const path = require('path');
const program = require('commander');
const isGitClean = require('is-git-clean');
const chalk = require('chalk');
const execa = require('execa');
const globby = require('globby');
const updateCheck = require('update-check');

const jscodeshiftBin = require.resolve('.bin/jscodeshift');
const pkg = require('../package.json');

const transformersDir = path.join(__dirname, '../', 'transforms');

const transformers = [
'v4-Icon-Outlined',
'v3-Icon-to-v4-Icon',
'v3-Modal-method-with-icon-to-v4',
'v3-component-with-string-icon-props-to-v4',
'v3-Component-to-compatible',
'v3-LocaleProvider-to-v4-ConfigProvider',
];

program.version(`${pkg.name} ${pkg.version}`).usage('<command> [options]');

program
.command('form <path>')
.command('run')
.description('antd codemod for antd v4 Form migration')
.action((path, cmd) => {
console.log(name, cmd);
});

program
.command('icon <path>')
.description('antd codemod for antd v4 Icon migration')
.action((path, cmd) => {
console.log(name, cmd);
.requiredOption('-p, --path <path>', 'The file path to transform')
.option('--parser', 'parser option to jscodeshift')
.option('-s, --style', 'Inject style from @ant-design/compatible')
.action(async cmd => {
if (process.env.NODE_ENV !== 'local') {
// check for updates
await checkUpdates();
// check for git status
await ensureGitClean();
}
// check for `path`
if (!cmd.path) {
console.log(chalk.yellow('You need to pass a `path` option'));
process.exit(1);
}
run(cmd);
});

program.parse(process.argv);

async function checkUpdates() {
let update;
try {
update = await updateCheck(pkg);
} catch (err) {
console.log(chalk.yellow(`Failed to check for updates: ${err}`));
}

if (update) {
console.log(
chalk.blue(`Latest version is ${update.latest}. Please update firstly`),
);
process.exit(1);
}
}

function getRunnerArgs(filePath, transformerPath, parserOption) {
const args = ['--verbose=2', '--ignore-pattern=**/node_modules/**'];

const extname = path.extname(filePath);
// use bablyon as default parser
// will you use Flow?
let parser = parserOption;
if (!parser && ['.tsx', '.ts'].includes(extname)) {
parser = 'tsx';
} else {
parser = 'babel';
}
args.push('--parser', parser);

if (parser === 'tsx') {
args.push('--extensions=tsx,ts,jsx,js');
} else {
args.push('--extensions=jsx,js');
}

args.push('--transform', transformerPath);
return args;
}

async function run(command) {
const { path: filePath, parser } = command;
const paths = await globby([filePath]);

for (const transformer of transformers) {
const transformerPath = path.join(transformersDir, `${transformer}.js`);
console.log(chalk.bgGreen.bold('Transform'), transformer);
const args = getRunnerArgs(filePath, transformerPath, parser);
try {
await execa(jscodeshiftBin, [...args, ...paths], {
stdio: 'inherit',
stripEof: false,
});
} catch (err) {
console.error(err);
}
}
}

async function ensureGitClean() {
let clean = false;
try {
clean = await isGitClean();
} catch (err) {
if (err && err.stderr && err.stderr.includes('Not a git repository')) {
clean = true;
}
}

if (!clean) {
console.log(chalk.yellow('Sorry that there are still some git changes'));
console.log('\n you must commit or stash them firstly');
process.exit(1);
}
}
7 changes: 6 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,14 @@
"dependencies": {
"@ant-design/compatible": "^0.0.1-alpha.5",
"@ant-design/icons": "^4.0.0-alpha.11",
"chalk": "^3.0.0",
"commander": "^4.0.1",
"execa": "^3.4.0",
"globby": "^10.0.1",
"is-git-clean": "^1.1.0",
"jscodeshift": "^0.6.4",
"rc-util": "^4.15.7"
"rc-util": "^4.15.7",
"update-check": "^1.5.3"
},
"devDependencies": {
"@umijs/fabric": "^1.1.10",
Expand Down
2 changes: 1 addition & 1 deletion transforms/__tests__/v3-Icon-to-v4-Icon.test.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const tests = ['basic', 'icon-static-methods'];
const tests = ['basic', 'icon-static-methods', 'misc'].slice(0, 1);

const defineTest = require('jscodeshift/dist/testUtils').defineTest;

Expand Down
105 changes: 57 additions & 48 deletions transforms/utils/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,16 +37,22 @@ function hasModuleImport(j, root, moduleName) {
}

function hasModuleDefaultImport(j, root, pkgName, localModuleName) {
return (
root
.find(j.ImportDeclaration, {
source: { value: pkgName },
})
.find(j.ImportDefaultSpecifier, {
name: localModuleName,
})
.size() > 1
);
let found = false;
root
.find(j.ImportDeclaration, {
source: { value: pkgName },
})
.forEach(nodePath => {
const defaultImport = nodePath.node.specifiers.filter(
n =>
n.type === 'ImportDefaultSpecifier' &&
n.local.name === localModuleName,
);
if (defaultImport.length) {
found = true;
}
});
return found;
}

function findImportAfterModule(j, root, moduleName) {
Expand Down Expand Up @@ -79,41 +85,7 @@ function useVar(j, root) {
return root.find(j.VariableDeclaration, { kind: 'const' }).length === 0;
}

function addModuleDefaultImport(j, root, pkgName, localModuleName) {
if (hasModuleDefaultImport(j, root, pkgName, localModuleName)) {
return;
}

const path = findImportAfterModule(j, root, pkgName);
if (path) {
const importStatement = j.importDeclaration(
[j.importDefaultSpecifier(j.identifier(localModuleName))],
j.literal(pkgName),
);

insertImportStatement(j, root, path, importStatement);
return;
}

throw new Error(`No ${pkgName} import found!`);
}

function addSubmoduleImport(
j,
root,
pkgName,
importedModuleName,
localModuleName,
) {
if (hasSubmoduleImport(j, root, pkgName, importedModuleName)) {
return;
}

const newImportSpecifier = j.importSpecifier(
j.identifier(importedModuleName),
localModuleName ? j.identifier(localModuleName) : null,
);

function addModuleImport(j, root, pkgName, importSpecifier) {
// if has module imported, just import new submodule from existed
// else just create a new import
if (hasModuleImport(j, root, pkgName)) {
Expand All @@ -124,7 +96,7 @@ function addSubmoduleImport(
.at(0)
.replaceWith(({ node }) => {
const mergedImportSpecifiers = node.specifiers
.concat(newImportSpecifier)
.concat(importSpecifier)
.sort((a, b) => {
if (a.type === 'ImportDefaultSpecifier') {
return -1;
Expand All @@ -138,17 +110,54 @@ function addSubmoduleImport(
});
return j.importDeclaration(mergedImportSpecifiers, j.literal(pkgName));
});
return;
return true;
}

const path = findImportAfterModule(j, root, pkgName);
if (path) {
const importStatement = j.importDeclaration(
[newImportSpecifier],
[importSpecifier],
j.literal(pkgName),
);

insertImportStatement(j, root, path, importStatement);
return true;
}
}

function addModuleDefaultImport(j, root, pkgName, localModuleName) {
if (hasModuleDefaultImport(j, root, pkgName, localModuleName)) {
return;
}

const newDefaultImportSpecifier = j.importDefaultSpecifier(
j.identifier(localModuleName),
);

if (addModuleImport(j, root, pkgName, newDefaultImportSpecifier)) {
return;
}

throw new Error(`No ${pkgName} import found!`);
}

function addSubmoduleImport(
j,
root,
pkgName,
importedModuleName,
localModuleName,
) {
if (hasSubmoduleImport(j, root, pkgName, importedModuleName)) {
return;
}

const newImportSpecifier = j.importSpecifier(
j.identifier(importedModuleName),
localModuleName ? j.identifier(localModuleName) : null,
);

if (addModuleImport(j, root, pkgName, newImportSpecifier)) {
return;
}

Expand Down
Loading