Files
client/scripts/publish-release.mjs
T

74 lines
2.9 KiB
JavaScript

// Publishes a Gitea release for the current tag: creates a DRAFT, uploads every asset, then publishes.
// Any failed request aborts and deletes the draft, so a partial release is never visible.
// The token is read only from the environment (TOKEN) and never printed or passed as an argument.
//
// TOKEN=… API=https://host/api/v1/repos/owner/repo TAG=v0.1.0 node scripts/publish-release.mjs <asset-dir> [notes-file]
import { readdirSync, readFileSync, statSync } from 'node:fs';
import path from 'node:path';
const { TOKEN, API, TAG } = process.env;
const assetDir = process.argv[2];
const notesFile = process.argv[3];
for (const [name, value] of Object.entries({ TOKEN, API, TAG, assetDir })) {
if (!value) {
console.error(`missing ${name}`);
process.exit(2);
}
}
function collect(dir) {
const files = [];
for (const entry of readdirSync(dir)) {
const full = path.join(dir, entry);
if (statSync(full).isDirectory()) files.push(...collect(full));
else files.push(full);
}
return files;
}
async function request(method, url, body, headers = {}) {
const res = await fetch(url, { method, headers: { Authorization: `token ${TOKEN}`, ...headers }, body });
const text = await res.text();
if (!res.ok) throw new Error(`${method} ${url.replace(API, '')} → HTTP ${res.status}: ${text.slice(0, 300)}`);
return text ? JSON.parse(text) : null;
}
const files = collect(assetDir);
if (files.length === 0) {
console.error(`no assets in ${assetDir}`);
process.exit(1);
}
const names = new Set();
for (const f of files) {
const n = path.basename(f);
if (names.has(n)) {
console.error(`duplicate asset name ${n}`);
process.exit(1);
}
names.add(n);
}
const body = notesFile ? readFileSync(notesFile, 'utf8') : '';
let release = null;
try {
release = await request('POST', `${API}/releases`, JSON.stringify({ tag_name: TAG, name: `TeamsPeach ${TAG}`, body, draft: true, prerelease: true }), { 'Content-Type': 'application/json' });
console.log(`draft release ${release.id} created for ${TAG}`);
for (const file of files) {
const form = new FormData();
form.append('attachment', new Blob([readFileSync(file)]), path.basename(file));
const asset = await request('POST', `${API}/releases/${release.id}/assets?name=${encodeURIComponent(path.basename(file))}`, form);
console.log(`uploaded ${asset.name} (${asset.size} bytes)`);
}
await request('PATCH', `${API}/releases/${release.id}`, JSON.stringify({ draft: false }), { 'Content-Type': 'application/json' });
console.log(`release ${TAG} published with ${files.length} assets`);
} catch (err) {
console.error(`release failed: ${err.message}`);
if (release) {
await request('DELETE', `${API}/releases/${release.id}`).then(
() => console.error(`draft ${release.id} deleted`),
(e) => console.error(`could not delete draft ${release.id}: ${e.message}`),
);
}
process.exit(1);
}