|
| 1 | +import type { Tree } from '@angular-devkit/schematics'; |
| 2 | +import { SchematicsException } from '@angular-devkit/schematics'; |
| 3 | + |
| 4 | +const CONFIG_PATH = 'angular.json'; |
| 5 | + |
| 6 | +export function getDefaultAngularAppName(config: any): string { |
| 7 | + const projects = config.projects; |
| 8 | + const projectNames = Object.keys(projects); |
| 9 | + |
| 10 | + for (const projectName of projectNames) { |
| 11 | + const projectConfig = projects[projectName]; |
| 12 | + if (isAngularBrowserProject(projectConfig)) { |
| 13 | + return projectName; |
| 14 | + } |
| 15 | + } |
| 16 | + |
| 17 | + return projectNames[0]; |
| 18 | +} |
| 19 | + |
| 20 | +export function addArchitectBuilder( |
| 21 | + host: Tree, |
| 22 | + projectName: string, |
| 23 | + builderName: string, |
| 24 | + builderOpts: any |
| 25 | +): void | never { |
| 26 | + const config = readConfig(host); |
| 27 | + const appConfig = getAngularAppConfig(config, projectName); |
| 28 | + appConfig.architect[builderName] = builderOpts; |
| 29 | + writeConfig(host, config); |
| 30 | +} |
| 31 | + |
| 32 | +export function readConfig(host: Tree): any { |
| 33 | + const sourceText = host.read(CONFIG_PATH)?.toString('utf-8'); |
| 34 | + if (!sourceText) { |
| 35 | + return; |
| 36 | + } |
| 37 | + return JSON.parse(sourceText); |
| 38 | +} |
| 39 | + |
| 40 | +export function writeConfig(host: Tree, config: JSON): void { |
| 41 | + host.overwrite(CONFIG_PATH, JSON.stringify(config, null, 2)); |
| 42 | +} |
| 43 | + |
| 44 | +function isAngularBrowserProject(projectConfig: any): boolean { |
| 45 | + if (projectConfig.projectType === 'application') { |
| 46 | + const buildConfig = projectConfig.architect.build; |
| 47 | + return buildConfig.builder === '@angular-devkit/build-angular:browser'; |
| 48 | + } |
| 49 | + |
| 50 | + return false; |
| 51 | +} |
| 52 | + |
| 53 | +export function getAngularAppConfig(config: any, projectName: string): any | never { |
| 54 | + // eslint-disable-next-line no-prototype-builtins |
| 55 | + if (!config.projects.hasOwnProperty(projectName)) { |
| 56 | + throw new SchematicsException(`Could not find project: ${projectName}`); |
| 57 | + } |
| 58 | + |
| 59 | + const projectConfig = config.projects[projectName]; |
| 60 | + if (isAngularBrowserProject(projectConfig)) { |
| 61 | + return projectConfig; |
| 62 | + } |
| 63 | + |
| 64 | + if (config.projectType !== 'application') { |
| 65 | + throw new SchematicsException(`Invalid projectType for ${projectName}: ${config.projectType}`); |
| 66 | + } else { |
| 67 | + const buildConfig = projectConfig.architect.build; |
| 68 | + throw new SchematicsException(`Invalid builder for ${projectName}: ${buildConfig.builder}`); |
| 69 | + } |
| 70 | +} |
0 commit comments