diff --git a/bin/prettier.js b/bin/prettier.js index dc854742..9599e88c 100755 --- a/bin/prettier.js +++ b/bin/prettier.js @@ -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
to
+ 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; } diff --git a/index.js b/index.js index b455bba1..e6348e70 100644 --- a/index.js +++ b/index.js @@ -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);