From bf377b6c51805695bf7c94f6c81d67ad45a441b6 Mon Sep 17 00:00:00 2001 From: David Sherret Date: Sat, 30 Oct 2021 17:34:16 -0400 Subject: [PATCH] fix: support renaming a property to a private identifier Closes #1198 --- .../StraightReplacementNodeHandler.ts | 7 ++++ .../ts-morph/src/tests/issues/1198tests.ts | 35 +++++++++++++++++++ 2 files changed, 42 insertions(+) create mode 100644 packages/ts-morph/src/tests/issues/1198tests.ts diff --git a/packages/ts-morph/src/manipulation/nodeHandlers/StraightReplacementNodeHandler.ts b/packages/ts-morph/src/manipulation/nodeHandlers/StraightReplacementNodeHandler.ts index 2baa085d0..7cca302ee 100644 --- a/packages/ts-morph/src/manipulation/nodeHandlers/StraightReplacementNodeHandler.ts +++ b/packages/ts-morph/src/manipulation/nodeHandlers/StraightReplacementNodeHandler.ts @@ -17,6 +17,13 @@ export class StraightReplacementNodeHandler implements NodeHandler { handleNode(currentNode: Node, newNode: ts.Node, newSourceFile: ts.SourceFile) { /* istanbul ignore if */ if (currentNode.getKind() !== newNode.kind) { + // support a private identifier and identifier being swapped + const kinds = [currentNode.getKind(), newNode.kind]; + if (kinds.includes(ts.SyntaxKind.Identifier) && kinds.includes(ts.SyntaxKind.PrivateIdentifier)) { + currentNode.forget(); + return; + } + throw new errors.InvalidOperationError(`Error replacing tree! Perhaps a syntax error was inserted ` + `(Current: ${currentNode.getKindName()} -- New: ${getSyntaxKindName(newNode.kind)}).`); } diff --git a/packages/ts-morph/src/tests/issues/1198tests.ts b/packages/ts-morph/src/tests/issues/1198tests.ts new file mode 100644 index 000000000..f1b7e54bb --- /dev/null +++ b/packages/ts-morph/src/tests/issues/1198tests.ts @@ -0,0 +1,35 @@ +import { expect } from "chai"; +import { Project } from "../../Project"; + +describe.only("tests for issue #1198", () => { + it("should not have issues when renaming private identifier", () => { + const project = new Project({ useInMemoryFileSystem: true }); + const sourceFile = project.createSourceFile("mod.ts", `class Foo { + private one: string; + private two: string; +}`); + const classDecl = sourceFile.getClasses()[0]; + for (const property of classDecl.getInstanceProperties()) { + const name = property.getName(); + property.toggleModifier("private", false); + property.rename(`#${name}`); + } + + expect(sourceFile.getText()).to.equal(`class Foo { + #one: string; + #two: string; +}`); + + // now swap them back + for (const property of classDecl.getInstanceProperties()) { + const name = property.getName().replace(/^#/, ""); + property.rename(`${name}`); + property.toggleModifier("private", true); + } + + expect(sourceFile.getText()).to.equal(`class Foo { + private one: string; + private two: string; +}`); + }); +});