From 79be776331cf2bb4db2f265ee6cf7260e90e3d5e Mon Sep 17 00:00:00 2001 From: Brandon Mills Date: Mon, 29 Mar 2021 23:35:24 -0400 Subject: [PATCH] Fix: More reliable comment attachment (fixes #76) (#177) Comment attachment was sensitive to whitespace around the code block and preceding comments. In some cases, the parser would place comments as descendants of code blocks' preceding sibling nodes. However, a depth-first traversal of the tree will still encounter the comments in linear order, which is sufficient for our purposes. --- lib/processor.js | 64 ++++++++++++++++++++++++++---------------- tests/lib/processor.js | 31 ++++++++++++++++++++ 2 files changed, 71 insertions(+), 24 deletions(-) diff --git a/lib/processor.js b/lib/processor.js index 41f6f7a2..57428d6a 100644 --- a/lib/processor.js +++ b/lib/processor.js @@ -22,25 +22,27 @@ let blocks = []; * Performs a depth-first traversal of the Markdown AST. * @param {ASTNode} node A Markdown AST node. * @param {Object} callbacks A map of node types to callbacks. - * @param {Object} [parent] The node's parent AST node. * @returns {void} */ -function traverse(node, callbacks, parent) { +function traverse(node, callbacks) { if (callbacks[node.type]) { - callbacks[node.type](node, parent); + callbacks[node.type](node); + } else { + callbacks["*"](); } if (typeof node.children !== "undefined") { for (let i = 0; i < node.children.length; i++) { - traverse(node.children[i], callbacks, node); + traverse(node.children[i], callbacks); } } } /** - * Converts leading HTML comments to JS block comments. + * Extracts `eslint-*` or `global` comments from HTML comments if present. * @param {string} html The text content of an HTML AST node. - * @returns {string[]} An array of JS block comments. + * @returns {string} The comment's text without the opening and closing tags or + * an empty string if the text is not an ESLint HTML comment. */ function getComment(html) { const commentStart = "", + "```js", + "console.log(\"Blank line\");", + "```", + "", + "* List item without a blank line", + "", + "```js", + "console.log(\"No blank line\");", + "```" + ].join("\n"); + const blocks = processor.preprocess(code); + + assert.strictEqual(blocks.length, 2); + assert.strictEqual(blocks[0].text, [ + "/* eslint-disable no-console */", + "console.log(\"Blank line\");", + "" + ].join("\n")); + assert.strictEqual(blocks[1].text, [ + "/* eslint-disable no-console */", + "console.log(\"No blank line\");", + "" + ].join("\n")); + }); + it("should ignore non-eslint comments", () => { const code = [ "",