feat(gitea): add embeds, modals and the issue and pull request commands
Creating an issue or a pull request needs a title and a description, which do not fit in a slash command option, so the branches chosen as options are kept in memory for a few minutes until the modal is submitted.
This commit is contained in:
7 files changed
+470
-12
No files matched your search
@@ -1,6 +1,8 @@
|
||||
import { SlashCommandBuilder } from 'discord.js';
|
||||
import { ACCESS_LEVELS } from '../../config/constants.js';
|
||||
import { notImplementedEmbed } from '../../ui/embeds.js';
|
||||
import { ACCESS_LEVELS, COLORS } from '../../config/constants.js';
|
||||
import { asList, gitea, repositoryUrl } from '../../services/gitea/gitea-client.js';
|
||||
import { replyGiteaFailure, assertGiteaConfigured } from '../../services/gitea/gitea-modals.js';
|
||||
import { baseEmbed, successEmbed } from '../../ui/embeds.js';
|
||||
|
||||
export const access = ACCESS_LEVELS.USER;
|
||||
|
||||
@@ -10,7 +12,62 @@ export const data = new SlashCommandBuilder()
|
||||
.addSubcommand((sub) => sub.setName('activity').setDescription('Commits, issues et PR récents'))
|
||||
.addSubcommand((sub) => sub.setName('release').setDescription('Releases disponibles'));
|
||||
|
||||
// TODO(M5-T06 / M5-T07): implement with services/gitea/gitea-client.js.
|
||||
const commitLines = (commits) =>
|
||||
asList(commits)
|
||||
.slice(0, 5)
|
||||
.map((commit) => {
|
||||
const message = commit.commit?.message?.split('\n')[0] ?? '(sans message)';
|
||||
return `\`${commit.sha?.slice(0, 7)}\` ${message} — *${commit.commit?.author?.name ?? 'inconnu'}*`;
|
||||
})
|
||||
.join('\n');
|
||||
|
||||
/** Read-only summaries of the repository (M5-T06 / M5-T07). */
|
||||
export async function execute(interaction) {
|
||||
await interaction.reply({ embeds: [notImplementedEmbed(`/gitea ${interaction.options.getSubcommand()}`)] });
|
||||
assertGiteaConfigured();
|
||||
await interaction.deferReply();
|
||||
|
||||
try {
|
||||
if (interaction.options.getSubcommand() === 'release') {
|
||||
const releases = asList(await gitea.listReleases(5));
|
||||
if (releases.length === 0) {
|
||||
await interaction.editReply({ embeds: [successEmbed('Aucune release publiée pour le moment.')] });
|
||||
return;
|
||||
}
|
||||
|
||||
const embed = baseEmbed(COLORS.gitea)
|
||||
.setTitle('Releases FWS Arch')
|
||||
.setURL(repositoryUrl())
|
||||
.setDescription(
|
||||
releases
|
||||
.map((release) => {
|
||||
const date = release.published_at
|
||||
? `<t:${Math.floor(new Date(release.published_at).getTime() / 1000)}:D>`
|
||||
: 'date inconnue';
|
||||
const tag = release.html_url ? `[${release.tag_name}](${release.html_url})` : release.tag_name;
|
||||
return `${release.prerelease ? '🧪' : '📦'} **${tag}** — ${release.name || 'sans titre'} · ${date}`;
|
||||
})
|
||||
.join('\n'),
|
||||
);
|
||||
await interaction.editReply({ embeds: [embed] });
|
||||
return;
|
||||
}
|
||||
|
||||
const [issues, pulls, commits] = await Promise.all([
|
||||
gitea.listIssues('state=open&type=issues&limit=50'),
|
||||
gitea.listPullRequests('state=open&limit=50'),
|
||||
gitea.listCommits(5),
|
||||
]);
|
||||
|
||||
const embed = baseEmbed(COLORS.gitea)
|
||||
.setTitle('Activité récente')
|
||||
.setURL(repositoryUrl())
|
||||
.setDescription(commitLines(commits) || 'Aucun commit récent.')
|
||||
.addFields(
|
||||
{ name: 'Issues ouvertes', value: String(asList(issues).length), inline: true },
|
||||
{ name: 'PR ouvertes', value: String(asList(pulls).length), inline: true },
|
||||
);
|
||||
await interaction.editReply({ embeds: [embed] });
|
||||
} catch (error) {
|
||||
await replyGiteaFailure(interaction, error);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,14 @@
|
||||
import { SlashCommandBuilder } from 'discord.js';
|
||||
import { ACCESS_LEVELS } from '../../config/constants.js';
|
||||
import { notImplementedEmbed } from '../../ui/embeds.js';
|
||||
import { ACCESS_LEVELS, COLORS } from '../../config/constants.js';
|
||||
import { UserFacingError } from '../../core/errors.js';
|
||||
import { asList, gitea, repositoryUrl } from '../../services/gitea/gitea-client.js';
|
||||
import { issueEmbed } from '../../services/gitea/gitea-embeds.js';
|
||||
import {
|
||||
assertGiteaConfigured,
|
||||
openIssueModal,
|
||||
replyGiteaFailure,
|
||||
} from '../../services/gitea/gitea-modals.js';
|
||||
import { baseEmbed, successEmbed } from '../../ui/embeds.js';
|
||||
|
||||
export const access = ACCESS_LEVELS.USER;
|
||||
|
||||
@@ -21,7 +29,43 @@ export const data = new SlashCommandBuilder()
|
||||
)
|
||||
.addSubcommand((sub) => sub.setName('list').setDescription('Lister les issues ouvertes'));
|
||||
|
||||
// TODO(M5-T02 / M5-T03): implement with services/gitea/gitea-client.js.
|
||||
/** Issues can be browsed and created straight from Discord (M5-T02 / M5-T03). */
|
||||
export async function execute(interaction) {
|
||||
await interaction.reply({ embeds: [notImplementedEmbed(`/issue ${interaction.options.getSubcommand()}`)] });
|
||||
const subcommand = interaction.options.getSubcommand();
|
||||
|
||||
if (subcommand === 'create') {
|
||||
await openIssueModal(interaction);
|
||||
return;
|
||||
}
|
||||
|
||||
assertGiteaConfigured();
|
||||
await interaction.deferReply();
|
||||
|
||||
try {
|
||||
if (subcommand === 'view') {
|
||||
const issue = await gitea.getIssue(interaction.options.getInteger('number', true));
|
||||
if (!issue?.number) throw new UserFacingError('Cette issue est introuvable sur Gitea.');
|
||||
await interaction.editReply({ embeds: [issueEmbed(issue)] });
|
||||
return;
|
||||
}
|
||||
|
||||
const issues = asList(await gitea.listIssues('state=open&type=issues&limit=15'));
|
||||
if (issues.length === 0) {
|
||||
await interaction.editReply({ embeds: [successEmbed('Aucune issue ouverte. 🎉')] });
|
||||
return;
|
||||
}
|
||||
|
||||
const embed = baseEmbed(COLORS.gitea)
|
||||
.setTitle('Issues ouvertes')
|
||||
.setURL(`${repositoryUrl()}/issues`)
|
||||
.setDescription(
|
||||
issues
|
||||
.map((issue) => `**#${issue.number}** ${issue.title} — *${issue.user?.login ?? 'inconnu'}*`)
|
||||
.join('\n'),
|
||||
)
|
||||
.setFooter({ text: `${issues.length} issue(s) affichée(s)` });
|
||||
await interaction.editReply({ embeds: [embed] });
|
||||
} catch (error) {
|
||||
await replyGiteaFailure(interaction, error);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,14 @@
|
||||
import { SlashCommandBuilder } from 'discord.js';
|
||||
import { ACCESS_LEVELS } from '../../config/constants.js';
|
||||
import { notImplementedEmbed } from '../../ui/embeds.js';
|
||||
import { ACCESS_LEVELS, COLORS } from '../../config/constants.js';
|
||||
import { UserFacingError } from '../../core/errors.js';
|
||||
import { asList, gitea, repositoryUrl } from '../../services/gitea/gitea-client.js';
|
||||
import { pullRequestEmbed } from '../../services/gitea/gitea-embeds.js';
|
||||
import {
|
||||
assertGiteaConfigured,
|
||||
openPullRequestModal,
|
||||
replyGiteaFailure,
|
||||
} from '../../services/gitea/gitea-modals.js';
|
||||
import { baseEmbed, successEmbed } from '../../ui/embeds.js';
|
||||
|
||||
export const access = ACCESS_LEVELS.USER;
|
||||
export const subcommandAccess = { create: ACCESS_LEVELS.DEV };
|
||||
@@ -25,7 +33,47 @@ export const data = new SlashCommandBuilder()
|
||||
)
|
||||
.addSubcommand((sub) => sub.setName('list').setDescription('Lister les pull requests ouvertes'));
|
||||
|
||||
// TODO(M5-T04 / M5-T05): implement with services/gitea/gitea-client.js.
|
||||
/** The title and description are collected through a modal (M5-T04 / M5-T05). */
|
||||
export async function execute(interaction) {
|
||||
await interaction.reply({ embeds: [notImplementedEmbed(`/pr ${interaction.options.getSubcommand()}`)] });
|
||||
const subcommand = interaction.options.getSubcommand();
|
||||
|
||||
if (subcommand === 'create') {
|
||||
await openPullRequestModal(interaction);
|
||||
return;
|
||||
}
|
||||
|
||||
assertGiteaConfigured();
|
||||
await interaction.deferReply();
|
||||
|
||||
try {
|
||||
if (subcommand === 'view') {
|
||||
const pull = await gitea.getPullRequest(interaction.options.getInteger('number', true));
|
||||
if (!pull?.number) throw new UserFacingError('Cette pull request est introuvable sur Gitea.');
|
||||
await interaction.editReply({ embeds: [pullRequestEmbed(pull)] });
|
||||
return;
|
||||
}
|
||||
|
||||
const pulls = asList(await gitea.listPullRequests('state=open&limit=15'));
|
||||
if (pulls.length === 0) {
|
||||
await interaction.editReply({ embeds: [successEmbed('Aucune pull request ouverte.')] });
|
||||
return;
|
||||
}
|
||||
|
||||
const embed = baseEmbed(COLORS.gitea)
|
||||
.setTitle('Pull requests ouvertes')
|
||||
.setURL(`${repositoryUrl()}/pulls`)
|
||||
.setDescription(
|
||||
pulls
|
||||
.map(
|
||||
(pull) =>
|
||||
`**#${pull.number}** ${pull.title} — ${pull.head?.ref ?? '?'} → ${pull.base?.ref ?? '?'} ` +
|
||||
`(*${pull.user?.login ?? 'inconnu'}*)`,
|
||||
)
|
||||
.join('\n'),
|
||||
)
|
||||
.setFooter({ text: `${pulls.length} PR affichée(s)` });
|
||||
await interaction.editReply({ embeds: [embed] });
|
||||
} catch (error) {
|
||||
await replyGiteaFailure(interaction, error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
import { COLORS } from '../../config/constants.js';
|
||||
import { baseEmbed } from '../../ui/embeds.js';
|
||||
|
||||
const DESCRIPTION_MAX = 1500;
|
||||
|
||||
/** Truncates free text coming from the API before it reaches Discord. */
|
||||
export function truncate(text, max = DESCRIPTION_MAX) {
|
||||
const value = String(text ?? '').trim();
|
||||
if (!value) return '';
|
||||
return value.length > max ? `${value.slice(0, max - 1)}…` : value;
|
||||
}
|
||||
|
||||
const authorOf = (source) =>
|
||||
source?.user?.login ?? source?.sender?.login ?? source?.author?.name ?? 'inconnu';
|
||||
|
||||
/** Shared header of an issue, used by `/issue` and the webhooks (M5-T02 / M9-T04). */
|
||||
export function issueEmbed(issue) {
|
||||
const embed = baseEmbed(COLORS.gitea)
|
||||
.setTitle(`#${issue.number} ${issue.title}`)
|
||||
.setDescription(truncate(issue.body) || 'Pas de description.')
|
||||
.addFields(
|
||||
{ name: 'Auteur', value: authorOf(issue), inline: true },
|
||||
{ name: 'État', value: issue.state === 'closed' ? 'Fermée' : 'Ouverte', inline: true },
|
||||
{ name: 'Commentaires', value: String(issue.comments ?? 0), inline: true },
|
||||
);
|
||||
if (issue.html_url) embed.setURL(issue.html_url);
|
||||
|
||||
const labels = (issue.labels ?? []).map((label) => label.name).filter(Boolean);
|
||||
if (labels.length > 0) embed.addFields({ name: 'Labels', value: labels.join(', ') });
|
||||
return embed;
|
||||
}
|
||||
|
||||
/** Shared header of a pull request (M5-T04 / M9-T05). */
|
||||
export function pullRequestEmbed(pull) {
|
||||
const state = pull.merged ? 'Fusionnée' : pull.state === 'closed' ? 'Fermée' : 'Ouverte';
|
||||
const embed = baseEmbed(COLORS.gitea)
|
||||
.setTitle(`PR #${pull.number} ${pull.title}`)
|
||||
.setDescription(truncate(pull.body) || 'Pas de description.')
|
||||
.addFields(
|
||||
{ name: 'Auteur', value: authorOf(pull), inline: true },
|
||||
{ name: 'État', value: state, inline: true },
|
||||
{ name: 'Branches', value: `${pull.head?.ref ?? '?'} → ${pull.base?.ref ?? '?'}`, inline: true },
|
||||
);
|
||||
if (pull.html_url) embed.setURL(pull.html_url);
|
||||
return embed;
|
||||
}
|
||||
|
||||
/** Release notes, shared by `/fws version`, `/fws changelog` and the webhooks. */
|
||||
export function releaseEmbed(release, { withNotes = true } = {}) {
|
||||
const embed = baseEmbed(COLORS.gitea)
|
||||
.setTitle(`${release.name || release.tag_name}`)
|
||||
.addFields(
|
||||
{ name: 'Tag', value: release.tag_name ?? 'inconnu', inline: true },
|
||||
{ name: 'Publiée par', value: authorOf(release), inline: true },
|
||||
{ name: 'Pré-version', value: release.prerelease ? 'Oui' : 'Non', inline: true },
|
||||
);
|
||||
if (release.html_url) embed.setURL(release.html_url);
|
||||
if (release.published_at) {
|
||||
const timestamp = Math.floor(new Date(release.published_at).getTime() / 1000);
|
||||
embed.addFields({ name: 'Date', value: `<t:${timestamp}:f>`, inline: true });
|
||||
}
|
||||
if (withNotes && release.body) embed.setDescription(truncate(release.body, 3900));
|
||||
return embed;
|
||||
}
|
||||
|
||||
/** Push notification: the last commits of a branch (M9-T06). */
|
||||
export function pushEmbed(payload, maxCommits = 5) {
|
||||
const commits = payload.commits ?? [];
|
||||
const branch = (payload.ref ?? '').replace('refs/heads/', '');
|
||||
const lines = commits
|
||||
.slice(0, maxCommits)
|
||||
.map((commit) => `\`${String(commit.id).slice(0, 7)}\` ${truncate(commit.message?.split('\n')[0], 90)}`);
|
||||
const remaining = commits.length - lines.length;
|
||||
|
||||
const embed = baseEmbed(COLORS.gitea)
|
||||
.setTitle(`Push sur ${branch || 'le dépôt'}`)
|
||||
.setDescription(lines.join('\n') || 'Aucun commit dans cet événement.')
|
||||
.addFields(
|
||||
{ name: 'Auteur', value: authorOf(payload), inline: true },
|
||||
{ name: 'Commits', value: String(commits.length), inline: true },
|
||||
);
|
||||
if (remaining > 0) embed.addFields({ name: 'Et', value: `${remaining} autre(s) commit(s)` });
|
||||
if (payload.repository?.html_url) embed.setURL(payload.repository.html_url);
|
||||
return embed;
|
||||
}
|
||||
|
||||
/** Git references created or deleted (`create` / `delete` events). */
|
||||
export function refEmbed(payload, action) {
|
||||
const ref = payload.ref ?? 'inconnu';
|
||||
const refType = payload.ref_type ?? 'ref';
|
||||
const embed = baseEmbed(COLORS.gitea)
|
||||
.setTitle(`${action === 'deleted' ? 'Suppression' : 'Création'} de ${refType} : ${ref}`)
|
||||
.setDescription(`${authorOf(payload)} a ${action === 'deleted' ? 'supprimé' : 'créé'} \`${ref}\`.`);
|
||||
if (payload.repository?.html_url) embed.setURL(payload.repository.html_url);
|
||||
return embed;
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
import { ActionRowBuilder, MessageFlags, ModalBuilder, TextInputBuilder, TextInputStyle } from 'discord.js';
|
||||
import { ExternalApiError, UserFacingError } from '../../core/errors.js';
|
||||
import { createLogger } from '../../core/logger.js';
|
||||
import { logEvent } from '../../database/repositories/event-log-repository.js';
|
||||
import { linkButtons } from '../../ui/buttons.js';
|
||||
import { errorEmbed } from '../../ui/embeds.js';
|
||||
import { issueEmbed, pullRequestEmbed } from './gitea-embeds.js';
|
||||
import { gitea, isGiteaConfigured } from './gitea-client.js';
|
||||
import { consume, remember } from './pending-actions.js';
|
||||
|
||||
const log = createLogger('gitea');
|
||||
|
||||
const PR_CONTEXT_TTL_MS = 10 * 60_000;
|
||||
|
||||
/** Fails fast with an actionable message when Gitea is not configured (M5-T01). */
|
||||
export function assertGiteaConfigured() {
|
||||
if (!isGiteaConfigured()) {
|
||||
throw new UserFacingError('Gitea n’est pas configuré : renseigne `GITEA_URL` et `GITEA_TOKEN`.');
|
||||
}
|
||||
}
|
||||
|
||||
function modal(id, title, fields) {
|
||||
return new ModalBuilder()
|
||||
.setCustomId(id)
|
||||
.setTitle(title)
|
||||
.addComponents(
|
||||
fields.map((field) =>
|
||||
new ActionRowBuilder().addComponents(
|
||||
new TextInputBuilder()
|
||||
.setCustomId(field.id)
|
||||
.setLabel(field.label)
|
||||
.setStyle(field.paragraph ? TextInputStyle.Paragraph : TextInputStyle.Short)
|
||||
.setMaxLength(field.maxLength)
|
||||
.setRequired(field.required ?? true),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/** `/issue create` collects the title and description through a modal (M5-T03). */
|
||||
export async function openIssueModal(interaction) {
|
||||
assertGiteaConfigured();
|
||||
await interaction.showModal(
|
||||
modal('issue:create', 'Nouvelle issue Gitea', [
|
||||
{ id: 'title', label: 'Titre', maxLength: 200 },
|
||||
{ id: 'body', label: 'Description', paragraph: true, maxLength: 4000 },
|
||||
]),
|
||||
);
|
||||
}
|
||||
|
||||
/** `/pr create` keeps the branch options and asks for the title through a modal. */
|
||||
export async function openPullRequestModal(interaction) {
|
||||
assertGiteaConfigured();
|
||||
const head = interaction.options.getString('head', true);
|
||||
const base = interaction.options.getString('base', true);
|
||||
|
||||
remember(`pr:${interaction.user.id}`, { head, base }, { ttlMs: PR_CONTEXT_TTL_MS });
|
||||
await interaction.showModal(
|
||||
modal('pr:create', 'Nouvelle pull request', [
|
||||
{ id: 'title', label: `Titre (${head} → ${base})`, maxLength: 200 },
|
||||
{ id: 'body', label: 'Description', paragraph: true, maxLength: 4000, required: false },
|
||||
]),
|
||||
);
|
||||
}
|
||||
|
||||
/** Turns an API failure into a message the user can act on (M5-T08). */
|
||||
export async function replyGiteaFailure(interaction, error) {
|
||||
log.error('Gitea request failed', error);
|
||||
const detail =
|
||||
error instanceof ExternalApiError && /not configured/.test(error.message)
|
||||
? 'Gitea n’est pas configuré.'
|
||||
: 'Gitea est momentanément indisponible. Réessaie dans quelques instants.';
|
||||
const payload = { embeds: [errorEmbed(detail)], flags: MessageFlags.Ephemeral };
|
||||
|
||||
if (interaction.deferred || interaction.replied) {
|
||||
await interaction.followUp(payload).catch(() => {});
|
||||
} else {
|
||||
await interaction.reply(payload).catch(() => {});
|
||||
}
|
||||
}
|
||||
|
||||
export async function submitIssueModal(interaction) {
|
||||
assertGiteaConfigured();
|
||||
await interaction.deferReply();
|
||||
|
||||
try {
|
||||
const issue = await gitea.createIssue({
|
||||
title: interaction.fields.getTextInputValue('title'),
|
||||
body: `${interaction.fields.getTextInputValue('body')}\n\n_Créée depuis Discord par ${interaction.user.tag}._`,
|
||||
});
|
||||
logEvent({
|
||||
guildId: interaction.guildId,
|
||||
type: 'gitea.issue.created',
|
||||
actorId: interaction.user.id,
|
||||
payload: { number: issue.number },
|
||||
});
|
||||
await interaction.editReply({
|
||||
embeds: [issueEmbed(issue)],
|
||||
components: linkButtons([{ label: 'Ouvrir sur Gitea', url: issue.html_url }]),
|
||||
});
|
||||
} catch (error) {
|
||||
await replyGiteaFailure(interaction, error);
|
||||
}
|
||||
}
|
||||
|
||||
export async function submitPullRequestModal(interaction) {
|
||||
assertGiteaConfigured();
|
||||
const context = consume(`pr:${interaction.user.id}`);
|
||||
if (!context) {
|
||||
throw new UserFacingError('Session expirée : relance `/pr create` pour choisir à nouveau les branches.');
|
||||
}
|
||||
|
||||
await interaction.deferReply();
|
||||
try {
|
||||
const pull = await gitea.createPullRequest({
|
||||
title: interaction.fields.getTextInputValue('title'),
|
||||
body: `${interaction.fields.getTextInputValue('body')}\n\n_Créée depuis Discord par ${interaction.user.tag}._`.trim(),
|
||||
head: context.head,
|
||||
base: context.base,
|
||||
});
|
||||
logEvent({
|
||||
guildId: interaction.guildId,
|
||||
type: 'gitea.pull_request.created',
|
||||
actorId: interaction.user.id,
|
||||
payload: { number: pull.number, head: context.head, base: context.base },
|
||||
});
|
||||
await interaction.editReply({
|
||||
embeds: [pullRequestEmbed(pull)],
|
||||
components: linkButtons([{ label: 'Ouvrir sur Gitea', url: pull.html_url }]),
|
||||
});
|
||||
} catch (error) {
|
||||
await replyGiteaFailure(interaction, error);
|
||||
}
|
||||
}
|
||||
|
||||
/** Routes the modal submissions opened by `/issue` and `/pr` (M5-T09). */
|
||||
export async function handleGiteaModal(interaction) {
|
||||
switch (interaction.customId) {
|
||||
case 'issue:create':
|
||||
await submitIssueModal(interaction);
|
||||
return;
|
||||
case 'pr:create':
|
||||
await submitPullRequestModal(interaction);
|
||||
return;
|
||||
default:
|
||||
log.debug(`Ignored unknown modal ${interaction.customId}`);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
/**
|
||||
* In-memory store for the short-lived context of a modal flow, e.g. the branches
|
||||
* of `/pr create` which are typed as options but sent with the modal (M5-T04).
|
||||
* Entries expire on their own and disappear on restart.
|
||||
*/
|
||||
const DEFAULT_TTL_MS = 5 * 60_000;
|
||||
|
||||
const entries = new Map();
|
||||
|
||||
export function remember(key, value, { ttlMs = DEFAULT_TTL_MS, now = Date.now() } = {}) {
|
||||
entries.set(key, { value, expiresAt: now + ttlMs });
|
||||
return value;
|
||||
}
|
||||
|
||||
/** Returns the stored value and forgets it, or null when missing or expired. */
|
||||
export function consume(key, { now = Date.now() } = {}) {
|
||||
const entry = entries.get(key);
|
||||
if (!entry) return null;
|
||||
entries.delete(key);
|
||||
return entry.expiresAt > now ? entry.value : null;
|
||||
}
|
||||
|
||||
export function purgeExpired(now = Date.now()) {
|
||||
for (const [key, entry] of entries) {
|
||||
if (entry.expiresAt <= now) entries.delete(key);
|
||||
}
|
||||
return entries.size;
|
||||
}
|
||||
|
||||
export function pendingCount() {
|
||||
return entries.size;
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { describe, it } from 'node:test';
|
||||
import { consume, pendingCount, purgeExpired, remember } from '../src/services/gitea/pending-actions.js';
|
||||
|
||||
describe('pending actions', () => {
|
||||
it('returns a stored value exactly once', () => {
|
||||
remember('pr:1', { head: 'feature', base: 'main' });
|
||||
assert.deepEqual(consume('pr:1'), { head: 'feature', base: 'main' });
|
||||
assert.equal(consume('pr:1'), null);
|
||||
});
|
||||
|
||||
it('returns null for an unknown key', () => {
|
||||
assert.equal(consume('pr:unknown'), null);
|
||||
});
|
||||
|
||||
it('drops an expired entry', () => {
|
||||
const start = 1_000;
|
||||
remember('pr:2', 'value', { ttlMs: 500, now: start });
|
||||
assert.equal(consume('pr:2', { now: start + 501 }), null);
|
||||
});
|
||||
|
||||
it('keeps a value still within its window', () => {
|
||||
remember('pr:3', 'value', { ttlMs: 500, now: 0 });
|
||||
assert.equal(consume('pr:3', { now: 499 }), 'value');
|
||||
});
|
||||
|
||||
it('purges expired entries without touching fresh ones', () => {
|
||||
remember('pr:4', 'old', { ttlMs: 10, now: 0 });
|
||||
remember('pr:5', 'fresh', { ttlMs: 10_000, now: 0 });
|
||||
assert.equal(purgeExpired(100), 1);
|
||||
assert.equal(pendingCount(), 1);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user