From 4f0d46063f5b6514c57d7e3bcff19c5423743aa0 Mon Sep 17 00:00:00 2001 From: erdemcaygor Date: Fri, 18 Apr 2025 18:46:46 +0300 Subject: [PATCH] refactoring --- .../packages/schematics/src/utils/index.ts | 1 + .../schematics/src/utils/ng-module.ts | 48 +++++++++++++++++++ 2 files changed, 49 insertions(+) create mode 100644 npm/ng-packs/packages/schematics/src/utils/ng-module.ts diff --git a/npm/ng-packs/packages/schematics/src/utils/index.ts b/npm/ng-packs/packages/schematics/src/utils/index.ts index 733f656ecb..06b96892fc 100644 --- a/npm/ng-packs/packages/schematics/src/utils/index.ts +++ b/npm/ng-packs/packages/schematics/src/utils/index.ts @@ -19,3 +19,4 @@ export * from './tree'; export * from './type'; export * from './workspace'; export * from './standalone'; +export * from './ng-module'; diff --git a/npm/ng-packs/packages/schematics/src/utils/ng-module.ts b/npm/ng-packs/packages/schematics/src/utils/ng-module.ts new file mode 100644 index 0000000000..ac960cd8d0 --- /dev/null +++ b/npm/ng-packs/packages/schematics/src/utils/ng-module.ts @@ -0,0 +1,48 @@ +import { SchematicsException, Tree } from '@angular-devkit/schematics'; +import { getMainFilePath } from './angular/standalone/util'; +import * as ts from 'typescript'; +import { getAppModulePath, getDecoratorMetadata, getMetadataField } from './angular'; +import { createSourceFile } from '../commands/change-theme/index'; + +export const hasImportInNgModule = async ( + host: Tree, + projectName: string, + metadataFn: string, + metadataName = 'imports', +): Promise => { + const mainFilePath = await getMainFilePath(host, projectName); + const appModulePath = getAppModulePath(host, mainFilePath); + const buffer = host.read(appModulePath); + + if (!buffer) { + throw new SchematicsException(`Could not read file: ${appModulePath}`); + } + + const source = createSourceFile(host, appModulePath); + + console.log('AppModule content:\n', buffer.toString('utf-8')); + + // Get the NgModule decorator metadata + const ngModuleDecorator = getDecoratorMetadata(source, 'NgModule', '@angular/core')[0]; + console.log( + 'Found NgModule decorators:', + getDecoratorMetadata(source, 'NgModule', '@angular/core'), + ); + if (!ngModuleDecorator) { + throw new SchematicsException('The app module does not found'); + } + + const matchingProperties = getMetadataField( + ngModuleDecorator as ts.ObjectLiteralExpression, + metadataName, + ); + const assignment = matchingProperties[0] as ts.PropertyAssignment; + const assignmentInit = assignment.initializer as ts.ArrayLiteralExpression; + + const elements = assignmentInit.elements; + if (!elements || elements.length < 1) { + throw new SchematicsException(`Elements could not found: ${elements}`); + } + + return elements.some(f => f.getText().match(metadataFn)); +};