/
workspace-generators.ts
205 lines (182 loc) · 5.53 KB
/
workspace-generators.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
import * as chalk from 'chalk';
import { execSync } from 'child_process';
import { readdirSync, existsSync } from 'fs';
import { copySync, removeSync } from 'fs-extra';
import * as path from 'path';
import * as yargsParser from 'yargs-parser';
import { workspaceRoot } from '../utils/workspace-root';
import { fileExists } from '../utils/fileutils';
import { output } from '../utils/output';
import type { CompilerOptions } from 'typescript';
import { generate } from './generate';
import { readJsonFile, writeJsonFile } from '../utils/fileutils';
import { logger } from '../utils/logger';
import { getPackageManagerCommand } from '../utils/package-manager';
import { normalizePath } from '../utils/path';
import { parserConfiguration } from './nx-commands';
const rootDirectory = workspaceRoot;
const toolsDir = path.join(rootDirectory, 'tools');
const generatorsDir = path.join(toolsDir, 'generators');
const toolsTsConfigPath = path.join(toolsDir, 'tsconfig.tools.json');
type TsConfig = {
extends: string;
compilerOptions: CompilerOptions;
files?: string[];
include?: string[];
exclude?: string[];
references?: Array<{ path: string }>;
};
export async function workspaceGenerators(args: string[]) {
const outDir = compileTools();
const collectionFile = path.join(outDir, 'workspace-generators.json');
const parsedArgs = parseOptions(args, outDir, collectionFile);
if (parsedArgs.listGenerators) {
return listGenerators(collectionFile);
} else {
process.exitCode = await generate(process.cwd(), parsedArgs);
}
}
export function workspaceGeneratorSchema(name: string) {
const schemaFile = path.join(generatorsDir, name, 'schema.json');
if (fileExists(schemaFile)) {
return readJsonFile(schemaFile);
} else {
logger.error(`Cannot find schema for ${name}. Does the generator exist?`);
process.exit(1);
}
}
// compile tools
function compileTools() {
const toolsOutDir = getToolsOutDir();
removeSync(toolsOutDir);
compileToolsDir(toolsOutDir);
const generatorsOutDir = path.join(toolsOutDir, 'generators');
const collectionData = constructCollection();
writeJsonFile(
path.join(generatorsOutDir, 'workspace-generators.json'),
collectionData
);
return generatorsOutDir;
}
function getToolsOutDir() {
const outDir = toolsTsConfig().compilerOptions.outDir;
if (!outDir) {
logger.error(`${toolsTsConfigPath} must specify an outDir`);
process.exit(1);
}
return path.resolve(toolsDir, outDir);
}
function compileToolsDir(outDir: string) {
copySync(generatorsDir, path.join(outDir, 'generators'));
const tmpTsConfigPath = createTmpTsConfig(toolsTsConfigPath, {
include: [path.join(generatorsDir, '**/*.ts')],
});
const pmc = getPackageManagerCommand();
const tsc = `${pmc.exec} tsc`;
try {
execSync(`${tsc} -p ${tmpTsConfigPath}`, {
stdio: 'inherit',
cwd: rootDirectory,
});
} catch {
process.exit(1);
}
}
function constructCollection() {
const generators = {};
readdirSync(generatorsDir).forEach((c) => {
const childDir = path.join(generatorsDir, c);
if (existsSync(path.join(childDir, 'schema.json'))) {
generators[c] = {
factory: `./${c}`,
schema: `./${normalizePath(path.join(c, 'schema.json'))}`,
description: `Schematic ${c}`,
};
}
});
return {
name: 'workspace-generators',
version: '1.0',
generators,
schematics: generators,
};
}
function toolsTsConfig(): TsConfig {
return readJsonFile<TsConfig>(toolsTsConfigPath);
}
function listGenerators(collectionFile: string) {
try {
const bodyLines: string[] = [];
const collection = readJsonFile(collectionFile);
bodyLines.push(chalk.bold(chalk.green('WORKSPACE GENERATORS')));
bodyLines.push('');
bodyLines.push(
...Object.entries(collection.generators).map(
([schematicName, schematicMeta]: [string, any]) => {
return `${chalk.bold(schematicName)} : ${schematicMeta.description}`;
}
)
);
bodyLines.push('');
output.log({
title: '',
bodyLines,
});
} catch (error) {
logger.fatal(error.message);
}
}
function parseOptions(
args: string[],
outDir: string,
collectionFile: string
): { [k: string]: any } {
const schemaPath = path.join(outDir, args[0], 'schema.json');
let booleanProps = [];
if (fileExists(schemaPath)) {
const { properties } = readJsonFile(
path.join(outDir, args[0], 'schema.json')
);
if (properties) {
booleanProps = Object.keys(properties).filter(
(key) => properties[key].type === 'boolean'
);
}
}
const parsed = yargsParser(args, {
boolean: ['dryRun', 'listGenerators', 'interactive', ...booleanProps],
alias: {
dryRun: ['d'],
listSchematics: ['l'],
},
default: {
interactive: true,
},
configuration: parserConfiguration,
});
parsed['generator'] = `${collectionFile}:${parsed['_'][0]}`;
parsed['_'] = parsed['_'].slice(1);
return parsed;
}
function createTmpTsConfig(
tsconfigPath: string,
updateConfig: Partial<TsConfig>
) {
const tmpTsConfigPath = path.join(
path.dirname(tsconfigPath),
'tsconfig.generated.json'
);
const originalTSConfig = readJsonFile<TsConfig>(tsconfigPath);
const generatedTSConfig: TsConfig = {
...originalTSConfig,
...updateConfig,
};
process.on('exit', () => cleanupTmpTsConfigFile(tmpTsConfigPath));
writeJsonFile(tmpTsConfigPath, generatedTSConfig);
return tmpTsConfigPath;
}
function cleanupTmpTsConfigFile(tmpTsConfigPath: string) {
if (tmpTsConfigPath) {
removeSync(tmpTsConfigPath);
}
}