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

Feature: Use listr to display progress and errors for transformations #92

Merged
merged 6 commits into from
Mar 24, 2017
Merged
Show file tree
Hide file tree
Changes from 3 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
84 changes: 57 additions & 27 deletions lib/migrate.js
Original file line number Diff line number Diff line change
@@ -1,36 +1,66 @@
const fs = require('fs');
const diff = require('diff');
const chalk = require('chalk');
const transform = require('./transformations').transform;
const jscodeshift = require('jscodeshift');
const transformations = require('./transformations').transformations;
const inquirer = require('inquirer');
const Listr = require('listr');

module.exports = (currentConfigPath, outputConfigPath) => {
const migrateTasks = function(ast) {
return Object.keys(transformations).map(key => {
const transform = transformations[key];
return {
title: key,
task: () => transform(ast)
};
});
};

module.exports = function tranformFile(currentConfigPath, outputConfigPath, options) {
const recastOptions = Object.assign({
quote: 'single'
}, options);
let currentConfig = fs.readFileSync(currentConfigPath, 'utf8');
const outputConfig = transform(currentConfig);
const diffOutput = diff.diffLines(currentConfig, outputConfig);
diffOutput.map(diffLine => {
if (diffLine.added) {
process.stdout.write(chalk.green(`+ ${diffLine.value}`));
} else if (diffLine.removed) {
process.stdout.write(chalk.red(`- ${diffLine.value}`));
const ast = jscodeshift(currentConfig);
const tasks = new Listr([
{
title: 'Migrating config from v1 to v2',
task: () => new Listr(migrateTasks(ast))
}
});
inquirer
.prompt([
{
type: 'confirm',
name: 'confirmMigration',
message: 'Are you sure these changes are fine?',
default: 'Y'
}
])
.then(answers => {
if (answers['confirmMigration']) {
// TODO validate the config
fs.writeFileSync(outputConfigPath, outputConfig, 'utf8');
process.stdout.write(chalk.green(`Congratulations! Your new webpack v2 config file is at ${outputConfigPath}`));
} else {
process.stdout.write(chalk.yellow('Migration aborted'));
}
]);

tasks.run()
.then(() => {
const outputConfig = ast.toSource(recastOptions);
const diffOutput = diff.diffLines(currentConfig, outputConfig);
diffOutput.map(diffLine => {
if (diffLine.added) {
process.stdout.write(chalk.green(`+ ${diffLine.value}`));
} else if (diffLine.removed) {
process.stdout.write(chalk.red(`- ${diffLine.value}`));
}
});
inquirer
.prompt([
{
type: 'confirm',
name: 'confirmMigration',
message: 'Are you sure these changes are fine?',
default: 'Y'
}
])
.then(answers => {
if (answers['confirmMigration']) {
// TODO validate the config
fs.writeFileSync(outputConfigPath, outputConfig, 'utf8');
process.stdout.write(chalk.green(`✔︎ New webpack v2 config file is at ${outputConfigPath}`));
} else {
process.stdout.write(chalk.red('✖ Migration aborted'));
}
});
})
.catch(err => {
console.error(chalk.red('✖ ︎Migration aborted due to some errors'));
console.error(err);
});
};
81 changes: 81 additions & 0 deletions lib/transformations/__testfixtures__/failing.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
var webpack = require('webpack');
var nodeEnvironment = process.env.NODE_ENV
var _ = require('lodash');

var config = {
entry: {
'lib': './app/index.js',
'email': './app/email.js'
},
plugins: [
new webpack.DefinePlugin({
'INCLUDE_ALL_MODULES': function includeAllModulesGlobalFn(modulesArray, application) {
modulesArray.forEach(function executeModuleIncludesFn(moduleFn) {
moduleFn(application);
});
},
ENVIRONMENT: JSON.stringify(nodeEnvironment)
})
],
output: {
path: __dirname + '/app',
filename: 'bundle.js'
},
resolve: {
root: __dirname + '/app'
},
module: {
// preLoaders: [
// { test: /\.js?$/, loader: 'eslint', exclude: /node_modules/ }
// ],
loaders: [
{ test: /\.js$/, exclude: /(node_modules)/, loader: 'babel' },
{ test: /\.html/, exclude: [/(node_modules)/, /src\/index\.html/], loader: 'html-loader' },
{ test: /\.s?css$/, loader: 'style!css!sass' },
{ test: /\.(png|jpg)$/, loader: 'url-loader?mimetype=image/png' }
]
},
// extra configuration options.
// eslint: {
// configFile: '.eslintrc.js'
// }
}

switch (nodeEnvironment) {
case 'production':
config.plugins.push(new webpack.optimize.UglifyJsPlugin());
case 'preproduction':
config.output.path = __dirname + '/dist';
config.plugins.push(new webpack.optimize.DedupePlugin());
config.plugins.push(new webpack.optimize.OccurenceOrderPlugin());

config.output.filename = '[name].js';

config.entry = {
'lib': ['./app/index.js', 'angular', 'lodash'],
'email': ['./app/email.js', 'angular']
};

config.devtool = 'source-map';
config.output.libraryTarget = 'commonjs2';

break;

case 'test':
config.entry = './index.js';
break;

case 'development':
config.entry = {
'lib': ['./app/index.js', 'webpack/hot/dev-server'],
'email': ['./app/email.js', 'webpack/hot/dev-server']
};
config.output.filename = '[name].js';
config.devtool = 'source-map';
break;

default:
console.warn('Unknown or Undefined Node Environment. Please refer to package.json for available build commands.');
}

module.exports = config;
8 changes: 4 additions & 4 deletions lib/transformations/defineTest.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ const path = require('path');
* - Test data should be located in a directory called __testfixtures__
* alongside the transform and __tests__ directory.
*/
function runTest(dirName, transformName, testFilePrefix) {
function runSingleTansform(dirName, transformName, testFilePrefix) {
if (!testFilePrefix) {
testFilePrefix = transformName;
}
Expand All @@ -53,8 +53,7 @@ function runTest(dirName, transformName, testFilePrefix) {
jscodeshift = jscodeshift.withParser(module.parser);
}
const ast = jscodeshift(source);
const output = transform(jscodeshift, ast).toSource({ quote: 'single' });
expect(output).toMatchSnapshot();
return transform(jscodeshift, ast).toSource({ quote: 'single' });
}

/**
Expand All @@ -67,7 +66,8 @@ function defineTest(dirName, transformName, testFilePrefix) {
: 'transforms correctly';
describe(transformName, () => {
it(testName, () => {
runTest(dirName, transformName, testFilePrefix);
const output = runSingleTansform(dirName, transformName, testFilePrefix);
expect(output).toMatchSnapshot();
});
});
}
Expand Down
50 changes: 37 additions & 13 deletions lib/transformations/index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
const jscodeshift = require('jscodeshift');
const pEachSeries = require('p-each-series');

const loadersTransform = require('./loaders/loaders');
const resolveTransform = require('./resolve/resolve');
Expand All @@ -9,7 +10,7 @@ const bannerPluginTransform = require('./bannerPlugin/bannerPlugin');
const extractTextPluginTransform = require('./extractTextPlugin/extractTextPlugin');
const removeDeprecatedPluginsTransform = require('./removeDeprecatedPlugins/removeDeprecatedPlugins');

const transformations = {
const transformsObject = {
loadersTransform,
resolveTransform,
removeJsonLoaderTransform,
Expand All @@ -20,28 +21,51 @@ const transformations = {
removeDeprecatedPluginsTransform
};

const transformations = Object.keys(transformsObject).reduce((res, key) => {
res[key] = (ast) => transformSingleAST(ast, transformsObject[key]);
return res;
}, {});

function transformSingleAST(ast, transformFunction) {
return new Promise((resolve, reject) => {
setTimeout(() => {
try {
resolve(transformFunction(jscodeshift, ast));
} catch (err) {
reject(err);
}
}, 0);
});
}

/*
* @function transform
*
* Tranforms a given source code by applying selected transformations to the AST
*
* @param { String } source - Source file contents
* @param { Array<Function> } transformations - List of trnasformation functions in defined the
* order to apply. By default all defined transfomations.
* @param { Object } options - Reacst formatting options
* @returns { String } Transformed source code
* */
* @function transform
*
* Tranforms a given source code by applying selected transformations to the AST
*
* @param { String } source - Source file contents
* @param { Array<Function> } transformations - List of trnasformation functions in defined the
* order to apply. By default all defined transfomations.
* @param { Object } options - Reacst formatting options
* @returns { String } Transformed source code
* */
function transform(source, transforms, options) {
const ast = jscodeshift(source);
const recastOptions = Object.assign({
quote: 'single'
}, options);
transforms = transforms || Object.keys(transformations).map(k => transformations[k]);
transforms.forEach(f => f(jscodeshift, ast));
return ast.toSource(recastOptions);
return pEachSeries(transforms, f => f(ast))
.then(() => {
return ast.toSource(recastOptions);
})
.catch(err => {
console.error(err);
});
}

module.exports = {
transform,
transformSingleAST,
transformations
};
32 changes: 20 additions & 12 deletions lib/transformations/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,26 +31,34 @@ module.exports = {
`;

describe('transform', () => {
it('should not transform if no transformations defined', () => {
const output = transform(input, []);
expect(output).toEqual(input);
it('should not transform if no transformations defined', (done) => {
transform(input, []).then(output => {
expect(output).toEqual(input);
done();
});
});

it('should transform using all transformations', () => {
const output = transform(input);
expect(output).toMatchSnapshot();
it('should transform using all transformations', (done) => {
transform(input).then(output => {
expect(output).toMatchSnapshot();
done();
});
});

it('should transform only using specified transformations', () => {
const output = transform(input, [transformations.loadersTransform]);
expect(output).toMatchSnapshot();
it('should transform only using specified transformations', (done) => {
transform(input, [transformations.loadersTransform]).then(output => {
expect(output).toMatchSnapshot();
done();
});
});

it('should respect recast options', () => {
const output = transform(input, undefined, {
it('should respect recast options', (done) => {
transform(input, undefined, {
quote: 'double',
trailingComma: true
}).then(output => {
expect(output).toMatchSnapshot();
done();
});
expect(output).toMatchSnapshot();
});
});
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,10 @@
"inquirer": "^2.0.0",
"interpret": "^1.0.1",
"jscodeshift": "^0.3.30",
"listr": "^0.11.0",
"loader-utils": "^0.2.16",
"lodash": "^4.17.4",
"p-each-series": "^1.0.0",
"recast": "git://github.com/kalcifer/recast.git#bug/allowbreak",
"rx": "^4.1.0",
"supports-color": "^3.1.2",
Expand Down