|
| 1 | +import {SchematicsException} from '@angular-devkit/schematics'; |
| 2 | +import {Tree} from '@angular-devkit/schematics'; |
| 3 | +import * as ts from 'typescript'; |
| 4 | +import {addImportToModule} from './devkit-utils/ast-utils'; |
| 5 | +import {getAppModulePath} from './devkit-utils/ng-ast-utils'; |
| 6 | +import {InsertChange} from './devkit-utils/change'; |
| 7 | +import {getConfig, getAppFromConfig} from './devkit-utils/config'; |
| 8 | +import {normalize} from '@angular-devkit/core'; |
| 9 | + |
| 10 | +/** |
| 11 | + * Reads file given path and returns TypeScript source file. |
| 12 | + */ |
| 13 | +export function getSourceFile(host: Tree, path: string): ts.SourceFile { |
| 14 | + const buffer = host.read(path); |
| 15 | + if (!buffer) { |
| 16 | + throw new SchematicsException(`Could not find file for path: ${path}`); |
| 17 | + } |
| 18 | + const content = buffer.toString(); |
| 19 | + const source = ts.createSourceFile(path, content, ts.ScriptTarget.Latest, true); |
| 20 | + return source; |
| 21 | +} |
| 22 | + |
| 23 | +/** |
| 24 | + * Import and add module to root app module. |
| 25 | + */ |
| 26 | +export function addModuleImportToRootModule(host: Tree, moduleName: string, src: string) { |
| 27 | + const config = getConfig(host); |
| 28 | + const app = getAppFromConfig(config, '0'); |
| 29 | + const modulePath = getAppModulePath(host, app); |
| 30 | + addModuleImportToModule(host, modulePath, moduleName, src); |
| 31 | +} |
| 32 | + |
| 33 | +/** |
| 34 | + * Import and add module to specific module path. |
| 35 | + * @param host the tree we are updating |
| 36 | + * @param modulePath src location of the module to import |
| 37 | + * @param moduleName name of module to import |
| 38 | + * @param src src location to import |
| 39 | + */ |
| 40 | +export function addModuleImportToModule( |
| 41 | + host: Tree, modulePath: string, moduleName: string, src: string) { |
| 42 | + const moduleSource = getSourceFile(host, modulePath); |
| 43 | + const changes = addImportToModule(moduleSource, modulePath, moduleName, src); |
| 44 | + const recorder = host.beginUpdate(modulePath); |
| 45 | + |
| 46 | + changes.forEach((change) => { |
| 47 | + if (change instanceof InsertChange) { |
| 48 | + recorder.insertLeft(change.pos, change.toAdd); |
| 49 | + } |
| 50 | + }); |
| 51 | + |
| 52 | + host.commitUpdate(recorder); |
| 53 | +} |
| 54 | + |
| 55 | +/** |
| 56 | + * Gets the app index.html file |
| 57 | + */ |
| 58 | +export function getIndexHtmlPath(host: Tree) { |
| 59 | + const config = getConfig(host); |
| 60 | + const app = getAppFromConfig(config, '0'); |
| 61 | + return normalize(`/${app.root}/${app.index}`); |
| 62 | +} |
0 commit comments