diff options
author | Florian Dold <florian.dold@gmail.com> | 2016-10-04 11:50:26 +0200 |
---|---|---|
committer | Florian Dold <florian.dold@gmail.com> | 2016-10-04 11:50:26 +0200 |
commit | 30b577138dda685f65a8529be1866afa6e321845 (patch) | |
tree | bfa92ee3ab485a6b11f86731777ecf5c5d166bab /config/codemod-const.js |
Squashed 'thirdparty/preact/' content from commit b2d90cc
git-subtree-dir: thirdparty/preact
git-subtree-split: b2d90cc116f1d1998f7a7c98dc6986bf4c1841f4
Diffstat (limited to 'config/codemod-const.js')
-rw-r--r-- | config/codemod-const.js | 39 |
1 files changed, 39 insertions, 0 deletions
diff --git a/config/codemod-const.js b/config/codemod-const.js new file mode 100644 index 000000000..4bffd9add --- /dev/null +++ b/config/codemod-const.js @@ -0,0 +1,39 @@ +/* eslint no-console:0 */ + +/** Find constants (identified by ALL_CAPS_DECLARATIONS), and inline them globally. + * This is safe because Preact *only* uses global constants. + */ +export default (file, api) => { + let j = api.jscodeshift, + code = j(file.source), + constants = {}, + found = 0; + + code.find(j.VariableDeclaration) + .filter( decl => { + for (let i=decl.value.declarations.length; i--; ) { + let node = decl.value.declarations[i], + name = node.id && node.id.name, + init = node.init; + if (name && init && name.match(/^[A-Z0-9_$]+$/g)) { + if (init.type==='Literal') { + console.log(`Inlining constant: ${name}=${init.raw}`); + found++; + constants[name] = init; + // remove declaration + decl.value.declarations.splice(i, 1); + // if it's the last, we'll remove the whole statement + return !decl.value.declarations.length; + } + } + } + return false; + }) + .remove(); + + code.find(j.Identifier) + .filter( path => path.value.name && constants.hasOwnProperty(path.value.name) ) + .replaceWith( path => (found++, constants[path.value.name]) ); + + return found ? code.toSource({ quote: 'single' }) : null; +}; |