Have --debug-check also run ast verification (#1337)

master
Christopher Chedeau 2017-04-21 16:09:33 -07:00 committed by GitHub
parent 768a81c5d5
commit 7a8380772d
2 changed files with 88 additions and 4 deletions

View File

@ -139,13 +139,94 @@ function format(input) {
}
if (argv["debug-check"]) {
function massageAST(ast) {
if (Array.isArray(ast)) {
return ast.map(e => massageAST(e)).filter(e => e);
}
if (ast && typeof ast === "object") {
// We remove extra `;` and add them when needed
if (ast.type === "EmptyStatement") {
return undefined;
}
// We move text around, including whitespaces and add {" "}
if (ast.type === "JSXText") {
return undefined;
}
if (
ast.type === "JSXExpressionContainer" &&
ast.expression.type === "Literal" &&
ast.expression.value === " "
) {
return undefined;
}
const newObj = {};
for (var key in ast) {
newObj[key] = massageAST(ast[key]);
}
[
"loc",
"range",
"raw",
"comments",
"start",
"end",
"tokens",
"flags"
].forEach(name => {
delete newObj[name];
});
// We convert <div></div> to <div />
if (ast.type === "JSXOpeningElement") {
delete newObj.selfClosing;
}
if (ast.type === "JSXElement") {
delete newObj.closingElement;
}
// We change {'key': value} into {key: value}
if (
ast.type === "Property" &&
typeof ast.key === "object" &&
ast.key &&
(ast.key.type === "Literal" || ast.key.type === "Identifier")
) {
delete newObj.key;
}
return newObj;
}
return ast;
}
function cleanAST(ast) {
return JSON.stringify(massageAST(ast), null, 2);
}
function diff(a, b) {
return require("diff")
.createTwoFilesPatch("", "", a, b, "", "", { context: 2 });
}
const pp = prettier.format(input, options);
const pppp = prettier.format(pp, options);
if (pp !== pppp) {
const diff = require(
"diff"
).createTwoFilesPatch("", "", pp, pppp, "", "", { context: 2 });
console.error(diff);
process.stdout.write("\n");
console.error('prettier(input) !== prettier(prettier(input))');
console.error(diff(pp, pppp));
} else {
const ast = cleanAST(prettier.__debug.parse(input, options));
const past = cleanAST(prettier.__debug.parse(pp, options));
if (ast !== past) {
process.stdout.write("\n");
console.error('ast(input) !== ast(prettier(input))');
console.error(diff(ast, past));
console.error(diff(input, pp));
}
}
return;
}

View File

@ -114,6 +114,9 @@ module.exports = {
},
version: version,
__debug: {
parse: function(text, opts) {
return parse(text, opts);
},
formatAST: function(ast, opts) {
opts = normalizeOptions(opts);
const doc = printAstToDoc(ast, opts);