@d-zero/release-automation 0.0.0 → 0.0.2

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/README.md CHANGED
@@ -35,19 +35,32 @@ yarn add -D @d-zero/release-automation@<version>
35
35
 
36
36
  ## コマンド
37
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 する |
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> [--exit-code <n>]` | 定期実行 | 依存の脆弱性の監査結果を系列の Issue にする(下記) |
50
+ | `approve-renovate --pr <n>` | `pull_request_target` | 自動マージ対象の Renovate の PR を Approve する |
51
+
52
+ ### `audit-report`
53
+
54
+ `--file`には`yarn npm audit --all --recursive --json`の標準出力を、`--exit-code`にはその終了コードを渡す。非推奨パッケージの告知は脆弱性ではないので数えない。
55
+
56
+ | 監査の結果 | 系列の Issue |
57
+ | ------------------------------------- | -------------------------------------------------------------------- |
58
+ | 脆弱性がある | 作る。開いていれば、内容が変わったときに本文を書き換えてコメントする |
59
+ | 脆弱性がなく、終了コードが 0 | 閉じる |
60
+ | 脆弱性がなく、終了コードが 0 以外 | そのまま。コマンドは終了コード 1 で失敗する |
61
+ | 脆弱性がなく、`--exit-code`の指定なし | そのまま(問題なしと失敗を区別できないため) |
62
+
63
+ Issue の本文は監査のたびに書き換わるので、メモはコメントに書く。
51
64
 
52
65
  ## 環境変数
53
66
 
package/dist/audit.js ADDED
@@ -0,0 +1,129 @@
1
+ /**
2
+ * Reads the output of `yarn npm audit --json` (one JSON object per line).
3
+ * Lines that are not JSON objects with a package name are skipped. Deprecation
4
+ * notices are counted but not taken as findings: rule 36 asks for an audit of
5
+ * vulnerabilities, and a notice never clears while the package stays. A line
6
+ * that starts with `{` but is not JSON throws, since skipping it could make a
7
+ * failed audit look clean.
8
+ * @param output - The audit output
9
+ * @returns The findings, in the order of the output, and the number of deprecation notices
10
+ * @example
11
+ * parseAudit('{"value":"tmp","children":{"ID":1,"Issue":"Path traversal","Severity":"high"}}');
12
+ * // { findings: [{ name: 'tmp', issue: 'Path traversal', severity: 'high', url: '' }], deprecations: 0 }
13
+ */
14
+ export function parseAudit(output) {
15
+ const entries = output
16
+ .split('\n')
17
+ .map((line, index) => ({ line, number: index + 1 }))
18
+ .filter(({ line }) => line.trim().startsWith('{'))
19
+ .map(({ line, number }) => {
20
+ try {
21
+ return JSON.parse(line);
22
+ }
23
+ catch (error) {
24
+ throw new Error(`Cannot read line ${number} of the audit output`, {
25
+ cause: error,
26
+ });
27
+ }
28
+ })
29
+ .flatMap((entry) => entry.value === undefined ? [] : [{ name: entry.value, children: entry.children }]);
30
+ const deprecations = entries.filter((entry) => isDeprecation(entry.children?.['ID']));
31
+ return {
32
+ findings: entries
33
+ .filter((entry) => !deprecations.includes(entry))
34
+ .map((entry) => ({
35
+ name: entry.name,
36
+ issue: text(entry.children?.['Issue']),
37
+ severity: text(entry.children?.['Severity']),
38
+ url: text(entry.children?.['URL']),
39
+ })),
40
+ deprecations: deprecations.length,
41
+ };
42
+ }
43
+ /**
44
+ * Decides what an audit means (rule 36), in this order:
45
+ * 1. findings are reported, whatever the exit code
46
+ * 2. without the exit code, nothing more can be told
47
+ * 3. exit code 0 is clean
48
+ * 4. deprecation notices alone are clean: Yarn exits with 1 on them, and they
49
+ * show that the audit reached the registry
50
+ * 5. otherwise the audit failed. `yarn npm audit` prints nothing to standard
51
+ * output both when it is clean and when it fails (for example, the registry
52
+ * is unreachable), so only the exit code tells them apart
53
+ * @param result - The result from {@link parseAudit}
54
+ * @param exitCode - The exit code of `yarn npm audit`, or null when the workflow did not pass it
55
+ * @returns The outcome
56
+ * @example
57
+ * auditOutcome({ findings: [], deprecations: 0 }, 0); // 'clean'
58
+ * auditOutcome({ findings: [], deprecations: 0 }, 1); // 'failed'
59
+ */
60
+ export function auditOutcome(result, exitCode) {
61
+ if (result.findings.length > 0) {
62
+ return 'report';
63
+ }
64
+ if (exitCode === null) {
65
+ return 'unknown';
66
+ }
67
+ if (exitCode === 0 || result.deprecations > 0) {
68
+ return 'clean';
69
+ }
70
+ return 'failed';
71
+ }
72
+ /**
73
+ * The audit Issue of a line (rule 36). The body holds the latest findings,
74
+ * sorted so that it depends only on the line and the findings, not on the
75
+ * order of the audit output: an unchanged audit gives an unchanged body, and
76
+ * the Nightly rewrites the Issue only when the findings change.
77
+ * @param line - The branch the audit ran on
78
+ * @param findings - The findings
79
+ * @returns The Issue
80
+ * @example
81
+ * auditIssue('dev', parseAudit(output)).marker; // '<!-- release-automation:audit:dev -->'
82
+ */
83
+ export function auditIssue(line, findings) {
84
+ const marker = auditMarker(line);
85
+ const lines = findings
86
+ .map((finding) => `- \`${finding.name}\`: ${finding.issue} (${finding.severity}) ${finding.url}`.trimEnd())
87
+ .toSorted();
88
+ return {
89
+ marker,
90
+ title: `Vulnerable dependencies on ${line}`,
91
+ body: [
92
+ marker,
93
+ '',
94
+ `The dependency audit of \`${line}\` found:`,
95
+ '',
96
+ ...lines,
97
+ '',
98
+ 'This list is rewritten with each audit. Write notes in comments, not here.',
99
+ '',
100
+ 'Fix them on the line (a vulnerability fix PR, `resolutions`, or the age gate exception of the repository policy), then this Issue closes after a clean audit.',
101
+ '',
102
+ ].join('\n'),
103
+ };
104
+ }
105
+ /**
106
+ * The marker of a line's audit Issue.
107
+ * @param line - The branch
108
+ * @returns The marker
109
+ * @example
110
+ * auditMarker('v3'); // '<!-- release-automation:audit:v3 -->'
111
+ */
112
+ export function auditMarker(line) {
113
+ return `<!-- release-automation:audit:${line} -->`;
114
+ }
115
+ /**
116
+ * Yarn gives a deprecation notice the ID `<name> (deprecation)`, and an
117
+ * advisory a number.
118
+ * @param id - The `ID` of an entry
119
+ */
120
+ function isDeprecation(id) {
121
+ return typeof id === 'string' && id.endsWith('(deprecation)');
122
+ }
123
+ /**
124
+ * A field as text, empty when missing.
125
+ * @param value - The field
126
+ */
127
+ function text(value) {
128
+ return typeof value === 'string' ? value : '';
129
+ }
@@ -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
+ }
package/dist/cli.js CHANGED
@@ -26,7 +26,11 @@ const COMMANDS = {
26
26
  publish: { 'dry-run': { type: 'boolean' } },
27
27
  'nightly-dispatch': { force: { type: 'boolean' } },
28
28
  'nightly-report': {},
29
- 'audit-report': { line: { type: 'string' }, file: { type: 'string' } },
29
+ 'audit-report': {
30
+ line: { type: 'string' },
31
+ file: { type: 'string' },
32
+ 'exit-code': { type: 'string' },
33
+ },
30
34
  'approve-renovate': { pr: { type: 'string' } },
31
35
  };
32
36
  const PROMOTIONS = new Set(['beta', 'rc', 'stable']);
@@ -53,6 +57,20 @@ function prNumber(values) {
53
57
  }
54
58
  return value;
55
59
  }
60
+ /**
61
+ * @param values - The parsed flags
62
+ * @returns The value of `--exit-code` as a number, or null when it is not given
63
+ */
64
+ function exitCode(values) {
65
+ const value = values['exit-code'];
66
+ if (value === undefined) {
67
+ return null;
68
+ }
69
+ if (typeof value !== 'string' || !/^\d+$/.test(value)) {
70
+ throw new Error(`--exit-code takes the exit code of yarn npm audit, but got ${JSON.stringify(value)}`);
71
+ }
72
+ return Number(value);
73
+ }
56
74
  try {
57
75
  const [command, ...rest] = process.argv.slice(2);
58
76
  if (command === undefined || !Object.hasOwn(COMMANDS, command)) {
@@ -108,9 +126,10 @@ try {
108
126
  break;
109
127
  }
110
128
  case 'audit-report': {
111
- await auditReportCommand({
129
+ process.exitCode = await auditReportCommand({
112
130
  line: required(flags, 'line'),
113
131
  output: readFileSync(required(flags, 'file'), 'utf8'),
132
+ exitCode: exitCode(flags),
114
133
  });
115
134
  break;
116
135
  }
@@ -1,4 +1,5 @@
1
1
  import { classify } from '../classify.js';
2
+ import { issuesToRewrite } from '../issue-body.js';
2
3
  import { createGit } from '../io/git.js';
3
4
  import { createGitHub } from '../io/github.js';
4
5
  import { readFacts } from '../io/repo.js';
@@ -53,13 +54,14 @@ export function github(tokenVariable) {
53
54
  * Classifies the repository and refuses to go on while it has errors.
54
55
  * @param git - Git access
55
56
  * @param now - The current time
57
+ * @param rev - The revision the definition is read from; `origin/dev` by default
56
58
  * @returns The lines and the review mode
57
59
  * @throws {Error} When the classification has errors
58
60
  * @example
59
61
  * const { lines } = classifiedLines(git, new Date());
60
62
  */
61
- export function classifiedLines(git, now) {
62
- const result = classify(readFacts(git, now));
63
+ export function classifiedLines(git, now, rev) {
64
+ const result = classify(readFacts(git, now, rev));
63
65
  if (result.errors.length > 0) {
64
66
  throw new Error(`The repository does not follow the rules yet:\n${result.errors.map((e) => `- ${e.message}`).join('\n')}`);
65
67
  }
@@ -101,6 +103,32 @@ export async function ensureIssue(gh, issue, labels) {
101
103
  });
102
104
  return true;
103
105
  }
106
+ /**
107
+ * Opens an Issue, or rewrites the body of the open Issues with the same
108
+ * marker when it differs and comments on them. For Issues that report the
109
+ * latest state, unlike {@link ensureIssue}, which keeps the first report.
110
+ * The comment is there because editing a body notifies no one. The title and
111
+ * the labels of an open Issue are left as they are.
112
+ * @param gh - The client
113
+ * @param issue - The Issue
114
+ * @param comment - The comment left on each rewritten Issue
115
+ * @example
116
+ * await upsertIssue(gh, auditIssue('dev', findings), 'The audit of `dev` changed.');
117
+ */
118
+ export async function upsertIssue(gh, issue, comment) {
119
+ const open = await openIssuesWith(gh, issue.marker);
120
+ if (open.length === 0) {
121
+ await gh.rest('POST', '/repos/{repo}/issues', {
122
+ title: issue.title,
123
+ body: issue.body,
124
+ });
125
+ return;
126
+ }
127
+ for (const number of issuesToRewrite(open, issue.body)) {
128
+ await gh.rest('PATCH', `/repos/{repo}/issues/${number}`, { body: issue.body });
129
+ await gh.rest('POST', `/repos/{repo}/issues/${number}/comments`, { body: comment });
130
+ }
131
+ }
104
132
  /**
105
133
  * Closes the open Issues with a marker.
106
134
  * @param gh - The client
@@ -1,5 +1,6 @@
1
1
  import { readFileSync, writeFileSync, existsSync } from 'node:fs';
2
2
  import path from 'node:path';
3
+ import { prependRelease } from '../changelog.js';
3
4
  import { parseCommit } from '../conventional-commit.js';
4
5
  import { runShell } from '../io/exec.js';
5
6
  import { versionAt } from '../io/repo.js';
@@ -68,13 +69,12 @@ export function generateRelease(input) {
68
69
  const parsed = parseCommit(message);
69
70
  return (parsed.breaking || ['feat', 'fix', 'perf', 'revert'].includes(parsed.type ?? ''));
70
71
  })
71
- .map(({ sha, message }) => `- ${message.split('\n')[0]} (${sha.slice(0, 7)})`);
72
- const entry = `## ${next.version} (${formatDate(input.now)})\n\n${counted.join('\n')}\n`;
73
- const previous = existsSync(changelogPath)
74
- ? readFileSync(changelogPath, 'utf8')
75
- : '# Changelog\n';
76
- const [title = '# Changelog', ...rest] = previous.split('\n');
77
- writeFileSync(changelogPath, `${title}\n\n${entry}${rest.join('\n').replace(/^\n*/, '\n')}`);
72
+ .map(({ sha, message }) => `${message.split('\n')[0]} (${sha.slice(0, 7)})`);
73
+ writeFileSync(changelogPath, prependRelease(existsSync(changelogPath) ? readFileSync(changelogPath, 'utf8') : null, {
74
+ version: next.version,
75
+ date: formatDate(input.now),
76
+ entries: counted,
77
+ }));
78
78
  }
79
79
  // The first stable release of a major on the current line graduates its
80
80
  // own prerelease (X.0.0-rc.n becomes X.0.0).
@@ -8,7 +8,8 @@ import { formatDate } from '../support-end.js';
8
8
  import { classifiedLines, localGit, summary } from './context.js';
9
9
  /**
10
10
  * Prints the classification of the repository: lines, modes, errors and the
11
- * actions the setup takes. Reads the remote refs; fetch them first.
11
+ * actions the setup takes. Reads the files of `HEAD` and the remote refs;
12
+ * fetch them first.
12
13
  * @param options - Output format
13
14
  * @param options.json - Print JSON
14
15
  * @returns The exit code: 1 when there are errors
@@ -16,7 +17,7 @@ import { classifiedLines, localGit, summary } from './context.js';
16
17
  * process.exitCode = classifyCommand({ json: false });
17
18
  */
18
19
  export function classifyCommand(options) {
19
- const result = classify(readFacts(localGit(), new Date()));
20
+ const result = classify(readFacts(localGit(), new Date(), 'HEAD'));
20
21
  if (options.json) {
21
22
  // oxlint-disable-next-line no-console -- the CLI prints its result
22
23
  console.log(JSON.stringify(result, null, 2));
@@ -40,13 +41,15 @@ export function classifyCommand(options) {
40
41
  }
41
42
  /**
42
43
  * Compares the files that name branches with the lines (see `checkLines`).
44
+ * Reads the definition of `HEAD`, so a pull request is checked against the
45
+ * lines it proposes.
43
46
  * @returns The exit code: 1 when they differ
44
47
  * @example
45
48
  * process.exitCode = await linesCheckCommand();
46
49
  */
47
50
  export async function linesCheckCommand() {
48
51
  const git = localGit();
49
- const { lines } = classifiedLines(git, new Date());
52
+ const { lines } = classifiedLines(git, new Date(), 'HEAD');
50
53
  const cwd = git.cwd;
51
54
  const read = (file) => {
52
55
  const full = path.join(cwd, file);
@@ -1,8 +1,9 @@
1
1
  import { parse as parseYaml } from 'yaml';
2
+ import { auditIssue, auditMarker, auditOutcome, parseAudit } from '../audit.js';
2
3
  import { fetchPackument } from '../io/npm.js';
3
4
  import { blockerMarker, isBlocked, nightlyAction } from '../nightly.js';
4
5
  import { eolIssues } from '../rotation.js';
5
- import { BLOCKER_LABEL, classifiedLines, closeIssuesWith, ensureIssue, FULL_CI_WORKFLOW, github, localGit, summary, } from './context.js';
6
+ import { BLOCKER_LABEL, classifiedLines, closeIssuesWith, ensureIssue, FULL_CI_WORKFLOW, github, localGit, summary, upsertIssue, } from './context.js';
6
7
  import { nightlyRuns } from './runs.js';
7
8
  /** How long a version stays behind the age gate. */
8
9
  const AGE_GATE_MS = 3 * 24 * 60 * 60 * 1000;
@@ -88,38 +89,41 @@ export async function nightlyReportCommand() {
88
89
  }
89
90
  }
90
91
  /**
91
- * Turns the output of `yarn npm audit --json` on a line into an Issue, or
92
- * closes the line's audit Issue when the audit is clean.
93
- * @param options - The line and the audit output
92
+ * Turns the output of `yarn npm audit --json` on a line into the line's audit
93
+ * Issue, by the outcome of {@link auditOutcome}: opens the Issue or rewrites it
94
+ * with the latest findings and a comment, closes it when the audit is clean,
95
+ * and keeps it when the audit failed or its exit code is unknown.
96
+ * @param options - The line and the audit
94
97
  * @param options.line - The branch the audit ran on
95
98
  * @param options.output - The audit output (one JSON object per line)
99
+ * @param options.exitCode - The exit code of `yarn npm audit`, or null when unknown
100
+ * @returns The exit code of the command: 1 when the audit failed
96
101
  * @example
97
- * await auditReportCommand({ line: 'v3', output: readFileSync('audit.json', 'utf8') });
102
+ * await auditReportCommand({ line: 'v3', output: readFileSync('audit.json', 'utf8'), exitCode: 1 });
98
103
  */
99
104
  export async function auditReportCommand(options) {
100
105
  const gh = github('GITHUB_TOKEN');
101
- const findings = options.output
102
- .split('\n')
103
- .filter((text) => text.trim().startsWith('{'))
104
- .map((text) => JSON.parse(text))
105
- .filter((finding) => finding.value !== undefined);
106
- const marker = `<!-- release-automation:audit:${options.line} -->`;
107
- if (findings.length === 0) {
108
- await closeIssuesWith(gh, marker, `The audit of \`${options.line}\` is clean.`);
109
- return;
106
+ const result = parseAudit(options.output);
107
+ const marker = auditMarker(options.line);
108
+ switch (auditOutcome(result, options.exitCode)) {
109
+ case 'report': {
110
+ await upsertIssue(gh, auditIssue(options.line, result.findings), `This Issue was rewritten with the latest audit of \`${options.line}\`.`);
111
+ await summary(`${options.line}: ${result.findings.length} findings`);
112
+ return 0;
113
+ }
114
+ case 'clean': {
115
+ await closeIssuesWith(gh, marker, `The audit of \`${options.line}\` is clean.`);
116
+ await summary(`${options.line}: the audit is clean`);
117
+ return 0;
118
+ }
119
+ case 'failed': {
120
+ await summary(`${options.line}: yarn npm audit failed with exit code ${options.exitCode}; the audit Issue is left as it is`);
121
+ return 1;
122
+ }
123
+ case 'unknown': {
124
+ // The workflow command makes the warning visible on the run, not only in its log.
125
+ await summary(`::warning::${options.line}: no findings, but without --exit-code a clean audit cannot be told from a failed one; the audit Issue is left as it is`);
126
+ return 0;
127
+ }
110
128
  }
111
- await ensureIssue(gh, {
112
- marker,
113
- title: `Vulnerable dependencies on ${options.line}`,
114
- body: [
115
- marker,
116
- '',
117
- `The dependency audit of \`${options.line}\` found:`,
118
- '',
119
- ...findings.map((finding) => `- \`${finding.value}\`: ${finding.children?.['Issue'] ?? ''} (${finding.children?.['Severity'] ?? ''}) ${finding.children?.['URL'] ?? ''}`),
120
- '',
121
- 'Fix them on the line (a vulnerability fix PR, `resolutions`, or the age gate exception of the repository policy), then this Issue closes after a clean audit.',
122
- '',
123
- ].join('\n'),
124
- }, []);
125
129
  }
@@ -206,14 +206,13 @@ async function syncToDev(git, gh, sha) {
206
206
  const token = requireEnv('PUBLISH_APP_TOKEN');
207
207
  const slug = requireEnv('PUBLISH_APP_SLUG');
208
208
  const bot = await gh.rest('GET', `/users/${encodeURIComponent(`${slug}[bot]`)}`);
209
- const remote = `https://x-access-token:${token}@github.com/${gh.repository}.git`;
210
209
  const syncBranch = `sync/${sha.slice(0, 12)}`;
211
210
  await retry(async () => {
212
211
  git.raw('fetch', 'origin', 'dev');
213
212
  git.raw('checkout', '--force', '--detach', 'origin/dev');
214
213
  git.raw('-c', `user.name=${slug}[bot]`, '-c', `user.email=${bot.id}+${slug}[bot]@users.noreply.github.com`, 'merge', '--no-ff', '--no-edit', sha);
215
214
  const merged = git.sha('HEAD');
216
- git.raw('push', '--force', remote, `HEAD:refs/heads/${syncBranch}`);
215
+ git.pushAs(token, gh.repository, `HEAD:refs/heads/${syncBranch}`);
217
216
  await waitForCheck(gh, merged, CI_OK);
218
217
  await gh.rest('PATCH', '/repos/{repo}/git/refs/heads/dev', {
219
218
  sha: merged,
@@ -268,7 +268,7 @@ async function pushRelease(input) {
268
268
  git.raw('add', '--all');
269
269
  git.raw('-c', `user.name=${appSlug}[bot]`, '-c', `user.email=${bot.id}+${appSlug}[bot]@users.noreply.github.com`, 'commit', '--no-verify', '--message', generated.message);
270
270
  const token = requireEnv('RELEASE_APP_TOKEN');
271
- git.raw('push', '--force', `https://x-access-token:${token}@github.com/${input.gh.repository}.git`, `HEAD:refs/heads/${releaseBranch(input.line.branch)}`);
271
+ git.pushAs(token, input.gh.repository, `HEAD:refs/heads/${releaseBranch(input.line.branch)}`);
272
272
  return { ok: true, version: generated.version };
273
273
  }
274
274
  /**
package/dist/io/exec.js CHANGED
@@ -1,4 +1,16 @@
1
1
  import { execFileSync } from 'node:child_process';
2
+ /**
3
+ * Hides the credentials in a text: a token in a URL (`https://x-access-token:<token>@…`).
4
+ * Pushes pass the token in the remote URL, and a failed command's error
5
+ * repeats its arguments, so every error from {@link run} goes through this.
6
+ * @param text - Any text
7
+ * @returns The text with the credentials replaced by `***`
8
+ * @example
9
+ * redact('https://x-access-token:ghs_abc@github.com/o/r.git'); // 'https://x-access-token:***@github.com/o/r.git'
10
+ */
11
+ export function redact(text) {
12
+ return text.replaceAll(/(https?:\/\/[^:/@\s]+:)[^@\s]+@/g, '$1***@');
13
+ }
2
14
  /**
3
15
  * Runs a program and returns its standard output.
4
16
  * @param file - The program
@@ -7,18 +19,29 @@ import { execFileSync } from 'node:child_process';
7
19
  * @param options.cwd - The working directory
8
20
  * @param options.env - Variables added to the environment
9
21
  * @returns The standard output, without the trailing newline
10
- * @throws {Error} When the program exits with a non-zero code
22
+ * @throws {Error} When the program exits with a non-zero code; the message
23
+ * names the command and its standard error, with credentials redacted
11
24
  * @example
12
25
  * run('git', ['rev-parse', 'HEAD'], { cwd: process.cwd() });
13
26
  */
14
27
  export function run(file, args, options) {
15
- return execFileSync(file, args, {
16
- cwd: options.cwd,
17
- encoding: 'utf8',
18
- maxBuffer: 256 * 1024 * 1024,
19
- env: { ...process.env, ...options.env },
20
- stdio: ['ignore', 'pipe', 'pipe'],
21
- }).replace(/\n$/, '');
28
+ try {
29
+ return execFileSync(file, args, {
30
+ cwd: options.cwd,
31
+ encoding: 'utf8',
32
+ maxBuffer: 256 * 1024 * 1024,
33
+ env: { ...process.env, ...options.env },
34
+ stdio: ['ignore', 'pipe', 'pipe'],
35
+ }).replace(/\n$/, '');
36
+ }
37
+ catch (error) {
38
+ const stderr = typeof error === 'object' && error !== null && 'stderr' in error
39
+ ? String(error.stderr)
40
+ : '';
41
+ // The original error is not attached as `cause`: its message repeats the
42
+ // arguments unredacted.
43
+ throw new Error(redact(`${file} ${args.join(' ')} failed\n${stderr}`.trim()));
44
+ }
22
45
  }
23
46
  /**
24
47
  * Runs a program with its output passed through, for long commands such as a publish.
package/dist/io/git.js CHANGED
@@ -1,4 +1,30 @@
1
1
  import { run } from './exec.js';
2
+ /**
3
+ * The arguments of a force push to a GitHub repository as the owner of a
4
+ * token. `actions/checkout` leaves the workflow's own token in
5
+ * `http.https://github.com/.extraheader`, and git sends that header in place
6
+ * of the credentials of the URL, so the push would run as
7
+ * `github-actions[bot]` with read access. An empty value of a multi-valued
8
+ * `http.extraHeader` resets the list, and a `-c` option comes last, so the
9
+ * token of the URL is the only credential.
10
+ * @param token - The token, such as a GitHub App installation token
11
+ * @param repository - `owner/name`
12
+ * @param refspec - What to push, such as `HEAD:refs/heads/release/dev`
13
+ * @returns The git arguments
14
+ * @example
15
+ * pushArgs('ghs_x', 'o/r', 'HEAD:refs/heads/b');
16
+ * // ['-c', 'http.https://github.com/.extraheader=', 'push', '--force', 'https://x-access-token:ghs_x@github.com/o/r.git', 'HEAD:refs/heads/b']
17
+ */
18
+ export function pushArgs(token, repository, refspec) {
19
+ return [
20
+ '-c',
21
+ 'http.https://github.com/.extraheader=',
22
+ 'push',
23
+ '--force',
24
+ `https://x-access-token:${token}@github.com/${repository}.git`,
25
+ refspec,
26
+ ];
27
+ }
2
28
  /**
3
29
  * @param cwd - The root of the checkout
4
30
  * @returns Git access for it
@@ -45,5 +71,8 @@ export function createGit(cwd) {
45
71
  return { sha, message: message.trim() };
46
72
  }),
47
73
  raw: (...args) => git(...args),
74
+ pushAs: (token, repository, refspec) => {
75
+ git(...pushArgs(token, repository, refspec));
76
+ },
48
77
  };
49
78
  }
package/dist/io/repo.js CHANGED
@@ -134,16 +134,23 @@ export function publishModeAt(git, rev) {
134
134
  return root.private === true ? 'custom' : 'npm-single';
135
135
  }
136
136
  /**
137
- * Reads the facts `classify` decides on, from the remote refs and `dev`.
138
- * The caller fetches the branches and tags first.
137
+ * Reads the facts `classify` decides on: the files at a revision, and the
138
+ * branches and tags of the remote. The caller fetches the branches and tags
139
+ * first.
140
+ *
141
+ * The revision is `origin/dev` by default: `dev` holds the definition the
142
+ * automation acts on. The checks of a pull request read `HEAD` instead, so
143
+ * that the pull request that brings in or changes the definition is checked
144
+ * against what it proposes.
139
145
  * @param git - Git access
140
146
  * @param now - The current time
147
+ * @param rev - The revision the files are read from
141
148
  * @returns The facts
142
149
  * @example
143
150
  * classify(readFacts(git, new Date()));
151
+ * classify(readFacts(git, new Date(), 'HEAD'));
144
152
  */
145
- export function readFacts(git, now) {
146
- const rev = `origin/${CURRENT_BRANCH}`;
153
+ export function readFacts(git, now, rev = `origin/${CURRENT_BRANCH}`) {
147
154
  const lerna = git.show(rev, 'lerna.json');
148
155
  const root = JSON.parse(git.show(rev, 'package.json') ?? '{}');
149
156
  const codeowners = git.show(rev, '.github/CODEOWNERS');
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Picks the open Issues whose body differs from the latest report, for the
3
+ * Issues that are rewritten with each run. Line endings and trailing
4
+ * whitespace are ignored, since GitHub may store the body with CRLF or trim it.
5
+ * @param open - The open Issues with the report's marker
6
+ * @param body - The latest body
7
+ * @returns The numbers of the Issues to rewrite
8
+ * @example
9
+ * issuesToRewrite([{ number: 1, body: 'old' }], 'new\n'); // [1]
10
+ */
11
+ export function issuesToRewrite(open, body) {
12
+ const latest = normalize(body);
13
+ return open
14
+ .filter((issue) => normalize(issue.body ?? '') !== latest)
15
+ .map((issue) => issue.number);
16
+ }
17
+ /**
18
+ * The body with LF line endings and no trailing whitespace.
19
+ * @param body - The body
20
+ */
21
+ function normalize(body) {
22
+ return body.replaceAll('\r\n', '\n').trimEnd();
23
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@d-zero/release-automation",
3
- "version": "0.0.0",
3
+ "version": "0.0.2",
4
4
  "description": "Release lines, Release PRs, nightly gates and publishing for D-ZERO repositories",
5
5
  "author": "D-ZERO",
6
6
  "license": "MIT",
@@ -53,7 +53,8 @@
53
53
  "lint:oxfmt:check": "oxfmt --check \"{*,**/*}.{md,json,js,cjs,mjs,ts,mts,yml,yaml}\"",
54
54
  "lint:textlint:fix": "textlint --fix \"{*,**/*}.md\"",
55
55
  "lint:textlint:check": "textlint \"{*,**/*}.md\"",
56
- "postinstall": "husky"
56
+ "postinstall": "husky",
57
+ "release-automation": "tsc && node dist/cli.js"
57
58
  },
58
59
  "dependencies": {
59
60
  "yaml": "2.9.1"
@@ -64,19 +65,20 @@
64
65
  "@d-zero/oxlint-config": "6.0.0-alpha.3",
65
66
  "@d-zero/textlint-config": "6.0.0-alpha.3",
66
67
  "@d-zero/tsconfig": "2.0.0",
67
- "@types/node": "26.0.1",
68
+ "@types/node": "26.6.6",
68
69
  "husky": "9.1.7",
69
- "npm-run-all2": "9.0.3",
70
- "oxfmt": "0.62.0",
71
- "oxlint": "1.77.0",
72
- "oxlint-tsgolint": "7.0.2005",
73
- "textlint": "15.8.0",
74
- "typescript": "6.0.3",
75
- "vitest": "4.1.12"
70
+ "npm-run-all2": "9.1.0",
71
+ "oxfmt": "0.80.0",
72
+ "oxlint": "1.95.0",
73
+ "oxlint-tsgolint": "7.0.2008",
74
+ "textlint": "16.1.3",
75
+ "typescript": "7.0.2",
76
+ "vite": "8.3.8",
77
+ "vitest": "5.1.1"
76
78
  },
77
- "packageManager": "yarn@4.18.1",
79
+ "packageManager": "yarn@4.19.0",
78
80
  "volta": {
79
- "node": "26.7.0",
80
- "yarn": "4.18.1"
81
+ "node": "26.13.1",
82
+ "yarn": "4.19.0"
81
83
  }
82
84
  }