@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.
@@ -0,0 +1,139 @@
1
+ import { classify } from '../classify.js';
2
+ import { createGit } from '../io/git.js';
3
+ import { createGitHub } from '../io/github.js';
4
+ import { readFacts } from '../io/repo.js';
5
+ /** The label of Release PRs. */
6
+ export const RELEASE_LABEL = 'release';
7
+ /** The label of a Release PR closed because a successor replaced it. */
8
+ export const REPLACED_LABEL = 'release-replaced';
9
+ /** The label of the Issues that stop Release PRs of a line. */
10
+ export const BLOCKER_LABEL = 'release-blocker';
11
+ /** The name of the check that verifies a Release PR. */
12
+ export const VERIFY_CHECK = 'release-pr-verified';
13
+ /** The file name of the Full CI workflow the Nightly dispatches. */
14
+ export const FULL_CI_WORKFLOW = 'full-ci.yml';
15
+ /**
16
+ * Reads an environment variable that must be set.
17
+ * @param name - The variable
18
+ * @returns Its value
19
+ * @throws {Error} When it is not set
20
+ * @example
21
+ * requireEnv('GITHUB_REPOSITORY');
22
+ */
23
+ export function requireEnv(name) {
24
+ const value = process.env[name];
25
+ if (value === undefined || value === '') {
26
+ throw new Error(`${name} is not set`);
27
+ }
28
+ return value;
29
+ }
30
+ /**
31
+ * Git access for the working directory.
32
+ * @returns The access
33
+ * @example
34
+ * const git = localGit();
35
+ */
36
+ export function localGit() {
37
+ return createGit(process.cwd());
38
+ }
39
+ /**
40
+ * A GitHub client authenticated with the token in an environment variable.
41
+ * @param tokenVariable - The variable that holds the token
42
+ * @returns The client for `GITHUB_REPOSITORY`
43
+ * @example
44
+ * const gh = github('RELEASE_APP_TOKEN');
45
+ */
46
+ export function github(tokenVariable) {
47
+ return createGitHub({
48
+ token: requireEnv(tokenVariable),
49
+ repository: requireEnv('GITHUB_REPOSITORY'),
50
+ });
51
+ }
52
+ /**
53
+ * Classifies the repository and refuses to go on while it has errors.
54
+ * @param git - Git access
55
+ * @param now - The current time
56
+ * @param rev - The revision the definition is read from; `origin/dev` by default
57
+ * @returns The lines and the review mode
58
+ * @throws {Error} When the classification has errors
59
+ * @example
60
+ * const { lines } = classifiedLines(git, new Date());
61
+ */
62
+ export function classifiedLines(git, now, rev) {
63
+ const result = classify(readFacts(git, now, rev));
64
+ if (result.errors.length > 0) {
65
+ throw new Error(`The repository does not follow the rules yet:\n${result.errors.map((e) => `- ${e.message}`).join('\n')}`);
66
+ }
67
+ return { lines: result.lines, collaborative: result.review?.mode === 'collaborative' };
68
+ }
69
+ /**
70
+ * Finds the open Issues whose body holds a marker.
71
+ * @param gh - The client
72
+ * @param marker - The marker
73
+ * @returns The Issues
74
+ * @example
75
+ * await openIssuesWith(gh, '<!-- release-blocker:dev -->');
76
+ */
77
+ export async function openIssuesWith(gh, marker) {
78
+ const issues = await gh.paginate('/repos/{repo}/issues?state=open');
79
+ return issues.filter((issue) => issue.pull_request === undefined && (issue.body ?? '').includes(marker));
80
+ }
81
+ /**
82
+ * Opens an Issue unless one with the same marker is open.
83
+ * @param gh - The client
84
+ * @param issue - The Issue
85
+ * @param issue.marker - The marker the body starts with
86
+ * @param issue.title - The title
87
+ * @param issue.body - The body
88
+ * @param labels - Labels to add
89
+ * @returns Whether an Issue was opened
90
+ * @example
91
+ * await ensureIssue(gh, rotationIssue(...), []);
92
+ */
93
+ export async function ensureIssue(gh, issue, labels) {
94
+ const open = await openIssuesWith(gh, issue.marker);
95
+ if (open.length > 0) {
96
+ return false;
97
+ }
98
+ await gh.rest('POST', '/repos/{repo}/issues', {
99
+ title: issue.title,
100
+ body: issue.body,
101
+ labels,
102
+ });
103
+ return true;
104
+ }
105
+ /**
106
+ * Closes the open Issues with a marker.
107
+ * @param gh - The client
108
+ * @param marker - The marker
109
+ * @param comment - The comment left on each
110
+ * @returns The number of Issues closed
111
+ * @example
112
+ * await closeIssuesWith(gh, blockerMarker('dev'), 'The Nightly passed again.');
113
+ */
114
+ export async function closeIssuesWith(gh, marker, comment) {
115
+ const issues = await openIssuesWith(gh, marker);
116
+ for (const issue of issues) {
117
+ await gh.rest('POST', `/repos/{repo}/issues/${issue.number}/comments`, {
118
+ body: comment,
119
+ });
120
+ await gh.rest('PATCH', `/repos/{repo}/issues/${issue.number}`, { state: 'closed' });
121
+ }
122
+ return issues.length;
123
+ }
124
+ /**
125
+ * Writes a line to the job summary when running in GitHub Actions, and to
126
+ * standard output always.
127
+ * @param text - The text
128
+ * @example
129
+ * summary('dev: Release PR opened');
130
+ */
131
+ export async function summary(text) {
132
+ // oxlint-disable-next-line no-console -- the CLI reports to its caller
133
+ console.log(text);
134
+ const file = process.env['GITHUB_STEP_SUMMARY'];
135
+ if (file) {
136
+ const { appendFile } = await import('node:fs/promises');
137
+ await appendFile(file, `${text}\n`);
138
+ }
139
+ }
@@ -0,0 +1,97 @@
1
+ import { readFileSync, writeFileSync, existsSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { prependRelease } from '../changelog.js';
4
+ import { parseCommit } from '../conventional-commit.js';
5
+ import { runShell } from '../io/exec.js';
6
+ import { versionAt } from '../io/repo.js';
7
+ import { nextVersion } from '../next-version.js';
8
+ import { withLockfileStop } from '../rotation.js';
9
+ import { formatDate } from '../support-end.js';
10
+ /**
11
+ * Applies the release changes of a line to the working tree, which is checked
12
+ * out at the line's head: the version, the changelog, and, for the first
13
+ * stable release of a major on the current line, the end of lock file
14
+ * maintenance on the previous lines that turn security-only with it. Does not
15
+ * commit. The same input gives the same tree, apart from the dates in the
16
+ * changelog, so the verification can generate it again and compare.
17
+ * @param input - The line and what to release
18
+ * @param input.git - Git access to the checkout
19
+ * @param input.mode - The publishing mode
20
+ * @param input.line - The line
21
+ * @param input.lines - Every line
22
+ * @param input.baseline - The revision of the last release
23
+ * @param input.promote - The stage a person asked for
24
+ * @param input.now - The date written into the changelog
25
+ * @returns The version, or why there is none
26
+ * @example
27
+ * generateRelease({ git, mode: 'lerna-fixed', line, lines, baseline: 'origin/main', promote: null, now: new Date() });
28
+ */
29
+ export function generateRelease(input) {
30
+ const { git, mode, line } = input;
31
+ const cwd = git.cwd;
32
+ if (mode === 'lerna-independent') {
33
+ if (input.promote !== null) {
34
+ return { ok: false, reason: 'Lerna independent mode has no stage to promote' };
35
+ }
36
+ runShell('yarn lerna version --conventional-commits --exact --no-git-tag-version --no-push --yes', cwd);
37
+ runShell('yarn install --mode=update-lockfile', cwd);
38
+ return { ok: true, version: null, message: 'chore(release): publish' };
39
+ }
40
+ const current = versionAt(git, 'HEAD');
41
+ if (current === null) {
42
+ return { ok: false, reason: 'No version on the line' };
43
+ }
44
+ const commits = git
45
+ .messages(input.baseline, 'HEAD')
46
+ .map(({ message }) => parseCommit(message));
47
+ const next = nextVersion({
48
+ current,
49
+ commits,
50
+ promote: input.promote,
51
+ lineMajor: line.major,
52
+ });
53
+ if (!next.ok) {
54
+ return { ok: false, reason: next.message };
55
+ }
56
+ if (mode === 'lerna-fixed') {
57
+ const prerelease = next.version.includes('-') ? ' --force-publish' : '';
58
+ runShell(`yarn lerna version ${next.version} --conventional-commits --exact --no-git-tag-version --no-push --yes${prerelease}`, cwd);
59
+ runShell('yarn install --mode=update-lockfile', cwd);
60
+ }
61
+ else {
62
+ const manifestPath = path.join(cwd, 'package.json');
63
+ const manifest = readFileSync(manifestPath, 'utf8');
64
+ writeFileSync(manifestPath, manifest.replace(/("version"\s*:\s*")[^"]*(")/, `$1${next.version}$2`));
65
+ const changelogPath = path.join(cwd, 'CHANGELOG.md');
66
+ const counted = git
67
+ .messages(input.baseline, 'HEAD')
68
+ .filter(({ message }) => {
69
+ const parsed = parseCommit(message);
70
+ return (parsed.breaking || ['feat', 'fix', 'perf', 'revert'].includes(parsed.type ?? ''));
71
+ })
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
+ }
79
+ // The first stable release of a major on the current line graduates its
80
+ // own prerelease (X.0.0-rc.n becomes X.0.0).
81
+ const firstStable = line.role === 'current' &&
82
+ /^\d+\.0\.0$/.test(next.version) &&
83
+ current.startsWith(`${next.version}-`);
84
+ if (firstStable) {
85
+ const turning = input.lines
86
+ .filter((other) => other.role === 'previous' && other.phase === 'fixes')
87
+ .map((other) => other.branch);
88
+ if (turning.length > 0) {
89
+ const renovatePath = path.join(cwd, '.github/renovate.json');
90
+ const text = readFileSync(renovatePath, 'utf8');
91
+ const indent = /^(\s+)"/m.exec(text)?.[1] ?? '\t';
92
+ const updated = withLockfileStop(JSON.parse(text), turning);
93
+ writeFileSync(renovatePath, `${JSON.stringify(updated, null, indent)}\n`);
94
+ }
95
+ }
96
+ return { ok: true, version: next.version, message: `chore(release): v${next.version}` };
97
+ }
@@ -0,0 +1,128 @@
1
+ import { readdirSync, readFileSync, existsSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { classify } from '../classify.js';
4
+ import { commitMessageError, guardedBranches } from '../guard.js';
5
+ import { readFacts, readLinesFile, versionAt } from '../io/repo.js';
6
+ import { checkLines } from '../lines-check.js';
7
+ import { formatDate } from '../support-end.js';
8
+ import { classifiedLines, localGit, summary } from './context.js';
9
+ /**
10
+ * Prints the classification of the repository: lines, modes, errors and the
11
+ * actions the setup takes. Reads the files of `HEAD` and the remote refs;
12
+ * fetch them first.
13
+ * @param options - Output format
14
+ * @param options.json - Print JSON
15
+ * @returns The exit code: 1 when there are errors
16
+ * @example
17
+ * process.exitCode = classifyCommand({ json: false });
18
+ */
19
+ export function classifyCommand(options) {
20
+ const result = classify(readFacts(localGit(), new Date(), 'HEAD'));
21
+ if (options.json) {
22
+ // oxlint-disable-next-line no-console -- the CLI prints its result
23
+ console.log(JSON.stringify(result, null, 2));
24
+ }
25
+ else {
26
+ const out = [
27
+ `publish mode: ${result.publishMode ?? '-'}`,
28
+ `review: ${result.review === null ? '-' : `${result.review.mode} (approvals: ${result.review.approvals})`}`,
29
+ `age gate: ${result.ageGate === null ? 'not supported' : `${result.ageGate.file} ${result.ageGate.key}: ${result.ageGate.value}`}`,
30
+ 'lines:',
31
+ ...result.lines.map((line) => ` ${line.branch} ${line.role} v${line.major} → ${line.publishBranch}${line.stage ? ` [${line.stage}]` : ''}${line.phase ? ` (${line.phase}${line.supportEnd ? ` until ${formatDate(line.supportEnd)}` : ''})` : ''}`),
32
+ 'errors:',
33
+ ...result.errors.map((finding) => ` ${finding.code}: ${finding.message}`),
34
+ 'actions:',
35
+ ...result.actions.map((finding) => ` ${finding.code}: ${finding.message}`),
36
+ ];
37
+ // oxlint-disable-next-line no-console -- the CLI prints its result
38
+ console.log(out.join('\n'));
39
+ }
40
+ return result.errors.length > 0 ? 1 : 0;
41
+ }
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.
46
+ * @returns The exit code: 1 when they differ
47
+ * @example
48
+ * process.exitCode = await linesCheckCommand();
49
+ */
50
+ export async function linesCheckCommand() {
51
+ const git = localGit();
52
+ const { lines } = classifiedLines(git, new Date(), 'HEAD');
53
+ const cwd = git.cwd;
54
+ const read = (file) => {
55
+ const full = path.join(cwd, file);
56
+ return existsSync(full) ? readFileSync(full, 'utf8') : null;
57
+ };
58
+ const workflowDir = path.join(cwd, '.github/workflows');
59
+ const workflows = existsSync(workflowDir)
60
+ ? readdirSync(workflowDir)
61
+ .filter((file) => /\.ya?ml$/.test(file))
62
+ .map((file) => ({
63
+ path: `.github/workflows/${file}`,
64
+ content: readFileSync(path.join(workflowDir, file), 'utf8'),
65
+ }))
66
+ : [];
67
+ const problems = checkLines(lines, {
68
+ renovate: JSON.parse(read('.github/renovate.json') ?? '{}'),
69
+ workflows,
70
+ securityMd: read('SECURITY.md'),
71
+ preCommit: read('.husky/pre-commit'),
72
+ });
73
+ for (const problem of problems) {
74
+ await summary(`- ${problem}`);
75
+ }
76
+ return problems.length > 0 ? 1 : 0;
77
+ }
78
+ /**
79
+ * Refuses a local commit on a guarded branch, for `.husky/pre-commit`.
80
+ * Reads the lines file of the working tree.
81
+ * @returns The exit code: 1 on a guarded branch
82
+ * @example
83
+ * process.exitCode = guardCommand();
84
+ */
85
+ export function guardCommand() {
86
+ const git = localGit();
87
+ const lines = readLinesFile(git, null);
88
+ const branch = git.currentBranch();
89
+ if (lines === null || branch === null) {
90
+ return 0;
91
+ }
92
+ if (guardedBranches(lines).includes(branch)) {
93
+ process.stderr.write(`${branch} changes through pull requests only. Create a topic branch: git switch -c <name>\n`);
94
+ return 1;
95
+ }
96
+ return 0;
97
+ }
98
+ /**
99
+ * Checks the commits of a pull request against its target branch (a
100
+ * breaking change on a stable line). Runs in CI.
101
+ * @param options - The range
102
+ * @param options.base - The target branch of the pull request
103
+ * @returns The exit code: 1 when a commit may not land
104
+ * @example
105
+ * process.exitCode = await commitCheckCommand({ base: 'dev' });
106
+ */
107
+ export async function commitCheckCommand(options) {
108
+ const git = localGit();
109
+ const lines = readLinesFile(git, `origin/${options.base}`) ?? readLinesFile(git, 'origin/dev');
110
+ if (lines === null) {
111
+ return 0;
112
+ }
113
+ const currentVersion = versionAt(git, 'origin/dev');
114
+ let failed = 0;
115
+ for (const { sha, message } of git.messages(`origin/${options.base}`, 'HEAD')) {
116
+ const error = commitMessageError({
117
+ message,
118
+ target: options.base,
119
+ currentVersion,
120
+ lines,
121
+ });
122
+ if (error !== null) {
123
+ failed++;
124
+ await summary(`${sha.slice(0, 9)}: ${error}`);
125
+ }
126
+ }
127
+ return failed > 0 ? 1 : 0;
128
+ }
@@ -0,0 +1,125 @@
1
+ import { parse as parseYaml } from 'yaml';
2
+ import { fetchPackument } from '../io/npm.js';
3
+ import { blockerMarker, isBlocked, nightlyAction } from '../nightly.js';
4
+ import { eolIssues } from '../rotation.js';
5
+ import { BLOCKER_LABEL, classifiedLines, closeIssuesWith, ensureIssue, FULL_CI_WORKFLOW, github, localGit, summary, } from './context.js';
6
+ import { nightlyRuns } from './runs.js';
7
+ /** How long a version stays behind the age gate. */
8
+ const AGE_GATE_MS = 3 * 24 * 60 * 60 * 1000;
9
+ /**
10
+ * Starts the Full CI of every line whose head has no successful run yet,
11
+ * by `workflow_dispatch` on the line's branch. A success on the same commit
12
+ * is reused; a failure is run again.
13
+ * @param options - Flags
14
+ * @param options.force - Run every line, reusing nothing
15
+ * @example
16
+ * await nightlyDispatchCommand({ force: false });
17
+ */
18
+ export async function nightlyDispatchCommand(options) {
19
+ const git = localGit();
20
+ const gh = github('GITHUB_TOKEN');
21
+ const { lines } = classifiedLines(git, new Date());
22
+ for (const line of lines) {
23
+ const head = git.sha(`origin/${line.branch}`);
24
+ const action = nightlyAction(head, await nightlyRuns(gh, line.branch), options.force);
25
+ if (action === 'run') {
26
+ await gh.rest('POST', `/repos/{repo}/actions/workflows/${FULL_CI_WORKFLOW}/dispatches`, {
27
+ ref: line.branch,
28
+ });
29
+ }
30
+ await summary(`${line.branch}: ${action === 'run' ? 'Full CI started' : `reused the success on ${head}`}`);
31
+ }
32
+ }
33
+ /**
34
+ * Brings the Issues in line with the state of the lines: a `release-blocker`
35
+ * Issue for each line whose newest Nightly failed (closed again by the
36
+ * automation once one passes), the end-of-support Issues that are due, and
37
+ * an Issue for each age gate exception that is no longer needed.
38
+ * @example
39
+ * await nightlyReportCommand();
40
+ */
41
+ export async function nightlyReportCommand() {
42
+ const now = new Date();
43
+ const git = localGit();
44
+ const gh = github('GITHUB_TOKEN');
45
+ const { lines } = classifiedLines(git, now);
46
+ for (const line of lines) {
47
+ const runs = await nightlyRuns(gh, line.branch);
48
+ const marker = blockerMarker(line.branch);
49
+ if (isBlocked(runs)) {
50
+ const opened = await ensureIssue(gh, {
51
+ marker,
52
+ title: `Nightly of ${line.branch} fails: new Release PRs of the line are stopped`,
53
+ body: `${marker}\n\nThe newest Full CI run of the Nightly on \`${line.branch}\` (${runs[0]?.sha ?? ''}) failed. No new Release PR of the line opens until a Nightly passes again; open Release PRs can still merge with their own Full CI.\n\nClosing this Issue does not lift the stop. Fix the failure, then run the Nightly again (by hand or on schedule).\n`,
54
+ }, [BLOCKER_LABEL]);
55
+ await summary(`${line.branch}: blocked${opened ? ' (Issue opened)' : ''}`);
56
+ }
57
+ else {
58
+ const closed = await closeIssuesWith(gh, marker, `The Nightly of \`${line.branch}\` passed again on ${runs[0]?.sha ?? ''}; Release PRs of the line resume.`);
59
+ if (closed > 0) {
60
+ await summary(`${line.branch}: unblocked`);
61
+ }
62
+ }
63
+ }
64
+ for (const issue of eolIssues(lines, now)) {
65
+ await ensureIssue(gh, issue, []);
66
+ }
67
+ const yarnrc = git.show('origin/dev', '.yarnrc.yml');
68
+ const approved = yarnrc === null
69
+ ? []
70
+ : (parseYaml(yarnrc)
71
+ .npmPreapprovedPackages ?? []);
72
+ for (const entry of Array.isArray(approved) ? approved : []) {
73
+ const match = typeof entry === 'string' ? /^(@?[^@]+)@(\d[^\s]*)$/.exec(entry) : null;
74
+ if (!match?.[1] || !match[2]) {
75
+ continue;
76
+ }
77
+ const packument = await fetchPackument(match[1]);
78
+ const published = packument?.times[match[2]];
79
+ if (published !== undefined &&
80
+ now.getTime() - new Date(published).getTime() >= AGE_GATE_MS) {
81
+ const marker = `<!-- release-automation:age-gate:${entry} -->`;
82
+ await ensureIssue(gh, {
83
+ marker,
84
+ title: `Remove the age gate exception for ${entry}`,
85
+ body: `${marker}\n\n\`${entry}\` was published more than three days ago, so the age gate no longer holds it back. Remove it from \`npmPreapprovedPackages\` in \`.yarnrc.yml\`, check the lockfile, and pass the required CI.\n`,
86
+ }, []);
87
+ }
88
+ }
89
+ }
90
+ /**
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
94
+ * @param options.line - The branch the audit ran on
95
+ * @param options.output - The audit output (one JSON object per line)
96
+ * @example
97
+ * await auditReportCommand({ line: 'v3', output: readFileSync('audit.json', 'utf8') });
98
+ */
99
+ export async function auditReportCommand(options) {
100
+ 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;
110
+ }
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
+ }