-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathindex.ts
More file actions
executable file
·594 lines (512 loc) · 20.3 KB
/
index.ts
File metadata and controls
executable file
·594 lines (512 loc) · 20.3 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
592
593
594
#!/usr/bin/env node
import {SubprocessError, type Result} from "nano-spawn";
import {spawnEnhanced} from "./utils.ts";
import {parseArgs} from "node:util";
import {basename, dirname, join, relative} 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"};
import {parse} from "smol-toml";
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 reNewline = /\r?\n/;
const reDatePattern = /([^0-9]|^)[0-9]{4}-[0-9]{2}-[0-9]{2}([^0-9]|$)/g;
const reReplaceString = /^s#([^#]+)#([^#]+)#(.*)$/;
function esc(str: string): string {
return str.replace(reEscapeChars, "\\$&");
}
function isSemver(str: string): boolean {
return reSemver.test(str.replace(reVersionPrefix, ""));
}
function uniq<T extends Array<any>>(arr: T): T {
return Array.from(new Set(arr)) as T;
}
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);
}
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`;
}
return str.replace(rePatchVersion, (_, m1, m2, m3) => `${m1}${Number(m2) + 1}${m3}`);
}
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);
}
}
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;
}
function readVersionFromPyprojectToml(projectRoot: string): string | null {
const pyprojectPath = findUp("pyproject.toml", projectRoot);
if (!pyprojectPath) return null;
try {
const content = readFileSync(pyprojectPath, "utf8");
const toml = parse(content) as any;
// Try project.version first (PEP 621 style)
if (toml.project?.version && isSemver(toml.project.version)) {
return toml.project.version.replace(reVersionPrefix, "");
}
// Try tool.poetry.version (Poetry style)
if (toml.tool?.poetry?.version && isSemver(toml.tool.poetry.version)) {
return toml.tool.poetry.version.replace(reVersionPrefix, "");
}
} catch {}
return null;
}
async function removeIgnoredFiles(files: Array<string>): Promise<Array<string>> {
let result: Result;
try {
result = await spawnEnhanced("git", ["check-ignore", "--", ...files]);
} catch {
return files;
}
const ignoredFiles = new Set<string>(result.stdout.split(reNewline));
return files.filter(file => !ignoredFiles.has(file));
}
type GetFileChangesOpts = {
file: string,
baseVersion: string,
newVersion: string,
replacements?: Array<{re: RegExp | string, replacement: string}>,
date?: string,
};
function getFileChanges({file, baseVersion, newVersion, replacements, date}: GetFileChangesOpts): Array<string> {
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, readFileSync(file, "utf8")];
}
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 toml = parse(projStr) as {project: {name: string}};
const name = toml.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];
}
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
function joinStrings(strings: Array<string | undefined>, separator: string): string {
const arr: Array<string> = [];
for (const string of strings) {
if (!string) continue;
arr.push(string);
}
return arr.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 ensureEol(str: string): string {
return str.endsWith(EOL) ? str : `${str}${EOL}`;
}
function getGithubToken(): string | null {
return process.env.VERSIONS_FORGE_TOKEN ||
process.env.GITHUB_API_TOKEN ||
process.env.GITHUB_TOKEN ||
process.env.GH_TOKEN ||
process.env.HOMEBREW_GITHUB_API_TOKEN ||
null;
}
function getGiteaToken(): string | null {
return process.env.VERSIONS_FORGE_TOKEN ||
process.env.GITEA_API_TOKEN ||
process.env.GITEA_AUTH_TOKEN ||
process.env.GITEA_TOKEN ||
null;
}
type RepoInfo = {
owner: string;
repo: string;
host: string;
type: "github" | "gitea";
};
async function getRepoInfo(): Promise<RepoInfo | null> {
try {
const {stdout} = await spawnEnhanced("git", ["remote", "get-url", "origin"]);
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;
}
}
async function createForgeRelease(repoInfo: RepoInfo, tagName: string, body: string, token: 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 releaseData = {
tag_name: tagName,
name: tagName,
body,
draft: false,
prerelease: rePrereleaseVersion.test(tagName) && tagName.includes("-"),
};
const headers: Record<string, string> = {
"Content-Type": "application/json",
"Authorization": repoInfo.type === "github" ? `Bearer ${token}` : `token ${token}`,
};
const response = await fetch(apiUrl, {
method: "POST",
headers,
body: JSON.stringify(releaseData),
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(`Failed to create release: ${response.status} ${response.statusText}\n${errorText}`);
}
const result = await response.json();
if (result.html_url) {
console.info(`Created release: ${result.html_url}`);
} else {
console.info("Created release");
}
}
function writeResult(result: Result): void {
if (result.stdout) stdout.write(ensureEol(result.stdout));
if (result.stderr) stdout.write(ensureEol(result.stderr));
}
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"},
packageless: {short: "P", 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 = uniq(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 with the changelog as body
-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;
// obtain old version
let baseVersion: 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 spawnEnhanced("git", ["describe", "--tags", "--abbrev=0"]);
const tag = result.stdout.trim();
if (isSemver(tag)) {
baseVersion = tag.replace(reVersionPrefix, "");
}
} catch {}
// Fall back to full tag list if describe didn't yield a semver tag
if (!baseVersion) {
try {
({stdout} = await spawnEnhanced("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 prerelease requirements
if (level === "prerelease" && !args.preid) {
return end(new Error("prerelease requires --preid option"));
}
// 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});
}
}
// start background tasks early (before file processing and custom command)
const repoInfoPromise = (!args.gitless && args.release) ? getRepoInfo() : null;
const filesToAddPromise = (!args.gitless && !args.all && files.length) ? removeIgnoredFiles(files) : 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
const todo: Array<Array<string>> = [];
for (const file of files) {
todo.push(getFileChanges({file, baseVersion, newVersion, replacements, date}));
}
for (const [file, newData] of todo) {
write(file, newData);
}
}
if (typeof args.command === "string") {
writeResult(await spawnEnhanced(args.command, [], {shell: true}));
}
if (args.gitless) return; // nothing else to do
const msgs = (args.message || []).filter(msg => typeof msg === "string");
const tagName = args["prefix"] ? `v${newVersion}` : newVersion;
// determine changelog range (parallel git queries)
let range = "";
{
const [showResult, describeResult] = await Promise.allSettled([
spawnEnhanced("git", ["show", tagName]),
spawnEnhanced("git", ["describe", "--abbrev=0"]),
]);
if (showResult.status === "fulfilled") {
range = `${tagName}..HEAD`;
} else if (describeResult.status === "fulfilled") {
range = `${describeResult.value.stdout}..HEAD`;
}
}
let changelog: string | undefined;
try {
const args = ["log"];
if (range) args.push(range);
// https://git-scm.com/docs/pretty-formats
const {stdout} = await spawnEnhanced("git", [...args, `--pretty=format:* %s (%aN)`]);
if (stdout?.length) changelog = stdout;
} catch {}
if (args.dry) {
return console.info(`Would create new tag and commit: ${tagName}`);
}
// create commit
const commitMsg = joinStrings([tagName, ...msgs, changelog], "\n\n");
if (args.all) {
writeResult(await spawnEnhanced("git", ["commit", "-a", "--allow-empty", "-F", "-"], {stdin: {string: commitMsg}}));
} else {
const filesToAdd = filesToAddPromise ? await filesToAddPromise : [];
if (filesToAdd.length) {
writeResult(await spawnEnhanced("git", ["commit", "-i", "-F", "-", "--", ...filesToAdd], {stdin: {string: commitMsg}}));
} else {
writeResult(await spawnEnhanced("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 spawnEnhanced("git", ["tag", "-f", "-F", "-", tagName], {stdin: {string: tagMsg}}));
// create release if requested
if (args.release) {
const repoInfo = await repoInfoPromise!;
if (!repoInfo) {
throw new Error("Could not determine repository type from git remote. Only GitHub and Gitea repositories are supported for release creation.");
}
const releaseBody = changelog || tagName;
if (repoInfo.type === "github") {
const token = getGithubToken();
if (!token) {
throw new Error("GitHub release requested but no token found in environment");
}
await createForgeRelease(repoInfo, tagName, releaseBody, token);
} else if (repoInfo.type === "gitea") {
const token = getGiteaToken();
if (!token) {
throw new Error("Gitea release requested but no token found in environment");
}
await createForgeRelease(repoInfo, tagName, releaseBody, token);
}
}
}
main().then(end).catch(end);