Created
July 9, 2016 17:55
-
-
Save yangsu/f778e467ba1f2a75b6c27aa09bed8e73 to your computer and use it in GitHub Desktop.
JsCodeShift script to convert eslint config numbers to string enums for better readability
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
/** | |
* Changes ESLint configs from numbers to string enums for better readability. | |
* | |
* e.g. | |
* | |
* indent: 0, | |
* eqeqeq: [1, 'allow-null'], | |
* 'no-param-reassign': [2, { props: true }], | |
* | |
* becomes: | |
* | |
* indent: 'off', | |
* eqeqeq: ['warn', 'allow-null'], | |
* 'no-param-reassign': ['error', { props: true }], | |
*/ | |
module.exports = (file, api, options) => { | |
const j = api.jscodeshift; | |
const printOptions = options.printOptions || {quote: 'single'}; | |
const root = j(file.source); | |
const numToStringEnum = { | |
0: 'off', | |
1: 'warn', | |
2: 'error', | |
}; | |
const knownLiterals = new Set(); | |
for (let key in numToStringEnum) { | |
knownLiterals.add(key); | |
knownLiterals.add(numToStringEnum[key]); | |
} | |
const convertLiteral = (literal) => { | |
if (literal.value in numToStringEnum) { | |
return j.literal(numToStringEnum[literal.value]); | |
} else { | |
if (!knownLiterals.has(literal.value)) { | |
console.warn( | |
"Unknown Literal: %s at line %d:%d", literal.value, | |
literal.loc.start.line, literal.loc.start.column); | |
} | |
return literal; | |
} | |
} | |
root | |
.find(j.Property, { | |
method: false, | |
shorthand: false, | |
computed: false, | |
}) | |
.filter(p => { | |
return p.parent.parent.node.key && | |
p.parent.parent.node.key.name === 'rules'; | |
}) | |
.forEach(p => { | |
switch (p.node.value.type) { | |
case 'Literal': | |
p.node.value = convertLiteral(p.node.value); | |
break; | |
case 'ArrayExpression': | |
const elements = p.node.value.elements; | |
if (elements.length > 0 && elements[0].type === 'Literal') { | |
elements[0] = convertLiteral(elements[0]); | |
} | |
break; | |
} | |
}); | |
return root.toSource(printOptions); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment