-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
add-nx-to-monorepo.ts
341 lines (300 loc) · 8.5 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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
#!/usr/bin/env node
import * as stripJsonComments from 'strip-json-comments';
import * as path from 'path';
import * as fs from 'fs';
import * as cp from 'child_process';
// eslint-disable-next-line @typescript-eslint/no-var-requires
import * as enquirer from 'enquirer';
import * as yargsParser from 'yargs-parser';
import { execSync } from 'child_process';
import { output } from '@nrwl/devkit';
// eslint-disable-next-line @typescript-eslint/no-var-requires
const ignore = require('ignore');
const parsedArgs = yargsParser(process.argv, {
boolean: ['nxCloud'],
configuration: {
'strip-dashed': true,
'strip-aliased': true,
},
});
addNxToMonorepo().catch((e) => console.error(e));
export async function addNxToMonorepo() {
const repoRoot = process.cwd();
output.log({
title: `🐳 Nx initialization`,
});
const useCloud = await askAboutNxCloud(parsedArgs);
output.log({
title: `🧑🔧 Analyzing the source code and creating configuration file`,
});
const packageJsonFiles = allProjectPackageJsonFiles(repoRoot);
const pds = createProjectDesc(repoRoot, packageJsonFiles);
if (pds.length === 0) {
output.error({ title: `Cannot find any projects in this monorepo` });
process.exit(1);
}
createNxJsonFile(repoRoot);
addDepsToPackageJson(repoRoot, useCloud);
output.log({ title: `📦 Installing dependencies` });
runInstall(repoRoot);
if (useCloud) {
initCloud(repoRoot);
}
printFinalMessage(repoRoot);
}
async function askAboutNxCloud(parsedArgs: any) {
if (parsedArgs.nxCloud === undefined) {
return enquirer
.prompt([
{
name: 'NxCloud',
message: `Use Nx Cloud? (It's free and doesn't require registration.)`,
type: 'select',
choices: [
{
name: 'Yes',
hint: 'Faster builds, run details, GitHub integration. Learn more at https://nx.app',
},
{
name: 'No',
},
],
initial: 'Yes' as any,
},
])
.then((a: { NxCloud: 'Yes' | 'No' }) => a.NxCloud === 'Yes');
} else {
return parsedArgs.nxCloud;
}
}
// 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.isDirectory() && 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;
}
// creating project descs
interface ProjectDesc {
name: string;
dir: string;
mainFilePath: string;
}
function createProjectDesc(
repoRoot: string,
packageJsonFiles: string[]
): ProjectDesc[] {
const res = [];
packageJsonFiles.forEach((p) => {
const dir = path.dirname(p);
const packageJson = readJsonFile(repoRoot, p);
if (!packageJson.name) return;
if (packageJson.main) {
res.push({
name: packageJson.name,
dir,
mainFilePath: path.join(dir, packageJson.main),
});
} else if (packageJson.index) {
res.push({
name: packageJson.name,
dir,
mainFilePath: path.join(dir, packageJson.index),
});
} else {
res.push({ name: packageJson.name, dir, mainFilePath: null });
}
});
return res;
}
function readJsonFile(repoRoot: string, file: string) {
return JSON.parse(
stripJsonComments(fs.readFileSync(path.join(repoRoot, file)).toString())
);
}
function detectWorkspaceScope(repoRoot: string) {
let scope = readJsonFile(repoRoot, `package.json`).name;
if (!scope) return 'undetermined';
if (scope.startsWith('@')) {
scope = scope.substring(1);
}
return scope.split('/')[0];
}
function createNxJsonFile(repoRoot: string) {
const res = {
extends: 'nx/presets/npm.json',
tasksRunnerOptions: {
default: {
runner: 'nx/tasks-runners/default',
options: {
cacheableOperations: ['build', 'test', 'lint', 'package', 'prepare'],
},
},
},
targetDependencies: {
build: [{ target: 'build', projects: 'dependencies' }],
prepare: [{ target: 'prepare', projects: 'dependencies' }],
package: [{ target: 'package', projects: 'dependencies' }],
},
affected: {
defaultBase: deduceDefaultBase(),
},
workspaceLayout: deduceWorkspaceLayout(repoRoot),
pluginsConfig: {
'@nrwl/js': {
analyzeSourceFiles: false,
},
},
};
fs.writeFileSync(`${repoRoot}/nx.json`, JSON.stringify(res, null, 2));
}
function deduceWorkspaceLayout(repoRoot: string) {
if (exists(path.join(repoRoot, 'packages'))) {
return undefined;
} else if (exists(path.join(repoRoot, 'projects'))) {
return { libsDir: 'projects', appsDir: 'projects' };
} else {
return undefined;
}
}
function exists(folder: string) {
try {
const s = fs.statSync(folder);
return s.isDirectory();
// eslint-disable-next-line no-empty
} catch (e) {
return false;
}
}
function deduceDefaultBase() {
try {
execSync(`git rev-parse --verify main`, {
stdio: ['ignore', 'ignore', 'ignore'],
});
return 'main';
} catch (e) {
try {
execSync(`git rev-parse --verify dev`, {
stdio: ['ignore', 'ignore', 'ignore'],
});
return 'dev';
} catch (e) {
try {
execSync(`git rev-parse --verify develop`, {
stdio: ['ignore', 'ignore', 'ignore'],
});
return 'develop';
} catch (e) {
try {
execSync(`git rev-parse --verify next`, {
stdio: ['ignore', 'ignore', 'ignore'],
});
return 'next';
} catch (e) {
return 'master';
}
}
}
}
}
// add dependencies
function addDepsToPackageJson(repoRoot: string, useCloud: boolean) {
const json = readJsonFile(repoRoot, `package.json`);
if (!json.devDependencies) json.devDependencies = {};
json.devDependencies['nx'] = 'NX_VERSION';
if (useCloud) {
json.devDependencies['@nrwl/nx-cloud'] = 'latest';
}
fs.writeFileSync(`package.json`, JSON.stringify(json, null, 2));
}
function runInstall(repoRoot: string) {
cp.execSync(getPackageManagerCommand(repoRoot).install, { stdio: [0, 1, 2] });
}
function initCloud(repoRoot: string) {
execSync(
`${getPackageManagerCommand(repoRoot).exec} nx g @nrwl/nx-cloud:init`,
{
stdio: [0, 1, 2],
}
);
}
function getPackageManagerCommand(repoRoot: string): {
install: string;
exec: string;
} {
const packageManager = fs.existsSync(path.join(repoRoot, 'yarn.lock'))
? 'yarn'
: fs.existsSync(path.join(repoRoot, 'pnpm-lock.yaml'))
? 'pnpm'
: 'npm';
switch (packageManager) {
case 'yarn':
return {
install: 'yarn',
exec: 'yarn',
};
case 'pnpm':
return {
install: 'pnpm install --no-frozen-lockfile', // explicitly disable in case of CI
exec: 'pnpx',
};
case 'npm':
return {
install: 'npm install --legacy-peer-deps',
exec: 'npx',
};
}
}
function printFinalMessage(repoRoot) {
output.success({
title: `🎉 Done!`,
bodyLines: [
`- Enabled Computation caching!`,
`- Run "${
getPackageManagerCommand(repoRoot).exec
} nx run-many --target=build --all" to run the build script for every project in the monorepo.`,
`- Run it again to replay the cached computation.`,
`- Run "${
getPackageManagerCommand(repoRoot).exec
} nx graph" to see the structure of the monorepo.`,
`- Learn more at https://nx.dev/migration/adding-to-monorepo`,
],
});
}