-
Notifications
You must be signed in to change notification settings - Fork 61
/
index.ts
98 lines (83 loc) 路 2.57 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
94
95
96
97
98
import {
chain,
externalSchematic,
Rule,
SchematicContext,
Tree
} from '@angular-devkit/schematics';
import { addImportToModule } from '@schematics/angular/utility/ast-utils';
import * as ts from '@schematics/angular/third_party/github.com/Microsoft/TypeScript/lib/typescript';
import * as fs from 'fs';
import { join } from 'path';
import { InsertChange } from '@schematics/angular/utility/change';
import { classify } from '@angular-devkit/core/src/utils/strings';
function overrideHtml(): Rule {
return (host: Tree, context: SchematicContext) => {
const path: string = host.actions.find(a =>
a.path.endsWith('.component.html')
).path;
const html = fs
.readFileSync(join(__dirname, './files/template.component.html'), 'utf-8')
.toString();
host.overwrite(path, html);
};
}
interface SlideSchema {
name: string;
project: string;
}
function updateSlidesModule(schema: SlideSchema): Rule {
return (host: Tree, context: SchematicContext) => {
const modulePath: string = host.actions.find(a =>
a.path.endsWith('.module.ts')
).path;
const sourceFile = ts.createSourceFile(
modulePath,
host.read(modulePath).toString('utf-8'),
ts.ScriptTarget.Latest,
true
);
let code = fs
.readFileSync(join(__dirname, './files/code.bs'), 'utf-8')
.toString();
const componentName = classify(schema.name.split('/').pop()) + 'Component';
code = code.replace('EmptyComponent', componentName);
const moduleImportChanges = addImportToModule(
sourceFile,
modulePath,
'SlidesModule',
'@codelab/slides'
);
const routingImportChanges = addImportToModule(
sourceFile,
modulePath,
'routes',
null
);
const changes = [...moduleImportChanges, ...routingImportChanges];
const recorder = host.beginUpdate(modulePath);
changes.forEach((change: InsertChange) => {
recorder.insertLeft(change.pos, change.toAdd);
});
const classDeclaration = [...sourceFile.statements].find(s =>
ts.isClassDeclaration(s)
);
recorder.insertLeft(classDeclaration.pos, code);
[...sourceFile.statements].find(s => ts.isIdentifier(s));
host.commitUpdate(recorder);
};
}
export default function(schema: SlideSchema): Rule {
return chain([
externalSchematic('@schematics/angular', 'module', {
name: schema.name,
project: schema.project
}),
updateSlidesModule(schema),
externalSchematic('@schematics/angular', 'component', {
name: schema.name,
project: schema.project
}),
overrideHtml()
]);
}