forked from nrwl/nx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
add-nx-to-monorepo.ts
185 lines (165 loc) · 5.29 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
import { prompt } from 'enquirer';
import { readdirSync, readFileSync, statSync } from 'fs';
import ignore from 'ignore';
import { join, relative } from 'path';
import { InitArgs } from '../init-v1';
import { readJsonFile } from '../../../utils/fileutils';
import { output } from '../../../utils/output';
import { getPackageManagerCommand } from '../../../utils/package-manager';
import {
addDepsToPackageJson,
createNxJsonFile,
initCloud,
markPackageJsonAsNxProject,
printFinalMessage,
runInstall,
updateGitIgnore,
} from './utils';
import { connectExistingRepoToNxCloudPrompt } from '../../connect/connect-to-nx-cloud';
type Options = Pick<InitArgs, 'nxCloud' | 'interactive' | 'cacheable'> & {
legacy?: boolean;
};
export async function addNxToMonorepo(options: Options) {
const repoRoot = process.cwd();
output.log({ title: '🐳 Nx initialization' });
const packageJsonFiles = allProjectPackageJsonFiles(repoRoot);
const scripts = combineAllScriptNames(repoRoot, packageJsonFiles);
let targetDefaults: string[];
let cacheableOperations: string[];
let scriptOutputs = {} as { [script: string]: string };
let useNxCloud: boolean;
if (options.interactive && scripts.length > 0) {
output.log({
title:
'🧑🔧 Please answer the following questions about the scripts found in your workspace in order to generate task runner configuration',
});
targetDefaults = (
(await prompt([
{
type: 'multiselect',
name: 'targetDefaults',
message:
'Which scripts need to be run in order? (e.g. before building a project, dependent projects must be built)',
choices: scripts,
},
])) as any
).targetDefaults;
cacheableOperations = (
(await prompt([
{
type: 'multiselect',
name: 'cacheableOperations',
message:
'Which 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) {
scriptOutputs[scriptName] = (
await 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)`,
},
])
)[scriptName];
}
useNxCloud =
options.nxCloud ?? (await connectExistingRepoToNxCloudPrompt());
} else {
targetDefaults = [];
cacheableOperations = options.cacheable ?? [];
useNxCloud =
options.nxCloud ??
(options.interactive
? await connectExistingRepoToNxCloudPrompt()
: false);
}
createNxJsonFile(
repoRoot,
targetDefaults,
cacheableOperations,
scriptOutputs
);
if (!options.legacy) {
packageJsonFiles.forEach((packageJsonPath) => {
markPackageJsonAsNxProject(
join(repoRoot, packageJsonPath),
cacheableOperations
);
});
}
updateGitIgnore(repoRoot);
addDepsToPackageJson(repoRoot);
output.log({ title: '📦 Installing dependencies' });
runInstall(repoRoot);
if (useNxCloud) {
output.log({ title: '🛠️ Setting up Nx Cloud' });
initCloud(repoRoot, 'nx-init-monorepo');
}
const pmc = getPackageManagerCommand();
printFinalMessage({
learnMoreLink: 'https://nx.dev/recipes/adopting-nx/adding-to-monorepo',
bodyLines: [
`- Run "${pmc.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 "${pmc.exec} nx graph" to see the structure of the monorepo.`,
],
});
}
// 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 = relative(repoRoot, dirName);
if (
relDirName &&
(ignoredGlobs.ignores(relDirName) ||
relDirName.indexOf(`node_modules`) > -1)
) {
return [];
}
let res = [];
try {
readdirSync(dirName).forEach((c) => {
const child = join(dirName, c);
if (ignoredGlobs.ignores(relative(repoRoot, child))) {
return;
}
try {
const s = statSync(child);
if (s.isFile() && c == 'package.json') {
res.push(relative(repoRoot, child));
} else if (s.isDirectory()) {
res = [...res, ...allPackageJsonFiles(repoRoot, child)];
}
} catch {}
});
} catch {}
return res;
}
function getIgnoredGlobs(repoRoot: string) {
const ig = ignore();
try {
ig.add(readFileSync(`${repoRoot}/.gitignore`, 'utf-8'));
} catch {}
return ig;
}
function combineAllScriptNames(
repoRoot: string,
packageJsonFiles: string[]
): string[] {
const res = new Set<string>();
packageJsonFiles.forEach((p) => {
const packageJson = readJsonFile(join(repoRoot, p));
Object.keys(packageJson.scripts || {}).forEach((scriptName) =>
res.add(scriptName)
);
});
return [...res];
}