From 2ffa417665a89cbff7b7def0a61eaad70c3b50cd Mon Sep 17 00:00:00 2001 From: Kristiyan Kostadinov Date: Mon, 29 Jul 2024 10:40:47 +0200 Subject: [PATCH] refactor(migrations): add the ability to remove imports in the change tracker (#57179) Updates the `ChangeTracker` to integrate the changes from #57110. PR Close #57179 --- .../core/schematics/utils/change_tracker.ts | 25 ++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/packages/core/schematics/utils/change_tracker.ts b/packages/core/schematics/utils/change_tracker.ts index a6081ced32f..390e6e2f021 100644 --- a/packages/core/schematics/utils/change_tracker.ts +++ b/packages/core/schematics/utils/change_tracker.ts @@ -140,6 +140,25 @@ export class ChangeTracker { }); } + /** + * Removes an import from a file. + * @param sourceFile File from which to remove the import. + * @param symbolName Original name of the symbol to be removed. Used even if the import is aliased. + * @param moduleName Module from which the symbol is imported. + */ + removeImport(sourceFile: ts.SourceFile, symbolName: string, moduleName: string): void { + // It's common for paths to be manipulated with Node's `path` utilties which + // can yield a path with back slashes. Normalize them since outputting such + // paths will also cause TS to escape the forward slashes. + moduleName = normalizePath(moduleName); + + if (!this._changes.has(sourceFile)) { + this._changes.set(sourceFile, []); + } + + this._importManager.removeImport(sourceFile, symbolName, moduleName); + } + /** * Gets the changes that should be applied to all the files in the migration. * The changes are sorted in the order in which they should be applied. @@ -201,12 +220,16 @@ export class ChangeTracker { /** Records the pending import changes from the import manager. */ private _recordImports(): void { - const {newImports, updatedImports} = this._importManager.finalize(); + const {newImports, updatedImports, deletedImports} = this._importManager.finalize(); for (const [original, replacement] of updatedImports) { this.replaceNode(original, replacement); } + for (const node of deletedImports) { + this.removeNode(node); + } + for (const [sourceFile] of this._changes) { const importsToAdd = newImports.get(sourceFile.fileName);