feat(bot): add /changelog command to post release notes to Discord
Posts a CHANGELOG.md release entry to #releases (new DISCORD_CHANGELOG_CHANNEL_ID, falls back to the announce channel). /changelog targets the latest entry; /changelog <version> targets a specific version for catch-up. Rendering is a pure, tested module (bot/lib/changelogRender.ts): entries are split on "# vX.Y.Z" headers, ### sections become bold, bullets become the bullet glyph, and entries over Discord's 4096-char limit are split across messages at section/bullet boundaries with the header re-attached to each chunk. Guild-scoped, staff-only command.
This commit is contained in:
parent
d4812de032
commit
2e23d074a4
6 changed files with 491 additions and 1 deletions
|
|
@ -8,7 +8,7 @@ Standalone long-running process (`bun run bot`). Imports `@payload-config` direc
|
|||
|
||||
## Env
|
||||
|
||||
Required: `DISCORD_TOKEN`, `DISCORD_GUILD_ID` (fail-fast on missing vars in `config.ts`). Optional: `DISCORD_OPS_CHANNEL_ID`, `DISCORD_ANNOUNCE_CHANNEL_ID`, `DISCORD_STAFF_ROLE_IDS`, `DISCORD_SIDE_OPS_CHANNEL_ID` (Friday open-slot notice channel), `DISCORD_COMMUNITY_ZEUS_ROLE_ID` (role ping for that notice), `APP_URL`, plus poll intervals `DISCORD_ATTENDANCE_POLL_MS` (default 60s), `DISCORD_NOTIFICATION_POLL_MS` (default 20s), `DISCORD_EVALUATION_POLL_MS` (default 60s), `DISCORD_IMMINENT_POLL_MS` (default 60s), `DISCORD_SIDE_OPS_POLL_MS` (default 30 min). Logs through `payload.logger`.
|
||||
Required: `DISCORD_TOKEN`, `DISCORD_GUILD_ID` (fail-fast on missing vars in `config.ts`). Optional: `DISCORD_OPS_CHANNEL_ID`, `DISCORD_ANNOUNCE_CHANNEL_ID`, `DISCORD_CHANGELOG_CHANNEL_ID` (dedicated #releases channel for `/changelog`; falls back to the announce channel), `DISCORD_STAFF_ROLE_IDS`, `DISCORD_SIDE_OPS_CHANNEL_ID` (Friday open-slot notice channel), `DISCORD_COMMUNITY_ZEUS_ROLE_ID` (role ping for that notice), `APP_URL`, plus poll intervals `DISCORD_ATTENDANCE_POLL_MS` (default 60s), `DISCORD_NOTIFICATION_POLL_MS` (default 20s), `DISCORD_EVALUATION_POLL_MS` (default 60s), `DISCORD_IMMINENT_POLL_MS` (default 60s), `DISCORD_SIDE_OPS_POLL_MS` (default 30 min). Logs through `payload.logger`.
|
||||
|
||||
## Structure
|
||||
|
||||
|
|
@ -23,6 +23,7 @@ bot/
|
|||
signup.ts # /signup (DM-only, creates Payload user with temp password)
|
||||
link.ts # /link (global, links discordId to existing user)
|
||||
announce.ts # /announce (guild-only, staff only; message omitted = compose modal with channel picker, handler in this file)
|
||||
changelog.ts # /changelog (guild-only, staff only; posts a CHANGELOG.md entry to #releases, native markdown, splits long entries)
|
||||
remindEvaluations.ts # /remind-evaluations (guild-only, staff only, manual evaluation-reminder trigger)
|
||||
|
||||
events/
|
||||
|
|
@ -55,6 +56,10 @@ bot/
|
|||
|
||||
`/signup` is DM-only. Creates Payload user with `username` = `discordUsername` = caller's Discord username. Ephemeral reply carries temp password (guaranteed delivery path); `interaction.user.send()` is best-effort persistent copy, so a blocked DM never orphans the account. `/link` works in servers and DMs — matches `discordUsername` → sets `discordId`. **DM gotcha**: a user with "Allow direct messages from server members" off in Discord privacy settings can neither receive the bot's DMs nor open a DM with the bot; the `/signup` rejection message explains how to enable it.
|
||||
|
||||
## 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.
|
||||
|
||||
## Feature flow: attendance
|
||||
|
||||
Bot posts RSVP embeds (Yes/Tentative/No) for future, Scheduled, visibility:"unit" missions into ops channel. Stores `discordMessageId` + `discordAttendanceHash` on mission. Reconciles hash changes every poll tick (web ↔ Discord two-way sync, loop-safe). The embed title links to the mission page, a mission summary sits under the title (truncated to 300 characters with an ellipsis), and an "Open the op" field carries the URL; `attendanceHash` includes an embed schema version so layout-only changes re-render live roll-calls once (idempotent). Web UI: `MissionAttendance` component. Weekly main missions are cloned by `bun run payload generate-mission` (a payload bin, see `src/scripts/AGENTS.md`).
|
||||
|
|
@ -84,6 +89,7 @@ At 8 PM Eastern on Wednesday (`America/New_York`, evaluated via `isNoticeDue` in
|
|||
| Task | Path |
|
||||
|------|------|
|
||||
| Add new slash command | `bot/commands/<name>.ts` + register in `bot/commands/index.ts` |
|
||||
| Changelog rendering/splitting | `bot/lib/changelogRender.ts` |
|
||||
| Add button interaction | `bot/events/interactionCreate.ts` (RSVP) or `transferInteractions.ts` (transfers) |
|
||||
| Modify embed lifecycle | `bot/services/missionEmbeds.ts` |
|
||||
| Change DM bridging | `bot/services/notificationBridge.ts` |
|
||||
|
|
|
|||
146
src/bot/commands/changelog.ts
Normal file
146
src/bot/commands/changelog.ts
Normal file
|
|
@ -0,0 +1,146 @@
|
|||
import {
|
||||
EmbedBuilder,
|
||||
MessageFlags,
|
||||
SlashCommandBuilder,
|
||||
type TextBasedChannelFields,
|
||||
type Guild,
|
||||
} from "discord.js";
|
||||
import { readFileSync } from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
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";
|
||||
|
||||
// CHANGELOG.md sits at the repo root; resolve it relative to this file so the
|
||||
// path is correct regardless of the process working directory.
|
||||
const CHANGELOG_PATH = path.resolve(
|
||||
path.dirname(fileURLToPath(import.meta.url)),
|
||||
"../../../CHANGELOG.md",
|
||||
);
|
||||
|
||||
const ANNOUNCE_COLOR = 0xf59e0b;
|
||||
|
||||
/** Resolve the releases channel, falling back to the configured announce channel. */
|
||||
const resolveChannel = async (
|
||||
guild: Guild,
|
||||
): Promise<TextBasedChannelFields | null> => {
|
||||
const channelId = botConfig.changelogChannelId ?? botConfig.announceChannelId;
|
||||
if (!channelId) return null;
|
||||
const channel = await guild.channels.fetch(channelId);
|
||||
if (!channel || !("send" in channel)) return null;
|
||||
return channel as TextBasedChannelFields;
|
||||
};
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
const postChangelog = async (
|
||||
channel: TextBasedChannelFields,
|
||||
result: ResolvedChangelog,
|
||||
): Promise<number> => {
|
||||
const total = result.messages.length;
|
||||
let posted = 0;
|
||||
for (let i = 0; i < result.messages.length; i += 1) {
|
||||
const embed = new EmbedBuilder()
|
||||
.setTitle(`Changelog v${result.version}`)
|
||||
.setColor(ANNOUNCE_COLOR)
|
||||
.setDescription(result.messages[i]);
|
||||
if (total > 1) {
|
||||
embed.setFooter({ text: `Page ${i + 1}/${total}` });
|
||||
}
|
||||
await channel.send({ embeds: [embed] });
|
||||
posted += 1;
|
||||
}
|
||||
return posted;
|
||||
};
|
||||
|
||||
export const changelogCommand: BotCommand = {
|
||||
builder: new SlashCommandBuilder()
|
||||
.setName("changelog")
|
||||
.setDescription("Post the latest 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."),
|
||||
) as SlashCommandBuilder,
|
||||
execute: async (interaction, payload) => {
|
||||
if (!interaction.inGuild() || !interaction.guild) {
|
||||
await interaction.reply({
|
||||
content: "This command only works in a server.",
|
||||
flags: MessageFlags.Ephemeral,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const member = await interaction.guild.members.fetch(interaction.user.id);
|
||||
if (!(await isStaff(member, payload))) {
|
||||
await interaction.reply({
|
||||
content: "You don't have permission to post a changelog.",
|
||||
flags: MessageFlags.Ephemeral,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
await interaction.deferReply({ flags: MessageFlags.Ephemeral });
|
||||
|
||||
const versionArg = interaction.options.getString("version")?.trim() ?? undefined;
|
||||
|
||||
let content: string;
|
||||
try {
|
||||
content = readFileSync(CHANGELOG_PATH, "utf8");
|
||||
} catch (error) {
|
||||
await interaction.editReply(
|
||||
`Could not read ${path.basename(CHANGELOG_PATH)}: ${
|
||||
error instanceof Error ? error.message : "Unknown error"
|
||||
}`,
|
||||
);
|
||||
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;
|
||||
}
|
||||
|
||||
const channel = await resolveChannel(interaction.guild);
|
||||
if (!channel) {
|
||||
await interaction.editReply(
|
||||
"The releases channel isn't configured (set DISCORD_CHANGELOG_CHANNEL_ID, or DISCORD_ANNOUNCE_CHANNEL_ID as a fallback).",
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const posted = await postChangelog(channel, result);
|
||||
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"}`,
|
||||
);
|
||||
}
|
||||
},
|
||||
};
|
||||
|
|
@ -4,6 +4,7 @@ import { pingCommand } from "./ping";
|
|||
import { signupCommand } from "./signup";
|
||||
import { linkCommand } from "./link";
|
||||
import { announceCommand } from "./announce";
|
||||
import { changelogCommand } from "./changelog";
|
||||
import { remindEvaluationsCommand } from "./remindEvaluations";
|
||||
|
||||
export interface BotCommand {
|
||||
|
|
@ -22,5 +23,6 @@ export const commands: BotCommand[] = [
|
|||
signupCommand,
|
||||
linkCommand,
|
||||
announceCommand,
|
||||
changelogCommand,
|
||||
remindEvaluationsCommand,
|
||||
];
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@ export interface BotConfig {
|
|||
staffRoleIds: string[];
|
||||
sideOpsChannelId: string | null;
|
||||
communityZeusRoleId: string | null;
|
||||
changelogChannelId: string | null;
|
||||
announceMentionRoleId: string | null;
|
||||
attendancePollMs: number;
|
||||
notificationPollMs: number;
|
||||
|
|
@ -53,6 +54,7 @@ export const botConfig: BotConfig = {
|
|||
.filter((id) => id.length > 0),
|
||||
sideOpsChannelId: optional("DISCORD_SIDE_OPS_CHANNEL_ID"),
|
||||
communityZeusRoleId: optional("DISCORD_COMMUNITY_ZEUS_ROLE_ID"),
|
||||
changelogChannelId: optional("DISCORD_CHANGELOG_CHANNEL_ID"),
|
||||
announceMentionRoleId: optional("DISCORD_ANNOUNCE_MENTION_ROLE_ID"),
|
||||
attendancePollMs: pollMs("DISCORD_ATTENDANCE_POLL_MS", 60_000),
|
||||
notificationPollMs: pollMs("DISCORD_NOTIFICATION_POLL_MS", 20_000),
|
||||
|
|
|
|||
198
src/bot/lib/changelogRender.ts
Normal file
198
src/bot/lib/changelogRender.ts
Normal file
|
|
@ -0,0 +1,198 @@
|
|||
/**
|
||||
* Pure helpers that turn a CHANGELOG.md release entry into Discord-formatted
|
||||
* messages. No Discord or Payload dependencies, so the logic is trivially
|
||||
* testable in isolation.
|
||||
*
|
||||
* Discord renders `**bold**`, *italic*, `code`, [links](url) and :emoji:, but
|
||||
* NOT markdown headings or list markers. Section headers therefore become bold
|
||||
* and list bullets become the "•" glyph. Entries longer than Discord's message
|
||||
* limit are split into multiple messages at section/bullet boundaries so a
|
||||
* chunk never lands mid-item.
|
||||
*/
|
||||
|
||||
/** Discord allows 4096 chars per message and per embed description; leave headroom. */
|
||||
const MAX_MESSAGE_CHARS = 4000;
|
||||
|
||||
/** A parsed `# vX.Y.Z` entry: the version and the raw markdown body under it. */
|
||||
export interface ChangelogEntry {
|
||||
version: string;
|
||||
rawBody: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* A unit that must stay together when splitting: the intro text (before the
|
||||
* first section header) or one `### ` section with its lines.
|
||||
*/
|
||||
interface Block {
|
||||
header: string | null;
|
||||
lines: string[];
|
||||
}
|
||||
|
||||
export interface ResolvedChangelog {
|
||||
/** False when nothing matched (empty file, or an unknown version). */
|
||||
found: boolean;
|
||||
/** The matched version (no leading "v"), present when found is true. */
|
||||
version?: string;
|
||||
/** Ordered messages; index 0 is the first message (carries the embed title). */
|
||||
messages: string[];
|
||||
}
|
||||
|
||||
const VERSION_HEADER = /^# v(\d+\.\d+\.\d+)[^\n]*$/gm;
|
||||
const SECTION_HEADER = /^\s*(#{1,3})\s+(.+?)\s*$/;
|
||||
const BULLET = /^\s*[-*]\s+(.*)$/;
|
||||
const ORDERED = /^\s*\d+[.)]\s+(.*)$/;
|
||||
|
||||
/**
|
||||
* Split raw CHANGELOG.md content into version entries. Entries are returned
|
||||
* newest-first, matching the file's layout (v0.8.0 at the top).
|
||||
*/
|
||||
export function parseChangelog(content: string): ChangelogEntry[] {
|
||||
const headers: { version: string; start: number; bodyStart: number }[] = [];
|
||||
let match: RegExpExecArray | null;
|
||||
while ((match = VERSION_HEADER.exec(content)) !== null) {
|
||||
const lineEnd = content.indexOf("\n", match.index + match[0].length);
|
||||
headers.push({
|
||||
version: match[1],
|
||||
start: match.index,
|
||||
bodyStart: lineEnd === -1 ? content.length : lineEnd + 1,
|
||||
});
|
||||
}
|
||||
return headers.map((header, index) => {
|
||||
const nextStart = headers[index + 1]?.start ?? content.length;
|
||||
return { version: header.version, rawBody: content.slice(header.bodyStart, nextStart) };
|
||||
});
|
||||
}
|
||||
|
||||
/** Group a raw entry body into blocks that should never be split across messages. */
|
||||
function intoBlocks(rawBody: string): Block[] {
|
||||
const blocks: Block[] = [];
|
||||
let current: Block | null = null;
|
||||
for (const line of rawBody.split("\n")) {
|
||||
const section = line.match(SECTION_HEADER);
|
||||
if (section) {
|
||||
current = { header: section[2].trim(), lines: [] };
|
||||
blocks.push(current);
|
||||
continue;
|
||||
}
|
||||
if (!current) {
|
||||
current = { header: null, lines: [] };
|
||||
blocks.push(current);
|
||||
}
|
||||
current.lines.push(line);
|
||||
}
|
||||
|
||||
const result: Block[] = [];
|
||||
for (const block of blocks) {
|
||||
let start = 0;
|
||||
let end = block.lines.length;
|
||||
while (start < end && /^\s*$/.test(block.lines[start])) start++;
|
||||
while (end > start && /^\s*$/.test(block.lines[end - 1])) end--;
|
||||
const lines = block.lines.slice(start, end);
|
||||
// Drop a leading/trailing all-blank intro block; keep section blocks even
|
||||
// if empty so their bold header still renders.
|
||||
if (lines.length === 0 && block.header === null) continue;
|
||||
result.push({ header: block.header, lines });
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
const formatLine = (raw: string): string => {
|
||||
const bullet = raw.match(BULLET);
|
||||
if (bullet) return `• ${bullet[1]}`;
|
||||
const ordered = raw.match(ORDERED);
|
||||
if (ordered) return `• ${ordered[1]}`;
|
||||
return raw;
|
||||
};
|
||||
|
||||
const blockToString = (block: Block): string => {
|
||||
const lines: string[] = [];
|
||||
if (block.header !== null) lines.push(`**${block.header}**`);
|
||||
for (const line of block.lines) lines.push(formatLine(line));
|
||||
return lines.join("\n");
|
||||
};
|
||||
|
||||
/** Format an entry body into a single Discord string, without splitting. */
|
||||
export function formatEntryDiscord(rawBody: string): string {
|
||||
return intoBlocks(rawBody).map(blockToString).join("\n\n");
|
||||
}
|
||||
|
||||
/**
|
||||
* Split an array of already-rendered lines into messages that fit the limit,
|
||||
* joining lines with blank lines and splitting at line boundaries.
|
||||
*/
|
||||
const splitLinesToMessages = (lines: string[], max: number): string[] => {
|
||||
const messages: string[] = [];
|
||||
let current = "";
|
||||
for (const line of lines) {
|
||||
const candidate = current ? `${current}\n${line}` : line;
|
||||
if (candidate.length > max && current.length > 0) {
|
||||
messages.push(current);
|
||||
current = line;
|
||||
} else {
|
||||
current = candidate;
|
||||
}
|
||||
}
|
||||
if (current) messages.push(current);
|
||||
return messages;
|
||||
};
|
||||
|
||||
/**
|
||||
* Split an entry body into messages that fit Discord's length limit. Blocks are
|
||||
* packed greedily and only broken at block (section/bullet) boundaries; a block
|
||||
* that is too long on its own is split further at line boundaries, re-attaching
|
||||
* its section header to every chunk.
|
||||
*/
|
||||
export function splitForDiscord(rawBody: string): string[] {
|
||||
const messages: string[] = [];
|
||||
let current = "";
|
||||
for (const block of intoBlocks(rawBody)) {
|
||||
const blockLines: string[] = [];
|
||||
if (block.header !== null) blockLines.push(`**${block.header}**`);
|
||||
for (const line of block.lines) blockLines.push(formatLine(line));
|
||||
if (blockLines.length === 0) continue;
|
||||
|
||||
const blockText = blockLines.join("\n");
|
||||
const candidate = current ? `${current}\n\n${blockText}` : blockText;
|
||||
if (blockText.length <= MAX_MESSAGE_CHARS && candidate.length <= MAX_MESSAGE_CHARS) {
|
||||
current = candidate;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (current) {
|
||||
messages.push(current);
|
||||
current = "";
|
||||
}
|
||||
|
||||
if (blockText.length <= MAX_MESSAGE_CHARS) {
|
||||
current = blockText;
|
||||
continue;
|
||||
}
|
||||
|
||||
const headerPrefix = block.header !== null ? `**${block.header}**` : null;
|
||||
// Reserve room for the re-attached header + separator on continuation chunks.
|
||||
const headroom = headerPrefix ? headerPrefix.length + "\n\n".length : 0;
|
||||
const blockChunks = splitLinesToMessages(blockLines, MAX_MESSAGE_CHARS - headroom);
|
||||
blockChunks.forEach((chunk, index) => {
|
||||
// The first chunk already carries the header inline; re-attach it to every
|
||||
// continuation chunk so each message stays self-identifying.
|
||||
const rendered = index === 0 || headerPrefix === null ? chunk : `${headerPrefix}\n\n${chunk}`;
|
||||
messages.push(rendered);
|
||||
});
|
||||
}
|
||||
if (current) messages.push(current);
|
||||
return messages;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve which message(s) to post for a changelog. With no version argument
|
||||
* the newest entry is used; otherwise the exact version is matched (a leading
|
||||
* "v" is ignored).
|
||||
*/
|
||||
export function resolveChangelog(content: string, versionArg?: string): ResolvedChangelog {
|
||||
const entries = parseChangelog(content);
|
||||
const target = versionArg
|
||||
? entries.find((entry) => entry.version === versionArg.replace(/^v/i, "").trim())
|
||||
: entries[0];
|
||||
if (!target) return { found: false, messages: [] };
|
||||
return { found: true, version: target.version, messages: splitForDiscord(target.rawBody) };
|
||||
}
|
||||
136
tests/int/changelog.int.spec.ts
Normal file
136
tests/int/changelog.int.spec.ts
Normal file
|
|
@ -0,0 +1,136 @@
|
|||
import { readFileSync } from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
formatEntryDiscord,
|
||||
parseChangelog,
|
||||
resolveChangelog,
|
||||
splitForDiscord,
|
||||
} from "@/bot/lib/changelogRender";
|
||||
|
||||
const CHANGELOG_PATH = path.resolve(
|
||||
path.dirname(fileURLToPath(import.meta.url)),
|
||||
"../../CHANGELOG.md",
|
||||
);
|
||||
|
||||
const SAMPLE = `# v0.4.0
|
||||
|
||||
Intro line describing the release.
|
||||
|
||||
### Features
|
||||
|
||||
- **Feature one:** does a thing.
|
||||
- **Feature two:** does another.
|
||||
|
||||
### Fixes
|
||||
|
||||
- Fixed a bug.
|
||||
`;
|
||||
|
||||
describe("parseChangelog", () => {
|
||||
it("returns entries newest-first with clean body boundaries", () => {
|
||||
const content = [
|
||||
"# Changelog",
|
||||
"",
|
||||
"# v0.5.0",
|
||||
"",
|
||||
"Fifth release.",
|
||||
"",
|
||||
"### Features",
|
||||
"",
|
||||
"- A.",
|
||||
"",
|
||||
"# v0.4.0",
|
||||
"",
|
||||
"Fourth release.",
|
||||
"",
|
||||
].join("\n");
|
||||
|
||||
const entries = parseChangelog(content);
|
||||
expect(entries.map((e) => e.version)).toEqual(["0.5.0", "0.4.0"]);
|
||||
expect(entries[0].rawBody).toContain("Fifth release.");
|
||||
expect(entries[0].rawBody).toContain("### Features");
|
||||
expect(entries[0].rawBody).not.toContain("# v0.4.0");
|
||||
expect(entries[1].rawBody.trim()).toBe("Fourth release.");
|
||||
});
|
||||
|
||||
it("ignores the file title header", () => {
|
||||
expect(parseChangelog("# Changelog\n\n# v1.0.0\n\nBody\n")).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveChangelog", () => {
|
||||
it("defaults to the newest (first) entry", () => {
|
||||
const content = ["# v0.3.0", "", "New.", "", "# v0.2.0", "", "Old."].join("\n");
|
||||
const resolved = resolveChangelog(content);
|
||||
expect(resolved.found).toBe(true);
|
||||
expect(resolved.version).toBe("0.3.0");
|
||||
});
|
||||
|
||||
it("matches a specific version and tolerates a leading v", () => {
|
||||
const content = ["# v0.2.0", "", "A.", "", "# v0.4.0", "", "B."].join("\n");
|
||||
expect(resolveChangelog(content, "0.4.0").version).toBe("0.4.0");
|
||||
expect(resolveChangelog(content, "v0.2.0").version).toBe("0.2.0");
|
||||
});
|
||||
|
||||
it("reports when nothing matches", () => {
|
||||
expect(resolveChangelog("# v0.4.0\n\nBody\n", "9.9.9").found).toBe(false);
|
||||
expect(resolveChangelog("# Changelog\n", "").found).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("formatEntryDiscord", () => {
|
||||
it("turns section headers bold and bullets into the bullet glyph", () => {
|
||||
const formatted = formatEntryDiscord(SAMPLE);
|
||||
expect(formatted).toContain("**Features**");
|
||||
expect(formatted).toContain("**Fixes**");
|
||||
expect(formatted).toContain("• **Feature one:** does a thing.");
|
||||
expect(formatted).not.toContain("# ");
|
||||
});
|
||||
|
||||
it("preserves inline markdown", () => {
|
||||
const formatted = formatEntryDiscord("Plain with **bold**, `code`, and [a link](https://example.com).");
|
||||
expect(formatted).toContain("**bold**");
|
||||
expect(formatted).toContain("`code`");
|
||||
expect(formatted).toContain("[a link](https://example.com)");
|
||||
});
|
||||
});
|
||||
|
||||
describe("splitForDiscord", () => {
|
||||
it("keeps a short entry as a single message", () => {
|
||||
expect(splitForDiscord(SAMPLE)).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("splits a long entry at block boundaries without losing bullets", () => {
|
||||
const bullets = Array.from({ length: 300 }, (_, i) => `- **Item ${i}:** descriptive text`).join("\n");
|
||||
const body = `### Features\n\n${bullets}\n`;
|
||||
const messages = splitForDiscord(body);
|
||||
|
||||
expect(messages.length).toBeGreaterThan(1);
|
||||
messages.forEach((message) => expect(message.length).toBeLessThanOrEqual(4000));
|
||||
// Every original bullet survives across the split, so nothing was cut mid-item.
|
||||
const bulletsInMessages = messages
|
||||
.flatMap((message) => message.split("\n"))
|
||||
.filter((line) => line.startsWith("• "));
|
||||
expect(bulletsInMessages).toHaveLength(300);
|
||||
// The first chunk leads with the section header.
|
||||
expect(messages[0]).toContain("**Features**");
|
||||
});
|
||||
});
|
||||
|
||||
describe("real CHANGELOG.md", () => {
|
||||
it("parses and renders the shipped entries", () => {
|
||||
const content = readFileSync(CHANGELOG_PATH, "utf8");
|
||||
const entries = parseChangelog(content);
|
||||
expect(entries.length).toBeGreaterThan(10);
|
||||
// The file is newest-first.
|
||||
expect(entries[0].version).toBe("0.8.0");
|
||||
|
||||
const v040 = resolveChangelog(content, "0.4.0");
|
||||
expect(v040.found).toBe(true);
|
||||
expect(v040.messages.length).toBeGreaterThan(0);
|
||||
expect(v040.messages[0]).toContain("**Features**");
|
||||
expect(v040.messages[0]).toContain("• **Mission planning maps**:");
|
||||
});
|
||||
});
|
||||
Loading…
Reference in a new issue