-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathindex.js
executable file
·335 lines (273 loc) · 9.91 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
#! /usr/bin/env node
"use strict";
// Needed for coloring terminal output
import colors from 'colors'
import semver from "semver";
import ora from "ora";
import { argv } from "./args.js";
function debugLog(message) {
if (argv.debug) {
console.log(message.blue);
}
}
import prompts from "prompts";
import { existsSync, readFileSync, writeFileSync } from "fs";
import { join } from "path";
import { spawn } from "child_process";
import { subDirectories } from "./io.js";
import ReplaceVersion from "./ReplaceVersion.js";
import { determineGradleCommand } from "./gradleCommand.js";
import { getBuildFiles } from "./buildFiles.js";
const { gradleCommand, gradleWrapper } = determineGradleCommand(debugLog);
if (!gradleCommand) {
console.log("Unable to find Gradle Wrapper or Gradle CLI.".bgRed);
process.exit();
}
const externalFiles = argv["external-file"];
const pathOfReport = argv["path-of-report"];
const outputDir = pathOfReport || "build/dependencyUpdates";
const buildFiles = getBuildFiles(externalFiles, debugLog);
debugLog(`Build Files:\n ${buildFiles.join("\n")}`);
if (!buildFiles.length) {
console.log("Unable to find build.gradle, build.gradle.kts or external build file.".bgRed);
process.exit();
}
async function executeCommandAndWaitForExitCode(command, args) {
let commandExitCode;
const child = spawn(command, args);
child.stdout.setEncoding("utf8");
child.stdout.on("data", (data) => {
debugLog(data);
});
child.stderr.setEncoding("utf8");
child.stderr.on("data", (data) => {
console.error(data);
});
child.on("close", (code) => {
commandExitCode = code;
});
child.on("exit", (code) => {
commandExitCode = code;
});
while (commandExitCode === undefined) {
debugLog("Waiting for command to finish");
await new Promise((resolve) => setTimeout(resolve, 500));
}
return commandExitCode;
}
(async () => {
console.log(`gradle-upgrade-interactive
${"info".blue} Color legend :
"${"<red>".red}" : Major Update backward-incompatible updates
"${"<yellow>".yellow}" : Minor Update backward-compatible features
"${"<green>".green}" : Patch Update backward-compatible bug fixes
`);
const spinner = ora({ text: "Checking for upgrades", spinner: "dots8Bit" }).start();
// info Color legend :
const gradleDependencyUpdateArgs = ["dependencyUpdates", "-DoutputFormatter=json", `-DoutputDir=${outputDir}`];
const gradleDependencyUpdateResolution = argv.resolution;
if (gradleDependencyUpdateResolution) {
gradleDependencyUpdateArgs.push(`-Drevision=${gradleDependencyUpdateResolution}`);
}
debugLog(`Executing command\n${gradleCommand} ${gradleDependencyUpdateArgs.join(" ")}\n`);
let gradleDependencyUpdateProcessExitCode = await executeCommandAndWaitForExitCode(gradleCommand, gradleDependencyUpdateArgs);
if (gradleDependencyUpdateProcessExitCode !== 0) {
informUserAboutInstallingUpdatePlugin(gradleDependencyUpdateProcessExitCode);
spinner.stop();
process.exit();
}
if (!buildFiles.length) {
console.log("Unable to find build.gradle, build.gradle.kts or external build file.".bgRed);
spinner.stop();
process.exit();
}
debugLog(`Reading JSON report file\n`);
const dependencyUpdates = findOutdatedDependencies();
const outdatedDependencies = dependencyUpdates.outdated.dependencies;
debugLog(`Outdated dependencies parsed\n${JSON.stringify(outdatedDependencies)}\n\n`);
let { choices, latestGradleRelease } = buildUpgradeChoicesForUser(outdatedDependencies, dependencyUpdates);
if (!choices.length) {
console.log("success".green + " All of your dependencies are up to date.");
spinner.stop();
process.exit();
}
spinner.stop();
const response = await prompts({
type: "multiselect",
name: "upgrades",
message: "Pick upgrades",
choices: choices,
});
if (!response.upgrades || !response.upgrades.length) {
console.log("No upgrades selected");
process.exit();
}
if (latestGradleRelease && response.upgrades.some((it) => it === "gradle")) {
console.log("Upgrading gradle wrapper");
const upgradeArgs = ["wrapper", "--gradle-version=" + latestGradleRelease];
debugLog(`Executing command\n${gradleCommand}${upgradeArgs.join(" ")}\n`);
let upgradeGradleWrapperExitCode = await executeCommandAndWaitForExitCode(gradleCommand, upgradeArgs);
if (upgradeGradleWrapperExitCode !== 0) {
console.log(`Error upgrading gradle wrapper (StatusCode=${upgradeGradleWrapperExitCode}).`.bgRed);
process.exit();
}
}
const allReplacements = [];
const buildFileContentMap = new Map();
buildFiles.forEach((buildFile) => {
debugLog(`Reading Gradle build file ${buildFile}\n`);
const fileDataBuffer = readFileSync(buildFile);
let buildFileAsString = fileDataBuffer.toString();
response.upgrades
.filter((it) => it !== "gradle")
.forEach((dependency) => {
debugLog(`Replacing version\n${JSON.stringify(dependency)}\n`);
const replaceVersionActions = ReplaceVersion.replace(buildFileAsString, dependency);
replaceVersionActions.forEach((action) => {
if (!allReplacements.some((it) => it.searchValue === action.searchValue && it.replaceValue === action.replaceValue)) {
allReplacements.push(action);
debugLog(`${action.searchValue} => ${action.replaceValue}`);
}
});
});
buildFileContentMap.set(buildFile, buildFileAsString);
});
buildFileContentMap.forEach((content, buildFile) => {
let modifiedContent = content;
allReplacements.forEach((replaceAction) => {
modifiedContent = modifiedContent.replace(replaceAction.searchValue, replaceAction.replaceValue);
});
debugLog(`Writing Gradle build file: ${buildFile}\n`);
try {
writeFileSync(buildFile, modifiedContent, "utf8");
} catch (err) {
console.log(`Unable to write gradle build file.\n${err}`.bgRed);
process.exit();
}
});
process.exit();
})();
function buildUpgradeChoicesForUser(outdatedDependencies, dependencyUpdates) {
let choices = outdatedDependencies.map((it) => {
const oldVersion = it.version;
const newVersion = it.available.release || it.available.milestone || it.available.integration;
let title = `${it.name} - ${it.version} => ${newVersion}`;
let semverDiff = null;
try {
semverDiff = semver.diff(oldVersion, newVersion);
if (semverDiff === "patch") {
title = title.green;
} else if (["minor", "preminor"].includes(semverDiff)) {
title = title.yellow;
} else if (["major", "premajor"].includes(semverDiff)) {
title = title.red;
}
} catch (err) {
debugLog(`Semver for ${title} cannot be diffed.`);
debugLog(err);
}
return {
description: it.projectUrl,
title: title,
value: {
group: it.group,
name: it.name,
oldVersion: it.version,
version: newVersion,
projectUrl: it.projectUrl,
semverDiff: semverDiff,
},
};
});
const includeSemverDiffs = argv.semver;
if (includeSemverDiffs && includeSemverDiffs.length) {
choices = choices.filter((it) => !it.value.semverDiff || includeSemverDiffs.includes(it.value.semverDiff));
}
choices.sort((a, b) => a.title.localeCompare(b.title));
debugLog(`Choices\n${JSON.stringify(choices)}\n\n`);
let latestGradleRelease;
if (dependencyUpdates.gradle) {
let currentGradleRelease = dependencyUpdates.gradle.running.version;
latestGradleRelease = dependencyUpdates.gradle.current.version;
if (gradleWrapper && currentGradleRelease !== latestGradleRelease) {
choices.unshift({
title: `Gradle - ${currentGradleRelease} => ${latestGradleRelease}`,
value: "gradle",
description: "Upgrades the gradle wrapper",
});
}
}
return {
choices,
latestGradleRelease,
};
}
function findOutdatedDependencies() {
const upgradeReportFiles = findUpgradeJsonReportFiles();
debugLog(`Found ${upgradeReportFiles.length} report files`);
debugLog(upgradeReportFiles.join("\n"));
let gradle;
const mergedOutdatedDependencies = [];
upgradeReportFiles.forEach((reportFile) => {
const upgradeReportFileData = readFileSync(reportFile);
let jsonReportData = JSON.parse(upgradeReportFileData);
// Overwrite if it occurs multiple times
if (jsonReportData.gradle) {
gradle = jsonReportData.gradle;
}
// Merge outdated dependencies
jsonReportData.outdated.dependencies.forEach((outdatedDependency) => {
if (!mergedOutdatedDependencies.some((it) => it === outdatedDependency)) {
mergedOutdatedDependencies.push(outdatedDependency);
}
});
});
return {
gradle,
outdated: {
dependencies: mergedOutdatedDependencies,
},
};
}
function findUpgradeJsonReportFiles() {
const reportJsonPath = `${outputDir}/report.json`;
const upgradeReportFiles = [];
if (existsSync(reportJsonPath)) {
upgradeReportFiles.push(reportJsonPath);
}
subDirectories("./").forEach((subDirectory) => {
const reportDir = join(subDirectory, reportJsonPath);
if (existsSync(reportDir)) {
upgradeReportFiles.push(reportDir);
}
});
return upgradeReportFiles;
}
function informUserAboutInstallingUpdatePlugin(exitCode) {
const newestVersion = "0.49.0";
console.log(`Error executing gradle dependency updates (StatusCode=${exitCode})`.bgRed);
console.log(
`\nIn case you haven't installed the gradle-versions-plugin (https://github.com/ben-manes/gradle-versions-plugin), put one of the following in your gradle build file:\n`
);
console.log(`Either Plugins block`);
console.log(
`
plugins {
id "com.github.ben-manes.versions" version "${newestVersion}"
}\n`.green
);
console.log("or buildscript block");
console.log(
`
buildscript {
repositories {
jcenter()
}
dependencies {
classpath "com.github.ben-manes:gradle-versions-plugin:${newestVersion}"
}
}
apply plugin: "com.github.ben-manes.versions"
`.green
);
}