-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathindex.js
347 lines (293 loc) · 9.45 KB
/
index.js
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
342
343
344
345
346
347
const path = require("path");
const inquirer = require("inquirer");
const chalk = require("chalk");
const uniq = require("lodash/uniq");
const orderBy = require("lodash/orderBy");
const globby = require("globby");
const perf = require("execution-time")();
const runCommand = require("./utils/runCommand");
const fileExists = require("./utils/fileExists");
const ui = require("./utils/ui");
const invariant = require("./utils/invariant");
const sanitizeGitBranchName = require("./utils/sanitizeGitBranchName");
const generateGitCommitMessage = require("./generateGitCommitMessage");
const lines = require("./utils/lines");
const composeCommand = require("./utils/composeCommand");
const composeJobs = require("./composeJobs");
const runJob = require("./runJob");
inquirer.registerPrompt(
"autocomplete",
require("inquirer-autocomplete-prompt")
);
inquirer.registerPrompt("semverList", require("./prompts/semverList"));
module.exports = async ({ input, flags }) => {
const { resolve } = path;
const projectDir = input.shift() || ".";
// Validate flags
flags.nonInteractive &&
invariant(
flags.dependency,
"`--dependency` option must be specified in non-interactive mode"
);
const projectPackageJsonPath = resolve(projectDir, "package.json");
invariant(
await fileExists(projectPackageJsonPath),
"No 'package.json' found in specified directory"
);
ui.logBottom("Resolving package locations...");
let packagesConfig = ["packages/*"];
const { name: projectName, workspaces } = require(projectPackageJsonPath);
// Attempt to get `workspaces` config from project package.json
if (Array.isArray(workspaces)) {
packagesConfig = workspaces;
ui.logBottom("Found `workspaces` config in `package.json['workspaces']`");
}
// Attempt to get `workspaces.packages` config from project package.json
if (workspaces && Array.isArray(workspaces.packages)) {
packagesConfig = workspaces.packages;
ui.logBottom(
"Found `packages` config in `package.json['workspaces']['packages']`"
);
}
// Attempt to get `packages` config from lerna.json
try {
const lernaConfig = require(resolve(projectDir, "lerna.json"));
if (Array.isArray(lernaConfig.packages)) {
packagesConfig = lernaConfig.packages;
ui.logBottom("Found `packages` config in `lerna.json['packages']`");
}
} catch (e) {}
ui.log.write(
`\n${chalk.bold("Lerna Update Wizard")}\n${chalk.grey(
"v" + require("../package.json").version
)}\n\n`
);
ui.logBottom("Collecting packages...");
const defaultPackagesGlobs = flags.packages
? flags.packages.split(",")
: packagesConfig;
const packagesRead = await globby(
defaultPackagesGlobs.map(glob => resolve(projectDir, glob, "package.json")),
{ expandDirectories: true }
);
const packages = orderBy(
packagesRead.map(path => ({
path: path.substr(0, path.length - "package.json".length),
config: require(path),
})),
"config.name"
);
invariant(
packages.length > 0,
"No packages found. Please specify via:",
"",
" package.json: ['workspaces']['packages']",
" lerna.json: ['packages']",
" --packages (CLI flag. See --help)"
);
ui.logBottom("");
const setSourceForDeps = (deps = [], source = "dependencies") =>
Object.keys(deps).map(name => ({
[name]: { version: deps[name], source },
}));
const dependencies = packages.reduce(
(
prev,
{ config: { dependencies, devDependencies, peerDependencies, name } }
) => {
return {
...prev,
[name]: [
...setSourceForDeps(dependencies),
...setSourceForDeps(devDependencies, "devDependencies"),
...setSourceForDeps(peerDependencies, "peerDependencies"),
].reduce((sourcedDeps, sourcedDep) => {
for (const depName of Object.keys(sourcedDep)) {
if (!sourcedDeps[depName]) {
sourcedDeps[depName] = [];
}
sourcedDeps[depName].push(sourcedDep[depName]);
}
return sourcedDeps;
}, {}),
};
},
{}
);
let dependencyMap = packages.reduce(
(prev, { config: { name: packageName } }) => {
const packDeps = dependencies[packageName];
return {
...prev,
...Object.keys(packDeps).reduce((prev, dep) => {
const prevDep = prev[dep] || { packs: {}, versions: [] };
const versions = uniq([
...prevDep.versions,
...packDeps[dep].map(({ version }) => version),
]);
let color = "grey";
const count = versions.length;
if (count > 1) color = "yellow";
if (count > 3) color = "red";
return {
...prev,
[dep]: {
...prevDep,
name: dep,
packs: {
...prevDep.packs,
[packageName]: packDeps[dep],
},
versions,
color,
},
};
}, prev),
};
},
{}
);
// filter out non-conflicted dependencies when deduping
if (flags.dedupe) {
dependencyMap = Object.values(dependencyMap)
.filter(({ versions }) => versions.length > 1)
.reduce(
(prev, { name }) => ({ ...prev, [name]: dependencyMap[name] }),
{}
);
}
const allDependencies = Object.keys(dependencyMap);
// INFO GATHER COMPLETE
const context = {
flags,
projectName,
dependencyMap,
allDependencies,
packages,
};
const jobs = await composeJobs(context);
// PROMPT: Yarn workspaces lazy installation
if (workspaces && !flags.lazy && !flags.nonInteractive) {
ui.logBottom("");
const { useLazy } = await inquirer.prompt([
{
name: "useLazy",
type: "list",
message: lines(
"It looks like you are using Yarn Workspaces!",
chalk.reset(
" A single install at the end is recommended to save time."
),
chalk.reset(
" Note: You can enable this automatically using the --lazy flag"
),
""
),
choices: [
{ name: "Run single-install (lazy)", value: true },
{ name: "Run individual installs (exhaustive)", value: false },
],
},
]);
context.flags.lazy = useLazy;
}
// INSTALL PROCESS START:
perf.start();
context.dependencyManager = (await fileExists(
resolve(projectDir, "yarn.lock")
))
? "yarn"
: "npm";
let totalInstalls = 0;
// Install process
for (const job of jobs) {
totalInstalls += await runJob(job, context);
}
// INSTALL END
// Final install lazy install after package.json files have been modified
if (flags.lazy) {
ui.log.write("");
const installCmd = composeCommand(
context.dependencyManager === "yarn" ? "yarn" : "npm install",
flags.installArgs
);
await runCommand(`cd ${projectDir} && ${installCmd}`, {
startMessage: `${chalk.white.bold(context.projectName)}: ${installCmd}`,
endMessage: chalk.green(`Packages installed ✓`),
logTime: true,
});
}
if (totalInstalls === 0) process.exit();
ui.log.write(
chalk.bold(`Installed ${totalInstalls} packages in ${perf.stop().words}`)
);
if (!flags.nonInteractive) {
const userName = (
(await runCommand("git config --get github.user", {
logOutput: false,
})) ||
(await runCommand("whoami", { logOutput: false })) ||
"upgrade"
)
.split("\n")
.shift();
const {
shouldCreateGitBranch,
shouldCreateGitCommit,
gitBranchName,
gitCommitMessage,
} = await inquirer.prompt([
{
type: "confirm",
name: "shouldCreateGitBranch",
message: "Do you want to create a new git branch for the change?",
},
{
type: "input",
name: "gitBranchName",
message: "Enter a name for your branch:",
when: ({ shouldCreateGitBranch }) => shouldCreateGitBranch,
default: sanitizeGitBranchName(
jobs.length === 1
? `${userName}/${jobs[0].targetDependency}-${jobs[0].targetVersionResolved}`
: `${userName}/upgrade-dependencies`
),
},
{
type: "confirm",
name: "shouldCreateGitCommit",
message: "Do you want to create a new git commit for the change?",
},
{
type: "input",
name: "gitCommitMessage",
message: "Enter a git commit message:",
when: ({ shouldCreateGitCommit }) => shouldCreateGitCommit,
default:
jobs.length === 1
? `Update dependency: ${jobs[0].targetDependency}@${jobs[0].targetVersionResolved}`
: `Update ${jobs.length} dependencies`,
},
]);
if (shouldCreateGitBranch) {
const createCmd = `git checkout -b ${gitBranchName}`;
await runCommand(`cd ${projectDir} && ${createCmd}`, {
startMessage: `${chalk.white.bold(projectName)}: ${createCmd}`,
endMessage: chalk.green(`Branch created ✓`),
});
}
if (shouldCreateGitCommit) {
const subMessage = generateGitCommitMessage(context, jobs);
const createCmd = `git add . && git commit -m '${gitCommitMessage}' -m '${subMessage}'`;
await runCommand(`cd ${projectDir} && ${createCmd}`, {
startMessage: `${chalk.white.bold(
projectName
)}: git add . && git commit`,
endMessage: chalk.green(`Commit created ✓`),
logOutput: false,
});
}
} else {
process.exit();
}
};