Releases from git tags and WHATS-NEW.md; docs, changelog (1.4.0)
The Hub reads the Cross Events repo's v* tags (each a release, the newest the latest version) and the client notes from WHATS-NEW.md as of the newest tag, every 15 minutes and on Sync now. Urgent/security in a version heading marks it urgent. Repo address, notes path and an optional encrypted token on the Releases page; manual releases only when no repo is set. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,149 @@
|
||||
/**
|
||||
* Releases from git (Gitea): every v1.2.3 tag of the Cross Events repo is a release, dated by its
|
||||
* commit, and the notes come from the repo's WHATS-NEW.md as of the newest tag ("## 1.2.3" sections;
|
||||
* "urgent" or "security" in the heading marks an urgent release). Runs every 15 minutes and from
|
||||
* "Sync now" on the Releases page, when a repo is set; git is then the only source of releases.
|
||||
*/
|
||||
|
||||
const prisma = require('../config/db');
|
||||
const { compareVersions } = require('./alerts');
|
||||
const { getSettings, setSettings, releaseRepoToken } = require('./settings');
|
||||
const { syncLatestVersion } = require('./releases');
|
||||
|
||||
const TIMEOUT_MS = 20000;
|
||||
const TAG_RE = /^v?(\d+\.\d+\.\d+)$/;
|
||||
|
||||
/** https://git.example.com/owner/repo(.git) → { api, owner, repo }, or null. */
|
||||
function parseRepoUrl(url) {
|
||||
try {
|
||||
const u = new URL(String(url || '').trim());
|
||||
if (!/^https?:$/.test(u.protocol)) return null;
|
||||
const [owner, repo] = u.pathname.replace(/\/+$/, '').replace(/\.git$/, '').split('/').filter(Boolean);
|
||||
if (!owner || !repo) return null;
|
||||
return { api: `${u.origin}/api/v1/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}`, owner, repo };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Markdown to the plain notes installs show: list lines stay "- ", the rest loses its markup. */
|
||||
function plainNotes(lines) {
|
||||
const out = [];
|
||||
for (const raw of lines) {
|
||||
let line = raw.replace(/\s+$/, '');
|
||||
if (!line.trim()) { out.push(''); continue; }
|
||||
const indent = /^\s{2,}[-*]\s/.test(line);
|
||||
line = line.trim()
|
||||
.replace(/^#{1,6}\s+/, '')
|
||||
.replace(/^[*+]\s+/, '- ')
|
||||
.replace(/\*\*(.+?)\*\*/g, '$1')
|
||||
.replace(/__(.+?)__/g, '$1')
|
||||
.replace(/`([^`]+)`/g, '$1')
|
||||
.replace(/\[([^\]]+)\]\([^)]+\)/g, '$1');
|
||||
// A wrapped line continues the line above: an indented one after a list item, any one in a paragraph.
|
||||
const prev = out[out.length - 1];
|
||||
const continues = prev && !line.startsWith('- ') && !indent && (prev.startsWith('- ') ? /^\s/.test(raw) : true);
|
||||
if (continues) out[out.length - 1] = `${prev} ${line}`;
|
||||
else out.push(line);
|
||||
}
|
||||
return out.join('\n').replace(/\n{3,}/g, '\n\n').trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* The sections of WHATS-NEW.md: { "1.46.2": { notes, urgent } }. A section is a "## 1.46.2" heading
|
||||
* (optionally "[1.46.2]", "v1.46.2", a date or "— urgent" after it) up to the next "## ".
|
||||
*/
|
||||
function parseNotes(markdown) {
|
||||
const text = String(markdown || '').replace(/<!--[\s\S]*?-->/g, '');
|
||||
const sections = {};
|
||||
let current = null;
|
||||
for (const line of text.split(/\r?\n/)) {
|
||||
const heading = /^##\s+(.*)$/.exec(line);
|
||||
if (heading) {
|
||||
const v = /\[?v?(\d+\.\d+\.\d+)\]?/.exec(heading[1]);
|
||||
current = v ? { version: v[1], urgent: /\b(urgent|security)\b/i.test(heading[1]), lines: [] } : null;
|
||||
if (current) sections[current.version] = current;
|
||||
continue;
|
||||
}
|
||||
if (/^#\s/.test(line)) { current = null; continue; }
|
||||
if (current) current.lines.push(line);
|
||||
}
|
||||
return Object.fromEntries(Object.values(sections).map(s => [s.version, { notes: plainNotes(s.lines), urgent: s.urgent }]));
|
||||
}
|
||||
|
||||
async function get(url, token, { raw = false } = {}) {
|
||||
let res;
|
||||
try {
|
||||
res = await fetch(url, { headers: token ? { Authorization: `token ${token}` } : {}, signal: AbortSignal.timeout(TIMEOUT_MS) });
|
||||
} catch (e) {
|
||||
throw new Error(`Git could not be reached: ${e?.message || e}`);
|
||||
}
|
||||
if (res.status === 404) return null;
|
||||
if (res.status === 401 || res.status === 403) throw new Error('Git refused access — check the access token (or that the repository is public).');
|
||||
if (!res.ok) throw new Error(`Git answered ${res.status} for ${url}`);
|
||||
return raw ? res.text() : res.json();
|
||||
}
|
||||
|
||||
/** Every v1.2.3 tag: [{ version, date }]. */
|
||||
async function fetchTags(repo, token) {
|
||||
const tags = [];
|
||||
for (let page = 1; page <= 20; page++) {
|
||||
const batch = await get(`${repo.api}/tags?limit=50&page=${page}`, token);
|
||||
if (batch === null) throw new Error('The repository was not found. Check its address (and the token if it is private).');
|
||||
for (const t of batch) {
|
||||
const m = TAG_RE.exec(t.name || '');
|
||||
if (m) tags.push({ version: m[1], date: t.commit?.created || null });
|
||||
}
|
||||
if (batch.length < 50) break;
|
||||
}
|
||||
return tags;
|
||||
}
|
||||
|
||||
/**
|
||||
* Bring the releases in line with git: add new tags, update notes and urgency from WHATS-NEW.md, and
|
||||
* remove releases that have no tag. Returns { tags, added, updated, removed, latest }.
|
||||
*/
|
||||
async function syncReleases() {
|
||||
const settings = await getSettings();
|
||||
const repo = parseRepoUrl(settings.release_repo_url);
|
||||
if (!repo) return { skipped: 'no repository set' };
|
||||
try {
|
||||
const token = await releaseRepoToken();
|
||||
const tags = await fetchTags(repo, token);
|
||||
if (!tags.length) throw new Error('The repository has no version tags (v1.2.3) yet.');
|
||||
const newest = tags.reduce((a, b) => (compareVersions(b.version, a.version) > 0 ? b : a));
|
||||
const path = (settings.release_notes_path || 'WHATS-NEW.md').replace(/^\/+/, '').split('/').map(encodeURIComponent).join('/');
|
||||
const markdown = await get(`${repo.api}/raw/${path}?ref=v${newest.version}`, token, { raw: true });
|
||||
const notes = parseNotes(markdown || '');
|
||||
|
||||
const existing = new Map((await prisma.release.findMany()).map(r => [r.version, r]));
|
||||
const tagged = new Set(tags.map(t => t.version));
|
||||
let added = 0;
|
||||
let updated = 0;
|
||||
for (const tag of tags) {
|
||||
const n = notes[tag.version] || { notes: '', urgent: false };
|
||||
const had = existing.get(tag.version);
|
||||
if (!had) {
|
||||
await prisma.release.create({ data: { version: tag.version, notes: n.notes, urgent: n.urgent, releasedAt: tag.date ? new Date(tag.date) : new Date() } });
|
||||
added++;
|
||||
} else {
|
||||
// Releases added by hand (or from the old latest_version setting) take the tag's date.
|
||||
const date = tag.date ? new Date(tag.date) : had.releasedAt;
|
||||
if (had.notes !== n.notes || had.urgent !== n.urgent || date.getTime() !== new Date(had.releasedAt).getTime()) {
|
||||
await prisma.release.update({ where: { id: had.id }, data: { notes: n.notes, urgent: n.urgent, releasedAt: date } });
|
||||
updated++;
|
||||
}
|
||||
}
|
||||
}
|
||||
const gone = [...existing.values()].filter(r => !tagged.has(r.version)).map(r => r.id);
|
||||
if (gone.length) await prisma.release.deleteMany({ where: { id: { in: gone } } });
|
||||
const latest = await syncLatestVersion();
|
||||
await setSettings({ release_synced_at: new Date().toISOString(), release_sync_error: markdown === null ? `${settings.release_notes_path} was not found at v${newest.version}, so there are no notes.` : '' });
|
||||
return { tags: tags.length, added, updated, removed: gone.length, latest };
|
||||
} catch (e) {
|
||||
await setSettings({ release_sync_error: `${new Date().toISOString()} ${e.message}`.slice(0, 500) });
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { parseRepoUrl, parseNotes, plainNotes, syncReleases };
|
||||
@@ -17,29 +17,45 @@ const DEFAULTS = {
|
||||
smtp_user: '',
|
||||
smtp_pass: '',
|
||||
smtp_from: '',
|
||||
// Releases and their notes are read from git (utils/releaseSync.js) when a repo is set.
|
||||
release_repo_url: 'https://c-git.crosscode.co.za/joshua/hope-events',
|
||||
release_notes_path: 'WHATS-NEW.md',
|
||||
release_repo_token: '',
|
||||
// Written by the sync, not the Settings page.
|
||||
release_synced_at: '',
|
||||
release_sync_error: '',
|
||||
};
|
||||
|
||||
// Stored encrypted and never sent to the browser: only "is one saved" (<key>_set).
|
||||
const SECRETS = ['smtp_pass', 'release_repo_token'];
|
||||
|
||||
async function rawSettings() {
|
||||
const rows = await prisma.setting.findMany();
|
||||
const saved = Object.fromEntries(rows.map(r => [r.key, r.value]));
|
||||
return { ...DEFAULTS, ...saved };
|
||||
}
|
||||
|
||||
/** Settings for the Settings page: the SMTP password only as "is one saved". */
|
||||
/** Settings for the Settings page: secrets (SMTP password, repo token) only as "is one saved". */
|
||||
async function getSettings() {
|
||||
const { smtp_pass, ...settings } = await rawSettings();
|
||||
return { ...settings, smtp_pass_set: smtp_pass ? 'true' : '' };
|
||||
const settings = await rawSettings();
|
||||
for (const key of SECRETS) {
|
||||
settings[`${key}_set`] = settings[key] ? 'true' : '';
|
||||
delete settings[key];
|
||||
}
|
||||
return settings;
|
||||
}
|
||||
|
||||
/**
|
||||
* Save settings. A blank smtp_pass keeps the saved password (the page never has it);
|
||||
* smtp_pass_clear removes it.
|
||||
* Save settings. A blank secret keeps the saved one (the page never has it); <key>_clear
|
||||
* removes it.
|
||||
*/
|
||||
async function setSettings(values) {
|
||||
const input = { ...(values || {}) };
|
||||
if (input.smtp_pass_clear) input.smtp_pass = '';
|
||||
else if (input.smtp_pass) input.smtp_pass = encrypt(input.smtp_pass);
|
||||
else delete input.smtp_pass;
|
||||
for (const key of SECRETS) {
|
||||
if (input[`${key}_clear`]) input[key] = '';
|
||||
else if (input[key]) input[key] = encrypt(input[key]);
|
||||
else delete input[key];
|
||||
}
|
||||
const updates = Object.entries(input).filter(([k]) => k in DEFAULTS);
|
||||
for (const [key, value] of updates) {
|
||||
await prisma.setting.upsert({ where: { key }, update: { value: String(value ?? '') }, create: { key, value: String(value ?? '') } });
|
||||
@@ -83,4 +99,10 @@ async function importSmtpFromEnv() {
|
||||
return true;
|
||||
}
|
||||
|
||||
module.exports = { DEFAULTS, getSettings, setSettings, smtpSettings, importSmtpFromEnv };
|
||||
/** The saved repo token, decrypted ('' when none). */
|
||||
async function releaseRepoToken() {
|
||||
const { release_repo_token } = await rawSettings();
|
||||
return release_repo_token ? decrypt(release_repo_token) : '';
|
||||
}
|
||||
|
||||
module.exports = { DEFAULTS, getSettings, setSettings, smtpSettings, importSmtpFromEnv, releaseRepoToken };
|
||||
|
||||
Reference in New Issue
Block a user