Created
December 18, 2017 03:57
-
-
Save rattrayalex/669eecbadcbb8f918b2ab61303623975 to your computer and use it in GitHub Desktop.
Hacking "check ast" into node_modules/prettier/bin/prettier.js at the bottom of `function format(argv, input, opt) {`
This file contains 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
// | |
// at the bottom of `function format(argv, input, opt) {`, near line 20367 | |
const pp = prettier$3.format(input, opt); | |
const ast = cleanAST(prettier$3.__debug.parse(input, opt)); | |
const past = cleanAST(prettier$3.__debug.parse(pp, opt)); | |
if (ast !== past) { | |
const MAX_AST_SIZE = 2097152; // 2MB | |
const astDiff = | |
ast.length > MAX_AST_SIZE || past.length > MAX_AST_SIZE | |
? "AST diff too large to render" | |
: diff(ast, past); | |
const safeJsxChanges = [ | |
'"children": []', | |
'"children": [', | |
'{', | |
'"type": "JSXExpressionContainer",', | |
'"expression": {', | |
'"type": "StringLiteral",', | |
'"value": " "', | |
'},', | |
'}', | |
']', | |
'],', | |
] | |
const safeNameRegex = /"name": "(\w+)",?/ | |
const minusLines = astDiff | |
.split('\n') | |
.filter(l => l.match(/^\-\s+\S/)) | |
.map(l => l.replace(/^\-\s+/, '')); | |
const plusLines = astDiff | |
.split('\n') | |
.filter(l => l.match(/^\+\s+\S/)) | |
.map(l => l.replace(/^\+\s+/, '')); | |
const unsafePlusLines = plusLines.filter(l => { | |
if (safeJsxChanges.includes(l)) return false; | |
if (l.match(/"type": "Identifier",?/)) return false; | |
if ( | |
l.match(safeNameRegex) && | |
minusLines.join('').includes(`"value": "${l.match(safeNameRegex)[1]}"`) | |
) return false; | |
return true; | |
}); | |
const unsafeMinusLines = minusLines.filter(l => { | |
if (safeJsxChanges.includes(l)) return false; | |
if (l.match(/"type": "StringLiteral",?/)) return false; | |
if (l.match(/"value": "\w+",?/)) return false; | |
return true; | |
}); | |
if (unsafePlusLines.length === 0 && unsafeMinusLines.length === 0) { | |
console.log() | |
console.warn('Safe diff:') | |
console.warn(astDiff) | |
} else { | |
throw new errors.DebugError( | |
"ast(input) !== ast(prettier(input))\n" + | |
astDiff + | |
"\n" //+ | |
// diff(input, pp) | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment