Skip to content

Commit 7992046

Browse files
authored
Fix Comment Being Duplicated on Root Node Replacement (#29)
* Fix issue with comments being duplicated when replacing the root node * Add test to verify comments aren't duplicated when replacing the root node
1 parent 8f6310b commit 7992046

File tree

2 files changed

+23
-2
lines changed

2 files changed

+23
-2
lines changed

src/arborist.js

+2-2
Original file line numberDiff line numberDiff line change
@@ -85,8 +85,8 @@ const Arborist = class {
8585
const leadingComments = rootNode.leadingComments || [];
8686
const trailingComments = rootNode.trailingComments || [];
8787
rootNode = rootNodeReplacement[1];
88-
if (leadingComments.length) rootNode.leadingComments = (rootNode.leadingComments || []).concat(leadingComments);
89-
if (trailingComments.length) rootNode.trailingComments = (rootNode.trailingComments || []).concat(trailingComments);
88+
if (leadingComments.length && rootNode.leadingComments !== leadingComments) rootNode.leadingComments = (rootNode.leadingComments || []).concat(leadingComments);
89+
if (trailingComments.length && rootNode.trailingComments !== trailingComments) rootNode.trailingComments = (rootNode.trailingComments || []).concat(trailingComments);
9090
} else {
9191
for (const targetNodeId of this.markedForDeletion) {
9292
try {

tests/arborist.test.js

+21
Original file line numberDiff line numberDiff line change
@@ -111,4 +111,25 @@ describe('Arborist tests', () => {
111111
arborist.applyChanges();
112112
assert.equal(arborist.script, code, 'Invalid changes were applied.');
113113
});
114+
it(`Verify comments aren't duplicated when replacing the root node`, () => {
115+
const code = `//comment1\nconst a = 1, b = 2;`;
116+
const expected = `//comment1\nconst a = 1;\nconst b = 2;`;
117+
const arb = new Arborist(code);
118+
const decls = [];
119+
arb.ast.forEach(n => {
120+
if (n.type === 'VariableDeclarator') {
121+
decls.push({
122+
type: 'VariableDeclaration',
123+
kind: 'const',
124+
declarations: [n],
125+
});
126+
}
127+
});
128+
arb.markNode(arb.ast[0], {
129+
...arb.ast[0],
130+
body: decls,
131+
});
132+
arb.applyChanges();
133+
assert.equal(arb.script, expected);
134+
});
114135
});

0 commit comments

Comments
 (0)