forked from projen/projen
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinventory.ts
262 lines (222 loc) · 6.91 KB
/
inventory.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
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
import * as path from 'path';
import * as fs from 'fs-extra';
// eslint-disable-next-line @typescript-eslint/no-require-imports
const decamelize = require('decamelize');
const PROJEN_MODULE_ROOT = path.join(__dirname, '..');
const PROJECT_BASE_FQN = 'projen.Project';
type JsiiTypes = { [name: string]: JsiiType };
export interface ProjectOption {
path: string[];
name: string;
switch: string;
type: string;
parent: string;
docs?: string;
default?: string;
optional?: boolean;
deprecated?: boolean;
}
export interface ProjectType {
moduleName: string;
pjid: string;
fqn: string;
typename: string;
options: ProjectOption[];
docs?: string;
docsurl: string;
}
interface JsiiType {
name: string;
assembly: string;
kind: string;
abstract?: boolean;
base?: string;
fqn: string;
interfaces?: string[];
initializer?: {
parameters?: Array<{
name: string;
type?: { fqn?: string };
}>;
};
properties?: Array<{
name: string;
docs: {
summary?: string;
default?: string;
deprecated?: string;
stability?: string;
};
optional?: boolean;
type?: {
primitive?: string;
fqn?: string;
};
}>;
docs?: {
summary?: string;
deprecated?: string;
custom?: {
pjid?: string;
};
};
}
/**
* Returns a list of project types exported the modules defined in `moduleDirs`.
* This list will always also include the built-in projen project types.
* Modules without a .jsii manifest are skipped.
*
* @param moduleDirs A list of npm module directories
*/
export function discover(...moduleDirs: string[]) {
const jsii: JsiiTypes = {};
const discoverJsii = (dir: string) => {
const jsiiFile = path.join(dir, '.jsii');
if (!fs.existsSync(jsiiFile)) { return; } // no jsii manifest
const manifest = fs.readJsonSync(jsiiFile);
for (const [fqn, type] of Object.entries(manifest.types as JsiiTypes)) {
jsii[fqn] = type;
}
};
// read all .jsii manifests from all modules (incl. projen itself) and merge
// them all into a single map of fqn->type.
for (const dir of [...moduleDirs, PROJEN_MODULE_ROOT]) {
discoverJsii(dir);
if (dir.includes('@') && fs.lstatSync(dir).isDirectory()) {
const childDirs = fs.readdirSync(dir).map(file => path.join(dir, file));
for (const child of childDirs) {
discoverJsii(child);
}
}
}
const result = new Array<ProjectType>();
for (const [fqn, typeinfo] of Object.entries(jsii)) {
if (!isProjectType(jsii, fqn)) {
continue;
}
// projen.web.ReactProject -> web.ReactProject
const typename = fqn.substring(fqn.indexOf('.') + 1);
const docsurl = `https://github.com/projen/projen/blob/master/API.md#projen-${typename.toLocaleLowerCase()}`;
let pjid = typeinfo.docs?.custom?.pjid ?? decamelize(typename).replace(/_project$/, '');
result.push({
moduleName: typeinfo.assembly,
typename,
pjid,
fqn,
options: discoverOptions(jsii, fqn).sort((o1, o2) => o1.name.localeCompare(o2.name)),
docs: typeinfo.docs?.summary,
docsurl,
});
}
return result.sort((r1, r2) => r1.pjid.localeCompare(r2.pjid));
}
function discoverOptions(jsii: JsiiTypes, fqn: string): ProjectOption[] {
const options: { [name: string]: ProjectOption } = {};
const params = jsii[fqn]?.initializer?.parameters ?? [];
const optionsParam = params[0];
const optionsTypeFqn = optionsParam?.type?.fqn;
if (params.length > 1 || (params.length === 1 && optionsParam?.name !== 'options')) {
throw new Error(`constructor for project ${fqn} must have a single "options" argument of a struct type. got ${JSON.stringify(params)}`);
}
addOptions(optionsTypeFqn);
const opts = Object.values(options);
return opts.sort((a, b) => a.switch.localeCompare(b.switch));
function addOptions(ofqn?: string, basePath: string[] = [], optional = false) {
if (!ofqn) {
return;
}
const struct = jsii[ofqn];
if (!struct) {
throw new Error(`unable to find options type ${ofqn} for project ${fqn}`);
}
for (const prop of struct.properties ?? []) {
const propPath = [...basePath, prop.name];
// protect against double-booking
if (prop.name in options) {
throw new Error(`duplicate option "${prop.name}" in ${fqn} (already declared in ${options[prop.name].parent})`);
}
let typeName;
if (prop.type?.primitive) {
typeName = prop.type?.primitive; // e.g. 'string', 'boolean', 'number'
} else if (prop.type?.fqn) {
typeName = prop.type?.fqn.split('.').pop(); // projen.NodeProjectOptions -> NodeProjectOptions
} else { // any other types such as collection types
typeName = 'unknown';
}
const isOptional = optional || prop.optional;
let defaultValue = prop.docs?.default;
if (defaultValue === 'undefined') {
defaultValue = undefined;
}
// if this is a mandatory option and we have a default value, it has to be JSON-parsable to the correct type
if (!isOptional && defaultValue) {
if (!prop.type?.primitive) {
throw new Error(`required option "${prop.name}" with a @default must use primitive types (string, number or boolean). type found is: ${typeName}`);
}
checkDefaultIsParsable(prop.name, defaultValue, prop.type?.primitive);
}
options[prop.name] = filterUndefined({
path: propPath,
parent: struct.name,
name: prop.name,
docs: prop.docs.summary,
type: typeName,
switch: propPath.map(p => decamelize(p).replace(/_/g, '-')).join('-'),
default: defaultValue,
optional: isOptional,
deprecated: prop.docs.stability === 'deprecated' ? true : undefined,
});
}
for (const ifc of struct.interfaces ?? []) {
addOptions(ifc);
}
}
}
function filterUndefined(obj: any) {
const ret: any = {};
for (const [k, v] of Object.entries(obj)) {
if (v !== undefined) {
ret[k] = v;
}
}
return ret;
}
function isProjectType(jsii: JsiiTypes, fqn: string) {
const type = jsii[fqn];
if (type.kind !== 'class') {
return false;
}
if (type.abstract) {
return false;
}
if (type.docs?.deprecated) {
return false;
}
let curr = type;
while (true) {
if (curr.fqn === PROJECT_BASE_FQN) {
return true;
}
if (!curr.base) {
return false;
}
curr = jsii[curr.base];
if (!curr) {
return false;
}
}
}
function checkDefaultIsParsable(prop: string, value: string, type: string) {
// macros are pass-through
if (value.startsWith('$')) {
return;
}
try {
const parsed = JSON.parse(value);
if (typeof(parsed) !== type) {
throw new Error(`cannot parse @default value for mandatory option ${prop} as a ${type}: ${parsed}`);
}
} catch (e) {
throw new Error(`unable to JSON.parse() value "${value}" specified as @default for mandatory option "${prop}": ${e.message}`);
}
}