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

Add support for template codemods #81

Merged
merged 7 commits into from
Jul 15, 2020
Merged
Show file tree
Hide file tree
Changes from 6 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
114 changes: 106 additions & 8 deletions commands/local/generate/codemod.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,19 @@ module.exports.command = 'codemod <codemod-name>';
module.exports.desc = 'Generate a new codemod file';

module.exports.builder = function builder(yargs) {
yargs.positional('codemod-name', {
describe: 'the name of the codemod to generate',
});
yargs
.positional('codemod-name', {
describe: 'the name of the codemod to generate',
})
.option('type', {
alias: 't',
describe: 'choose the transform type',
choices: ['js', 'hbs'],
default: 'js',
});
};

module.exports.handler = function handler(options) {
function jsHandler(options) {
const fs = require('fs-extra');
const { stripIndent } = require('common-tags');
const importCwd = require('import-cwd');
Expand Down Expand Up @@ -36,7 +43,9 @@ module.exports.handler = function handler(options) {
.join('');
})
.toSource();
}
};

module.exports.type = 'js';
`,
'utf8'
);
Expand All @@ -47,8 +56,7 @@ module.exports.handler = function handler(options) {

const { runTransformTest } = require('codemod-cli');

runTransformTest({
type: 'jscodeshift',
runTransformTest({
name: '${codemodName}',
});
`,
Expand Down Expand Up @@ -86,5 +94,95 @@ module.exports.handler = function handler(options) {
'utf8'
);

generateFixture({ codemodName, fixtureName: 'basic' });
generateFixture({ codemodName, fixtureName: 'basic', type: options.type });
}

function hbsHandler(options) {
const fs = require('fs-extra');
const { stripIndent } = require('common-tags');
const importCwd = require('import-cwd');
const generateFixture = require('./fixture').handler;

let { codemodName } = options;
let projectName = importCwd('./package.json').name;
let codemodDir = `${process.cwd()}/transforms/${codemodName}`;

fs.outputFileSync(
`${codemodDir}/index.js`,
stripIndent`
module.exports = function ({ source /*, path*/ }, { parse, visit }) {
const ast = parse(source);

return visit(ast, (env) => {
let { builders: b } = env.syntax;

return {
MustacheStatement() {
return b.mustache(b.path('wat-wat'));
},
};
});
};

module.exports.type = 'hbs';
`,
'utf8'
);
fs.outputFileSync(
`${codemodDir}/test.js`,
stripIndent`
'use strict';

const { runTransformTest } = require('codemod-cli');

runTransformTest({
name: '${codemodName}',
});
`,
'utf8'
);
fs.outputFileSync(
`${codemodDir}/README.md`,
stripIndent`
# ${codemodName}\n

## Usage

\`\`\`
npx ${projectName} ${codemodName} path/of/files/ or/some**/*glob.hbs

# or

yarn global add ${projectName}
${projectName} ${codemodName} path/of/files/ or/some**/*glob.hbs
\`\`\`

## Local Usage
\`\`\`
node ./bin/cli.js ${codemodName} path/of/files/ or/some**/*glob.hbs
\`\`\`

## Input / Output

<!--FIXTURES_TOC_START-->
<!--FIXTURES_TOC_END-->

<!--FIXTURES_CONTENT_START-->
<!--FIXTURES_CONTENT_END-->
`,
'utf8'
);

generateFixture({ codemodName, fixtureName: 'basic', type: options.type });
}

module.exports.handler = function handler(options) {
switch (options.type) {
case 'js':
return jsHandler(options);
case 'hbs':
return hbsHandler(options);
default:
throw new Error(`Unknown type: "${options.type}"`);
}
};
8 changes: 6 additions & 2 deletions commands/local/generate/fixture.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,15 @@ module.exports.builder = function builder(yargs) {

module.exports.handler = function handler(options) {
const fs = require('fs-extra');
const { getTransformType } = require('../../../src/transform-support');

let { codemodName, fixtureName } = options;
let codemodDir = `${process.cwd()}/transforms/${codemodName}`;
let codemodTransform = `${codemodDir}/index.js`;
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we need to add index.js here? I wonder if we can basically just let it fall through via the require that is done down in getTransformType (since require(codemodDir) and require(codemodDir + '/index.js') are effectively the same thing)? That would allow folks to use other extensions (for example .ts)...

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done

let fixturePath = `${codemodDir}/__testfixtures__/${fixtureName}`;

fs.outputFileSync(`${fixturePath}.input.js`, '');
fs.outputFileSync(`${fixturePath}.output.js`, '');
let transformType = getTransformType(codemodTransform);

fs.outputFileSync(`${fixturePath}.input.${transformType}`, '');
fs.outputFileSync(`${fixturePath}.output.${transformType}`, '');
};
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
"@babel/parser": "^7.6.0",
"chalk": "^2.4.2",
"common-tags": "^1.8.0",
"ember-template-recast": "^4.1.4",
"execa": "^2.0.4",
"fs-extra": "^8.1.0",
"globby": "^10.0.1",
Expand Down
54 changes: 51 additions & 3 deletions src/bin-support.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,14 @@
'use strict';

const DEFAULT_EXTENSIONS = 'js,ts';
const DEFAULT_JS_EXTENSIONS = 'js,ts';

async function runTransform(binRoot, transformName, args, extensions = DEFAULT_EXTENSIONS) {
function getTransformPath(binRoot, transformName) {
const path = require('path');

return path.join(binRoot, '..', 'transforms', transformName, 'index.js');
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we do require.resolve(path.join(binRoot, '..', 'transforms', transformName))?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done

}

async function runJsTransform(binRoot, transformName, args, extensions = DEFAULT_JS_EXTENSIONS) {
const globby = require('globby');
const execa = require('execa');
const chalk = require('chalk');
Expand All @@ -15,7 +21,7 @@ async function runTransform(binRoot, transformName, args, extensions = DEFAULT_E
let foundPaths = await globby(paths, {
expandDirectories: { extensions: extensions.split(',') },
});
let transformPath = path.join(binRoot, '..', 'transforms', transformName, 'index.js');
let transformPath = getTransformPath(binRoot, transformName);

let jscodeshiftPkg = require('jscodeshift/package');
let jscodeshiftPath = path.dirname(require.resolve('jscodeshift/package'));
Expand All @@ -37,6 +43,48 @@ async function runTransform(binRoot, transformName, args, extensions = DEFAULT_E
}
}

async function runTemplateTransform(binRoot, transformName, args) {
const execa = require('execa');
const chalk = require('chalk');
const { parseTransformArgs } = require('./options-support');

let { paths, options } = parseTransformArgs(args);

try {
let transformPath = getTransformPath(binRoot, transformName);
let binOptions = ['-t', transformPath, ...paths];

return execa('ember-template-recast', binOptions, {
stdio: 'inherit',
preferLocal: true,
env: {
CODEMOD_CLI_ARGS: JSON.stringify(options),
},
});
} catch (error) {
console.error(chalk.red(error.stack)); // eslint-disable-line no-console
process.exitCode = 1;

throw error;
}
}

async function runTransform(binRoot, transformName, args, extensions) {
const { getTransformType } = require('./transform-support');

let transformPath = getTransformPath(binRoot, transformName);
let type = getTransformType(transformPath);

switch (type) {
case 'js':
return runJsTransform(binRoot, transformName, args, extensions);
case 'hbs':
return runTemplateTransform(binRoot, transformName, args);
default:
throw new Error(`Unknown type passed to runTransform: "${type}"`);
}
}

module.exports = {
runTransform,
};
80 changes: 10 additions & 70 deletions src/test-support.js
Original file line number Diff line number Diff line change
@@ -1,79 +1,19 @@
'use strict';

/* global it, describe, beforeEach, afterEach */
const jscodeshiftTest = require('./test-support/jscodeshift');
const templateTest = require('./test-support/template');
const { transformDetails } = require('./test-support/utils');

const { runInlineTest } = require('jscodeshift/dist/testUtils');
const fs = require('fs-extra');
const path = require('path');
const globby = require('globby');

function transformDetails(options) {
let root = process.cwd() + `/transforms/${options.name}/`;

return {
name: options.name,
root,
transformPath: root + 'index',
fixtureDir: root + '__testfixtures__/',
};
}

function jscodeshiftTest(options) {
function runTransformTest(options) {
let details = transformDetails(options);

let transform = require(details.transformPath);

describe(details.name, function() {
globby
.sync('**/*.input.*', {
cwd: details.fixtureDir,
absolute: true,
})
.map(entry => entry.slice(entry.indexOf('__testfixtures__') + '__testfixtures__'.length + 1))
.forEach(filename => {
let extension = path.extname(filename);
let testName = filename.replace(`.input${extension}`, '');
let testInputPath = path.join(details.fixtureDir, `${testName}${extension}`);
let inputPath = path.join(details.fixtureDir, `${testName}.input${extension}`);
let outputPath = path.join(details.fixtureDir, `${testName}.output${extension}`);
let optionsPath = path.join(details.fixtureDir, `${testName}.options.json`);
let options = fs.pathExistsSync(optionsPath) ? fs.readFileSync(optionsPath) : '{}';

describe(testName, function() {
beforeEach(function() {
process.env.CODEMOD_CLI_ARGS = options;
});

afterEach(function() {
process.env.CODEMOD_CLI_ARGS = '';
});

it('transforms correctly', function() {
runInlineTest(
transform,
{},
{ path: testInputPath, source: fs.readFileSync(inputPath, 'utf8') },
fs.readFileSync(outputPath, 'utf8')
);
});

it('is idempotent', function() {
runInlineTest(
transform,
{},
{ path: testInputPath, source: fs.readFileSync(outputPath, 'utf8') },
fs.readFileSync(outputPath, 'utf8')
);
});
});
});
});
}

function runTransformTest(options) {
switch (options.type) {
case 'jscodeshift':
switch (details.transformType) {
case 'js':
return jscodeshiftTest(options);
case 'hbs':
return templateTest(options);
default:
throw new Error(`Unknown type of transform: "${details.transformType}"`);
}
}

Expand Down
61 changes: 61 additions & 0 deletions src/test-support/jscodeshift.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
'use strict';

/* global it, describe, beforeEach, afterEach */

const { runInlineTest } = require('jscodeshift/dist/testUtils');
const fs = require('fs-extra');
const path = require('path');
const globby = require('globby');
const { transformDetails } = require('./utils');

module.exports = function jscodeshiftTest(options) {
let details = transformDetails(options);

let transform = require(details.transformPath);

describe(details.name, function() {
globby
.sync('**/*.input.*', {
cwd: details.fixtureDir,
absolute: true,
})
.map(entry => entry.slice(entry.indexOf('__testfixtures__') + '__testfixtures__'.length + 1))
.forEach(filename => {
let extension = path.extname(filename);
let testName = filename.replace(`.input${extension}`, '');
let testInputPath = path.join(details.fixtureDir, `${testName}${extension}`);
let inputPath = path.join(details.fixtureDir, `${testName}.input${extension}`);
let outputPath = path.join(details.fixtureDir, `${testName}.output${extension}`);
let optionsPath = path.join(details.fixtureDir, `${testName}.options.json`);
let options = fs.pathExistsSync(optionsPath) ? fs.readFileSync(optionsPath) : '{}';

describe(testName, function() {
beforeEach(function() {
process.env.CODEMOD_CLI_ARGS = options;
});

afterEach(function() {
process.env.CODEMOD_CLI_ARGS = '';
});

it('transforms correctly', function() {
runInlineTest(
transform,
{},
{ path: testInputPath, source: fs.readFileSync(inputPath, 'utf8') },
fs.readFileSync(outputPath, 'utf8')
);
});

it('is idempotent', function() {
runInlineTest(
transform,
{},
{ path: testInputPath, source: fs.readFileSync(outputPath, 'utf8') },
fs.readFileSync(outputPath, 'utf8')
);
});
});
});
});
};
Loading