Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix Comment Being Duplicated on Root Node Replacement #29

Merged
merged 2 commits into from
Oct 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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);
});
});
Loading