-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathrelease-alpha-train.mjs
More file actions
484 lines (441 loc) · 14.7 KB
/
Copy pathrelease-alpha-train.mjs
File metadata and controls
484 lines (441 loc) · 14.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
#!/usr/bin/env node
import { execFile as execFileCallback } from "node:child_process";
import { mkdir, readFile, readdir, unlink, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { promisify } from "node:util";
const execFile = promisify(execFileCallback);
export const PUBLIC_PACKAGE_MANIFESTS = [
"apps/cli/package.json",
"packages/api/package.json",
"packages/components/package.json",
"packages/sdk-core/package.json",
"packages/sdk-next/package.json",
"packages/sdk-nuxt/package.json",
"packages/sdk-react/package.json",
"packages/sdk-vue/package.json",
"packages/sdk-angular/package.json",
];
export const PUBLIC_PACKAGE_NAMES = [
"@zitadel/cli",
"@zitadel/api",
"@zitadel/components",
"@zitadel/sdk-core",
"@zitadel/sdk-next",
"@zitadel/sdk-nuxt",
"@zitadel/sdk-react",
"@zitadel/sdk-vue",
"@zitadel/sdk-angular",
];
export const SERVER_IMAGE_NAME = "ghcr.io/zitadel/nextgen";
const ALPHA_VERSION_RE = /^\d+\.\d+\.\d+-alpha\.\d+$/;
export async function prepareAlphaReleaseTrain(options = {}) {
const cwd = options.cwd ?? process.cwd();
const readFileFn = options.readFile ?? readFile;
const writeFileFn = options.writeFile ?? writeFile;
const mkdirFn = options.mkdir ?? mkdir;
const execFileFn = options.execFile ?? execFile;
const outDir = options.outDir ?? join(cwd, "dist/alpha-release");
const state = await inspectAlphaReleaseTrain({
cwd,
execFile: execFileFn,
readFile: readFileFn,
readdir: options.readdir ?? readdir,
published: options.published,
remote: options.remote,
});
if (state.skipReason) {
throw new Error(`alpha release train is not ready to complete: ${state.skipReason}`);
}
if (state.releaseExists && !state.imageExists) {
throw new Error(
`GitHub Release ${state.tagName} exists but ${state.image} is missing; recover that partial release manually before rerunning the alpha train`,
);
}
const { image, packages, tagName, title, version } = state;
const notes = renderAlphaReleaseNotes({ title, version, image, packages });
await mkdirFn(outDir, { recursive: true });
const notesPath = join(outDir, `zitadel-alpha-${version}-notes.md`);
await writeFileFn(notesPath, notes);
return {
version,
tagName,
title,
image,
notesPath,
packages,
shouldComplete: state.shouldComplete,
shouldCreateTag: state.shouldCreateTag,
shouldRunGoreleaser: state.shouldRunGoreleaser,
shouldUpdateRelease: state.shouldUpdateRelease,
tagExists: state.tagExists,
releaseExists: state.releaseExists,
imageExists: state.imageExists,
};
}
export async function inspectAlphaReleaseTrain(options = {}) {
const cwd = options.cwd ?? process.cwd();
const readFileFn = options.readFile ?? readFile;
const readdirFn = options.readdir ?? readdir;
const execFileFn = options.execFile ?? execFile;
const published = normalizeBoolean(options.published);
const remote = options.remote === undefined ? true : normalizeBoolean(options.remote);
const packages = await readPublicPackageManifests(cwd, readFileFn);
const config = JSON.parse(await readFileFn(join(cwd, ".changeset/config.json"), "utf8"));
validateChangesetsFixedGroup(config);
const versions = new Set(packages.map((pkg) => pkg.version));
if (versions.size !== 1) {
throw new Error(
`public package versions must be lockstep: ${packages
.map((pkg) => `${pkg.name}@${pkg.version}`)
.join(", ")}`,
);
}
const version = [...versions][0];
validateAlphaVersion(version);
const tagName = `v${version}`;
const image = `${SERVER_IMAGE_NAME}:${version}`;
const title = `ZITADEL Alpha ${version}`;
const activeChangesets = await activeChangesetFiles(cwd, {
readFile: readFileFn,
readdir: readdirFn,
});
const headCommit = await gitOutput(execFileFn, cwd, ["rev-parse", "HEAD"]);
const tagCommit = await tagCommitFor(tagName, execFileFn, cwd);
const tagExists = Boolean(tagCommit);
const tagMatchesHead = tagCommit === headCommit;
if (!published && activeChangesets.length > 0) {
return {
version,
tagName,
title,
image,
packages,
activeChangesets,
headCommit,
tagCommit,
tagExists,
tagMatchesHead,
releaseExists: false,
imageExists: false,
shouldComplete: false,
shouldCreateTag: false,
shouldRunGoreleaser: false,
shouldUpdateRelease: false,
skipReason: `pending changesets: ${activeChangesets.join(", ")}`,
};
}
const releaseExists = remote ? await githubReleaseExists(tagName, execFileFn, cwd) : false;
const imageExists = remote ? await containerImageExists(image, execFileFn, cwd) : false;
if (releaseExists && !imageExists) {
throw new Error(
`GitHub Release ${tagName} exists but ${image} is missing; recover that partial release manually before rerunning the alpha train`,
);
}
const shouldRunGoreleaser = !(releaseExists && imageExists);
return {
version,
tagName,
title,
image,
packages,
activeChangesets,
headCommit,
tagCommit,
tagExists,
tagMatchesHead,
releaseExists,
imageExists,
shouldComplete: true,
shouldCreateTag: !tagExists,
shouldRunGoreleaser,
shouldUpdateRelease: true,
skipReason: "",
};
}
export async function readPublicPackageManifests(cwd, readFileFn = readFile) {
const packages = [];
for (let index = 0; index < PUBLIC_PACKAGE_MANIFESTS.length; index += 1) {
const path = PUBLIC_PACKAGE_MANIFESTS[index];
const expectedName = PUBLIC_PACKAGE_NAMES[index];
const manifest = JSON.parse(await readFileFn(join(cwd, path), "utf8"));
if (manifest.name !== expectedName) {
throw new Error(`${path} must be ${expectedName}`);
}
if (manifest.private === true) {
throw new Error(`${expectedName} must not be private`);
}
if (typeof manifest.version !== "string" || manifest.version.length === 0) {
throw new Error(`${expectedName} must have a version`);
}
packages.push({ name: manifest.name, version: manifest.version, path });
}
return packages;
}
export function validateChangesetsFixedGroup(config) {
const expected = new Set(PUBLIC_PACKAGE_NAMES);
const groups = Array.isArray(config.fixed) ? config.fixed : [];
const group = groups.find((candidate) => {
if (!Array.isArray(candidate)) {
return false;
}
const names = new Set(candidate);
return (
names.size === expected.size &&
[...expected].every((name) => names.has(name)) &&
[...names].every((name) => expected.has(name))
);
});
if (!group) {
throw new Error("changesets fixed group must contain exactly the public alpha packages");
}
}
export function validateAlphaVersion(version) {
if (!ALPHA_VERSION_RE.test(version)) {
throw new Error(`alpha release version must match x.y.z-alpha.N: ${version}`);
}
}
export async function tagExists(tagName, execFileFn = execFile, cwd = process.cwd()) {
return Boolean(await tagCommitFor(tagName, execFileFn, cwd));
}
export async function pruneEmptyChangesets(options = {}) {
const cwd = options.cwd ?? process.cwd();
const readFileFn = options.readFile ?? readFile;
const readdirFn = options.readdir ?? readdir;
const unlinkFn = options.unlink ?? unlink;
const removed = [];
const files = await changesetMarkdownFiles(cwd, readdirFn);
for (const file of files) {
const path = join(cwd, ".changeset", file);
const content = await readFileFn(path, "utf8");
if (!changesetHasReleaseBump(content)) {
await unlinkFn(path);
removed.push(file);
}
}
return removed.sort();
}
export function renderAlphaReleaseNotes({ title, version, image, packages }) {
const lines = [
`# ${title}`,
"",
"This alpha release is a tested lockstep train across the server image, CLI, and public SDK packages.",
"It is a GitHub prerelease and does not move the Docker `latest` tag.",
"",
"## Tester Commands",
"",
"Latest alpha stream:",
"",
"```sh",
"npx @zitadel/cli@alpha doctor",
"npx @zitadel/cli@alpha start",
"npx @zitadel/cli@alpha setup --framework next --server local",
"```",
"",
"Exact reproducible train:",
"",
"```sh",
`npx @zitadel/cli@${version} doctor`,
`npx @zitadel/cli@${version} start`,
`npx @zitadel/cli@${version} setup --framework next --server local`,
"```",
"",
"## Components",
"",
"| Kind | Name | Version | Reference |",
"| --- | --- | --- | --- |",
`| container | \`${SERVER_IMAGE_NAME}\` | \`${version}\` | \`${image}\` |`,
];
for (const pkg of packages) {
lines.push(`| npm | \`${pkg.name}\` | \`${pkg.version}\` | npm |`);
}
lines.push("");
return lines.join("\n");
}
export function parseAlphaReleaseArgs(args) {
const command = args[0];
if (command !== "prepare" && command !== "status" && command !== "prune-empty-changesets") {
throw new Error(
"Usage: release-alpha-train.mjs <status|prepare|prune-empty-changesets> [--out-dir <path>] [--published <true|false>]",
);
}
const values = {};
for (let index = 1; index < args.length; index += 1) {
const arg = args[index];
if (!arg.startsWith("--")) {
throw new Error(`Unexpected argument ${arg}`);
}
const key = camelCase(arg.slice(2));
const value = args[index + 1];
if (!value || value.startsWith("--")) {
throw new Error(`Missing value for ${arg}`);
}
values[key] = value;
index += 1;
}
return { command, values };
}
function camelCase(value) {
return value.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase());
}
async function activeChangesetFiles(cwd, options = {}) {
const readFileFn = options.readFile ?? readFile;
const readdirFn = options.readdir ?? readdir;
const prereleaseChangesets = await prereleaseTrackedChangesets(cwd, readFileFn);
const files = await changesetMarkdownFiles(cwd, readdirFn);
const active = [];
for (const file of files) {
if (prereleaseChangesets.has(changesetSlug(file))) {
continue;
}
const content = await readFileFn(join(cwd, ".changeset", file), "utf8");
if (changesetHasReleaseBump(content)) {
active.push(file);
}
}
return active.sort();
}
async function changesetMarkdownFiles(cwd, readdirFn = readdir) {
let entries = [];
try {
entries = await readdirFn(join(cwd, ".changeset"), { withFileTypes: true });
} catch (error) {
if (isMissingPath(error)) {
return [];
}
throw error;
}
return entries
.filter((entry) => entry.isFile?.() ?? false)
.map((entry) => entry.name)
.filter((name) => name.endsWith(".md") && name !== "README.md")
.sort();
}
async function prereleaseTrackedChangesets(cwd, readFileFn = readFile) {
let preState;
try {
preState = JSON.parse(await readFileFn(join(cwd, ".changeset/pre.json"), "utf8"));
} catch (error) {
if (isMissingPath(error)) {
return new Set();
}
throw error;
}
if (!Array.isArray(preState.changesets)) {
return new Set();
}
return new Set(preState.changesets.filter((name) => typeof name === "string"));
}
function changesetSlug(file) {
return file.replace(/\.md$/, "");
}
function changesetHasReleaseBump(content) {
const frontmatter = changesetFrontmatter(content);
if (frontmatter === undefined) {
return true;
}
return frontmatter.split("\n").some((line) => {
const trimmed = line.trim();
return trimmed.length > 0 && !trimmed.startsWith("#");
});
}
function changesetFrontmatter(content) {
const normalized = content.replace(/\r\n/g, "\n");
if (!normalized.startsWith("---\n")) {
return undefined;
}
const lines = normalized.split("\n");
for (let index = 1; index < lines.length; index += 1) {
if (lines[index] === "---") {
return lines.slice(1, index).join("\n");
}
}
return undefined;
}
async function tagCommitFor(tagName, execFileFn = execFile, cwd = process.cwd()) {
try {
return await gitOutput(execFileFn, cwd, ["rev-list", "-n", "1", tagName]);
} catch (error) {
if (isExpectedMissingCommand(error)) {
return "";
}
throw error;
}
}
async function githubReleaseExists(tagName, execFileFn = execFile, cwd = process.cwd()) {
try {
await execFileFn("gh", ["release", "view", tagName, "--json", "tagName"], { cwd });
return true;
} catch (error) {
if (isExpectedMissingCommand(error)) {
return false;
}
throw error;
}
}
async function containerImageExists(image, execFileFn = execFile, cwd = process.cwd()) {
try {
await execFileFn("docker", ["manifest", "inspect", image], { cwd });
return true;
} catch (error) {
if (isExpectedMissingCommand(error)) {
return false;
}
throw error;
}
}
async function gitOutput(execFileFn, cwd, args) {
const result = await execFileFn("git", args, { cwd });
return String(result.stdout ?? "").trim();
}
function normalizeBoolean(value) {
return value === true || value === "true";
}
function isMissingPath(error) {
return error && typeof error === "object" && error.code === "ENOENT";
}
function isExpectedMissingCommand(error) {
const code = error && typeof error === "object" ? error.code : undefined;
return code === 1 || code === 128;
}
function printAlphaOutputs(result) {
console.log(`version=${result.version}`);
console.log(`tag=${result.tagName}`);
console.log(`title=${result.title}`);
console.log(`image=${result.image}`);
if (result.notesPath) {
console.log(`notes_path=${result.notesPath}`);
}
console.log(`should_complete=${String(result.shouldComplete)}`);
console.log(`create_tag=${String(result.shouldCreateTag)}`);
console.log(`run_goreleaser=${String(result.shouldRunGoreleaser)}`);
console.log(`update_release=${String(result.shouldUpdateRelease)}`);
console.log(`tag_exists=${String(result.tagExists)}`);
console.log(`release_exists=${String(result.releaseExists)}`);
console.log(`image_exists=${String(result.imageExists)}`);
if (result.skipReason) {
console.log(`skip_reason=${result.skipReason}`);
}
}
function printPrunedChangesets(files) {
console.log(`pruned_empty_changesets=${files.join(",")}`);
}
function isDirectRun(url) {
return process.argv[1] && url === new URL(`file://${process.argv[1]}`).href;
}
if (isDirectRun(import.meta.url)) {
try {
const { command, values } = parseAlphaReleaseArgs(process.argv.slice(2));
if (command === "prune-empty-changesets") {
printPrunedChangesets(await pruneEmptyChangesets(values));
} else {
const result =
command === "status"
? await inspectAlphaReleaseTrain(values)
: await prepareAlphaReleaseTrain(values);
printAlphaOutputs(result);
}
} catch (error) {
console.error(error instanceof Error ? error.message : String(error));
process.exit(1);
}
}