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

feat(component): add migration for replacing ReactiveComponentModule #3506

Merged
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
77 changes: 77 additions & 0 deletions modules/component/migrations/14_1_0/index.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
import { Tree } from '@angular-devkit/schematics';
import {
SchematicTestRunner,
UnitTestTree,
} from '@angular-devkit/schematics/testing';
import * as path from 'path';
import { createPackageJson } from '@ngrx/schematics-core/testing/create-package';
import { waitForAsync } from '@angular/core/testing';

describe('Component Store Migration 14_1_0', () => {
let appTree: UnitTestTree;
const collectionPath = path.join(__dirname, '../migration.json');
const pkgName = 'component';

beforeEach(() => {
appTree = new UnitTestTree(Tree.empty());
appTree.create(
'/tsconfig.json',
`
{
"include": [**./*.ts"]
}
`
);
createPackageJson('', pkgName, appTree);
});

describe('Replace ReactiveComponentModule', () => {
it(
`should replace the ReactiveComponentModule with LetModule and PushModule`,
waitForAsync(async () => {
const input = `
import { ReactiveComponentModule } from '@ngrx/component';

const reactiveComponentModule: ReactiveComponentModule;

@NgModule({
imports: [
AuthModule,
AppRoutingModule,
ReactiveComponentModule,
CoreModule,
],
bootstrap: [AppComponent],
})
export class AppModule {}
`;
const expected = `
import { LetModule, PushModule } from '@ngrx/component';

const reactiveComponentModule: ReactiveComponentModule;
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not migrating assignments to ReactiveComponentModule. However, currently I am not preserving the import. This PR could be enhanced by preserving the import of ReactiveComponentModule when it has not been replaced in the file.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it should be preserved in this case.
A migration shouldn't break an application (Ideally 😅).
If it's hard to do that, I would prefer to keep the ReactiveComponentModule import for all cases.


@NgModule({
imports: [
AuthModule,
AppRoutingModule,
LetModule, PushModule,
CoreModule,
],
bootstrap: [AppComponent],
})
export class AppModule {}
`;

appTree.create('./app.module.ts', input);
const runner = new SchematicTestRunner('schematics', collectionPath);

const newTree = await runner
.runSchematicAsync(`ngrx-${pkgName}-migration-14-1`, {}, appTree)
.toPromise();
const file = newTree.readContent('app.module.ts');

expect(file).toBe(expected);
})
);
});
});
125 changes: 125 additions & 0 deletions modules/component/migrations/14_1_0/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
import * as ts from 'typescript';
import { Rule, chain, Tree } from '@angular-devkit/schematics';
import {
visitTSSourceFiles,
commitChanges,
createReplaceChange,
ReplaceChange,
} from '../../schematics-core';

const reactiveComponentModuleText = 'ReactiveComponentModule';
const reactiveComponentModuleReplacement = 'LetModule, PushModule';

function migrateReactiveComponentModule() {
return (tree: Tree) => {
visitTSSourceFiles(tree, (sourceFile) => {
const componentStoreImports = sourceFile.statements
.filter(ts.isImportDeclaration)
.filter(({ moduleSpecifier }) =>
moduleSpecifier.getText(sourceFile).includes('@ngrx/component')
);

if (componentStoreImports.length === 0) {
return;
}

const changes = [
...findReactiveComponentModuleImportDeclarations(
sourceFile,
componentStoreImports
),
...findReactiveComponentModuleImportReplacements(sourceFile),
];

commitChanges(tree, sourceFile.fileName, changes);
});
};
}

function findReactiveComponentModuleImportDeclarations(
sourceFile: ts.SourceFile,
imports: ts.ImportDeclaration[]
) {
const changes = imports
.map((p) => (p?.importClause?.namedBindings as ts.NamedImports)?.elements)
.reduce(
(imports, curr) => imports.concat(curr ?? []),
[] as ts.ImportSpecifier[]
)
.map((specifier) => {
if (!ts.isImportSpecifier(specifier)) {
return { hit: false };
}

if (specifier.name.text === reactiveComponentModuleText) {
return { hit: true, specifier, text: specifier.name.text };
}

// if import is renamed
if (
specifier.propertyName &&
specifier.propertyName.text === reactiveComponentModuleText
) {
return { hit: true, specifier, text: specifier.propertyName.text };
}

return { hit: false };
})
.filter(({ hit }) => hit)
.map(({ specifier, text }) =>
!!specifier && !!text
? createReplaceChange(
sourceFile,
specifier,
text,
reactiveComponentModuleReplacement
)
: undefined
)
.filter((change) => !!change) as Array<ReplaceChange>;

return changes;
}

function findReactiveComponentModuleImportReplacements(
sourceFile: ts.SourceFile
) {
const changes: ReplaceChange[] = [];
ts.forEachChild(sourceFile, (node) => find(node, changes));
return changes;

function find(node: ts.Node, changes: ReplaceChange[]) {
let change = undefined;

// ReactiveComponentModule in NgModule `imports` array
if (
ts.isIdentifier(node) &&
node.text === reactiveComponentModuleText &&
ts.isArrayLiteralExpression(node.parent) &&
ts.isPropertyAssignment(node.parent.parent) &&
node.parent.parent.getText().startsWith('imports:')
) {
change = {
node: node,
text: node.text,
};
}

if (change) {
changes.push(
createReplaceChange(
sourceFile,
change.node,
change.text,
reactiveComponentModuleReplacement
)
);
}

ts.forEachChild(node, (childNode) => find(childNode, changes));
}
}

export default function (): Rule {
return chain([migrateReactiveComponentModule()]);
}
8 changes: 7 additions & 1 deletion modules/component/migrations/migration.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
{
"$schema": "../../../node_modules/@angular-devkit/schematics/collection-schema.json",
"schematics": {}
"schematics": {
"ngrx-component-migration-14-1": {
"description": "Version 14.1",
"version": "14.1",
"factory": "./14_1_0/index"
}
}
}