diff --git a/src/bot/AGENTS.md b/src/bot/AGENTS.md index e428f5ef..4d1379e8 100644 --- a/src/bot/AGENTS.md +++ b/src/bot/AGENTS.md @@ -58,7 +58,7 @@ bot/ ## Feature flow: changelogs -`/changelog` (guild-only, staff only) posts a `CHANGELOG.md` release entry to the releases channel (`DISCORD_CHANGELOG_CHANNEL_ID`, falling back to `DISCORD_ANNOUNCE_CHANNEL_ID`). `/changelog` targets the newest entry; `/changelog v0.4.0` targets a specific version (for catching up on missed posts). Rendering lives in `bot/lib/changelogRender.ts` (pure, no Discord/Payload deps): entries are split on `# vX.Y.Z` headers, `### ` sections become `**bold**`, bullets become `•`, and entries over Discord's 4096-char limit are split across messages at section boundaries. The command reads `CHANGELOG.md` from the repo root relative to the file (works from the deploy server) and posts each chunk as an amber embed, the first carrying the `Changelog vX.Y.Z` title and multi-message releases adding a page footer. Idempotency ("don't repost") is intentionally out of scope for the manual command; the same rendering can be reused by a future automatic trigger. +`/changelog` (guild-only, staff only) posts a `CHANGELOG.md` release entry to the releases channel (`DISCORD_CHANGELOG_CHANNEL_ID`, falling back to `DISCORD_ANNOUNCE_CHANNEL_ID`). `/changelog` targets the newest entry; `/changelog v0.4.0` targets a specific version (for catching up on missed posts); `/changelog v0.3.0..v0.5.0` targets a range (inclusive slice, output oldest-to-newest). Either range end is open (`v0.3.0..` to the latest, `..v0.5.0` from the oldest) and a reversed range is normalized. Rendering lives in `bot/lib/changelogRender.ts` (pure, no Discord/Payload deps): entries are split on `# vX.Y.Z` headers, `### ` sections become `**bold**`, bullets become `•`, and entries over Discord's 4096-char limit are split across messages at section boundaries. The command reads `CHANGELOG.md` from the repo root relative to the file (works from the deploy server) and posts each version as its own amber embed, the first message of each version carrying the `Changelog vX.Y.Z` title and multi-message versions adding a page footer. Ranges spanning more than `WIDE_RANGE_THRESHOLD` (10) versions post an ephemeral warning but proceed. Idempotency ("don't repost") is intentionally out of scope for the manual command; the same rendering can be reused by a future automatic trigger. ## Feature flow: attendance diff --git a/src/bot/commands/changelog.ts b/src/bot/commands/changelog.ts index c5b8720b..3188600f 100644 --- a/src/bot/commands/changelog.ts +++ b/src/bot/commands/changelog.ts @@ -12,7 +12,12 @@ import type { Payload } from "payload"; import type { BotCommand } from "./index"; import { botConfig } from "@/bot/config"; import { isStaff } from "@/bot/lib/roles"; -import { resolveChangelog, type ResolvedChangelog } from "@/bot/lib/changelogRender"; +import { + resolveChangelog, + resolveChangelogRange, + type ResolvedChangelog, + type ChangelogBatch, +} from "@/bot/lib/changelogRender"; // CHANGELOG.md sits at the repo root; resolve it relative to this file so the // path is correct regardless of the process working directory. @@ -23,10 +28,16 @@ const CHANGELOG_PATH = path.resolve( const ANNOUNCE_COLOR = 0xf59e0b; +/** Ranges spanning more versions than this trigger an ephemeral warning. */ +const WIDE_RANGE_THRESHOLD = 10; + +interface VersionPost { + version: string; + messages: string[]; +} + /** Resolve the releases channel, falling back to the configured announce channel. */ -const resolveChannel = async ( - guild: Guild, -): Promise => { +const resolveChannel = async (guild: Guild): Promise => { const channelId = botConfig.changelogChannelId ?? botConfig.announceChannelId; if (!channelId) return null; const channel = await guild.channels.fetch(channelId); @@ -35,20 +46,21 @@ const resolveChannel = async ( }; /** - * Post each chunk as an amber embed. The first message carries the version - * title; multi-message releases add a page footer so order stays clear. + * Post one version's messages as amber embeds. The first carries the version + * title; multi-message versions add a page footer so order stays clear. */ -const postChangelog = async ( +const postVersion = async ( channel: TextBasedChannelFields, - result: ResolvedChangelog, + version: string, + messages: string[], ): Promise => { - const total = result.messages.length; + const total = messages.length; let posted = 0; - for (let i = 0; i < result.messages.length; i += 1) { + for (let i = 0; i < messages.length; i += 1) { const embed = new EmbedBuilder() - .setTitle(`Changelog v${result.version}`) + .setTitle(`Changelog v${version}`) .setColor(ANNOUNCE_COLOR) - .setDescription(result.messages[i]); + .setDescription(messages[i]); if (total > 1) { embed.setFooter({ text: `Page ${i + 1}/${total}` }); } @@ -61,11 +73,13 @@ const postChangelog = async ( export const changelogCommand: BotCommand = { builder: new SlashCommandBuilder() .setName("changelog") - .setDescription("Post the latest release notes to #releases (staff only)") + .setDescription("Post release notes to #releases (staff only)") .addStringOption((option) => option - .setName("version") - .setDescription("Specific version to post (e.g. 0.4.0). Omit for the latest entry."), + .setName("range") + .setDescription( + "Version or range: v0.4.0 (single), v0.3.0..v0.5.0 (inclusive), v0.3.0.. (to latest), ..v0.5.0 (from oldest). Omit for the latest entry.", + ), ) as SlashCommandBuilder, execute: async (interaction, payload) => { if (!interaction.inGuild() || !interaction.guild) { @@ -87,7 +101,7 @@ export const changelogCommand: BotCommand = { await interaction.deferReply({ flags: MessageFlags.Ephemeral }); - const versionArg = interaction.options.getString("version")?.trim() ?? undefined; + const rangeArg = interaction.options.getString("range")?.trim(); let content: string; try { @@ -101,25 +115,41 @@ export const changelogCommand: BotCommand = { return; } - let result: ResolvedChangelog; - try { - result = resolveChangelog(content, versionArg); - } catch (error) { - await interaction.editReply( - `Failed to parse the changelog: ${ - error instanceof Error ? error.message : "Unknown error" - }`, - ); - return; - } - - if (!result.found || result.messages.length === 0) { - await interaction.editReply( - versionArg - ? `No changelog entry found for version ${versionArg}.` - : "The changelog file has no entries to post.", - ); - return; + // A range uses "from..to" notation; anything else is a single version. + let posts: VersionPost[]; + let summaryFrom = ""; + let summaryTo = ""; + if (rangeArg && rangeArg.includes("..")) { + const [fromPart, toPart] = rangeArg.split(".."); + const from = fromPart?.trim() || undefined; + const to = toPart?.trim() || undefined; + const batch: ChangelogBatch = resolveChangelogRange(content, from, to); + if (!batch.found || batch.versions.length === 0) { + await interaction.editReply( + from && to + ? `No changelog entries found between ${from} and ${to}.` + : from + ? `Could not find version ${from}.` + : `Could not find version ${to}.`, + ); + return; + } + posts = batch.versions.map((version, i) => ({ version, messages: batch.messages[i] })); + summaryFrom = batch.versions[0]; + summaryTo = batch.versions[batch.versions.length - 1]; + } else { + const single: ResolvedChangelog = resolveChangelog(content, rangeArg ?? undefined); + if (!single.found || single.messages.length === 0) { + await interaction.editReply( + rangeArg + ? `No changelog entry found for version ${rangeArg}.` + : "The changelog file has no entries to post.", + ); + return; + } + posts = [{ version: single.version ?? "", messages: single.messages }]; + summaryFrom = single.version ?? ""; + summaryTo = summaryFrom; } const channel = await resolveChannel(interaction.guild); @@ -130,17 +160,21 @@ export const changelogCommand: BotCommand = { return; } - try { - const posted = await postChangelog(channel, result); + if (posts.length > WIDE_RANGE_THRESHOLD) { await interaction.editReply( - posted > 1 - ? `Posted **Changelog v${result.version}** across ${posted} messages.` - : `Posted **Changelog v${result.version}**.`, - ); - } catch (error) { - await interaction.editReply( - `Changelog post failed: ${error instanceof Error ? error.message : "Unknown error"}`, + `⚠️ Posting ${posts.length} changelog(s) (${summaryFrom} → ${summaryTo}). This may take a moment.`, ); } + + let totalMessages = 0; + for (const post of posts) { + totalMessages += await postVersion(channel, post.version, post.messages); + } + + await interaction.editReply( + posts.length > 1 + ? `Posted ${posts.length} changelog(s) for ${summaryFrom} → ${summaryTo} (${totalMessages} messages).` + : `Posted **Changelog v${summaryFrom}**.`, + ); }, }; diff --git a/src/bot/lib/changelogRender.ts b/src/bot/lib/changelogRender.ts index 8303ba38..b9520605 100644 --- a/src/bot/lib/changelogRender.ts +++ b/src/bot/lib/changelogRender.ts @@ -196,3 +196,62 @@ export function resolveChangelog(content: string, versionArg?: string): Resolved if (!target) return { found: false, messages: [] }; return { found: true, version: target.version, messages: splitForDiscord(target.rawBody) }; } + +export interface ChangelogBatch { + /** False when no version in the range exists, or the range was empty. */ + found: boolean; + /** Matched versions, oldest-to-newest. */ + versions: string[]; + /** Discord messages per version, parallel to `versions`. */ + messages: string[][]; +} + +/** Numeric major.minor.patch comparison (CHANGELOG versions carry no prerelease). */ +const compareVersions = (a: string, b: string): number => { + const parts = (v: string) => v.split(".").map((n) => Number.parseInt(n, 10) || 0); + const pa = parts(a); + const pb = parts(b); + for (let i = 0; i < 3; i += 1) { + const diff = (pa[i] ?? 0) - (pb[i] ?? 0); + if (diff !== 0) return diff; + } + return 0; +}; + +/** + * Resolve a version range to an ordered batch of entries. `from`/`to` are bare + * versions (no leading "v"); either may be omitted to open that end of the + * range ("from here to the latest", or "from the oldest to here"). A range is a + * contiguous slice of CHANGELOG.md between the two versions; output is always + * sorted oldest-to-newest. A reversed range (newer first) is accepted and + * normalized, so `v0.5.0..v0.3.0` behaves like `v0.3.0..v0.5.0`. + */ +export function resolveChangelogRange( + content: string, + fromArg?: string, + toArg?: string, +): ChangelogBatch { + const entries = parseChangelog(content); + const from = fromArg ? fromArg.replace(/^v/i, "").trim() : undefined; + const to = toArg ? toArg.replace(/^v/i, "").trim() : undefined; + + if (!from && !to) return { found: false, versions: [], messages: [] }; + + const idxFrom = from ? entries.findIndex((entry) => entry.version === from) : 0; + const idxTo = to ? entries.findIndex((entry) => entry.version === to) : entries.length - 1; + if (idxFrom === -1 || idxTo === -1) { + return { found: false, versions: [], messages: [] }; + } + + const start = Math.min(idxFrom, idxTo); + const end = Math.max(idxFrom, idxTo); + const slice = entries + .slice(start, end + 1) + .sort((a, b) => compareVersions(a.version, b.version)); + + return { + found: true, + versions: slice.map((entry) => entry.version), + messages: slice.map((entry) => splitForDiscord(entry.rawBody)), + }; +} diff --git a/tests/int/changelog.int.spec.ts b/tests/int/changelog.int.spec.ts index 9495d696..6143daf0 100644 --- a/tests/int/changelog.int.spec.ts +++ b/tests/int/changelog.int.spec.ts @@ -6,6 +6,7 @@ import { formatEntryDiscord, parseChangelog, resolveChangelog, + resolveChangelogRange, splitForDiscord, } from "@/bot/lib/changelogRender"; @@ -80,6 +81,53 @@ describe("resolveChangelog", () => { }); }); +// Newest-first file so index order == reverse-chronological order. +const DESC_CONTENT = ["# v0.5.0", "", "V5", "", "# v0.4.0", "", "V4", "", "# v0.3.0", "", "V3", "", "# v0.2.0", "", "V2", "", "# v0.1.0", "", "V1"].join( + "\n", +); + +describe("resolveChangelogRange", () => { + it("returns an inclusive slice, oldest-to-newest", () => { + const batch = resolveChangelogRange(DESC_CONTENT, "0.3.0", "0.5.0"); + expect(batch.found).toBe(true); + expect(batch.versions).toEqual(["0.3.0", "0.4.0", "0.5.0"]); + expect(batch.messages).toHaveLength(3); + }); + + it("opens the top end (from here to the latest)", () => { + const batch = resolveChangelogRange(DESC_CONTENT, "0.3.0", undefined); + expect(batch.versions).toEqual(["0.1.0", "0.2.0", "0.3.0"]); + }); + + it("opens the bottom end (from the oldest to here)", () => { + const batch = resolveChangelogRange(DESC_CONTENT, undefined, "0.4.0"); + expect(batch.versions).toEqual(["0.4.0", "0.5.0"]); + }); + + it("normalizes a reversed range", () => { + expect(resolveChangelogRange(DESC_CONTENT, "0.5.0", "0.3.0").versions).toEqual([ + "0.3.0", + "0.4.0", + "0.5.0", + ]); + }); + + it("treats an empty range (..) as nothing to post", () => { + expect(resolveChangelogRange(DESC_CONTENT, undefined, undefined).found).toBe(false); + }); + + it("reports an unknown bound", () => { + expect(resolveChangelogRange(DESC_CONTENT, "0.3.0", "9.9.9").found).toBe(false); + }); + + it("ignores a leading v on either side", () => { + expect(resolveChangelogRange(DESC_CONTENT, "v0.4.0", "v0.5.0").versions).toEqual([ + "0.4.0", + "0.5.0", + ]); + }); +}); + describe("formatEntryDiscord", () => { it("turns section headers bold and bullets into the bullet glyph", () => { const formatted = formatEntryDiscord(SAMPLE); @@ -133,4 +181,15 @@ describe("real CHANGELOG.md", () => { expect(v040.messages[0]).toContain("**Features**"); expect(v040.messages[0]).toContain("• **Mission planning maps**:"); }); + + it("resolves an inclusive range on the shipped file", () => { + const content = readFileSync(CHANGELOG_PATH, "utf8"); + const batch = resolveChangelogRange(content, "0.4.0", "0.5.0"); + expect(batch.found).toBe(true); + expect(batch.versions).toEqual(["0.4.0", "0.4.1", "0.5.0"]); + batch.messages.forEach((messages) => { + expect(messages.length).toBeGreaterThanOrEqual(1); + messages.forEach((message) => expect(message.length).toBeLessThanOrEqual(4000)); + }); + }); });