Skip to content

Commit

Permalink
Fix Comment Being Duplicated on Root Node Replacement (#29)
Browse files Browse the repository at this point in the history
* Fix issue with comments being duplicated when replacing the root node

* Add test to verify comments aren't duplicated when replacing the root node
  • Loading branch information
BenBaryoPX authored Oct 16, 2024
1 parent 8f6310b commit 7992046
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 2 deletions.
4 changes: 2 additions & 2 deletions src/arborist.js
Original file line number Diff line number Diff line change
Expand Up @@ -85,8 +85,8 @@ const Arborist = class {
const leadingComments = rootNode.leadingComments || [];
const trailingComments = rootNode.trailingComments || [];
rootNode = rootNodeReplacement[1];
if (leadingComments.length) rootNode.leadingComments = (rootNode.leadingComments || []).concat(leadingComments);
if (trailingComments.length) rootNode.trailingComments = (rootNode.trailingComments || []).concat(trailingComments);
if (leadingComments.length && rootNode.leadingComments !== leadingComments) rootNode.leadingComments = (rootNode.leadingComments || []).concat(leadingComments);
if (trailingComments.length && rootNode.trailingComments !== trailingComments) rootNode.trailingComments = (rootNode.trailingComments || []).concat(trailingComments);
} else {
for (const targetNodeId of this.markedForDeletion) {
try {
Expand Down
21 changes: 21 additions & 0 deletions tests/arborist.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -111,4 +111,25 @@ describe('Arborist tests', () => {
arborist.applyChanges();
assert.equal(arborist.script, code, 'Invalid changes were applied.');
});
it(`Verify comments aren't duplicated when replacing the root node`, () => {
const code = `//comment1\nconst a = 1, b = 2;`;
const expected = `//comment1\nconst a = 1;\nconst b = 2;`;
const arb = new Arborist(code);
const decls = [];
arb.ast.forEach(n => {
if (n.type === 'VariableDeclarator') {
decls.push({
type: 'VariableDeclaration',
kind: 'const',
declarations: [n],
});
}
});
arb.markNode(arb.ast[0], {
...arb.ast[0],
body: decls,
});
arb.applyChanges();
assert.equal(arb.script, expected);
});
});

0 comments on commit 7992046

Please sign in to comment.