-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
add-nx-to-monorepo.ts
320 lines (288 loc) · 8.55 KB
/
add-nx-to-monorepo.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
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
312
313
314
315
316
317
318
319
320
#!/usr/bin/env node
import * as path from 'path';
import * as fs from 'fs';
import * as cp from 'child_process';
import { execSync } from 'child_process';
import * as enquirer from 'enquirer';
import {
getPackageManagerCommand,
joinPathFragments,
output,
readJsonFile,
writeJsonFile,
} from '@nrwl/devkit';
import ignore from 'ignore';
import * as yargsParser from 'yargs-parser';
const parsedArgs = yargsParser(process.argv, {
boolean: ['yes'],
alias: {
yes: ['y'],
},
});
addNxToMonorepo().catch((e) => {
console.error(e);
process.exit(1);
});
export async function addNxToMonorepo() {
const repoRoot = process.cwd();
if (!fs.existsSync(joinPathFragments(repoRoot, 'package.json'))) {
output.error({
title: `Run the command in the folder with a package.json file.`,
});
process.exit(1);
}
output.log({
title: `🐳 Nx initialization`,
});
const packageJsonFiles = allProjectPackageJsonFiles(repoRoot);
const scripts = combineAllScriptNames(repoRoot, packageJsonFiles);
let targetDefaults: string[];
let cacheableOperations: string[];
let scriptOutputs = {};
let useCloud;
if (parsedArgs.yes !== true) {
output.log({
title: `🧑🔧 Please answer the following questions about the scripts found in your workspace in order to generate task runner configuration`,
});
targetDefaults = (
(await enquirer.prompt([
{
type: 'multiselect',
name: 'targetDefaults',
message:
'Which of the following scripts need to be run in deterministic/topological order?',
choices: scripts,
},
])) as any
).targetDefaults;
cacheableOperations = (
(await enquirer.prompt([
{
type: 'multiselect',
name: 'cacheableOperations',
message:
'Which of the following scripts are cacheable? (Produce the same output given the same input, e.g. build, test and lint usually are, serve and start are not)',
choices: scripts,
},
])) as any
).cacheableOperations;
for (const scriptName of cacheableOperations) {
// eslint-disable-next-line no-await-in-loop
scriptOutputs[scriptName] = await enquirer.prompt([
{
type: 'input',
name: scriptName,
message: `Does the "${scriptName}" script create any outputs? If not, leave blank, otherwise provide a path relative to a project root (e.g. dist, lib, build, coverage)`,
},
]);
}
useCloud = await askAboutNxCloud();
} else {
targetDefaults = [];
cacheableOperations = [];
useCloud = false;
}
createNxJsonFile(
repoRoot,
targetDefaults,
cacheableOperations,
scriptOutputs
);
addDepsToPackageJson(repoRoot, useCloud);
output.log({ title: `📦 Installing dependencies` });
runInstall(repoRoot);
if (useCloud) {
initCloud(repoRoot);
}
printFinalMessage();
}
async function askAboutNxCloud() {
return enquirer
.prompt([
{
name: 'NxCloud',
message: `Enable distributed caching to make your CI faster`,
type: 'autocomplete',
choices: [
{
name: 'Yes',
hint: 'I want faster builds',
},
{
name: 'No',
},
],
initial: 'Yes' as any,
},
])
.then((a: { NxCloud: 'Yes' | 'No' }) => a.NxCloud === 'Yes');
}
// scanning package.json files
function allProjectPackageJsonFiles(repoRoot: string) {
const packageJsonFiles = allPackageJsonFiles(repoRoot, repoRoot);
return packageJsonFiles.filter((c) => c != 'package.json');
}
function allPackageJsonFiles(repoRoot: string, dirName: string) {
const ignoredGlobs = getIgnoredGlobs(repoRoot);
const relDirName = path.relative(repoRoot, dirName);
if (
relDirName &&
(ignoredGlobs.ignores(relDirName) ||
relDirName.indexOf(`node_modules`) > -1)
) {
return [];
}
let res = [];
try {
fs.readdirSync(dirName).forEach((c) => {
const child = path.join(dirName, c);
if (ignoredGlobs.ignores(path.relative(repoRoot, child))) {
return;
}
try {
const s = fs.statSync(child);
if (s.isFile() && c == 'package.json') {
res.push(path.relative(repoRoot, child));
} else if (s.isDirectory()) {
res = [...res, ...allPackageJsonFiles(repoRoot, child)];
}
// eslint-disable-next-line no-empty
} catch (e) {}
});
// eslint-disable-next-line no-empty
} catch (e) {}
return res;
}
function getIgnoredGlobs(repoRoot: string) {
const ig = ignore();
try {
ig.add(fs.readFileSync(`${repoRoot}/.gitignore`).toString());
// eslint-disable-next-line no-empty
} catch (e) {}
return ig;
}
function combineAllScriptNames(
repoRoot: string,
packageJsonFiles: string[]
): string[] {
const res = new Set<string>();
packageJsonFiles.forEach((p) => {
const packageJson = readJsonFile(path.join(repoRoot, p));
Object.keys(packageJson.scripts || {}).forEach((scriptName) =>
res.add(scriptName)
);
});
return [...res];
}
function createNxJsonFile(
repoRoot: string,
targetDefaults: string[],
cacheableOperations: string[],
scriptOutputs: { [name: string]: string }
) {
const nxJsonPath = joinPathFragments(repoRoot, 'nx.json');
let nxJson = {} as any;
try {
nxJson = readJsonFile(nxJsonPath);
// eslint-disable-next-line no-empty
} catch {}
nxJson.tasksRunnerOptions = nxJson.tasksRunnerOptions || {};
nxJson.tasksRunnerOptions.default = nxJson.tasksRunnerOptions.default || {};
nxJson.tasksRunnerOptions.default.runner =
nxJson.tasksRunnerOptions.default.runner || 'nx/tasks-runners/default';
nxJson.tasksRunnerOptions.default.options =
nxJson.tasksRunnerOptions.default.options || {};
nxJson.tasksRunnerOptions.default.options.cacheableOperations =
cacheableOperations;
nxJson.targetDefaults = nxJson.targetDefaults || {};
for (const scriptName of targetDefaults) {
nxJson.targetDefaults[scriptName] = nxJson.targetDefaults[scriptName] || {};
nxJson.targetDefaults[scriptName] = { dependsOn: [`^${scriptName}`] };
}
for (const [scriptName, scriptAnswerData] of Object.entries(scriptOutputs)) {
if (!scriptAnswerData[scriptName]) {
// eslint-disable-next-line no-continue
continue;
}
nxJson.targetDefaults[scriptName] = nxJson.targetDefaults[scriptName] || {};
nxJson.targetDefaults[scriptName].outputs = [
`{projectRoot}/${scriptAnswerData[scriptName]}`,
];
}
nxJson.defaultBase = deduceDefaultBase();
writeJsonFile(nxJsonPath, nxJson);
}
function deduceDefaultBase() {
try {
execSync(`git rev-parse --verify main`, {
stdio: ['ignore', 'ignore', 'ignore'],
});
return 'main';
} catch {
try {
execSync(`git rev-parse --verify dev`, {
stdio: ['ignore', 'ignore', 'ignore'],
});
return 'dev';
} catch {
try {
execSync(`git rev-parse --verify develop`, {
stdio: ['ignore', 'ignore', 'ignore'],
});
return 'develop';
} catch {
try {
execSync(`git rev-parse --verify next`, {
stdio: ['ignore', 'ignore', 'ignore'],
});
return 'next';
} catch {
return 'master';
}
}
}
}
}
// add dependencies
function addDepsToPackageJson(repoRoot: string, useCloud: boolean) {
const json = readJsonFile(joinPathFragments(repoRoot, `package.json`));
if (!json.devDependencies) json.devDependencies = {};
json.devDependencies['nx'] = require('../package.json').version;
if (useCloud) {
json.devDependencies['@nrwl/nx-cloud'] = 'latest';
}
writeJsonFile(`package.json`, json);
}
function runInstall(repoRoot: string) {
cp.execSync(getPackageManagerCommand().install, {
stdio: [0, 1, 2],
cwd: repoRoot,
});
}
function initCloud(repoRoot: string) {
execSync(
`${
getPackageManagerCommand().exec
} nx g @nrwl/nx-cloud:init --installationSource=add-nx-to-monorepo`,
{
stdio: [0, 1, 2],
cwd: repoRoot,
}
);
}
function printFinalMessage() {
output.success({
title: `🎉 Done!`,
bodyLines: [
`- Enabled Computation caching!`,
`- Run "${
getPackageManagerCommand().exec
} nx run-many --target=build" to run the build script for every project in the monorepo.`,
`- Run it again to replay the cached computation.`,
`- Run "${
getPackageManagerCommand().exec
} nx graph" to see the structure of the monorepo.`,
`- Learn more at https://nx.dev/recipes/adopting-nx/adding-to-monorepo`,
],
});
}