@peiyanlu/release 1.3.1 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1032 @@
1
+ import { getBooleanInput, getInput, setFailed, setOutput } from "@actions/core";
2
+ import { context, getOctokit } from "@actions/github";
3
+ import { assert, dedent, isBoolean, isEmpty, isIndex, isNotEmpty, isNull, isString, isUndefined, newline, sleep, throwError, tryCall } from "@peiyanlu/ts-utils";
4
+ import { existsSync, readFileSync } from "node:fs";
5
+ import path, { join, parse, resolve } from "node:path";
6
+ import { fileURLToPath, pathToFileURL } from "node:url";
7
+ import { getGithubUrl, gitAdd, gitBranch, gitBranchCurrent, gitCheckoutBranch, gitCheckoutBranchForce, gitCommitMessage, gitConfigSet, gitFetch, gitLog, gitLsRemote, gitPush, gitPushBranch, gitRevParse, gitTag } from "@peiyanlu/cli-utils";
8
+ import { readJsonFileSync } from "@peiyanlu/node-utils";
9
+ import "conventional-changelog";
10
+ import "conventional-changelog-conventionalcommits";
11
+ import "conventional-recommended-bump";
12
+ import "@conventional-changelog/template";
13
+ import "semver";
14
+ import { Octokit } from "@octokit/rest";
15
+ import open from "open";
16
+ import { glob } from "tinyglobby";
17
+ import "yaml";
18
+ import "@clack/prompts";
19
+ import "ansis";
20
+ // src/config/index.ts
21
+ const loadJavaScriptFile = async (file) => {
22
+ const { href } = pathToFileURL(file);
23
+ const mod = await import(href);
24
+ const temp = "default" in mod ? mod.default : mod;
25
+ return typeof temp === "function" ? temp() : temp;
26
+ };
27
+ const findFile = (cwd, filename, extensions) => {
28
+ for (const ext of extensions) {
29
+ const path = resolve(cwd, `${filename}.${ext}`);
30
+ if (existsSync(path)) return path;
31
+ }
32
+ };
33
+ const loadConfig = async (cwd = process.cwd()) => {
34
+ const file = findFile(cwd, "release.config", [
35
+ "ts",
36
+ "mts",
37
+ "js",
38
+ "mjs"
39
+ ]);
40
+ if (!file) return {
41
+ file: "",
42
+ config: {}
43
+ };
44
+ return {
45
+ file,
46
+ config: await loadJavaScriptFile(file)
47
+ };
48
+ };
49
+ // src/core/hosting/hosting.ts
50
+ /** Git 仓库托管服务的基类 */
51
+ var GitRepositoryHosting = class {};
52
+ // src/core/utils.ts
53
+ const when = (condition, ...value) => condition ? [...value] : [];
54
+ // src/core/logger.ts
55
+ const defaultPrinter = ({ dryRun, stage, message }) => {
56
+ console.log(`${dryRun ? `[dry-run]` : ""}[${stage}]:`, message);
57
+ };
58
+ /** 一个子消息记录器,绑定到特定阶段 */
59
+ var ChildLogger = class {
60
+ parent;
61
+ stage;
62
+ /**
63
+ * 创建子日志记录器。
64
+ * @param parent - 要继承其选项的父日志记录器。
65
+ * @param stage - 此日志记录器所属的处理阶段。
66
+ */
67
+ constructor(parent, stage) {
68
+ this.parent = parent;
69
+ this.stage = stage;
70
+ }
71
+ /**
72
+ * 记录一条普通信息。
73
+ * @param message - 要记录的信息。
74
+ */
75
+ info(message) {
76
+ this.parent.info(this.stage, message);
77
+ }
78
+ /**
79
+ * 记录一条详细信息。
80
+ * @param message - 要记录的信息。
81
+ */
82
+ verbose(message) {
83
+ this.parent.verbose(this.stage, message);
84
+ }
85
+ };
86
+ /** 消息记录器 */
87
+ var Logger = class {
88
+ options;
89
+ printer;
90
+ colors;
91
+ colorMap = /* @__PURE__ */ new Map();
92
+ constructor(options = {}) {
93
+ this.options = options;
94
+ const { colors = [], printer = defaultPrinter } = options;
95
+ this.colors = colors;
96
+ this.printer = printer;
97
+ }
98
+ info(stage, message) {
99
+ const { silent, dryRun } = this.options;
100
+ if (!silent) {
101
+ const color = this.getColor(stage);
102
+ this.printer({
103
+ dryRun,
104
+ stage,
105
+ message,
106
+ color
107
+ });
108
+ }
109
+ }
110
+ verbose(stage, message) {
111
+ const { silent, verbose, dryRun } = this.options;
112
+ if (!silent && (verbose || dryRun)) {
113
+ const color = this.getColor(stage);
114
+ this.printer({
115
+ dryRun,
116
+ stage,
117
+ message,
118
+ color
119
+ });
120
+ }
121
+ }
122
+ createChild(stage) {
123
+ return new ChildLogger(this, stage);
124
+ }
125
+ getColor(stage) {
126
+ const cached = this.colorMap.get(stage);
127
+ if (cached) return cached;
128
+ const index = this.colorMap.size % this.colors.length;
129
+ const color = this.colors[index] ?? ((text) => text);
130
+ this.colorMap.set(stage, color);
131
+ return color;
132
+ }
133
+ };
134
+ // src/core/releaser.ts
135
+ var Releaser = class {
136
+ options;
137
+ project;
138
+ hosting;
139
+ logger;
140
+ stepsOptions = {};
141
+ skippedSteps = {};
142
+ state = {};
143
+ queue = [];
144
+ constructor(options) {
145
+ this.options = options;
146
+ const { project, hosting, logger, ...log } = options;
147
+ this.project = project;
148
+ this.hosting = hosting;
149
+ this.logger = logger ?? new Logger(log);
150
+ }
151
+ enqueue(fn) {
152
+ this.queue.push(fn);
153
+ return this;
154
+ }
155
+ setOptions(options) {
156
+ const logger = this.logger.createChild("set-options");
157
+ logger.verbose("Setting options for steps:");
158
+ logger.verbose(options);
159
+ for (const [key, value] of Object.entries(options)) Object.assign(this.stepsOptions[key] ??= {}, value);
160
+ logger.verbose("Final options for steps:");
161
+ logger.verbose(this.stepsOptions);
162
+ return this;
163
+ }
164
+ setUser(options) {
165
+ return this.enqueue(async () => {
166
+ const { options: { dryRun }, stepsOptions: { setUser } } = this;
167
+ const { username, email } = {
168
+ ...setUser,
169
+ ...options
170
+ };
171
+ const logger = this.logger.createChild("set-user");
172
+ if (this.shouldSkip("setUser")) {
173
+ logger.info("Skipping set git user.");
174
+ return;
175
+ }
176
+ logger.info("Setting git user...");
177
+ if (!username && !email) {
178
+ logger.info("No git user configuration provided.");
179
+ return;
180
+ }
181
+ if (username) {
182
+ logger.verbose(`Setting git user.name to "${username}".`);
183
+ if (!dryRun) await gitConfigSet("user.name", username);
184
+ }
185
+ if (email) {
186
+ logger.verbose(`Setting git user.email to "${email}".`);
187
+ if (!dryRun) await gitConfigSet("user.email", email);
188
+ }
189
+ });
190
+ }
191
+ setSkippedSteps(options) {
192
+ const logger = this.logger.createChild("set-skipped-steps");
193
+ logger.verbose("Setting skipped for steps:");
194
+ logger.verbose(options);
195
+ Object.assign(this.skippedSteps, options);
196
+ logger.verbose("Final skipped for steps:");
197
+ logger.verbose(this.skippedSteps);
198
+ return this;
199
+ }
200
+ checkout(options) {
201
+ return this.enqueue(async () => {
202
+ const { options: { dryRun }, stepsOptions: { checkout } } = this;
203
+ const { branch: headBranch = "release-branch", fetch, force } = {
204
+ ...checkout,
205
+ ...options
206
+ };
207
+ const logger = this.logger.createChild("checkout");
208
+ if (this.shouldSkip("checkout")) {
209
+ logger.info("Skipping checkout.");
210
+ return;
211
+ }
212
+ logger.info(`Checking out branch "${headBranch}"...`);
213
+ this.state.headBranch = headBranch;
214
+ this.state.baseBranch = await this.getBaseBranch();
215
+ if (fetch) {
216
+ logger.verbose(`Fetching all commits and tags from the remote repository...`);
217
+ if (!dryRun) await gitFetch([
218
+ "--prune",
219
+ "--unshallow",
220
+ "--tags",
221
+ "--",
222
+ "origin",
223
+ "HEAD"
224
+ ]);
225
+ }
226
+ if (force) {
227
+ logger.verbose(`Force checking out branch "${headBranch}"...`);
228
+ if (!dryRun) await gitCheckoutBranchForce(headBranch);
229
+ } else {
230
+ logger.verbose(`Checking out branch "${headBranch}"...`);
231
+ if (!dryRun) await gitCheckoutBranch(headBranch);
232
+ }
233
+ });
234
+ }
235
+ bump(options) {
236
+ return this.enqueue(async () => {
237
+ const { project, options: { dryRun }, stepsOptions: { bump } } = this;
238
+ const logger = this.logger.createChild("bump");
239
+ if (this.shouldSkip("bump")) {
240
+ logger.info("Skipping bump.");
241
+ return;
242
+ }
243
+ logger.info("Bumping version...");
244
+ const done = await project.bump({
245
+ dryRun,
246
+ logger,
247
+ ...bump,
248
+ ...options
249
+ });
250
+ this.state.bump = done;
251
+ if (!done) logger.info("No version changes detected.");
252
+ });
253
+ }
254
+ commit(options) {
255
+ return this.enqueue(async () => {
256
+ const { project, options: { dryRun }, state, stepsOptions: { commit } } = this;
257
+ const { sign, allowEmpty } = {
258
+ ...commit,
259
+ ...options
260
+ };
261
+ const logger = this.logger.createChild("commit");
262
+ if (this.shouldSkip("commit")) {
263
+ logger.info("Skipping commit.");
264
+ return;
265
+ }
266
+ logger.info(`Committing changes...`);
267
+ if (!state.bump) {
268
+ logger.info("No changes to commit.");
269
+ return;
270
+ }
271
+ const files = project.changedFiles;
272
+ const message = await project.getCommitMessage();
273
+ logger.verbose(`Files to commit:`);
274
+ files.forEach((file) => {
275
+ logger.verbose(`- ${file}`);
276
+ });
277
+ logger.verbose(message.includes("\n") ? `Commit message:\n\n${message}` : `Commit message: ${message}`);
278
+ if (!dryRun) {
279
+ await gitAdd(["--", ...files]);
280
+ await gitCommitMessage(message, [
281
+ ...when(sign, "--gpg-sign"),
282
+ ...when(allowEmpty, "--allow-empty"),
283
+ "--no-verify"
284
+ ]);
285
+ }
286
+ });
287
+ }
288
+ revert() {
289
+ return this.enqueue(async () => {
290
+ const { project, logger, options: { dryRun } } = this;
291
+ logger.info("revert", "Reverting version updates...");
292
+ if (!await project.revert({
293
+ dryRun,
294
+ logger: logger.createChild("revert")
295
+ })) {
296
+ logger.info("revert", "No version updates to revert.");
297
+ return;
298
+ }
299
+ this.state.bump = false;
300
+ });
301
+ }
302
+ maintenanceBranch(options) {
303
+ return this.enqueue(async () => {
304
+ const { project, options: { dryRun }, stepsOptions: { maintenanceBranch } } = this;
305
+ const { enabled, force } = {
306
+ ...maintenanceBranch,
307
+ ...options
308
+ };
309
+ const logger = this.logger.createChild("maintenance-branch");
310
+ if (this.shouldSkip("maintenanceBranch")) {
311
+ logger.info("Skipping create maintenance branches.");
312
+ return;
313
+ }
314
+ logger.info("Creating maintenance branches...");
315
+ if (!enabled) {
316
+ logger.info("Maintenance branch creation is disabled.");
317
+ return;
318
+ }
319
+ logger.verbose("Fetching fresh tags from the remote repository...");
320
+ if (!dryRun) await gitFetch(["--tags"]);
321
+ const branches = await project.getMaintenanceBranches();
322
+ if (!branches.length) {
323
+ logger.info("No maintenance branches to create.");
324
+ return;
325
+ }
326
+ logger.verbose("Branches to create:");
327
+ for (const { from, to } of branches) {
328
+ logger.verbose(`- ${to} from ${from}`);
329
+ if (dryRun) continue;
330
+ if ((await gitRevParse(["--verify", `refs/heads/${to}`]) || await gitLsRemote([
331
+ "--heads",
332
+ "origin",
333
+ to
334
+ ])) && !force) {
335
+ logger.info(`Branch ${to} already exists, skipping.`);
336
+ continue;
337
+ }
338
+ const args = when(force, "--force");
339
+ await gitBranch([
340
+ ...args,
341
+ "--",
342
+ to,
343
+ from
344
+ ]);
345
+ await gitPushBranch("origin", to, ["--no-verify", ...args]);
346
+ }
347
+ });
348
+ }
349
+ tag(options) {
350
+ return this.enqueue(async () => {
351
+ const { project, options: { dryRun }, stepsOptions: { tag } } = this;
352
+ const { fetch, sign } = {
353
+ ...tag,
354
+ ...options
355
+ };
356
+ const logger = this.logger.createChild("tag");
357
+ if (this.shouldSkip("tag")) {
358
+ logger.info("Skipping tag.");
359
+ return;
360
+ }
361
+ logger.info("Tagging version...");
362
+ if (fetch) {
363
+ logger.verbose("Fetching fresh tags from the remote repository...");
364
+ if (!dryRun) await gitFetch(["--tags"]);
365
+ }
366
+ const tags = await project.getTags();
367
+ this.state.tags = tags.length > 0;
368
+ if (!this.state.tags) {
369
+ logger.info("No version changes detected.");
370
+ return;
371
+ }
372
+ logger.verbose(`Tags to create:`);
373
+ for (const tag of tags) {
374
+ logger.verbose(`- ${tag}`);
375
+ if (!dryRun) await gitTag([
376
+ sign ? "--sign" : "--annotate",
377
+ "--message",
378
+ tag,
379
+ tag
380
+ ]);
381
+ }
382
+ });
383
+ }
384
+ push(options) {
385
+ return this.enqueue(async () => {
386
+ const { options: { dryRun }, state, stepsOptions: { push } } = this;
387
+ const { force } = {
388
+ ...push,
389
+ ...options
390
+ };
391
+ const logger = this.logger.createChild("push");
392
+ if (this.shouldSkip("push")) {
393
+ logger.info("Skipping push.");
394
+ return;
395
+ }
396
+ const branch = await gitBranchCurrent();
397
+ logger.info(`Pushing changes to "${branch}"...`);
398
+ if (!state.bump && !state.tags) {
399
+ logger.info("Nothing to push.");
400
+ return;
401
+ }
402
+ if (!dryRun) {
403
+ if (state.bump) await gitPushBranch("origin", branch, [...when(force, "--force"), "--no-verify"]);
404
+ if (state.tags) await gitPush([
405
+ "origin",
406
+ "--tags",
407
+ "--no-verify"
408
+ ]);
409
+ }
410
+ });
411
+ }
412
+ publish(options) {
413
+ return this.enqueue(async () => {
414
+ const { project, options: { dryRun }, stepsOptions: { publish } } = this;
415
+ const logger = this.logger.createChild("publish");
416
+ if (this.shouldSkip("publish")) {
417
+ logger.info("Skipping publish.");
418
+ return;
419
+ }
420
+ logger.info("Publishing...");
421
+ const tagsMap = await project.getDefaultPublishTag();
422
+ const name = await project.manifest.getName();
423
+ const tag = tagsMap.get(name);
424
+ await project.publish({
425
+ dryRun,
426
+ logger,
427
+ tag,
428
+ ...publish,
429
+ ...options
430
+ });
431
+ });
432
+ }
433
+ release(option) {
434
+ const { hosting } = this;
435
+ if (!hosting) throwError("Hosting service is not configured. Please set the hosting option.");
436
+ return this.enqueue(async () => {
437
+ const { project, options: { dryRun }, stepsOptions: { release } } = this;
438
+ const logger = this.logger.createChild("release");
439
+ if (this.shouldSkip("release")) {
440
+ logger.info("Skipping release.");
441
+ return;
442
+ }
443
+ logger.info("Creating release...");
444
+ await hosting.createRelease({
445
+ project,
446
+ dryRun,
447
+ logger,
448
+ ...release,
449
+ ...option
450
+ });
451
+ });
452
+ }
453
+ pullRequest(option) {
454
+ const { hosting } = this;
455
+ if (!hosting) throwError("Hosting service is not configured. Please set the hosting option.");
456
+ return this.enqueue(async () => {
457
+ const { project, state, options: { dryRun }, stepsOptions: { pullRequest } } = this;
458
+ const logger = this.logger.createChild("pull-request");
459
+ if (this.shouldSkip("pullRequest")) {
460
+ logger.info("Skipping pull request.");
461
+ return;
462
+ }
463
+ logger.info("Creating pull request...");
464
+ if (!state.bump) {
465
+ logger.info("No version changes detected, skipping pull request creation.");
466
+ return;
467
+ }
468
+ if (!state.headBranch) {
469
+ logger.info("Head branch is not set, skipping pull request creation.");
470
+ return;
471
+ }
472
+ await hosting.createPullRequest({
473
+ project,
474
+ dryRun,
475
+ logger,
476
+ from: state.headBranch,
477
+ to: await this.getBaseBranch(),
478
+ ...pullRequest,
479
+ ...option
480
+ });
481
+ });
482
+ }
483
+ async run(condition) {
484
+ let shouldRun = true;
485
+ if (condition) {
486
+ const logger = this.logger.createChild("run");
487
+ logger.info("Checking condition...");
488
+ shouldRun = await condition(this);
489
+ if (shouldRun) logger.info("Condition passed, running release steps...");
490
+ else logger.info("Condition failed, skipping release steps.");
491
+ }
492
+ if (shouldRun) for (const fn of this.queue) await fn();
493
+ const logger = this.logger.createChild("done");
494
+ this.queue.length = 0;
495
+ logger.info(`Done!`);
496
+ }
497
+ shouldSkip(step) {
498
+ return this.skippedSteps[step] === true;
499
+ }
500
+ async getBaseBranch() {
501
+ const { state: { baseBranch } } = this;
502
+ if (baseBranch) return baseBranch;
503
+ return gitBranchCurrent();
504
+ }
505
+ };
506
+ // src/hosting-github/github.ts
507
+ var GithubHosting = class extends GitRepositoryHosting {
508
+ options;
509
+ octokit;
510
+ browser;
511
+ constructor(options = {}) {
512
+ const { octokit, token, browser } = options;
513
+ super();
514
+ this.options = options;
515
+ this.browser = browser ?? (!octokit && !token);
516
+ this.octokit = octokit ?? new Octokit({ auth: token });
517
+ }
518
+ async createRelease(options) {
519
+ const { project, dryRun, logger } = options;
520
+ const { octokit, browser } = this;
521
+ const releaseData = await project.getReleaseData();
522
+ if (isEmpty(releaseData)) {
523
+ logger?.info("No release data found. Skipping release creation.");
524
+ return;
525
+ }
526
+ const [owner, repo] = await this.getRepositoryId(project);
527
+ for (const data of releaseData) {
528
+ logger?.verbose(`Creating GitHub release "${data.title}"...`);
529
+ const browserRelease = async () => {
530
+ const url = new URL(`${getGithubUrl(owner, repo)}/releases/new`);
531
+ Object.entries({
532
+ tag: data.nextTag,
533
+ title: data.title,
534
+ body: data.notes,
535
+ prerelease: data.isPrerelease
536
+ }).forEach(([key, value]) => {
537
+ url.searchParams.set(key, String(value));
538
+ });
539
+ logger?.verbose(`Opening GitHub release page for tag "${data.nextTag}"...`);
540
+ await open(url.toString());
541
+ await sleep(1500);
542
+ };
543
+ const resetRelease = async () => {
544
+ const res = await (async () => {
545
+ const release = await this.getRelease({
546
+ owner,
547
+ repo,
548
+ tag: data.nextTag
549
+ });
550
+ const opts = {
551
+ owner,
552
+ repo,
553
+ tag_name: data.nextTag,
554
+ name: data.title,
555
+ body: data.notes,
556
+ prerelease: data.isPrerelease,
557
+ make_latest: data.isLatest ? "true" : "false"
558
+ };
559
+ if (release) {
560
+ const { data } = await octokit.rest.repos.updateRelease({
561
+ ...opts,
562
+ release_id: release.id
563
+ });
564
+ return data;
565
+ } else {
566
+ const { data } = await octokit.rest.repos.createRelease({
567
+ ...opts,
568
+ draft: false
569
+ });
570
+ return data;
571
+ }
572
+ })();
573
+ if (!res) return;
574
+ await this.uploadAssets({
575
+ owner,
576
+ repo,
577
+ release_id: res.id,
578
+ assets: []
579
+ });
580
+ };
581
+ if (!dryRun) browser ? await browserRelease() : await resetRelease();
582
+ }
583
+ }
584
+ async createPullRequest(options) {
585
+ const { project, dryRun, draft, logger } = options;
586
+ let { from, to } = options;
587
+ const { octokit } = this;
588
+ const [owner, repo] = await this.getRepositoryId(project);
589
+ from ||= await gitBranchCurrent();
590
+ to ||= await this.getDefaultBranch(owner, repo);
591
+ if (from === to) throwError("Cannot create a pull request from the same branch.");
592
+ const [pr] = await this.listPullRequest({
593
+ owner,
594
+ repo,
595
+ from
596
+ });
597
+ if (pr) logger?.info(`Updating existing pull request #${pr.number}`);
598
+ logger?.verbose("Pull request data:");
599
+ if (!pr && draft) logger?.verbose("Draft: true");
600
+ const { title, body } = await this.getPullRequestData(project, from, to);
601
+ logger?.verbose(`${from} -> ${to}`);
602
+ logger?.verbose(`Title: ${title}`);
603
+ logger?.verbose(`Body:\n\n${body}`);
604
+ const opts = {
605
+ owner,
606
+ repo,
607
+ title,
608
+ body
609
+ };
610
+ if (!dryRun) {
611
+ if (pr) await octokit.rest.pulls.update({
612
+ ...opts,
613
+ pull_number: pr.number
614
+ });
615
+ else await octokit.rest.pulls.create({
616
+ ...opts,
617
+ base: to,
618
+ head: from,
619
+ draft
620
+ });
621
+ }
622
+ }
623
+ async getRepositoryId(project) {
624
+ let { options: { owner, repo } } = this;
625
+ const i = project.getHostedGitInfo();
626
+ return [owner ?? (await i).owner, repo ?? (await i).repo];
627
+ }
628
+ async uploadAssets(options) {
629
+ const { octokit } = this;
630
+ const { owner, repo, release_id, assets } = options;
631
+ const files = await glob(assets);
632
+ await Promise.all(files.map((file) => {
633
+ const { base: filename } = parse(file);
634
+ return octokit.rest.repos.uploadReleaseAsset({
635
+ owner,
636
+ repo,
637
+ release_id,
638
+ name: filename,
639
+ data: readFileSync(file, "utf-8")
640
+ });
641
+ }));
642
+ }
643
+ async getRelease(options) {
644
+ const { octokit } = this;
645
+ const { data } = await tryCall(() => octokit.rest.repos.getReleaseByTag({ ...options }), { data: void 0 });
646
+ return data;
647
+ }
648
+ async listPullRequest(options) {
649
+ const { octokit } = this;
650
+ const { owner, repo, from } = options;
651
+ const { data } = await tryCall(() => octokit.rest.pulls.list({
652
+ owner,
653
+ repo,
654
+ head: `${owner}:${from}`,
655
+ state: "open"
656
+ }), { data: [] });
657
+ return data;
658
+ }
659
+ async getDefaultBranch(owner, repo) {
660
+ const { octokit } = this;
661
+ const { data: { default_branch } } = await tryCall(() => octokit.rest.repos.get({
662
+ owner,
663
+ repo
664
+ }), { data: { default_branch: "master" } });
665
+ return default_branch;
666
+ }
667
+ async getPullRequestData(project, from, to) {
668
+ return {
669
+ title: (await project.getCommitMessage()).split("\n")[0],
670
+ body: [project.versionUpdates.map(({ name, notes }) => `# ${name}${newline(2)}${notes.trim()}`).join(newline(2)), dedent(`
671
+ <!--
672
+ Release pull request metadata.
673
+ release-pull-request: true
674
+ release-branch-from: ${from}
675
+ release-branch-to: ${to}
676
+ -->
677
+ `)].join(newline(2))
678
+ };
679
+ }
680
+ };
681
+ // src/releaser-github-action/comment.ts
682
+ const ALLOWED_AUTHOR_ASSOCIATIONS = [
683
+ "OWNER",
684
+ "COLLABORATOR",
685
+ "MEMBER"
686
+ ];
687
+ const JSON_START = "```json";
688
+ const JSON_START_OFFSET = 7;
689
+ const JSON_END = "```";
690
+ /** 所有支持的拉取请求评论命令 */
691
+ const COMMANDS = ["!release/set-options", "!release/set-preamble"];
692
+ /**
693
+ * 判断正文是否以命令开头,并且命令后紧跟空白字符或正文结束。
694
+ * 这样可以避免将更长的标记(例如 `!release/set-options-foo`)误判为匹配的命令
695
+ */
696
+ const startsWithCommand = (body, command) => {
697
+ if (!body.startsWith(command)) return false;
698
+ const nextChar = body[command.length];
699
+ return isUndefined(nextChar) || /\s/.test(nextChar);
700
+ };
701
+ /** 评论内容是否是支持的命令评论之一 */
702
+ const isCommandComment = (body) => isString(body) && COMMANDS.some((command) => startsWithCommand(body, command));
703
+ /** 解析 releaser 参数 */
704
+ const parseSetOptionsComment = (comment) => {
705
+ if (ALLOWED_AUTHOR_ASSOCIATIONS.includes(comment.author_association)) {
706
+ const { body } = comment;
707
+ if (body && startsWithCommand(body, "!release/set-options")) {
708
+ const start = body.indexOf(JSON_START);
709
+ const end = isIndex(start) ? body.indexOf(JSON_END, start + JSON_START_OFFSET) : -1;
710
+ if (!isIndex(start) || !isIndex(end)) return;
711
+ return body.substring(start + JSON_START_OFFSET, end).trim();
712
+ }
713
+ }
714
+ };
715
+ /** 解析日志前言 */
716
+ function parseSetPreambleComment(comment) {
717
+ if (ALLOWED_AUTHOR_ASSOCIATIONS.includes(comment.author_association)) {
718
+ const { body } = comment;
719
+ if (body && startsWithCommand(body, "!release/set-preamble")) {
720
+ const newlineIndex = body.indexOf("\n");
721
+ const firstLine = isIndex(newlineIndex) ? body.slice(0, newlineIndex) : body;
722
+ const secondLine = isIndex(newlineIndex) ? body.slice(newlineIndex + 1).trim() : "";
723
+ const name = firstLine.slice(21).replace(/`/g, "").trim().split(/\s+/)[0];
724
+ const preamble = secondLine;
725
+ if (preamble) return {
726
+ name,
727
+ preamble
728
+ };
729
+ }
730
+ }
731
+ return null;
732
+ }
733
+ // src/releaser-github-action/conditions.ts
734
+ const ifReleaseCommit = async (releaser) => {
735
+ const { project, options: { dryRun } } = releaser;
736
+ const logger = releaser.logger.createChild("if-release-commit");
737
+ if (!(await gitLog(["-1", "--pretty=%B"]))?.startsWith("chore(release):")) {
738
+ logger.verbose("Current commit is not a release commit.");
739
+ return false;
740
+ }
741
+ const authorName = await gitLog(["-1", "--pretty=%an"]);
742
+ if (!authorName?.startsWith("github-actions[bot]")) {
743
+ logger.info(`Release commit author "${authorName ?? "unknown"}" is not "github-actions[bot]".`);
744
+ process.exit(0);
745
+ }
746
+ logger.verbose("Checking for existing release tags...");
747
+ if (!dryRun) await gitFetch(["--tags"]);
748
+ const tags = await project.getTags();
749
+ const canRelease = tags.length > 0;
750
+ if (canRelease) {
751
+ logger.verbose(`Found release tags:`);
752
+ for (const tag of tags) logger.verbose(`- ${tag}`);
753
+ } else logger.verbose(`No release tags found.`);
754
+ return canRelease;
755
+ };
756
+ /**
757
+ * 检测当前事件是否为针对处于打开状态的发布拉取请求的受支持命令评论:
758
+ * (`!release/set-options` 或 `!release/set-preamble`)
759
+ *
760
+ * @returns 如果是此类评论,则返回 `目标分支`;如果是评论事件但不是命令评论,则返回 `false`;如果根本不是评论事件,则返回 `null`
761
+ */
762
+ const ifCommandComment = () => {
763
+ const { eventName, payload: { issue, comment } } = context;
764
+ if (eventName !== "issue_comment") return null;
765
+ const isPullRequest = issue?.pull_request;
766
+ const issueAuthor = (issue?.user)?.login;
767
+ const issueBody = issue?.body;
768
+ const issueState = issue?.state;
769
+ const commentBody = comment?.body;
770
+ if (isPullRequest && issueAuthor === "github-actions[bot]" && issueState === "open" && issueBody?.includes("release-pull-request: true") && isCommandComment(commentBody)) {
771
+ const matches = issueBody.match(/release-branch-to:\s*(\S+)/);
772
+ return matches ? matches[1] : false;
773
+ }
774
+ return false;
775
+ };
776
+ // src/releaser-github-action/options.ts
777
+ const omitEmpty = (object) => {
778
+ const result = {};
779
+ for (const [key, value] of Object.entries(object)) if (isBoolean(value) || Boolean(value)) result[key] = value;
780
+ return result;
781
+ };
782
+ const getOptionalBooleanInput = (name) => getInput(name) ? getBooleanInput(name) : void 0;
783
+ const getOptionalJsonInput = (name) => {
784
+ const value = getInput(name);
785
+ return value ? JSON.parse(value) : void 0;
786
+ };
787
+ const getInputOptions = () => ({
788
+ checkout: omitEmpty({ branch: getInput("checkout-branch") }),
789
+ bump: omitEmpty({
790
+ version: getInput("bump-version"),
791
+ as: getInput("bump-as"),
792
+ prerelease: getInput("bump-prerelease"),
793
+ snapshot: getInput("bump-snapshot"),
794
+ firstRelease: getOptionalBooleanInput("bump-first-release"),
795
+ byProject: getOptionalJsonInput("bump-by-project")
796
+ }),
797
+ maintenanceBranch: omitEmpty({ enabled: getOptionalBooleanInput("maintenance-branch-enabled") }),
798
+ publish: omitEmpty({
799
+ access: getInput("publish-access"),
800
+ tag: getInput("publish-tag")
801
+ })
802
+ });
803
+ const getInputSkippedSteps = () => ({
804
+ bump: getOptionalBooleanInput("bump-skip"),
805
+ publish: getOptionalBooleanInput("publish-skip")
806
+ });
807
+ // src/releaser-github-action/releaser.ts
808
+ var ReleaserGithubAction = class extends Releaser {
809
+ setUser(options = {}) {
810
+ return super.setUser({
811
+ username: "github-actions[bot]",
812
+ email: "github-actions[bot]@users.noreply.github.com",
813
+ ...options
814
+ });
815
+ }
816
+ checkout(options = {}) {
817
+ return super.checkout({
818
+ fetch: true,
819
+ force: true,
820
+ ...options
821
+ });
822
+ }
823
+ tag(options = {}) {
824
+ return super.tag({
825
+ fetch: true,
826
+ ...options
827
+ });
828
+ }
829
+ push(options = {}) {
830
+ return super.push({
831
+ force: true,
832
+ ...options
833
+ });
834
+ }
835
+ constructor(options) {
836
+ super({
837
+ hosting: new GithubHosting({ octokit: options.octokit }),
838
+ ...options
839
+ });
840
+ }
841
+ fetchOptions() {
842
+ return this.enqueue(async () => {
843
+ const { state: { headBranch }, stepsOptions: { bump: bumpOpts } } = this;
844
+ if (!headBranch) throwError("Head branch is not set. Please call `checkout` before `fetchParams`.");
845
+ const { project, hosting } = this;
846
+ const logger = this.logger.createChild("fetch-options");
847
+ logger.info("Fetching options from pull request comments...");
848
+ const { octokit } = hosting;
849
+ const [owner, repo] = await hosting.getRepositoryId(project);
850
+ const { data: [pr] } = await octokit.rest.pulls.list({
851
+ owner,
852
+ repo,
853
+ head: `${owner}:${headBranch}`,
854
+ state: "open"
855
+ });
856
+ if (!pr) {
857
+ logger.info("No open pull request found.");
858
+ return;
859
+ }
860
+ const { data: comments } = await octokit.rest.issues.listComments({
861
+ owner,
862
+ repo,
863
+ issue_number: pr.number
864
+ });
865
+ let optionsApplied = false;
866
+ let preamble;
867
+ const preambleByName = /* @__PURE__ */ new Map();
868
+ for (let i = comments.length - 1, comment; i >= 0; i--) {
869
+ comment = comments[i];
870
+ if (!optionsApplied) {
871
+ const json = parseSetOptionsComment(comment);
872
+ if (json) {
873
+ try {
874
+ const options = JSON.parse(json);
875
+ logger.verbose("Found set-options comment:");
876
+ logger.verbose(json);
877
+ this.setOptions(options);
878
+ optionsApplied = true;
879
+ } catch {
880
+ logger.verbose("Failed to parse parameters comment:");
881
+ logger.verbose(json);
882
+ }
883
+ continue;
884
+ }
885
+ }
886
+ const setPreamble = parseSetPreambleComment(comment);
887
+ if (setPreamble) {
888
+ const { name, preamble: markdown } = setPreamble;
889
+ if (name) {
890
+ if (!preambleByName.has(name)) preambleByName.set(name, markdown);
891
+ } else if (isUndefined(preamble)) preamble = markdown;
892
+ }
893
+ }
894
+ if (isEmpty(preamble) && isEmpty(preambleByName)) return;
895
+ const bump = { ...bumpOpts };
896
+ if (isNotEmpty(preamble)) {
897
+ logger.verbose("Found global set-preamble comment.");
898
+ bump.preamble = preamble;
899
+ }
900
+ if (isNotEmpty(preambleByName)) for (const [name, markdown] of preambleByName) (bump.byProject ??= {})[name] = {
901
+ ...bump.byProject?.[name],
902
+ preamble: markdown
903
+ };
904
+ this.setOptions({ bump });
905
+ });
906
+ }
907
+ fetch() {
908
+ return this.enqueue(async () => {
909
+ const { logger, options: { dryRun } } = this;
910
+ logger.info("fetch", "Fetching all commits and tags from the remote repository...");
911
+ if (!dryRun) {
912
+ const unshallow = await gitRevParse(["--is-shallow-repository"]) === "true" ? ["--unshallow"] : [];
913
+ await gitFetch([
914
+ "--prune",
915
+ "--tags",
916
+ ...unshallow,
917
+ "--",
918
+ "origin",
919
+ "HEAD"
920
+ ]);
921
+ }
922
+ });
923
+ }
924
+ async runPullRequestAction() {
925
+ await this.setUser().checkout().fetchOptions().bump().commit().push().pullRequest().run();
926
+ }
927
+ async runReleaseAction(check = true) {
928
+ await this.setUser().maintenanceBranch().tag().push().publish().release().run(check ? ifReleaseCommit : void 0);
929
+ }
930
+ async runSnapshotAction(snapshotTag) {
931
+ if (!snapshotTag) throwError("Snapshot tag is required.");
932
+ await this.fetch().bump({
933
+ snapshot: snapshotTag,
934
+ skipChangelog: true
935
+ }).publish({ tag: snapshotTag }).revert().run();
936
+ }
937
+ async runAction() {
938
+ const logger = this.logger.createChild("run");
939
+ logger.info("Detecting action...");
940
+ const commandComment = ifCommandComment();
941
+ let isReleaseCommit = false;
942
+ if (commandComment === false) {
943
+ logger.info("Action triggered by a pull request comment.");
944
+ logger.info("No command comment found in a comment. Stopping action.");
945
+ return;
946
+ }
947
+ if (!isNull(commandComment)) {
948
+ logger.info("Action triggered by a pull request comment.");
949
+ if (await gitBranchCurrent() !== commandComment) this.checkout({
950
+ branch: commandComment,
951
+ fetch: true,
952
+ force: false
953
+ });
954
+ } else isReleaseCommit = await ifReleaseCommit(this);
955
+ if (isReleaseCommit) {
956
+ logger.info("Running release action...");
957
+ await this.runReleaseAction(false);
958
+ } else {
959
+ logger.info("Running pull request action...");
960
+ await this.runPullRequestAction();
961
+ }
962
+ }
963
+ };
964
+ // node_modules/.pnpm/tsdown@0.23.4_publint@0.3.25_typescript@6.0.3/node_modules/tsdown/esm-shims.js
965
+ const getFilename = () => fileURLToPath(import.meta.url);
966
+ const getDirname = () => path.dirname(getFilename());
967
+ readJsonFileSync(join(/* @__PURE__ */ getDirname(), "..", "package.json"));
968
+ // src/action.ts
969
+ const workflow = getInput("workflow");
970
+ console.log(`Triggered by: ${context.eventName}`);
971
+ console.log(`Current workflow: ${workflow}`);
972
+ if (workflow === "check" && ifCommandComment() === false) {
973
+ setOutput("continue", "false");
974
+ setOutput("workflow", "none");
975
+ process.exit(0);
976
+ }
977
+ const GITHUB_TOKEN = getInput("github-token", { required: true });
978
+ const NODE_AUTH_TOKEN = getInput("npm-token");
979
+ const inputOptions = getInputOptions();
980
+ const skippedSteps = getInputSkippedSteps();
981
+ if (NODE_AUTH_TOKEN) process.env.NODE_AUTH_TOKEN = NODE_AUTH_TOKEN;
982
+ try {
983
+ const { config: { project, hosting, releaser, ...options }, file } = await loadConfig(process.cwd());
984
+ assert(project, "Project is required.");
985
+ console.log(`Legacy config file: ${file}`);
986
+ const gha = new ReleaserGithubAction({
987
+ project,
988
+ octokit: getOctokit(GITHUB_TOKEN),
989
+ ...releaser
990
+ }).setOptions({
991
+ ...options,
992
+ checkout: {
993
+ ...options.checkout,
994
+ ...inputOptions.checkout
995
+ },
996
+ bump: {
997
+ ...options.bump,
998
+ ...inputOptions.bump
999
+ },
1000
+ maintenanceBranch: {
1001
+ ...options.maintenanceBranch,
1002
+ ...inputOptions.maintenanceBranch
1003
+ },
1004
+ publish: {
1005
+ ...options.publish,
1006
+ ...inputOptions.publish
1007
+ }
1008
+ }).setSkippedSteps(skippedSteps);
1009
+ switch (workflow) {
1010
+ case "check":
1011
+ const workflow = await ifReleaseCommit(gha) ? "release" : "pull-request";
1012
+ console.log(`Next workflow: ${workflow}`);
1013
+ setOutput("continue", "true");
1014
+ setOutput("workflow", workflow);
1015
+ break;
1016
+ case "full":
1017
+ await gha.runAction();
1018
+ break;
1019
+ case "pull-request":
1020
+ await gha.runPullRequestAction();
1021
+ break;
1022
+ case "release":
1023
+ await gha.runReleaseAction();
1024
+ break;
1025
+ case "snapshot": await gha.runSnapshotAction(inputOptions.bump?.snapshot);
1026
+ }
1027
+ } catch (error) {
1028
+ if (error instanceof Error) setFailed(error.message);
1029
+ else setFailed("An unknown error occurred");
1030
+ throw error;
1031
+ }
1032
+ export {};