-
Notifications
You must be signed in to change notification settings - Fork 144
/
index.ts
93 lines (78 loc) · 2.72 KB
/
index.ts
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
import {
apply,
MergeStrategy,
mergeWith,
move,
Rule,
SchematicsException,
template,
Tree,
url
} from '@angular-devkit/schematics';
import { strings as stringUtils } from '@angular-devkit/core';
import * as JSON5 from 'json5';
import * as crudModelUtils from '../utils/crud-model-utils'
import { CrudOptions } from './schema';
import { CrudModel } from './model';
import { capitalize } from '@angular-devkit/core/src/utils/strings';
import { getWorkspace } from '@schematics/angular/utility/workspace';
import { addModuleImportToModule } from '@angular/cdk/schematics';
export const BOOTSTRAP = 'bootstrap';
export const MATERIAL = 'material';
export const PAPER_DASHBOARD = 'paper-dashboard';
function getFramework(host: Tree): string {
let possibleFiles = ['/package.json'];
const path = possibleFiles.filter(path => host.exists(path))[0];
const configBuffer = host.read(path);
if (configBuffer === null) {
throw new SchematicsException(`Could not find (${path})`);
} else {
const content = JSON.parse(configBuffer.toString());
if (content.dependencies['bootstrap']) {
return BOOTSTRAP;
} else if (content.dependencies['@angular/material']) {
return MATERIAL;
} else {
return PAPER_DASHBOARD;
}
}
}
export function generate(options: CrudOptions): Rule {
return async (host: Tree) => {
// allow passing the CSS framework in (for testing)
let cssFramework = options.style;
// if no CSS framework defined, try to detect it
// defaults to paper-dashboard if nothing found (for backward compatibility)
if (!cssFramework) {
cssFramework = getFramework(host);
}
const workspace = await getWorkspace(host);
if (!options.project) {
options.project = workspace.projects.keys().next().value;
}
const project = workspace.projects.get(options.project);
const appPath = `${project?.sourceRoot}/app`;
const modelFile = `${appPath}/${options.name}/${options.model}`;
const modelBuffer = host.read(modelFile);
if (modelBuffer === null) {
throw new SchematicsException(`Model file ${options.model} does not exist.`);
}
const modelJson = modelBuffer.toString('utf-8');
const model = JSON5.parse(modelJson) as CrudModel;
// add imports to app.module.ts
addModuleImportToModule(host,
`${appPath}/app.module.ts`,
`${capitalize(model.entity)}Module`,
`./${options.name}/${model.entity}.module`);
const templateSource = apply(url(`./files/${cssFramework}`), [
template({
...stringUtils,
...options,
...crudModelUtils as any,
model
}),
move(`${appPath}/${options.name}`),
]);
return mergeWith(templateSource, MergeStrategy.Overwrite);
}
}