Repository navigation
Expand file tree
/
Copy pathangular-project-parser.ts
More file actions
311 lines (253 loc) · 8.75 KB
/
Copy pathangular-project-parser.ts
File metadata and controls
311 lines (253 loc) · 8.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
import * as ts from 'typescript';
import { basename } from 'path';
import { SchematicsException, Tree } from '@angular-devkit/schematics';
import { findBootstrapModuleCall, findBootstrapModulePath } from '@schematics/angular/utility/ng-ast-utils';
import { getWorkspace } from '@schematics/angular/utility/workspace';
import { safeGet } from './utils';
import { findImportPath, findNode, getSourceFile } from './ts-utils';
export interface AngularProjectSettings {
/** default: '' */
root: string;
/** default: 'src' */
sourceRoot: string;
architect?: any;
/** default: 'main' */
mainName: string;
/** default: 'src/main.ts' */
mainPath: string;
/** default: 'app' */
prefix: string;
/** default: 'src/tsconfig.json' */
tsConfig: string;
/** default: 'AppModule' */
entryModuleClassName: string;
/** default: 'App' */
entryModuleName: string;
/** default: 'src/app/app.module.ts' */
entryModulePath: string;
/** default: './app/app.module' */
entryModuleImportPath: string;
/** default: 'AppComponent' */
entryComponentClassName: string;
/** default: 'App' */
entryComponentName: string;
/** default: 'src/app/app.component.ts' */
entryComponentPath: string;
/** default: './app.component' */
entryComponentImportPath: string;
/** default: 'app-root' */
indexAppRootTag: string;
/** Typescript resolver for this project */
tsResolver: TypescriptResolver;
}
export interface CoreProjectSettings {
root: string;
sourceRoot: string;
mainName: string;
mainPath: string;
prefix: string;
tsConfig: string;
}
/**
* Metadata for a component or module class
*/
export interface ClassMetadata {
/**
* Full Class name
* For Example: 'HomeComponent'
*/
className: string;
/**
* The name of the class without the Class
* For Example: 'Home'
*/
name: string;
/**
* Relative import path:
* For Example: './home/home.component'
*/
importPath: string;
/**
* Full path to the file:
* For Example: 'src/home/home.component.ts
*/
path: string;
}
type TypescriptResolver = (moduleName: string, containingFilePath: string) => string;
export async function getAngularProjectSettings(tree: Tree, projectName: string): Promise<AngularProjectSettings> {
const projectSettings = await getCoreProjectSettings(tree, projectName);
const tsResolver = getTypescriptResolver(tree, projectSettings.tsConfig);
const entryModule = getEntryModuleMetadata(tree, projectSettings.mainPath, tsResolver);
const entryComponent = getEntryComponentMetadata(tree, entryModule.path, tsResolver);
const indexAppRootTag = getAppRootTag(tree, entryComponent.path);
return {
...projectSettings,
entryModuleClassName: entryModule.className,
entryModuleImportPath: entryModule.importPath,
entryModuleName: entryModule.name,
entryModulePath: entryModule.path,
entryComponentClassName: entryComponent.className,
entryComponentImportPath: entryComponent.importPath,
entryComponentName: entryComponent.name,
entryComponentPath: entryComponent.path,
indexAppRootTag,
tsResolver,
};
}
async function getCoreProjectSettings(tree: Tree, projectName: string): Promise<CoreProjectSettings> {
const { targets, project } = await parseAngularConfig(tree, projectName);
if (!targets) {
throw new SchematicsException(
`Failed to find build targets for project ${projectName}!`,
);
}
const buildTarget = targets.get('build');
if (!buildTarget) {
throw new SchematicsException(
`Failed to find build target for project ${projectName}!`,
);
}
const root = project.root;
const sourceRoot = project.sourceRoot || 'src';
const mainPath = safeGet(buildTarget, 'options', 'main');
const mainName = mainPath && basename(mainPath).replace(/\.ts$/, '');
const prefix = project.prefix as string;
const tsConfig = safeGet(buildTarget, 'options', 'tsConfig');
return {
root,
sourceRoot,
mainName,
mainPath,
prefix,
tsConfig,
};
}
export async function getTsConfigFromProject(tree: Tree, projectName: string) {
const { targets } = await parseAngularConfig(tree, projectName);
return safeGet(targets, 'build', 'options', 'tsConfig');
}
async function parseAngularConfig(tree, projectName: string) {
const project = await getProjectObject(tree, projectName);
const targets = project.targets;
return { targets, project };
}
export async function getProjectObject(tree: Tree, projectName: string) {
const workspace = await getWorkspace(tree);
const project = workspace.projects.get(projectName);
if (!project) {
throw new SchematicsException(`Couldn't find project "${projectName}" in the workspace!`);
}
return project;
}
function getEntryModuleMetadata(tree: Tree, mainPath: string, tsResolver: TypescriptResolver): ClassMetadata {
const bootstrapCall = findBootstrapModuleCall(tree, mainPath);
if (!bootstrapCall) {
throw new SchematicsException('Bootstrap call not found! Cannot build project data!');
}
const className = bootstrapCall.arguments[0].getText();
const name = className.replace(/Module$/, '');
const importPath = findBootstrapModulePath(tree, mainPath);
const path = tsResolver(importPath, mainPath);
const metadata = {
className,
name,
importPath,
path,
};
return metadata;
}
// Step 3 - get appComponent and appComponentPath => open ${appRoot}/${entryModulePath}
// - get appComponent from bootstrap: [ __value__ ]
// - get appComponentPath from import { ${appComponent} } from '__value__'
function getEntryComponentMetadata(tree: Tree, entryModulePath: string, tsResolver: TypescriptResolver): ClassMetadata {
const source = getSourceFile(tree, entryModulePath);
// find -> bootstrap -> array -> array value
// bootstrap: [
// AppComponent <- end result
// ],
const node = findNode<ts.ArrayLiteralExpression>(source, [
{ kind: ts.SyntaxKind.PropertyAssignment, name: 'bootstrap' },
{ kind: ts.SyntaxKind.ArrayLiteralExpression },
]);
const className = node.elements[0].getText();
const name = className.replace('Component', '');
const importPath = findImportPath(source, className);
const path = tsResolver(importPath, entryModulePath);
return {
className,
name,
importPath,
path,
};
}
// Step 4 - get indexAppRootTag => open ${appRoot}/${appComponentPath} - get from selector: '__value__'
function getAppRootTag(tree: Tree, entryComponentPath: string): string {
const source = getSourceFile(tree, entryComponentPath);
const node = findNode<ts.StringLiteral>(source, [
{ kind: ts.SyntaxKind.PropertyAssignment, name: 'selector' },
{ kind: ts.SyntaxKind.StringLiteral },
]);
const indexAppRootTag = node.text;
return indexAppRootTag;
}
function getTypescriptResolver(tree: Tree, tsConfigName: string): TypescriptResolver {
const parseConfigFileHost = createParseConfigFileHost(tree);
const tsConfig = ts.getParsedCommandLineOfConfigFile(
tsConfigName,
ts.getDefaultCompilerOptions(),
parseConfigFileHost,
);
if (!tsConfig) {
throw new SchematicsException(`Could not load tsconfig file: ${tsConfigName}`);
}
const compilerOptions = tsConfig.options;
const moduleResolutionHost: ts.ModuleResolutionHost = {
fileExists: parseConfigFileHost.fileExists,
readFile: parseConfigFileHost.readFile,
};
return (moduleName: string, containingFilePath: string): string => {
const resolutionResult = ts.resolveModuleName(
moduleName,
containingFilePath,
compilerOptions,
moduleResolutionHost,
);
if (resolutionResult.resolvedModule) {
return resolutionResult.resolvedModule.resolvedFileName;
} else {
throw new SchematicsException(`Could not resolve ${moduleName} using config: ${tsConfigName}`);
}
};
}
function createParseConfigFileHost(tree): ts.ParseConfigFileHost {
const readFile = (filePath: string): string | undefined => {
const mainBuffer = tree.read(filePath);
if (!mainBuffer) {
throw new SchematicsException(`Main file (${filePath}) not found`);
}
return mainBuffer.toString('utf-8');
};
const fileExists = (filePath: string): boolean => {
return tree.exists(filePath);
};
// NOTE: readDirectory is called when there are include/exclude options in the tsconfig.
// We don't need these for resolving so (hopefully) it's OK to just return []
const readDirectory = (
path: string,
extensions?: ReadonlyArray<string>,
exclude?: ReadonlyArray<string>,
include?: ReadonlyArray<string>,
depth?: number,
): Array<string> => {
return [];
};
const parseConfigFileHost: ts.ParseConfigFileHost = {
getCurrentDirectory: () => '/',
useCaseSensitiveFileNames: false,
readDirectory,
fileExists,
readFile,
onUnRecoverableConfigFileDiagnostic: () => Object,
};
return parseConfigFileHost;
}