-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathindex.ts
More file actions
executable file
·591 lines (515 loc) · 21 KB
/
index.ts
File metadata and controls
executable file
·591 lines (515 loc) · 21 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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
#!/usr/bin/env node
import {SubprocessError, type Result, exec, reNewline, tomlGetString} from "./utils.ts";
import {parseArgs} from "node:util";
import {basename, dirname, join, relative, resolve} from "node:path";
import {cwd, exit, stdout} from "node:process";
import {EOL, platform} from "node:os";
import {readFileSync, writeFileSync, accessSync, truncateSync, statSync} from "node:fs";
import pkg from "./package.json" with {type: "json"};
export type SemverLevel = "patch" | "minor" | "major" | "prerelease";
const reEscapeChars = /[|\\{}()[\]^$+*?.-]/g;
const reSemver = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/;
const reVersionPrefix = /^v/;
const reVerToken = /_VER_/g;
const reMajorToken = /_MAJOR_/g;
const reMinorToken = /_MINOR_/g;
const rePatchToken = /_PATCH_/g;
const reMajorVersion = /([0-9]+)\.[0-9]+\.[0-9]+(.*)/;
const reMinorVersion = /([0-9]+\.)([0-9]+)\.[0-9]+(.*)/;
const rePatchVersion = /([0-9]+\.[0-9]+\.)([0-9]+)(.*)/;
const rePrereleaseVersion = /^(\d+)\.(\d+)\.(\d+)(?:-([a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*))?/;
const rePrereleaseIdNum = /^([a-zA-Z0-9-]+)\.(\d+)$/;
const reDatePattern = /([^0-9]|^)[0-9]{4}-[0-9]{2}-[0-9]{2}([^0-9]|$)/g;
const reReplaceString = /^s#([^#]+)#([^#]+)#(.*)$/;
export function esc(str: string): string {
return str.replace(reEscapeChars, "\\$&");
}
export function isSemver(str: string): boolean {
return reSemver.test(str.replace(reVersionPrefix, ""));
}
export function replaceTokens(str: string, newVersion: string): string {
const [major, minor, patch] = newVersion.split(".");
return str
.replace(reVerToken, newVersion)
.replace(reMajorToken, major)
.replace(reMinorToken, minor)
.replace(rePatchToken, patch);
}
export function incrementSemver(str: string, level: string, preid?: string): string {
if (!isSemver(str)) throw new Error(`Invalid semver: ${str}`);
if (level === "major") {
const newVer = str.replace(reMajorVersion, (_, m1) => `${Number(m1) + 1}.0.0`);
return preid ? `${newVer}-${preid}.0` : newVer;
}
if (level === "minor") {
const newVer = str.replace(reMinorVersion, (_, m1, m2) => `${m1}${Number(m2) + 1}.0`);
return preid ? `${newVer}-${preid}.0` : newVer;
}
if (level === "patch") {
const newVer = str.replace(rePatchVersion, (_, m1, m2) => `${m1}${Number(m2) + 1}`);
return preid ? `${newVer}-${preid}.0` : newVer;
}
if (level === "prerelease") {
if (!preid) throw new Error("prerelease requires --preid option");
// Check if current version has a prerelease
const match = rePrereleaseVersion.exec(str);
if (!match) throw new Error(`Invalid semver: ${str}`);
const [, major, minor, patch, prerelease] = match;
if (!prerelease) {
// No prerelease, increment patch and add prerelease
return `${major}.${minor}.${Number(patch) + 1}-${preid}.0`;
}
// Has prerelease, check if it matches the requested preid
const prereleaseMatch = rePrereleaseIdNum.exec(prerelease);
if (prereleaseMatch) {
const [, currentPreid, preNum] = prereleaseMatch;
if (currentPreid === preid) {
// Same preid, increment the number
return `${major}.${minor}.${patch}-${preid}.${Number(preNum) + 1}`;
}
}
// Different preid or no number, replace with new preid
return `${major}.${minor}.${patch}-${preid}.0`;
}
throw new Error(`Invalid semver level: ${level}`);
}
export function findUp(filename: string, dir: string, stopDir?: string): string | null {
const path = join(dir, filename);
try {
accessSync(path);
return path;
} catch {}
const parent = dirname(dir);
if ((stopDir && path === stopDir) || parent === dir) {
return null;
} else {
return findUp(filename, parent, stopDir);
}
}
export function readVersionFromPackageJson(projectRoot: string): string | null {
const packageJsonPath = findUp("package.json", projectRoot);
if (!packageJsonPath) return null;
try {
const content = readFileSync(packageJsonPath, "utf8");
const pkg = JSON.parse(content);
if (pkg.version && isSemver(pkg.version)) {
return pkg.version.replace(reVersionPrefix, "");
}
} catch {}
return null;
}
export function readVersionFromPyprojectToml(projectRoot: string): string | null {
const pyprojectPath = findUp("pyproject.toml", projectRoot);
if (!pyprojectPath) return null;
try {
const content = readFileSync(pyprojectPath, "utf8");
const projectVersion = tomlGetString(content, "project", "version");
if (projectVersion && isSemver(projectVersion)) {
return projectVersion.replace(reVersionPrefix, "");
}
const poetryVersion = tomlGetString(content, "tool.poetry", "version");
if (poetryVersion && isSemver(poetryVersion)) {
return poetryVersion.replace(reVersionPrefix, "");
}
} catch {}
return null;
}
export async function removeIgnoredFiles(files: Array<string>, cwd?: string): Promise<Array<string>> {
let result: Result;
try {
result = await exec("git", ["check-ignore", "--", ...files], cwd ? {cwd} : undefined);
} catch {
return files;
}
const ignoredFiles = new Set<string>(result.stdout.split(reNewline));
return files.filter(file => !ignoredFiles.has(file));
}
export type GetFileChangesOpts = {
file: string,
baseVersion: string,
newVersion: string,
replacements?: Array<{re: RegExp | string, replacement: string}>,
date?: string,
};
export function getFileChanges({file, baseVersion, newVersion, replacements, date}: GetFileChangesOpts): [string, string | null] {
const fileName = basename(file);
// Unhandled lockfiles do not store a project version. Doing a blind
// search-and-replace would corrupt dependency versions.
if ((/lock/i.test(fileName) || fileName === "go.sum") && fileName !== "package-lock.json" && fileName !== "uv.lock") {
return [file, null];
}
const oldData = readFileSync(file, "utf8");
let newData: string;
if (fileName === "package.json") {
newData = oldData.replace(/("version":[^]*?")\d+\.\d+\.\d+(?:[^"\d][^"]*)?(")/,
(_, p1, p2) => `${p1}${newVersion}${p2}`);
} else if (fileName === "package-lock.json") {
// special case for package-lock.json which contains a lot of version
// strings which make regexp replacement risky.
const lockFile = JSON.parse(oldData);
if (lockFile.version) lockFile.version = newVersion; // v1 and v2
if (lockFile?.packages?.[""]?.version) lockFile.packages[""].version = newVersion; // v2 and v3
newData = `${JSON.stringify(lockFile, null, 2)}\n`;
} else if (fileName === "pyproject.toml") {
newData = oldData.replace(/(^version ?= ?["'])\d+\.\d+\.\d+(?:[^"'\d][^"']*)?(["'].*)/gm,
(_, p1, p2) => `${p1}${newVersion}${p2}`);
} else if (fileName === "uv.lock") {
// uv.lock is a tricky case because it lists all packages and the current package. we parse pyproject.toml
// to obtain the current package name and then search for that name in uv.lock and replace the version
// on the next line which luckily is possible because of static ordering.
const projStr = readFileSync(file.replace(/uv\.lock$/, "pyproject.toml"), "utf8");
const name = tomlGetString(projStr, "project", "name")!;
const re = new RegExp(`(\\[\\[package\\]\\]\r?\n.+${esc(name)}.+\r?\nversion = ").+?(")`);
newData = oldData.replace(re, (_m, p1, p2) => `${p1}${newVersion}${p2}`);
} else {
const re = new RegExp(esc(baseVersion), "g");
newData = oldData.replace(re, newVersion);
}
if (date) {
const re = reDatePattern;
newData = newData.replace(re, (_, p1, p2) => `${p1}${date}${p2}`);
}
if (replacements?.length) {
for (const replacement of replacements) {
newData = newData.replace(replacement.re, replacement.replacement);
}
}
return [file, newData];
}
export function write(file: string, content: string): void {
if (platform() === "win32") {
try {
truncateSync(file);
writeFileSync(file, content, {flag: "r+"});
} catch {
writeFileSync(file, content);
}
} else {
writeFileSync(file, content);
}
}
// join strings, ignoring falsy values and trimming the result
export function joinStrings(strings: Array<string | undefined>, separator: string): string {
return strings.filter(Boolean).join(separator).trim();
}
function end(err?: Error | string | void): void {
if (err instanceof SubprocessError) {
console.info(`${err.message}\n${err.output}`);
} else if (err instanceof Error) {
console.info(String(err.stack || err.message || err).trim());
} else if (err) {
console.info(err);
}
exit(err ? 1 : 0);
}
function getEnvTokens(names: string[]): string[] {
const tokens: string[] = [];
for (const name of names) {
if (process.env[name]) tokens.push(process.env[name]);
}
return tokens;
}
export async function getGithubTokens(): Promise<string[]> {
const tokens = getEnvTokens(["VERSIONS_FORGE_TOKEN", "GITHUB_API_TOKEN", "GITHUB_TOKEN", "GH_TOKEN", "HOMEBREW_GITHUB_API_TOKEN"]);
try {
const {stdout} = await exec("gh", ["auth", "token"]);
if (stdout) tokens.push(stdout.trim());
} catch {}
return Array.from(new Set(tokens));
}
export function getGiteaTokens(): string[] {
return Array.from(new Set(getEnvTokens(["VERSIONS_FORGE_TOKEN", "GITEA_API_TOKEN", "GITEA_AUTH_TOKEN", "GITEA_TOKEN"])));
}
export type RepoInfo = {
owner: string;
repo: string;
host: string;
type: "github" | "gitea";
};
export async function getRepoInfo(cwd?: string): Promise<RepoInfo | null> {
try {
const {stdout} = await exec("git", ["remote", "get-url", "origin"], cwd ? {cwd} : undefined);
const url = stdout.trim();
// Parse git URLs: https://host/owner/repo.git or git@host:owner/repo.git
const httpsMatch = /https:\/\/([^/]+)\/([^/]+)\/([^/.]+)/.exec(url);
const sshMatch = /git@([^:]+):([^/]+)\/([^/.]+)/.exec(url);
const match = httpsMatch || sshMatch;
if (match) {
return {
owner: match[2],
repo: match[3],
host: match[1],
type: match[1] === "github.com" ? "github" : "gitea",
};
}
return null;
} catch {
return null;
}
}
export async function createForgeRelease(repoInfo: RepoInfo, tagName: string, body: string, tokens: string[]): Promise<void> {
const apiUrl = repoInfo.type === "github" ?
`https://api.github.com/repos/${repoInfo.owner}/${repoInfo.repo}/releases` :
`https://${repoInfo.host}/api/v1/repos/${repoInfo.owner}/${repoInfo.repo}/releases`;
const releaseBody = JSON.stringify({
tag_name: tagName,
name: tagName,
body,
draft: false,
prerelease: tagName.includes("-"),
});
let lastError: Error | undefined;
for (const token of tokens) {
let response: Response;
try {
response = await fetch(apiUrl, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": repoInfo.type === "github" ? `Bearer ${token}` : `token ${token}`,
},
body: releaseBody,
});
} catch (err: any) {
throw new Error(`Failed to create release: ${err.cause?.message || err.message || "Unknown error"}`);
}
if (response.ok) {
const result = await response.json();
if (result.html_url) {
console.info(`Created release: ${result.html_url}`);
} else {
console.info("Created release");
}
return;
}
const errorText = await response.text();
lastError = new Error(`Failed to create release: ${response.status} ${response.statusText}\n${errorText}`);
if (response.status !== 401 && response.status !== 403) throw lastError;
}
throw lastError ?? new Error("No tokens provided");
}
export function writeResult(result: Result): void {
if (result.stdout) stdout.write(result.stdout.endsWith(EOL) ? result.stdout : `${result.stdout}${EOL}`);
if (result.stderr) stdout.write(result.stderr.endsWith(EOL) ? result.stderr : `${result.stderr}${EOL}`);
}
async function main(): Promise<void> {
const commands = new Set(["patch", "minor", "major", "prerelease"]);
const result = parseArgs({
strict: false,
allowPositionals: true,
options: {
all: {short: "a", type: "boolean"},
dry: {short: "D", type: "boolean"},
gitless: {short: "g", type: "boolean"},
help: {short: "h", type: "boolean"},
prefix: {short: "p", type: "boolean"},
version: {short: "v", type: "boolean"},
date: {short: "d", type: "boolean"},
release: {short: "R", type: "boolean"},
base: {short: "b", type: "string"},
command: {short: "c", type: "string"},
replace: {short: "r", type: "string", multiple: true},
message: {short: "m", type: "string", multiple: true},
preid: {short: "i", type: "string"},
},
});
const args = result.values;
let [level, ...files] = result.positionals;
files = Array.from(new Set(files));
if (args.version) {
console.info(pkg.version || "0.0.0");
end();
}
if (!commands.has(level) || args.help) {
console.info(`usage: versions [options] patch|minor|major|prerelease [files...]
Options:
-a, --all Add all changed files to the commit
-b, --base <version> Base version. Default is from latest git tag, package.json, pyproject.toml, or 0.0.0
-p, --prefix Prefix version string with a "v" character. Default is none
-c, --command <cmd> Run command after files are updated but before git commit and tag
-d, --date Replace dates in format YYYY-MM-DD with current date
-i, --preid <id> Prerelease identifier, e.g., alpha, beta, rc
-m, --message <str> Custom tag and commit message
-r, --replace <str> Additional replacements in the format "s#regexp#replacement#flags"
-g, --gitless Do not perform any git action like creating commit and tag
-D, --dry Do not create a tag or commit, just print what would be done
-R, --release Create a GitHub or Gitea release, push commit and tag to origin
-v, --version Print the version
-h, --help Print this help
The message and replacement strings accept tokens _VER_, _MAJOR_, _MINOR_, _PATCH_.
Examples:
$ versions patch
$ versions prerelease --preid=alpha
$ versions -c 'npm run build' -m 'Release _VER_' minor file.css`);
end();
}
let date = "";
if (args.date) {
date = (new Date()).toISOString().substring(0, 10);
}
const pwd = cwd();
const gitDir = findUp(".git", pwd);
let projectRoot = gitDir ? dirname(gitDir) : null;
if (!projectRoot) projectRoot = pwd;
const releasePrep = (!args.gitless && args.release) ? (() => {
const repoInfo = getRepoInfo();
return {
repoInfo,
tokens: repoInfo.then(info => {
if (!info) return [];
return info.type === "github" ? getGithubTokens() : getGiteaTokens();
}),
};
})() : null;
// obtain old version
let baseVersion: string = "";
let cachedDescribeTag: string = "";
if (!args.base) {
let stdout: string = "";
if (!args.gitless) {
// Try git describe first (O(depth) vs O(n·log n) for full tag list)
try {
const result = await exec("git", ["describe", "--tags", "--abbrev=0"]);
cachedDescribeTag = result.stdout.trim();
if (isSemver(cachedDescribeTag)) {
baseVersion = cachedDescribeTag.replace(reVersionPrefix, "");
}
} catch {}
// Fall back to full tag list if describe didn't yield a semver tag
if (!baseVersion) {
try {
({stdout} = await exec("git", ["tag", "--list", "--sort=-creatordate"]));
} catch {}
for (const tag of stdout.split(reNewline).map(v => v.trim()).filter(Boolean)) {
if (isSemver(tag)) {
baseVersion = tag.replace(reVersionPrefix, "");
break;
}
}
}
}
if (!baseVersion) {
// Try to get version from package.json first, then pyproject.toml as fallback
// package.json takes precedence for JavaScript/TypeScript projects
baseVersion = readVersionFromPackageJson(projectRoot) || readVersionFromPyprojectToml(projectRoot) || "";
if (!baseVersion && args.gitless) {
return end(new Error(`--gitless requires --base to be set or a version in package.json or pyproject.toml`));
}
if (!baseVersion) {
baseVersion = "0.0.0";
}
}
} else {
baseVersion = String(args.base);
}
// chop off "v"
if (baseVersion.startsWith("v")) baseVersion = baseVersion.substring(1);
// validate old version
if (!isSemver(baseVersion)) {
throw new Error(`Invalid base version: ${baseVersion}`);
}
// convert paths to relative
files = files.map(file => relative(pwd, file));
// validate flag combinations
if (level === "prerelease" && !args.preid) {
return end(new Error("prerelease requires --preid option"));
}
if (args.gitless && args.release) {
return end(new Error("--gitless and --release are mutually exclusive"));
}
// set new version
const newVersion = incrementSemver(baseVersion, level, typeof args.preid === "string" ? args.preid : undefined);
const replacements: Array<{re: RegExp, replacement: string}> = [];
if (args.replace?.length) {
const replace = args.replace.filter(arg => typeof arg === "string");
for (const replaceStr of replace) {
let [, re, replacement, flags] = (reReplaceString.exec(replaceStr) || []);
if (!re || !replacement) {
end(new Error(`Invalid replace string: ${replaceStr}`));
}
replacement = replaceTokens(replacement, newVersion);
replacements.push({re: new RegExp(re, flags || undefined), replacement});
}
}
const msgs = (args.message || []).filter(msg => typeof msg === "string");
const tagName = args["prefix"] ? `v${newVersion}` : newVersion;
// start background tasks early (before file processing and custom command)
const filesToAddPromise = (!args.gitless && !args.all && files.length) ? removeIgnoredFiles(files) : null;
const changelogPromise = (!args.gitless && !args.dry) ? (async () => {
let range = "";
const tagExists = await exec("git", ["rev-parse", "--verify", `refs/tags/${tagName}`]).then(() => true, () => false);
if (tagExists) {
range = `${tagName}..HEAD`;
} else if (cachedDescribeTag) {
range = `${cachedDescribeTag}..HEAD`;
}
try {
const logArgs = ["log"];
if (range) logArgs.push(range);
// https://git-scm.com/docs/pretty-formats
const {stdout} = await exec("git", [...logArgs, `--pretty=format:* %s (%aN)`]);
return stdout?.length ? stdout : undefined;
} catch {
return undefined;
}
})() : null;
if (files.length) {
// verify files exist
for (const file of files) {
const stats = statSync(file);
if (!stats.isFile() && !stats.isSymbolicLink()) {
throw new Error(`${file} is not a file`);
}
}
// update files
for (const file of files) {
const [filePath, newData] = getFileChanges({file, baseVersion, newVersion, replacements, date});
if (newData !== null) write(filePath, newData);
}
}
if (typeof args.command === "string") {
writeResult(await exec(args.command, [], {shell: true}));
}
if (args.gitless) return; // nothing else to do
if (args.dry) {
return console.info(`Would create new tag and commit: ${tagName}`);
}
const changelog = (await changelogPromise) ?? undefined;
// create commit
const commitMsg = joinStrings([tagName, ...msgs, changelog], "\n\n");
if (args.all) {
writeResult(await exec("git", ["commit", "-a", "--allow-empty", "-F", "-"], {stdin: {string: commitMsg}}));
} else {
const filesToAdd = (await filesToAddPromise) ?? [];
if (filesToAdd.length) {
writeResult(await exec("git", ["commit", "-i", "-F", "-", "--", ...filesToAdd], {stdin: {string: commitMsg}}));
} else {
writeResult(await exec("git", ["commit", "--allow-empty", "-F", "-"], {stdin: {string: commitMsg}}));
}
}
// create tag
const tagMsg = joinStrings([...msgs, changelog], "\n\n");
// adding explicit -a here seems to make git no longer sign the tag
writeResult(await exec("git", ["tag", "-f", "-F", "-", tagName], {stdin: {string: tagMsg}}));
// create release if requested
if (releasePrep) {
const repoInfo = await releasePrep.repoInfo;
if (!repoInfo) {
throw new Error("Could not determine repository type from git remote. Only GitHub and Gitea repositories are supported for release creation.");
}
const {stdout: branchOut} = await exec("git", ["rev-parse", "--abbrev-ref", "HEAD"]);
const branch = branchOut.trim();
if (branch === "HEAD") throw new Error("Cannot create release from detached HEAD");
writeResult(await exec("git", ["push", "origin", branch, tagName]));
const releaseBody = changelog || tagName;
const forgeName = repoInfo.type === "github" ? "GitHub" : "Gitea";
const tokens = await releasePrep.tokens;
if (!tokens.length) {
throw new Error(`${forgeName} release requested but no token found in environment`);
}
await createForgeRelease(repoInfo, tagName, releaseBody, tokens);
}
}
if (import.meta.filename === resolve(process.argv[1] ?? "")) {
main().then(end).catch(end);
}