-
Notifications
You must be signed in to change notification settings - Fork 40
Expand file tree
/
Copy pathutils.js
More file actions
417 lines (351 loc) · 13.9 KB
/
utils.js
File metadata and controls
417 lines (351 loc) · 13.9 KB
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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
/*
* (c) Copyright IBM Corp. 2024
*/
'use strict';
const path = require('path');
// eslint-disable-next-line import/no-extraneous-dependencies
const semver = require('semver');
// eslint-disable-next-line import/no-extraneous-dependencies
const moment = require('moment');
const { execSync } = require('child_process');
const fs = require('fs');
exports.getRootDependencyVersion = name => {
const pkgjson = require(path.join(__dirname, '..', '..', 'package.json'));
return pkgjson.devDependencies[name] || pkgjson.optionalDependencies[name];
};
exports.getDevDependencyVersion = name => {
const pkgjson = require(path.join(__dirname, '..', '..', 'package.json'));
return pkgjson.devDependencies[name];
};
exports.getOptionalDependencyVersion = name => {
const pkgjson = require(path.join(__dirname, '..', '..', 'package.json'));
return pkgjson.optionalDependencies[name];
};
exports.getPackageName = name => {
const dirs = fs.readdirSync(path.join(__dirname, '..', '..', 'packages'));
let targetPkg;
dirs.forEach(dir => {
try {
const subpkgjson = require(path.join(__dirname, '..', '..', 'packages', dir, 'package.json'));
if (subpkgjson.devDependencies?.[name] || subpkgjson.optionalDependencies?.[name]) {
targetPkg = `packages/${dir}`;
}
} catch (error) {
return undefined;
}
});
return targetPkg;
};
exports.getPackageDependencyVersion = name => {
const dirs = fs.readdirSync(path.join(__dirname, '..', '..', 'packages'));
return dirs
.map(dir => {
try {
const subpkgjson = require(path.join(__dirname, '..', '..', 'packages', dir, 'package.json'));
return subpkgjson.devDependencies?.[name] || subpkgjson.optionalDependencies?.[name];
} catch (error) {
return undefined;
}
})
.find(version => version !== undefined);
};
const hasPrereleaseTag = (packageName, majorVersion) => {
const tags = JSON.parse(execSync(`npm view ${packageName} dist-tags --json`).toString());
let toReturn = false;
Object.keys(tags).forEach(tag => {
if (tag !== 'latest' && semver.major(tags[tag]) === majorVersion) {
toReturn = true;
}
});
return toReturn;
};
const getAllVersions = packageName => {
return JSON.parse(execSync(`npm view ${packageName} versions --json`).toString());
};
const getHighestMajorVersion = versions => {
let highestMajorVersion;
versions.forEach(version => {
if (
!highestMajorVersion ||
(semver.major(version) >= semver.major(highestMajorVersion) && semver.gt(version, highestMajorVersion))
) {
highestMajorVersion = version;
}
});
return highestMajorVersion;
};
exports.getLatestVersion = ({ pkgName, installedVersion, isBeta, fromInstalledMajor }) => {
let latestVersion;
// CASE: get the latest version within the installed major version
if (fromInstalledMajor) {
const installedMajor = semver.major(installedVersion);
const versions = execSync(`npm info ${pkgName}@${installedMajor} version`).toString().trim().split('\n');
if (versions.length === 1) {
latestVersion = versions[0].replaceAll("'", '');
} else {
latestVersion = versions[versions.length - 1].split(' ')[1].replaceAll("'", '');
}
} else {
latestVersion = execSync(`npm info ${pkgName} version`).toString().trim();
}
const allVersions = getAllVersions(pkgName);
const highestMajorVersion = getHighestMajorVersion(allVersions);
if (!fromInstalledMajor && semver.major(highestMajorVersion) > semver.major(latestVersion)) {
const highestMajorVersionIsPrerelease =
hasPrereleaseTag(pkgName, semver.major(highestMajorVersion)) || semver.prerelease(highestMajorVersion);
console.log(
// eslint-disable-next-line max-len
`Detected a higher major version: ${highestMajorVersion} and this version is a prerelease: ${!!highestMajorVersionIsPrerelease}`
);
// If isBeta is true, then we allow prerelease version as latest in currency report
if (!highestMajorVersionIsPrerelease || isBeta) {
latestVersion = highestMajorVersion;
}
}
// some packages released a wrong order of versions
if (installedVersion && semver.lt(latestVersion, installedVersion)) {
return installedVersion;
}
return latestVersion;
};
function filterStableReleases(releaseList) {
const unstableReleaseKeyWords = [
'alpha',
'beta',
'canary',
'dev',
'experimental',
'integration',
'next',
'rc',
'unstable'
];
return Object.fromEntries(
Object.entries(releaseList).filter(
([version]) => !unstableReleaseKeyWords.some(keyword => version.includes(keyword))
)
);
}
function calculateDaysDifference(date1, date2) {
const timeDiff = Math.abs(moment(date2).diff(moment(date1), 'days'));
return timeDiff;
}
const getNextVersion = (versions, installedVersionIndex, installedVersion) => {
const nextIndex = installedVersionIndex + 1;
const nextVersion = versions[nextIndex];
// CASE: Check if the next version is invalid based on two conditions:
// 1. The next version is from an older major version.
// 2. The next version has the same major version but is lower than the installed version.
if (
nextVersion &&
(semver.major(installedVersion) > semver.major(nextVersion) ||
(semver.major(installedVersion) === semver.major(nextVersion) && semver.lt(nextVersion, installedVersion)))
) {
return getNextVersion(versions, nextIndex, installedVersion);
}
return nextVersion;
};
exports.getDaysBehind = (releaseList, installedVersion, today = new Date()) => {
const stableReleaseList = filterStableReleases(releaseList);
const versions = Object.keys(stableReleaseList);
const installedVersionIndex = versions.indexOf(installedVersion);
// CASE: the installed version is the latest release or the installed version is a prerelease
if (installedVersionIndex === -1 || installedVersionIndex === versions.length - 1) {
return 0;
}
// Step 1: Get the "next" version release date, because the days behind is the number between
// the next release AFTER our installed version and TODAY
const nextVersion = getNextVersion(versions, installedVersionIndex, installedVersion);
const nextVersionDate = stableReleaseList[nextVersion];
console.log(`From: ${nextVersionDate}`);
console.log(`To: ${today}`);
// Step 2: Calculate the days
return calculateDaysDifference(nextVersionDate, today);
};
exports.hasCommits = (branch, cwd) => {
try {
const result = execSync(`git log main..${branch} --pretty=format:"%h"`, { cwd }).toString().trim();
console.log(`Commits in branch '${branch}' not in 'main':\n${result}`);
return result && result.length > 0;
} catch (err) {
return false;
}
};
exports.getPackageJsonPathsUnderPackagesDir = packagesDir => {
const results = [];
if (!fs.existsSync(packagesDir)) {
console.warn(`Directory not found: ${packagesDir}`);
return results;
}
const entries = fs.readdirSync(packagesDir, { withFileTypes: true });
entries.forEach(entry => {
if (entry.isDirectory()) {
const pkgJsonPath = path.join(packagesDir, entry.name, 'package.json');
if (fs.existsSync(pkgJsonPath)) {
results.push({
pkgRelDir: `packages/${entry.name}`,
pkgJsonAbsPath: pkgJsonPath
});
}
}
});
return results;
};
/**
* Creates a standardized branch name for dependency updates
* @param {string} baseBranch - The base branch name
* @param {string} packageName - The package name being updated
* @param {string} version - The new version to update to
* @returns {string} Formatted branch name
*/
exports.createBranchName = (baseBranch, packageName, version) => {
return `${baseBranch}-${packageName.replace(/[^a-zA-Z0-9]/g, '')}-${version.replace(/\./g, '')}`;
};
/**
* Checks if a branch already exists in the remote repository
* @param {string} branchName - The branch name to check
* @param {string} cwd - Current working directory
* @returns {boolean} True if branch exists, false otherwise
*/
exports.branchExists = (branchName, cwd) => {
try {
execSync(`git ls-remote --exit-code --heads origin ${branchName}`, { cwd });
return true;
} catch (err) {
return false;
}
};
/**
* Prepares the git environment for dependency updates
* @param {string} branchName - The branch name to checkout or create
* @param {string} cwd - Current working directory
* @param {boolean} isMainBranch - Whether the current branch is 'main'
*/
exports.prepareGitEnvironment = (branchName, cwd, isMainBranch, isDryRun) => {
if (!isDryRun) {
execSync('git checkout main', { cwd });
execSync('npm i --no-audit', { cwd });
if (!isMainBranch) {
execSync(`git checkout -b ${branchName}`, { cwd });
}
} else {
console.log('[DRY RUN] git checkout main');
console.log('[DRY RUN] npm i --no-audit');
if (!isMainBranch) {
console.log(`[DRY RUN] git checkout -b ${branchName}`);
}
}
};
/**
* Commits changes and creates a PR for dependency updates
* @param {Object} options - Options object
* @param {string} options.packageName - package name being updated
* @param {string} options.currentVersion - current version
* @param {string} options.newVersion - new version to update to
* @param {string} options.branchName - branch name
* @param {string} options.cwd - current working directory
* @param {boolean} options.skipPush - whether to skip pushing to remote
* @param {string} options.prTitle - custom PR title
* @returns {boolean} True if PR was created, false otherwise
*/
exports.commitAndCreatePR = options => {
const { packageName, currentVersion, newVersion, branchName, cwd, skipPush, prTitle, isDryRun } = options;
if (!isDryRun) {
execSync("git add '*package.json' package-lock.json", { cwd });
execSync(`git commit -m "build: bumped ${packageName} from ${currentVersion} to ${newVersion}"`, { cwd });
} else {
console.log("[DRY RUN] git add '*package.json' package-lock.json");
console.log(`[DRY RUN] git commit -m "build: bumped ${packageName} from ${currentVersion} to ${newVersion}"`);
}
if (exports.hasCommits(branchName, cwd)) {
if (!skipPush && !isDryRun) {
execSync(`git push origin ${branchName} --no-verify`, { cwd });
execSync(`gh pr create --base main --head ${branchName} --title "${prTitle}" --body "Tada!"`, { cwd });
console.log(`Pushed the branch: ${branchName} and raised PR`);
return true;
} else {
console.log(`[DRY RUN] git push origin ${branchName} --no-verify`);
console.log(`[DRY RUN] gh pr create --base main --head ${branchName} --title "${prTitle}" --body "Tada!"`);
return true;
}
} else {
console.log(`Branch ${branchName} has no commits.`);
}
return false;
};
exports.isExactVersion = ({ workspaceFlag, packageName, cwd, saveFlag }) => {
const pkgJsonPath = path.join(cwd, workspaceFlag ? path.join(workspaceFlag, 'package.json') : 'package.json');
const pkgJson = require(pkgJsonPath);
const isDev = saveFlag === '--save-dev';
const isOptional = saveFlag === '--save-optional';
let pkg;
if (isDev) {
pkg = pkgJson.devDependencies[packageName];
} else if (isOptional) {
pkg = pkgJson.optionalDependencies[packageName];
} else {
pkg = pkgJson.dependencies[packageName];
}
return pkg && !pkg.startsWith('~') && !pkg.startsWith('^');
};
/**
* Installs a package with the specified version
* @param {Object} options - Options object
* @param {string} options.packageName - The package name to install
* @param {string} options.version - The version to install
* @param {string} options.cwd - Current working directory
* @param {string} options.saveFlag - The save flag (--save-dev, --save-optional, etc.)
* @param {string} options.workspaceFlag - Optional workspace flag (-w packageName)
* @param {Function} options.execSyncFn - Optional custom execSync function
*/
exports.installPackage = options => {
const { packageName, version, cwd, saveFlag, workspaceFlag, execSyncFn, isDryRun } = options;
const workspaceOption = workspaceFlag ? `-w ${workspaceFlag}` : '';
let command = `npm i ${saveFlag} ${packageName}@${version} ${workspaceOption} --no-audit`;
const isExactVersion = exports.isExactVersion({ workspaceFlag, packageName, cwd, saveFlag });
const execFn = execSyncFn || execSync;
if (isExactVersion) {
command += ' --save-exact';
}
if (!isDryRun) {
execFn(command, { stdio: 'inherit', cwd });
} else {
console.log(`[DRY RUN] ${command}`);
}
// For optional dependencies, run an extra npm install due to npm bug
if (saveFlag === '--save-optional') {
if (!isDryRun) {
execFn('npm i', { stdio: 'inherit', cwd });
} else {
console.log('[DRY RUN] npm i');
}
}
};
/**
* Cleans and normalizes a version string into a valid semver value
* @param {string} version - The version string to clean
* @returns {string} Cleaned version string
*/
exports.cleanVersionString = version => {
if (semver.valid(version)) return version;
// "<" returns one minor version below the upper bound (e.g. "1.9.0")
// "<=" returns the upper bound itself (e.g. "1.10.0")
// TODO: Fix version handling in installPackage().
// Currently, npm installs the latest version instead of respecting the defined upper bound.
// Example: "@opentelemetry/api": ">=1.3.0 <1.10.0"
// If version 1.10.0 exists, npm installs it instead of adhering to the intended limit.
// The range should instead be updated to "<1.11.0" to maintain correct behavior.
const upperMatch = version.match(/<\s*=?\s*(\d+\.\d+\.\d+)/);
if (upperMatch) {
const upper = semver.coerce(upperMatch[1]).version;
const hasEqual = version.includes('<=');
if (hasEqual) return upper;
const parsed = semver.parse(upper);
return `${parsed.major}.${Math.max(0, parsed.minor - 1)}.0`;
}
const versions = version.match(/\d+\.\d+\.\d+/g);
if (versions) return versions.sort(semver.rcompare)[0];
// Fallback
const coerced = semver.coerce(version);
return coerced ? coerced.version : '0.0.0';
};