@d-zero/release-automation 0.0.0-stage → 0.0.1

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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 D-ZERO Co., Ltd.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,59 @@
1
- # Temporary Holding Version
1
+ # @d-zero/release-automation
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ D-ZERO のリポジトリ運用ルールが要求する自動処理を実行する CLI。リリース系列の判定、Release PR の生成と検証、公開、Nightly、Renovate の PR の Approve を担う。各リポジトリは devDependencies に入れ、自分のワークフローから呼び出す。
4
+
5
+ ## インストール
6
+
7
+ ```sh
8
+ yarn add -D @d-zero/release-automation@<version>
9
+ ```
10
+
11
+ 呼び出すのはワークフローとエージェントだけなので、ヘルプ表示はない。コマンドとフラグは下の表のとおり。
12
+
13
+ ## 系列定義ファイル
14
+
15
+ `.github/release-lines.json`にリポジトリの系列を書く。
16
+
17
+ ```json
18
+ {
19
+ "lines": [
20
+ { "branch": "dev", "role": "current" },
21
+ { "branch": "v3", "role": "previous", "successorStable": "2026-04-01" }
22
+ ],
23
+ "supportMonths": 12,
24
+ "securityBatchMinutes": 60
25
+ }
26
+ ```
27
+
28
+ | キー | 意味 |
29
+ | ------------------------- | -------------------------------------------------------------------------------------------------------------------------------- |
30
+ | `lines[].role` | `current`(`dev`で開発し`main`から公開)、`next`(次メジャー。`v<N>`で開発・公開)、`previous`(旧メジャー。`v<N>`で保守・公開) |
31
+ | `lines[].successorStable` | 旧系列の後継メジャーの正式版の公開日。省略時はタグから読む |
32
+ | `supportMonths` | 旧系列のサポート期間。既定は12 |
33
+ | `securityBatchMinutes` | セキュリティ修正をまとめる時間。既定は60 |
34
+ | `publishCommand` | npm 公開しないリポジトリの公開コマンド。`DIST_TAG`環境変数を受け取る |
35
+
36
+ ## コマンド
37
+
38
+ | コマンド | 実行場所 | 内容 |
39
+ | -------------------------------------------------------- | ------------------------ | ---------------------------------------------------------------------------- |
40
+ | `classify [--json]` | ローカル | 系列・公開方式・レビュー方式を判定し、エラーとセットアップの作業を表示する |
41
+ | `lines-check` | CI | Renovate・ワークフロー・`SECURITY.md`・pre-commit が系列と一致するか検査する |
42
+ | `guard` | pre-commit | 系列のブランチと`main`への直接コミットを拒否する |
43
+ | `commit-check --base <branch>` | PR の CI | マージ先の系列が受け付けない破壊的変更を拒否する |
44
+ | `release-pr [--line] [--manual] [--promote] [--dry-run]` | 定期実行・手動 | 各系列の Release PR を作成・更新・差し替えする |
45
+ | `verify-release-pr --pr <n>` | `pull_request_target` | Release PR が自動生成されたものか検証する |
46
+ | `publish [--dry-run]` | 公開ブランチへの push | Release PR のマージを公開し、`dev`へ反映する |
47
+ | `nightly-dispatch [--force]` | 定期実行 | 各系列の Full CI を起動する(同じコミットの成功は再利用) |
48
+ | `nightly-report` | 定期実行・Full CI 完了時 | `release-blocker`・サポート終了・年齢ゲート例外の Issue を管理する |
49
+ | `audit-report --line <branch> --file <path>` | 定期実行 | 依存の監査結果を Issue にする |
50
+ | `approve-renovate --pr <n>` | `pull_request_target` | 自動マージ対象の Renovate の PR を Approve する |
51
+
52
+ ## 環境変数
53
+
54
+ | 変数 | 使うコマンド |
55
+ | --------------------------------------- | -------------------------------------------- |
56
+ | `GITHUB_REPOSITORY`、`GITHUB_TOKEN` | GitHub を読み書きするすべてのコマンド |
57
+ | `RELEASE_APP_TOKEN`、`RELEASE_APP_SLUG` | `release-pr`、`verify-release-pr`、`publish` |
58
+ | `PUBLISH_APP_TOKEN`、`PUBLISH_APP_SLUG` | `publish` |
59
+ | `APPROVE_APP_TOKEN` | `approve-renovate` |
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Adds a release to the top of a changelog, under its title. The result
3
+ * ends with exactly one newline and has one blank line between blocks, the
4
+ * shape Markdown formatters (oxfmt, Prettier) leave unchanged, so the
5
+ * format check of the Release PR passes.
6
+ * @param previous - The current changelog, or `null` when there is none
7
+ * @param release - The release
8
+ * @param release.version - The version
9
+ * @param release.date - The date, `YYYY-MM-DD`
10
+ * @param release.entries - One line per change, without the leading `- `
11
+ * @returns The new changelog
12
+ * @example
13
+ * prependRelease(null, { version: '0.0.1', date: '2026-11-26', entries: ['fix: x (abc1234)'] });
14
+ * // '# Changelog\n\n## 0.0.1 (2026-11-26)\n\n- fix: x (abc1234)\n'
15
+ */
16
+ export function prependRelease(previous, release) {
17
+ const [title = '# Changelog', ...rest] = (previous ?? '# Changelog\n').split('\n');
18
+ const body = rest.join('\n').trim();
19
+ const entry = [
20
+ `## ${release.version} (${release.date})`,
21
+ release.entries.map((line) => `- ${line}`).join('\n'),
22
+ ]
23
+ .filter((block) => block !== '')
24
+ .join('\n\n');
25
+ return `${[title, entry, body].filter((block) => block !== '').join('\n\n')}\n`;
26
+ }
@@ -0,0 +1,406 @@
1
+ import { compareVersions, formatVersion, parseVersion, stableTagVersion, } from './semver.js';
2
+ import { addMonths, formatDate } from './support-end.js';
3
+ import { CURRENT_BRANCH, CURRENT_PUBLISH_BRANCH, DEFAULT_SUPPORT_MONTHS, } from './types.js';
4
+ const LINE_BRANCH = /^v(0|[1-9]\d*)$/;
5
+ /**
6
+ * Decides how the rules apply to a repository: its publishing mode, review
7
+ * mode, age gate, and release lines, with the errors that stop the setup and
8
+ * the actions that bring the repository into shape.
9
+ *
10
+ * The lines file is the definition of the lines. A person confirms it once
11
+ * per repository: without the file, the lines are proposed from the branches
12
+ * and the tags (`source: 'proposal'`) for that confirmation. With the file,
13
+ * its lines are used, and only what contradicts the branches and the version
14
+ * on `dev` is an error. Tags are an imperfect record of the past (a history
15
+ * may lack tags, or carry those of an older project), so they never override
16
+ * the file.
17
+ * @param facts - What the repository states
18
+ * @returns The classification
19
+ * @example
20
+ * const { lines, errors, actions } = classify(facts);
21
+ */
22
+ export function classify(facts) {
23
+ const errors = [];
24
+ const actions = [];
25
+ const supportMonths = facts.linesFile?.supportMonths ?? DEFAULT_SUPPORT_MONTHS;
26
+ const publishMode = decidePublishMode(facts);
27
+ if (publishMode === 'custom' && !facts.linesFile?.publishCommand) {
28
+ errors.push({
29
+ code: 'missing-publish-command',
30
+ message: 'The repository publishes no npm package; set "publishCommand" in .github/release-lines.json',
31
+ });
32
+ }
33
+ const review = decideReview(facts.codeowners);
34
+ if (review === null) {
35
+ errors.push({
36
+ code: 'missing-codeowners',
37
+ message: 'Decide the code owners and write .github/CODEOWNERS',
38
+ });
39
+ }
40
+ const branchMajors = facts.branches
41
+ .map((branch) => ({ branch, match: LINE_BRANCH.exec(branch) }))
42
+ .filter((entry) => entry.match !== null)
43
+ .map(({ branch, match }) => ({ branch, major: Number(match[1]) }))
44
+ .toSorted((a, b) => a.major - b.major);
45
+ const stableByMajor = new Map();
46
+ for (const { tag, date } of facts.stableTags) {
47
+ const version = stableTagVersion(tag);
48
+ if (version) {
49
+ stableByMajor.set(version.major, [
50
+ ...(stableByMajor.get(version.major) ?? []),
51
+ { tag, date, version },
52
+ ]);
53
+ }
54
+ }
55
+ const successorFromTags = (major) => earliest([...stableByMajor.entries()]
56
+ .filter(([m]) => m > major)
57
+ .flatMap(([, list]) => list.map(({ date }) => date)));
58
+ const previousLine = (branch, major, successorStable) => {
59
+ const supportEnd = successorStable ? addMonths(successorStable, supportMonths) : null;
60
+ const phase = supportEnd === null
61
+ ? 'fixes'
62
+ : facts.now.getTime() < supportEnd.getTime()
63
+ ? 'security'
64
+ : 'ended';
65
+ return {
66
+ branch,
67
+ role: 'previous',
68
+ major,
69
+ publishBranch: branch,
70
+ stage: 'stable',
71
+ phase,
72
+ successorStable,
73
+ supportEnd,
74
+ };
75
+ };
76
+ const newestTag = (major) => (stableByMajor.get(major) ?? []).toSorted((a, b) => compareVersions(b.version, a.version))[0]?.tag;
77
+ const lines = [];
78
+ if (publishMode === 'lerna-independent') {
79
+ lines.push(currentLine(0, null));
80
+ for (const { branch } of branchMajors) {
81
+ errors.push({
82
+ code: 'branch-on-independent',
83
+ branch,
84
+ message: `${branch}: a repository in Lerna independent mode has one line; delete or rename the branch`,
85
+ });
86
+ }
87
+ return finish('proposal-or-file');
88
+ }
89
+ let dev;
90
+ try {
91
+ dev = parseVersion(facts.devVersion ?? '');
92
+ }
93
+ catch {
94
+ errors.push({
95
+ code: 'invalid-dev-version',
96
+ message: `The version on dev is not a valid version: ${facts.devVersion ?? '(none)'}`,
97
+ });
98
+ return finish('proposal-or-file');
99
+ }
100
+ lines.push(currentLine(dev.major, dev.pre?.id ?? 'stable'));
101
+ for (const { branch } of branchMajors.filter(({ major }) => major === dev.major)) {
102
+ errors.push({
103
+ code: 'branch-same-as-current',
104
+ branch,
105
+ message: `${branch}: dev carries v${dev.major}; delete or rename the branch`,
106
+ });
107
+ }
108
+ if (facts.linesFile !== null) {
109
+ fromFile(facts.linesFile, dev);
110
+ return finish('file');
111
+ }
112
+ const nextBranches = branchMajors.filter(({ major }) => major > dev.major);
113
+ for (const [index, { branch, major }] of nextBranches.entries()) {
114
+ if (!checkNext(branch, index, nextBranches[0]?.branch)) {
115
+ continue;
116
+ }
117
+ lines.push({
118
+ branch,
119
+ role: 'next',
120
+ major,
121
+ publishBranch: branch,
122
+ stage: null,
123
+ phase: null,
124
+ successorStable: null,
125
+ supportEnd: null,
126
+ });
127
+ }
128
+ const branchByMajor = new Map(branchMajors.filter(({ major }) => major < dev.major).map((b) => [b.major, b.branch]));
129
+ const olderMajors = [...new Set([...branchByMajor.keys(), ...stableByMajor.keys()])]
130
+ .filter((major) => major < dev.major)
131
+ .toSorted((a, b) => b - a);
132
+ for (const major of olderMajors) {
133
+ const branch = branchByMajor.get(major);
134
+ if ((stableByMajor.get(major) ?? []).length === 0) {
135
+ if (branch !== undefined) {
136
+ actions.push({
137
+ code: 'lock-branch',
138
+ branch,
139
+ message: `${branch}: v${major} has no stable release, so it is not a line; lock the branch and keep it`,
140
+ });
141
+ }
142
+ continue;
143
+ }
144
+ const line = previousLine(`v${major}`, major, successorFromTags(major));
145
+ if (line.phase === 'ended') {
146
+ if (branch !== undefined) {
147
+ actions.push({
148
+ code: 'lock-branch',
149
+ branch,
150
+ message: `${branch}: support ended; lock the branch and keep it`,
151
+ });
152
+ }
153
+ continue;
154
+ }
155
+ if (branch === undefined) {
156
+ const tag = newestTag(major);
157
+ actions.push({
158
+ code: 'create-branch',
159
+ branch: line.branch,
160
+ ...(tag ? { fromTag: tag } : {}),
161
+ message: `${line.branch}: v${major} is still supported; create the branch from ${tag ?? '?'}`,
162
+ });
163
+ }
164
+ lines.push(line);
165
+ }
166
+ return finish('proposal-or-file');
167
+ /**
168
+ * Takes the lines from the file and reports what contradicts the facts.
169
+ * @param file - The lines file
170
+ * @param current - The version on `dev`
171
+ */
172
+ function fromFile(file, current) {
173
+ const entries = file.lines;
174
+ if (!entries.some(({ branch, role }) => branch === CURRENT_BRANCH && role === 'current')) {
175
+ invalid(`the file needs { "branch": "${CURRENT_BRANCH}", "role": "current" }`);
176
+ }
177
+ const nextEntries = entries.filter(({ role }) => role === 'next');
178
+ for (const entry of entries) {
179
+ if (entry.role === 'current') {
180
+ if (entry.branch !== CURRENT_BRANCH) {
181
+ invalid(`${entry.branch}: the current line is on ${CURRENT_BRANCH}`);
182
+ }
183
+ continue;
184
+ }
185
+ const major = Number(LINE_BRANCH.exec(entry.branch)?.[1] ?? Number.NaN);
186
+ if (Number.isNaN(major)) {
187
+ invalid(`${entry.branch}: a ${entry.role} line is on a v<major> branch`);
188
+ continue;
189
+ }
190
+ if (entry.role === 'next') {
191
+ if (major <= current.major) {
192
+ invalid(`${entry.branch}: a next-major line is above v${current.major}`);
193
+ continue;
194
+ }
195
+ if (!checkNext(entry.branch, nextEntries.indexOf(entry), nextEntries[0]?.branch)) {
196
+ continue;
197
+ }
198
+ if (!facts.branches.includes(entry.branch)) {
199
+ invalid(`${entry.branch}: the branch does not exist`);
200
+ }
201
+ lines.push({
202
+ branch: entry.branch,
203
+ role: 'next',
204
+ major,
205
+ publishBranch: entry.branch,
206
+ stage: null,
207
+ phase: null,
208
+ successorStable: null,
209
+ supportEnd: null,
210
+ });
211
+ continue;
212
+ }
213
+ if (major >= current.major) {
214
+ invalid(`${entry.branch}: a previous line is below v${current.major}`);
215
+ continue;
216
+ }
217
+ const line = previousLine(entry.branch, major, successorDate(entry) ?? successorFromTags(major));
218
+ if (!facts.branches.includes(entry.branch)) {
219
+ const tag = newestTag(major);
220
+ if (tag === undefined) {
221
+ invalid(`${entry.branch}: the branch does not exist and no v${major}.x.y tag to create it from`);
222
+ continue;
223
+ }
224
+ actions.push({
225
+ code: 'create-branch',
226
+ branch: entry.branch,
227
+ fromTag: tag,
228
+ message: `${entry.branch}: create the branch from ${tag}`,
229
+ });
230
+ }
231
+ if (line.phase === 'ended') {
232
+ actions.push({
233
+ code: 'line-ended',
234
+ branch: entry.branch,
235
+ message: `${entry.branch}: support ended on ${formatDate(line.supportEnd ?? facts.now)}; run the end-of-support work of the major-rotation skill`,
236
+ });
237
+ }
238
+ lines.push(line);
239
+ }
240
+ const listed = new Set(entries.map(({ branch }) => branch));
241
+ for (const { branch, major } of branchMajors) {
242
+ if (!listed.has(branch) && major !== current.major) {
243
+ actions.push({
244
+ code: 'lock-branch',
245
+ branch,
246
+ message: `${branch}: not a line in the lines file; lock the branch and keep it`,
247
+ });
248
+ }
249
+ }
250
+ }
251
+ /**
252
+ * @param entry - A line of the file
253
+ * @returns The date the file states, or `null`
254
+ */
255
+ function successorDate(entry) {
256
+ if (entry.successorStable === undefined) {
257
+ return null;
258
+ }
259
+ const date = new Date(`${entry.successorStable}T00:00:00Z`);
260
+ if (Number.isNaN(date.getTime())) {
261
+ invalid(`${entry.branch}: "successorStable" is not a YYYY-MM-DD date`);
262
+ return null;
263
+ }
264
+ return date;
265
+ }
266
+ /**
267
+ * @param branch - A next-major branch
268
+ * @param index - Its position among the next-major branches
269
+ * @param first - The first next-major branch
270
+ * @returns Whether it can be the next-major line
271
+ */
272
+ function checkNext(branch, index, first) {
273
+ if (dev.pre !== null) {
274
+ errors.push({
275
+ code: 'next-while-prerelease',
276
+ branch,
277
+ message: `${branch}: the next major cannot start while dev (${formatVersion(dev)}) is a prerelease; delete the branch or release dev as stable first`,
278
+ });
279
+ return false;
280
+ }
281
+ if (index > 0) {
282
+ errors.push({
283
+ code: 'multiple-next',
284
+ branch,
285
+ message: `${branch}: only one next-major line is allowed (${first ?? '?'} is the next major); delete the branch`,
286
+ });
287
+ return false;
288
+ }
289
+ return true;
290
+ }
291
+ /**
292
+ * @param message - What is wrong with the lines file
293
+ */
294
+ function invalid(message) {
295
+ errors.push({
296
+ code: 'invalid-lines-file',
297
+ message: `.github/release-lines.json: ${message}`,
298
+ });
299
+ }
300
+ /**
301
+ * @param major - The major on `dev`
302
+ * @param stage - Its stage
303
+ * @returns The current line
304
+ */
305
+ function currentLine(major, stage) {
306
+ return {
307
+ branch: CURRENT_BRANCH,
308
+ role: 'current',
309
+ major,
310
+ publishBranch: CURRENT_PUBLISH_BRANCH,
311
+ stage,
312
+ phase: null,
313
+ successorStable: null,
314
+ supportEnd: null,
315
+ };
316
+ }
317
+ /**
318
+ * @param mode - `file` when the lines came from the file
319
+ * @returns The classification
320
+ */
321
+ function finish(mode) {
322
+ const source = mode === 'file' ? 'file' : facts.linesFile === null ? 'proposal' : 'file';
323
+ const expectedLinesFile = source === 'file' && facts.linesFile !== null
324
+ ? facts.linesFile
325
+ : {
326
+ ...facts.linesFile,
327
+ lines: lines.map(({ branch, role }) => ({ branch, role })),
328
+ };
329
+ if (facts.linesFile === null) {
330
+ actions.push({
331
+ code: 'write-lines-file',
332
+ message: 'Confirm the proposed lines with a person, then write .github/release-lines.json',
333
+ });
334
+ }
335
+ return {
336
+ publishMode,
337
+ review,
338
+ ageGate: decideAgeGate(facts.packageManager),
339
+ source,
340
+ lines,
341
+ expectedLinesFile,
342
+ errors,
343
+ actions,
344
+ };
345
+ }
346
+ }
347
+ /**
348
+ * @param facts - The repository facts
349
+ * @returns The publishing mode
350
+ */
351
+ function decidePublishMode(facts) {
352
+ if (facts.lernaVersion === 'independent') {
353
+ return 'lerna-independent';
354
+ }
355
+ if (facts.lernaVersion !== null) {
356
+ return 'lerna-fixed';
357
+ }
358
+ return facts.rootPrivate ? 'custom' : 'npm-single';
359
+ }
360
+ /**
361
+ * A team owner (`@org/team`) counts as more than one person.
362
+ * @param codeowners - The owners, or `null` without the file
363
+ * @returns The review mode and the number of approvals, or `null` without owners
364
+ */
365
+ function decideReview(codeowners) {
366
+ const owners = codeowners === null ? [] : [...new Set(codeowners)];
367
+ if (owners.length === 0) {
368
+ return null;
369
+ }
370
+ const collaborative = owners.length > 1 || owners.some((owner) => owner.includes('/'));
371
+ return collaborative
372
+ ? { mode: 'collaborative', approvals: 1 }
373
+ : { mode: 'solo', approvals: 0 };
374
+ }
375
+ /**
376
+ * @param packageManager - `package.json#packageManager`
377
+ * @returns The age gate setting, or `null` when the version supports none
378
+ */
379
+ function decideAgeGate(packageManager) {
380
+ const match = /^(yarn|pnpm)@(\d+)\.(\d+)\.(\d+)/.exec(packageManager ?? '');
381
+ if (!match) {
382
+ return null;
383
+ }
384
+ const [, name, major, minor] = match;
385
+ const atLeast = (m, n) => Number(major) > m || (Number(major) === m && Number(minor) >= n);
386
+ if (name === 'yarn' && atLeast(4, 10)) {
387
+ return { file: '.yarnrc.yml', key: 'npmMinimalAgeGate', value: '3d' };
388
+ }
389
+ if (name === 'pnpm' && atLeast(10, 16)) {
390
+ return { file: 'pnpm-workspace.yaml', key: 'minimumReleaseAge', value: '4320' };
391
+ }
392
+ return null;
393
+ }
394
+ /**
395
+ * @param dates - Dates
396
+ * @returns The earliest, or `null` for none
397
+ */
398
+ function earliest(dates) {
399
+ let result = null;
400
+ for (const date of dates) {
401
+ if (result === null || date.getTime() < result.getTime()) {
402
+ result = date;
403
+ }
404
+ }
405
+ return result;
406
+ }
package/dist/cli.js ADDED
@@ -0,0 +1,126 @@
1
+ #!/usr/bin/env node
2
+ import { readFileSync } from 'node:fs';
3
+ import { parseArgs } from 'node:util';
4
+ import { approveRenovateCommand } from './commands/approve-renovate.js';
5
+ import { classifyCommand, commitCheckCommand, guardCommand, linesCheckCommand, } from './commands/local.js';
6
+ import { auditReportCommand, nightlyDispatchCommand, nightlyReportCommand, } from './commands/nightly.js';
7
+ import { publishCommand } from './commands/publish.js';
8
+ import { releasePrCommand } from './commands/release-pr.js';
9
+ import { verifyReleasePrCommand } from './commands/verify-release-pr.js';
10
+ /**
11
+ * The commands and their flags. Workflows and agents call the CLI, not people,
12
+ * so there is no help text: the README lists the commands.
13
+ */
14
+ const COMMANDS = {
15
+ classify: { json: { type: 'boolean' } },
16
+ 'lines-check': {},
17
+ guard: {},
18
+ 'commit-check': { base: { type: 'string' } },
19
+ 'release-pr': {
20
+ line: { type: 'string' },
21
+ manual: { type: 'boolean' },
22
+ promote: { type: 'string' },
23
+ 'dry-run': { type: 'boolean' },
24
+ },
25
+ 'verify-release-pr': { pr: { type: 'string' } },
26
+ publish: { 'dry-run': { type: 'boolean' } },
27
+ 'nightly-dispatch': { force: { type: 'boolean' } },
28
+ 'nightly-report': {},
29
+ 'audit-report': { line: { type: 'string' }, file: { type: 'string' } },
30
+ 'approve-renovate': { pr: { type: 'string' } },
31
+ };
32
+ const PROMOTIONS = new Set(['beta', 'rc', 'stable']);
33
+ /**
34
+ * @param values - The parsed flags
35
+ * @param name - A flag that must be given
36
+ * @returns Its value
37
+ */
38
+ function required(values, name) {
39
+ const value = values[name];
40
+ if (typeof value !== 'string' || value === '') {
41
+ throw new Error(`--${name} is required`);
42
+ }
43
+ return value;
44
+ }
45
+ /**
46
+ * @param values - The parsed flags
47
+ * @returns The value of `--pr` as a pull request number
48
+ */
49
+ function prNumber(values) {
50
+ const value = Number(required(values, 'pr'));
51
+ if (!Number.isInteger(value) || value <= 0) {
52
+ throw new Error('--pr takes a pull request number');
53
+ }
54
+ return value;
55
+ }
56
+ try {
57
+ const [command, ...rest] = process.argv.slice(2);
58
+ if (command === undefined || !Object.hasOwn(COMMANDS, command)) {
59
+ throw new Error(`Unknown command: ${command ?? '(none)'}. Commands: ${Object.keys(COMMANDS).join(', ')}`);
60
+ }
61
+ const name = command;
62
+ const { values } = parseArgs({ args: rest, options: COMMANDS[name], strict: true });
63
+ const flags = values;
64
+ switch (name) {
65
+ case 'classify': {
66
+ process.exitCode = classifyCommand({ json: flags['json'] === true });
67
+ break;
68
+ }
69
+ case 'lines-check': {
70
+ process.exitCode = await linesCheckCommand();
71
+ break;
72
+ }
73
+ case 'guard': {
74
+ process.exitCode = guardCommand();
75
+ break;
76
+ }
77
+ case 'commit-check': {
78
+ process.exitCode = await commitCheckCommand({ base: required(flags, 'base') });
79
+ break;
80
+ }
81
+ case 'release-pr': {
82
+ const promote = typeof flags['promote'] === 'string' ? flags['promote'] : null;
83
+ if (promote !== null && !PROMOTIONS.has(promote)) {
84
+ throw new Error('--promote takes beta, rc or stable');
85
+ }
86
+ await releasePrCommand({
87
+ ...(typeof flags['line'] === 'string' ? { line: flags['line'] } : {}),
88
+ manual: flags['manual'] === true,
89
+ promote: promote,
90
+ dryRun: flags['dry-run'] === true,
91
+ });
92
+ break;
93
+ }
94
+ case 'verify-release-pr': {
95
+ await verifyReleasePrCommand({ pr: prNumber(flags) });
96
+ break;
97
+ }
98
+ case 'publish': {
99
+ await publishCommand({ dryRun: flags['dry-run'] === true });
100
+ break;
101
+ }
102
+ case 'nightly-dispatch': {
103
+ await nightlyDispatchCommand({ force: flags['force'] === true });
104
+ break;
105
+ }
106
+ case 'nightly-report': {
107
+ await nightlyReportCommand();
108
+ break;
109
+ }
110
+ case 'audit-report': {
111
+ await auditReportCommand({
112
+ line: required(flags, 'line'),
113
+ output: readFileSync(required(flags, 'file'), 'utf8'),
114
+ });
115
+ break;
116
+ }
117
+ case 'approve-renovate': {
118
+ await approveRenovateCommand({ pr: prNumber(flags) });
119
+ break;
120
+ }
121
+ }
122
+ }
123
+ catch (error) {
124
+ process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
125
+ process.exitCode = 1;
126
+ }
@@ -0,0 +1,35 @@
1
+ import { canApproveRenovatePr } from '../pr-checks.js';
2
+ import { github, summary } from './context.js';
3
+ /**
4
+ * Approves a Renovate pull request with the Approve App's token
5
+ * (`APPROVE_APP_TOKEN`) when {@link canApproveRenovatePr} allows it. Reads
6
+ * everything from the API, so it runs on `pull_request_target` without
7
+ * checking out the pull request.
8
+ * @param options - The pull request
9
+ * @param options.pr - Its number
10
+ * @example
11
+ * await approveRenovateCommand({ pr: 42 });
12
+ */
13
+ export async function approveRenovateCommand(options) {
14
+ const gh = github('APPROVE_APP_TOKEN');
15
+ const pr = await gh.rest('GET', `/repos/{repo}/pulls/${options.pr}`);
16
+ const commits = await gh.paginate(`/repos/{repo}/pulls/${options.pr}/commits`);
17
+ const result = canApproveRenovatePr({
18
+ author: pr.user.login,
19
+ commits: commits.map((commit) => ({
20
+ author: commit.author?.login ?? null,
21
+ verified: commit.commit.verification?.verified === true,
22
+ })),
23
+ body: pr.body ?? '',
24
+ labels: pr.labels.map(({ name }) => name),
25
+ });
26
+ if (!result.ok) {
27
+ await summary(`#${options.pr}: not approved (${result.reasons.join('; ')})`);
28
+ return;
29
+ }
30
+ await gh.rest('POST', `/repos/{repo}/pulls/${options.pr}/reviews`, {
31
+ event: 'APPROVE',
32
+ commit_id: pr.head.sha,
33
+ });
34
+ await summary(`#${options.pr}: approved`);
35
+ }