Created
October 26, 2016 21:15
-
-
Save mdebbar/741d4297ae1bd28efcc3fa05d4d6982a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // USAGE: | |
| // | |
| // This script is supposed to be used with `jscodeshift`. Here is how you would invoke it: | |
| // $ jscodeshift -t add-unit-true-to-ember-tests.js --fn=moduleForComponent path/to/unit/tests/ | |
| // | |
| // The `--fn` argument above can be changed to `moduleFor`, `moduleForModel`, etc. | |
| module.exports = function transform(file, api, options) { | |
| var j = api.jscodeshift; | |
| var fn = options.fn || 'moduleForComponent'; | |
| var affected = false; | |
| function shouldAddUnit(obj) { | |
| return obj.properties.every(p => p.key.name !== 'unit' && p.key.name !== 'needs'); | |
| } | |
| function addUnitToObject(obj) { | |
| if (shouldAddUnit(obj)) { | |
| obj.properties.unshift(j.property('init', j.identifier('unit'), j.literal(true))); | |
| return true; | |
| } | |
| } | |
| function transformCall(call) { | |
| var args = call.value.arguments; | |
| var obj = null; | |
| for (var i = 0; i < args.length; i++) { | |
| if (j.ObjectExpression.check(args[i])) { | |
| obj = args[i]; | |
| break; | |
| } | |
| } | |
| if (!obj) { | |
| obj = j.objectExpression([]); | |
| args.push(obj); | |
| } | |
| if (addUnitToObject(obj)) { | |
| affected = true; | |
| } | |
| return call; | |
| } | |
| function forceReprint(path) { | |
| path.node.original = null; | |
| } | |
| const transformed = | |
| j(file.source) | |
| .find(j.CallExpression, { callee: { name: fn } }) | |
| .forEach(transformCall) | |
| .toSource({ trailingComma: true, wrapColumn: 120 }); | |
| if (affected) { | |
| // Remove trailing comma from function calls. This won't be necessary after this issue is closed | |
| // https://github.com/benjamn/recast/issues/335 | |
| return j(transformed) | |
| .find(j.CallExpression, { callee: { name: fn } }) | |
| .forEach(forceReprint) | |
| .toSource({ trailingComma: false, wrapColumn: 120 }); | |
| } else { | |
| return transformed; | |
| } | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment