-
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathrelease-notes.ts
More file actions
411 lines (363 loc) · 11.5 KB
/
release-notes.ts
File metadata and controls
411 lines (363 loc) · 11.5 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
// Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
/**
* Changelog parsing and GitHub Release synchronization.
*
* Can be used as a library or as a standalone script.
*
* Library usage:
* ```typescript
* import * as releaseNotes from "@eserstack/codebase/release-notes";
*
* // Parse changelog
* const { entries } = await releaseNotes.parseChangelog({ root: "." });
* console.log(entries[0].version, entries[0].notes);
*
* // Sync to GitHub Release
* const result = await releaseNotes.syncReleaseNotes({
* repo: "owner/repo",
* tag: "v4.0.43",
* createIfMissing: true,
* });
* console.log(result.action); // "created" | "updated" | "skipped"
* ```
*
* CLI usage:
* deno run --allow-all ./release-notes.ts --repo owner/repo [--tag v1.0.0] [--create-if-missing]
*
* @module
*/
import * as cliParseArgs from "@std/cli/parse-args";
import * as stdPath from "@std/path";
import * as primitives from "@eserstack/primitives";
import * as standards from "@eserstack/standards";
import * as functions from "@eserstack/functions";
import type * as shellArgs from "@eserstack/shell/args";
import * as shell from "@eserstack/shell";
import * as tui from "@eserstack/shell/tui";
import { createCliContext, runCliMain, toCliEvent } from "./cli-support.ts";
const { ctx, output: out } = createCliContext();
/**
* A parsed entry from a CHANGELOG.md file.
*/
export type ChangelogEntry = {
/** Version string (e.g., "4.0.43") */
readonly version: string;
/** Release date (e.g., "2024-07-16"), empty if not specified */
readonly date: string;
/** Git tag (e.g., "v4.0.43") */
readonly tag: string;
/** Formatted release notes markdown */
readonly notes: string;
};
/**
* Options for parsing a changelog file.
*/
export type ParseChangelogOptions = {
/** Path to CHANGELOG.md relative to root (default: "CHANGELOG.md") */
readonly changelogPath?: string;
/** Root directory (default: ".") */
readonly root?: string;
};
/**
* Result of parsing a changelog file.
*/
export type ParseChangelogResult = {
/** All changelog entries, most recent first */
readonly entries: ReadonlyArray<ChangelogEntry>;
};
/**
* Options for syncing release notes to GitHub.
*/
export type SyncReleaseNotesOptions = {
/** GitHub repository slug (e.g., "owner/repo") */
readonly repo: string;
/** Target tag (e.g., "v4.0.43"). If omitted, uses latest changelog entry */
readonly tag?: string;
/** Create release if it doesn't exist (default: false) */
readonly createIfMissing?: boolean;
/** Path to CHANGELOG.md relative to root (default: "CHANGELOG.md") */
readonly changelogPath?: string;
/** Root directory (default: ".") */
readonly root?: string;
/** Release title template. Use {tag} placeholder. (default: "eserstack {tag}") */
readonly releaseTitle?: string;
};
/**
* Result of syncing release notes.
*/
export type SyncReleaseNotesResult = {
/** The tag that was synced */
readonly tag: string;
/** The changelog entry that was used */
readonly entry: ChangelogEntry;
/** Action taken */
readonly action: "created" | "updated" | "skipped";
};
const HEADING_PATTERN =
/^##\s{1,100}\[?([^\]\s]+)\]?\s{0,100}-?\s{0,100}([0-9]{4}-[0-9]{2}-[0-9]{2})?\s{0,100}$/;
/**
* Normalizes a tag string by stripping `refs/tags/` prefix and ensuring a `v` prefix.
*
* @param rawTag - The raw tag string
* @returns Normalized tag with `v` prefix
*/
export const normalizeTag = (rawTag: string): string => {
const trimmed = rawTag.trim().replace(/^refs\/tags\//, "");
return trimmed.startsWith("v") ? trimmed : `v${trimmed}`;
};
/**
* Parses raw changelog text into structured entries.
* This is a pure function with no I/O — useful for testing.
*
* @param text - Raw CHANGELOG.md content
* @returns Array of changelog entries, most recent first
*/
export const parseChangelogText = (text: string): ChangelogEntry[] => {
const lines = text.split(/\r?\n/);
const headings: {
version: string;
date: string;
headingLineIndex: number;
}[] = [];
for (let index = 0; index < lines.length; index += 1) {
const line = lines[index]!;
const m = line.match(HEADING_PATTERN);
if (m === null) {
continue;
}
// Skip non-version headings like [Unreleased]
if (!/^\d/.test(m[1]!)) {
continue;
}
headings.push({
version: m[1]!,
date: m[2] ?? "",
headingLineIndex: index,
});
}
if (headings.length === 0) {
return [];
}
return headings.map((heading, index) => {
const nextHeading = headings[index + 1];
const bodyStart = heading.headingLineIndex + 1;
const bodyEnd = nextHeading !== undefined
? nextHeading.headingLineIndex
: lines.length;
const bodyLines = lines.slice(bodyStart, bodyEnd);
while (bodyLines.length > 0 && bodyLines[0]!.trim() === "") {
bodyLines.shift();
}
while (
bodyLines.length > 0 && bodyLines[bodyLines.length - 1]!.trim() === ""
) {
bodyLines.pop();
}
const notesParts = [
`## ${heading.version}${heading.date !== "" ? ` - ${heading.date}` : ""}`,
];
if (bodyLines.length > 0) {
notesParts.push("", ...bodyLines);
}
return {
version: heading.version,
date: heading.date,
tag: `v${heading.version}`,
notes: `${notesParts.join("\n").trim()}\n`,
};
});
};
/**
* Reads and parses a CHANGELOG.md file into structured entries.
*
* @param options - Options for the operation
* @returns Result with changelog entries
*/
export const parseChangelog = async (
options: ParseChangelogOptions = {},
): Promise<ParseChangelogResult> => {
const { changelogPath = "CHANGELOG.md", root = "." } = options;
const fullPath = stdPath.resolve(root, changelogPath);
const text = await standards.crossRuntime.runtime.fs.readTextFile(fullPath);
const entries = parseChangelogText(text);
return { entries };
};
/**
* Checks whether a GitHub Release exists for a given tag.
*
* @param tag - The tag to check (e.g., "v4.0.43")
* @param repo - The repository slug (e.g., "owner/repo")
* @returns true if the release exists
*/
export const hasGitHubRelease = async (
tag: string,
repo: string,
): Promise<boolean> => {
try {
await shell.exec.exec`gh release view ${tag} --repo ${repo}`.quiet().text();
return true;
} catch {
return false;
}
};
/**
* Syncs a changelog entry to a GitHub Release.
*
* Finds the changelog entry matching the target tag, then creates or updates
* the corresponding GitHub Release with the entry's notes.
*
* @param options - Options for the operation
* @returns Result describing what action was taken
*/
export const syncReleaseNotes = async (
options: SyncReleaseNotesOptions,
): Promise<SyncReleaseNotesResult> => {
const {
repo,
createIfMissing = false,
changelogPath = "CHANGELOG.md",
root = ".",
releaseTitle = "eserstack {tag}",
} = options;
const { entries } = await parseChangelog({ changelogPath, root });
if (entries.length === 0) {
throw new Error("No release headings found in CHANGELOG.md.");
}
const targetTag = options.tag !== undefined
? normalizeTag(options.tag)
: entries[0]!.tag;
const entry = entries.find((e) => e.tag === targetTag);
if (entry === undefined) {
throw new Error(`No matching changelog section found for ${targetTag}.`);
}
// Write notes to a temp file for gh CLI
const tempDir = await standards.crossRuntime.runtime.fs.makeTempDir({
prefix: "eserstack-release-",
});
const notesPath = stdPath.join(tempDir, `${targetTag}-notes.md`);
await standards.crossRuntime.runtime.fs.writeTextFile(notesPath, entry.notes);
try {
const exists = await hasGitHubRelease(targetTag, repo);
if (exists) {
await shell.exec
.exec`gh release edit ${targetTag} --repo ${repo} --notes-file ${notesPath}`
.spawn();
return { tag: targetTag, entry, action: "updated" };
}
if (!createIfMissing) {
return { tag: targetTag, entry, action: "skipped" };
}
const title = releaseTitle.replace("{tag}", targetTag);
try {
await shell.exec
.exec`gh release create ${targetTag} --repo ${repo} --title ${title} --notes-file ${notesPath}`
.spawn();
return { tag: targetTag, entry, action: "created" };
} catch {
// Race condition: release may have been created between check and create
await shell.exec
.exec`gh release edit ${targetTag} --repo ${repo} --notes-file ${notesPath}`
.spawn();
return { tag: targetTag, entry, action: "updated" };
}
} finally {
await standards.crossRuntime.runtime.fs.remove(tempDir, {
recursive: true,
});
}
};
// --- Handler ---
/** Handler: wraps syncReleaseNotes as a Task via fromPromise. */
export const syncReleaseNotesHandler: functions.handler.Handler<
SyncReleaseNotesOptions,
SyncReleaseNotesResult,
Error
> = (input) => functions.task.fromPromise(() => syncReleaseNotes(input));
// --- CLI Adapter ---
/** Adapter: functions.triggers.CliEvent → SyncReleaseNotesOptions (extracts --repo, --tag, --create-if-missing flags). */
const cliAdapter: functions.handler.Adapter<
functions.triggers.CliEvent,
SyncReleaseNotesOptions
> = (
event,
) => {
const repo = (event.flags["repo"] as string | undefined) ??
standards.crossRuntime.runtime.env.get("GITHUB_REPOSITORY") ?? "";
if (repo === "") {
return primitives.results.fail(
functions.handler.adaptError(
"Missing repository. Pass --repo or set GITHUB_REPOSITORY.",
),
);
}
return primitives.results.ok({
repo,
tag: (event.flags["tag"] as string | undefined) ?? undefined,
createIfMissing: event.flags["create-if-missing"] === true,
});
};
// --- CLI ResponseMapper ---
/** ResponseMapper: formats SyncReleaseNotesResult for CLI output. */
const cliResponseMapper: functions.handler.ResponseMapper<
SyncReleaseNotesResult,
Error | functions.handler.AdaptError,
shellArgs.CliResult<void>
> = (result) => {
if (primitives.results.isFail(result)) {
const err = result.error;
const message = err instanceof Error
? err.message
: (err as functions.handler.AdaptError).message ?? String(err);
tui.log.error(ctx, message);
return primitives.results.fail({ exitCode: 1 });
}
const { value } = result;
switch (value.action) {
case "created":
tui.log.success(
ctx,
`Created release ${value.tag} with changelog notes.`,
);
break;
case "updated":
tui.log.success(ctx, `Updated release notes for ${value.tag}.`);
break;
case "skipped":
tui.log.warn(
ctx,
`Release ${value.tag} not found. Skipping (pass --create-if-missing to create).`,
);
break;
}
return primitives.results.ok(undefined);
};
// --- CLI Trigger ---
/** Runnable CLI trigger for release-notes. */
export const handleCli: (
event: functions.triggers.CliEvent,
) => Promise<shellArgs.CliResult<void>> = functions.handler.createTrigger({
handler: syncReleaseNotesHandler,
adaptInput: cliAdapter,
adaptOutput: cliResponseMapper,
});
/** CLI entry point for dispatcher compatibility. */
export const main = async (
cliArgs?: readonly string[],
): Promise<shellArgs.CliResult<void>> => {
const parsed = cliParseArgs.parseArgs(
(cliArgs ?? []) as string[],
{
string: ["repo", "tag"],
boolean: ["create-if-missing"],
alias: { h: "help" },
},
);
const event = toCliEvent("release-notes", parsed);
return await handleCli(event);
};
if (import.meta.main) {
runCliMain(
await main(standards.crossRuntime.runtime.process.args as string[]),
out,
);
}