ci: Gitea Actions, release con il solo zip del sito e documentazione senza Forgejo
Il progetto vive in modo definitivo su Gitea: i workflow passano da .forgejo/ a .gitea/workflows/ e la documentazione non nomina più la piattaforma precedente. - ci.yml: i controlli di npm run verify sono passi separati (si vede subito quale è fallito) e alla fine la CI crea lo zip di rilascio e ne verifica il contenuto, così un errore di pacchetto emerge prima del tag. Runner ubuntu-latest, azioni da github.com con URL completo, upload-artifact@v3 (la v4 non funziona su Gitea). - release.yml: a ogni tag vX.Y.Z verifica tutto, crea lo zip e lo pubblica nella Release con scripts/release-upload.sh e l'API di Gitea, senza action esterne di release. - La release contiene un solo file, sito-studio-grasso-vX.Y.Z.zip (contenuto di dist/ alla radice, .htaccess compreso): tolti tar.gz, SHA256SUMS.txt e BUILD-INFO.txt da package.mjs, check-package.mjs e dalla documentazione. - release-upload.sh: variabili GITEA_*, si ferma su errori diversi da 404 invece di provare a creare la release, rifiuta una cartella vuota; provato su una finta API Gitea. - deploy/gitea-deploy.yml.example convertito per Gitea (resta disattivato). - Versione 1.0.1 pronta (package.json, CHANGELOG, D-056 e D-057 in DECISIONS.md); il tag v1.0.1 non è stato creato. Verifica: npm run verify completo (lint, formato, tipi, build, HTML, link, e2e 39, a11y 51, conformità 1455, Lighthouse) e npm run package eseguiti in una copia fuori da .claude/. I workflow non sono ancora stati eseguiti su un runner Gitea. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
083489ac8b
commit
31ac5b7f68
20 files changed
+645
-657
No files matched your search
@@ -1,21 +1,13 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Stampa la sezione di CHANGELOG.md relativa a una versione: diventa il testo della release.
|
||||
* Uso: `node scripts/changelog-notes.mjs v1.0.0 [--shell-safe]` (oppure 1.0.0). Esce con
|
||||
* Uso: `node scripts/changelog-notes.mjs v1.0.0` (oppure 1.0.0). Esce con
|
||||
* codice 1 se la sezione non esiste, così non si pubblica una release senza note.
|
||||
*
|
||||
* `--shell-safe` (usato da release.yml): niente caratteri che una shell interpreterebbe se
|
||||
* l'action li inserisse tra virgolette doppie: `codice` → «codice», " → ”, \ → /, $ → $.
|
||||
*/
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { resolve } from 'node:path';
|
||||
|
||||
const args = process.argv.slice(2);
|
||||
const shellSafe = args.includes('--shell-safe');
|
||||
const arg = (args.find((a) => !a.startsWith('--')) ?? process.env.RELEASE_VERSION ?? '').replace(
|
||||
/^refs\/tags\//,
|
||||
'',
|
||||
);
|
||||
const arg = (process.argv[2] ?? process.env.RELEASE_VERSION ?? '').replace(/^refs\/tags\//, '');
|
||||
const version = arg.replace(/^v/, '');
|
||||
if (!/^\d+\.\d+\.\d+/.test(version)) {
|
||||
console.error('Uso: node scripts/changelog-notes.mjs vX.Y.Z');
|
||||
@@ -44,11 +36,4 @@ if (!body) {
|
||||
console.error(`La sezione ${version} di CHANGELOG.md è vuota.`);
|
||||
process.exit(1);
|
||||
}
|
||||
const safe = (text) =>
|
||||
text
|
||||
.replace(/`([^`\n]*)`/g, '«$1»')
|
||||
.replace(/`/g, '')
|
||||
.replace(/"/g, '”')
|
||||
.replace(/\\/g, '/')
|
||||
.replace(/\$/g, '$');
|
||||
process.stdout.write(`${shellSafe ? safe(body) : body}\n`);
|
||||
process.stdout.write(`${body}\n`);
|
||||
+16
-96
@@ -1,17 +1,15 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Integrità del pacchetto di rilascio (brief §11.7), da eseguire dopo scripts/package.mjs:
|
||||
* Integrità del pacchetto di rilascio, da eseguire dopo scripts/package.mjs:
|
||||
*
|
||||
* - in release/ ci sono solo zip, tar.gz, SHA256SUMS.txt e BUILD-INFO.txt, con i nomi attesi;
|
||||
* - le impronte di SHA256SUMS.txt sono corrette (anche con `sha256sum -c`, se disponibile);
|
||||
* - zip e tar.gz, estratti in una cartella temporanea, contengono esattamente i file di dist/
|
||||
* (stessi percorsi, dimensioni e contenuto), alla radice, con .htaccess e tutte le pagine;
|
||||
* - lo zip non supera 5 MB; BUILD-INFO.txt riporta versione, commit e data.
|
||||
* - in release/ c'è solo lo zip, con il nome atteso (nessun altro file);
|
||||
* - lo zip, aperto con un lettore minimale (CRC e dimensioni compresi), contiene esattamente
|
||||
* i file di dist/ (stessi percorsi, dimensioni e contenuto), alla radice, con .htaccess e
|
||||
* tutte le pagine del sitemap;
|
||||
* - lo zip non supera 5 MB.
|
||||
*/
|
||||
import { execFileSync, spawnSync } from 'node:child_process';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { existsSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { crc32, inflateRawSync } from 'node:zlib';
|
||||
import { readSitemapPaths } from './lib/pages.mjs';
|
||||
@@ -63,32 +61,6 @@ function readZip(file) {
|
||||
return entries;
|
||||
}
|
||||
|
||||
/**
|
||||
* Estrazione del tar.gz con `tar` di sistema in una cartella temporanea. L'archivio arriva da
|
||||
* stdin: su Windows il GNU tar di Git Bash interpreta «C:\…» come host remoto.
|
||||
*/
|
||||
function readTarGz(file) {
|
||||
const dir = mkdtempSync(join(tmpdir(), 'sito-studio-grasso-'));
|
||||
try {
|
||||
execFileSync('tar', ['-xzf', '-'], { cwd: dir, input: readFileSync(file) });
|
||||
const entries = new Map();
|
||||
for (const rel of listAll(dir)) entries.set(rel, readFileSync(join(dir, rel)));
|
||||
return entries;
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
function listAll(dir, base = '') {
|
||||
const out = [];
|
||||
for (const e of readdirSync(join(dir, base), { withFileTypes: true })) {
|
||||
const rel = base ? `${base}/${e.name}` : e.name;
|
||||
if (e.isDirectory()) out.push(...listAll(dir, rel));
|
||||
else out.push(rel);
|
||||
}
|
||||
return out.sort();
|
||||
}
|
||||
|
||||
function compareWithDist(label, entries, expected) {
|
||||
const names = [...entries.keys()].sort();
|
||||
const missing = expected.filter((f) => !entries.has(f));
|
||||
@@ -130,80 +102,28 @@ try {
|
||||
console.error(`✘ ${e.message}`);
|
||||
process.exit(1);
|
||||
}
|
||||
const names = archiveNames(version);
|
||||
const expectedRelease = [names.zip, names.tgz, 'SHA256SUMS.txt', 'BUILD-INFO.txt'].sort();
|
||||
const { zip } = archiveNames(version);
|
||||
|
||||
if (!existsSync(releaseDir)) {
|
||||
console.error('✘ release/ assente: eseguire `npm run package`.');
|
||||
process.exit(1);
|
||||
}
|
||||
const present = readdirSync(releaseDir).sort();
|
||||
for (const f of expectedRelease) if (!present.includes(f)) fail(`release/: manca ${f}`);
|
||||
const present = readdirSync(releaseDir);
|
||||
if (!present.includes(zip)) fail(`release/: manca ${zip}`);
|
||||
for (const f of present)
|
||||
if (!expectedRelease.includes(f))
|
||||
fail(`release/: file inatteso ${f} (la cartella deve contenere solo il pacchetto)`);
|
||||
if (f !== zip) fail(`release/: file inatteso ${f} (la cartella deve contenere solo lo zip)`);
|
||||
|
||||
// impronte
|
||||
const sumsFile = join(releaseDir, 'SHA256SUMS.txt');
|
||||
if (existsSync(sumsFile)) {
|
||||
const lines = readFileSync(sumsFile, 'utf8').trim().split('\n');
|
||||
const listed = new Set();
|
||||
for (const line of lines) {
|
||||
const m = line.match(/^([0-9a-f]{64}) {2}(.+)$/);
|
||||
if (!m) {
|
||||
fail(`SHA256SUMS.txt: riga non valida «${line}»`);
|
||||
continue;
|
||||
}
|
||||
listed.add(m[2]);
|
||||
const target = join(releaseDir, m[2]);
|
||||
if (!existsSync(target)) fail(`SHA256SUMS.txt: il file ${m[2]} non esiste`);
|
||||
else if (sha256(readFileSync(target)) !== m[1])
|
||||
fail(`SHA256SUMS.txt: impronta errata per ${m[2]}`);
|
||||
}
|
||||
for (const f of [names.zip, names.tgz]) if (!listed.has(f)) fail(`SHA256SUMS.txt: manca ${f}`);
|
||||
const tool = spawnSync('sha256sum', ['-c', 'SHA256SUMS.txt'], {
|
||||
cwd: releaseDir,
|
||||
encoding: 'utf8',
|
||||
});
|
||||
if (tool.error)
|
||||
console.log(' (sha256sum non disponibile: impronte verificate solo con Node.js)');
|
||||
else if (tool.status !== 0) fail(`sha256sum -c non superato:\n${tool.stdout}${tool.stderr}`);
|
||||
else console.log(` sha256sum -c: ${tool.stdout.trim().split('\n').join(' · ')}`);
|
||||
}
|
||||
|
||||
// contenuto degli archivi
|
||||
const expected = listFiles(distDir);
|
||||
const zipPath = join(releaseDir, names.zip);
|
||||
const tgzPath = join(releaseDir, names.tgz);
|
||||
const zipPath = join(releaseDir, zip);
|
||||
if (existsSync(zipPath)) {
|
||||
const size = statSync(zipPath).size;
|
||||
if (size > MAX_ZIP)
|
||||
fail(`${names.zip}: ${(size / 1048576).toFixed(2)} MB oltre il limite di 5 MB`);
|
||||
if (size > MAX_ZIP) fail(`${zip}: ${(size / 1048576).toFixed(2)} MB oltre il limite di 5 MB`);
|
||||
try {
|
||||
compareWithDist(names.zip, readZip(zipPath), expected);
|
||||
compareWithDist(zip, readZip(zipPath), expected);
|
||||
} catch (e) {
|
||||
fail(`${names.zip}: ${e.message}`);
|
||||
fail(`${zip}: ${e.message}`);
|
||||
}
|
||||
}
|
||||
if (existsSync(tgzPath)) {
|
||||
try {
|
||||
compareWithDist(names.tgz, readTarGz(tgzPath), expected);
|
||||
} catch (e) {
|
||||
fail(`${names.tgz}: ${e.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
// BUILD-INFO
|
||||
const infoFile = join(releaseDir, 'BUILD-INFO.txt');
|
||||
if (existsSync(infoFile)) {
|
||||
const info = readFileSync(infoFile, 'utf8');
|
||||
if (!info.includes(`Versione: ${version}`)) fail('BUILD-INFO.txt: manca «Versione»');
|
||||
if (!/^Commit: [0-9a-f]{7,40}$/m.test(info)) fail('BUILD-INFO.txt: manca l’hash del commit');
|
||||
if (!/^Data: \d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/m.test(info))
|
||||
fail('BUILD-INFO.txt: manca la data ISO');
|
||||
if (!/^Node\.js: v\d+/m.test(info) || !/^Astro: \d+/m.test(info))
|
||||
fail('BUILD-INFO.txt: mancano le versioni di Node.js e Astro');
|
||||
}
|
||||
|
||||
if (errors.length) {
|
||||
console.error(`✘ Pacchetto v${version}: ${errors.length} errori`);
|
||||
@@ -212,5 +132,5 @@ if (errors.length) {
|
||||
}
|
||||
const zipKb = (statSync(zipPath).size / 1024).toFixed(1);
|
||||
console.log(
|
||||
`✔ Pacchetto v${version} verificato: ${expected.length} file identici a dist/ in zip (${zipKb} KB) e tar.gz, impronte corrette.`,
|
||||
`✔ Pacchetto v${version} verificato: ${expected.length} file identici a dist/ nello zip (${zipKb} KB), unico file di release/.`,
|
||||
);
|
||||
@@ -33,7 +33,6 @@ export function resolveVersion() {
|
||||
|
||||
export const archiveNames = (version) => ({
|
||||
zip: `${ARCHIVE_PREFIX}-v${version}.zip`,
|
||||
tgz: `${ARCHIVE_PREFIX}-v${version}.tar.gz`,
|
||||
});
|
||||
|
||||
/** Elenco ordinato dei file di una cartella (percorsi relativi con «/»), esclusioni applicate. */
|
||||
|
||||
+25
-84
@@ -1,25 +1,21 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Pacchetto di rilascio (brief §12.4). Da `dist/` crea in `release/`:
|
||||
* Pacchetto di rilascio. Da `dist/` crea in `release/` un solo file:
|
||||
*
|
||||
* sito-studio-grasso-v<versione>.zip per i pannelli di hosting (cPanel, Plesk, …)
|
||||
* sito-studio-grasso-v<versione>.tar.gz per server Linux/SSH, nginx, object storage
|
||||
* SHA256SUMS.txt impronte SHA-256 (verificabili con `sha256sum -c`)
|
||||
* BUILD-INFO.txt versione, commit, data, Node, Astro
|
||||
* sito-studio-grasso-v<versione>.zip da estrarre nella cartella pubblica dell'hosting
|
||||
*
|
||||
* Il contenuto di dist/ è alla radice degli archivi (nessuna cartella di primo livello), con
|
||||
* `.htaccess`. Voci ordinate, date fisse e header gzip senza il sistema operativo: a parità di
|
||||
* dist/ (e di versione di Node.js) gli archivi sono identici anche tra Windows, macOS e Linux.
|
||||
* Il contenuto di dist/ è alla radice dello zip (nessuna cartella di primo livello), con
|
||||
* `.htaccess`. Voci ordinate e date fisse: a parità di dist/ lo zip è identico anche tra
|
||||
* Windows, macOS e Linux.
|
||||
* Versione: variabile RELEASE_VERSION (tag vX.Y.Z) oppure package.json.
|
||||
*/
|
||||
process.env.TZ = 'UTC';
|
||||
|
||||
import { createHash } from 'node:crypto';
|
||||
import { createReadStream, createWriteStream, existsSync, readFileSync, statSync } from 'node:fs';
|
||||
import { mkdir, readFile, rm, writeFile } from 'node:fs/promises';
|
||||
import { join, resolve } from 'node:path';
|
||||
import { createWriteStream, existsSync, readFileSync, statSync } from 'node:fs';
|
||||
import { mkdir, rm } from 'node:fs/promises';
|
||||
import { join } from 'node:path';
|
||||
import { pipeline } from 'node:stream/promises';
|
||||
import { TarArchive, ZipArchive } from 'archiver';
|
||||
import { ZipArchive } from 'archiver';
|
||||
import { siteUrl } from '../site.config.mjs';
|
||||
import {
|
||||
archiveEpoch,
|
||||
@@ -29,7 +25,6 @@ import {
|
||||
listFiles,
|
||||
releaseDir,
|
||||
resolveVersion,
|
||||
root,
|
||||
} from './lib/release.mjs';
|
||||
|
||||
if (!existsSync(join(distDir, 'index.html'))) {
|
||||
@@ -44,82 +39,28 @@ try {
|
||||
console.error(`✘ ${e.message}`);
|
||||
process.exit(1);
|
||||
}
|
||||
const names = archiveNames(version);
|
||||
const { zip } = archiveNames(version);
|
||||
const files = listFiles(distDir);
|
||||
const date = new Date(archiveEpoch() * 1000);
|
||||
|
||||
await rm(releaseDir, { recursive: true, force: true });
|
||||
await mkdir(releaseDir, { recursive: true });
|
||||
|
||||
async function build(archive, target) {
|
||||
const output = createWriteStream(target);
|
||||
const done = pipeline(archive, output);
|
||||
archive.on('warning', (err) => {
|
||||
throw err;
|
||||
});
|
||||
for (const rel of files) {
|
||||
// contenuto letto in memoria: l'ordine delle voci resta quello dell'elenco ordinato
|
||||
archive.append(readFileSync(join(distDir, rel)), { name: rel, date, mode: 0o644 });
|
||||
}
|
||||
await archive.finalize();
|
||||
await done;
|
||||
const target = join(releaseDir, zip);
|
||||
const archive = new ZipArchive({ zlib: { level: 9 } });
|
||||
const output = createWriteStream(target);
|
||||
const done = pipeline(archive, output);
|
||||
archive.on('warning', (err) => {
|
||||
throw err;
|
||||
});
|
||||
for (const rel of files) {
|
||||
// contenuto letto in memoria: l'ordine delle voci resta quello dell'elenco ordinato
|
||||
archive.append(readFileSync(join(distDir, rel)), { name: rel, date, mode: 0o644 });
|
||||
}
|
||||
await archive.finalize();
|
||||
await done;
|
||||
|
||||
/**
|
||||
* Il byte 9 dell'header gzip indica il sistema operativo (zlib scrive 10 su Windows, 19 su
|
||||
* macOS, 3 altrove): lo si fissa a 3 (Unix) così il tar.gz non dipende dalla piattaforma.
|
||||
* Il byte non è coperto da alcun CRC (flag FHCRC assente; il CRC finale riguarda i dati).
|
||||
*/
|
||||
async function normalizeGzipOs(file) {
|
||||
const buf = await readFile(file);
|
||||
const isGzip = buf[0] === 0x1f && buf[1] === 0x8b && buf[2] === 8;
|
||||
if (!isGzip || (buf[3] & 0x02) !== 0) throw new Error(`${file}: header gzip inatteso`);
|
||||
if (buf[9] !== 3) {
|
||||
buf[9] = 3;
|
||||
await writeFile(file, buf);
|
||||
}
|
||||
}
|
||||
|
||||
await build(new ZipArchive({ zlib: { level: 9 } }), join(releaseDir, names.zip));
|
||||
await build(new TarArchive({ gzip: true, gzipOptions: { level: 9 } }), join(releaseDir, names.tgz));
|
||||
await normalizeGzipOs(join(releaseDir, names.tgz));
|
||||
|
||||
const sha256 = (file) =>
|
||||
new Promise((ok, ko) => {
|
||||
const hash = createHash('sha256');
|
||||
createReadStream(file)
|
||||
.on('data', (d) => hash.update(d))
|
||||
.on('end', () => ok(hash.digest('hex')))
|
||||
.on('error', ko);
|
||||
});
|
||||
|
||||
const pkgLock = JSON.parse(readFileSync(resolve(root, 'package-lock.json'), 'utf8'));
|
||||
const astroVersion = pkgLock.packages?.['node_modules/astro']?.version ?? 'sconosciuta';
|
||||
const info = [
|
||||
'Sito web dello Studio Grasso — Studio Tributario e Societario',
|
||||
`Versione: ${version}`,
|
||||
`Commit: ${gitCommit()}`,
|
||||
`Data: ${new Date().toISOString()}`,
|
||||
`Data dei file negli archivi: ${date.toISOString()}`,
|
||||
`Node.js: ${process.version}`,
|
||||
`Astro: ${astroVersion}`,
|
||||
`SITE_URL: ${siteUrl()}`,
|
||||
`File: ${files.length}`,
|
||||
'',
|
||||
'Pubblicazione: estrarre il contenuto dell’archivio nella cartella pubblica del sito',
|
||||
'(es. public_html o httpdocs), includendo il file nascosto .htaccess. Vedi docs/DEPLOY.md.',
|
||||
'',
|
||||
].join('\n');
|
||||
await writeFile(join(releaseDir, 'BUILD-INFO.txt'), info);
|
||||
|
||||
const sums = [];
|
||||
for (const name of [names.zip, names.tgz, 'BUILD-INFO.txt']) {
|
||||
sums.push(`${await sha256(join(releaseDir, name))} ${name}`);
|
||||
}
|
||||
await writeFile(join(releaseDir, 'SHA256SUMS.txt'), sums.join('\n') + '\n');
|
||||
|
||||
const kb = (f) => `${(statSync(join(releaseDir, f)).size / 1024).toFixed(1)} KB`;
|
||||
const kb = (statSync(target).size / 1024).toFixed(1);
|
||||
console.log(`✔ Pacchetto v${version} creato in release/ (${files.length} file da dist/):`);
|
||||
for (const f of [names.zip, names.tgz, 'SHA256SUMS.txt', 'BUILD-INFO.txt']) {
|
||||
console.log(` ${f.padEnd(40)} ${kb(f)}`);
|
||||
}
|
||||
console.log(` ${zip} ${kb} KB`);
|
||||
console.log(` commit ${gitCommit().slice(0, 12)} · dominio ${siteUrl()}`);
|
||||
+39
-24
@@ -1,22 +1,22 @@
|
||||
#!/usr/bin/env bash
|
||||
# =============================================================================
|
||||
# Pubblica una release su Forgejo tramite API REST e carica i file di release/.
|
||||
# Alternativa manuale (o step di riserva) all'action forgejo-release del workflow.
|
||||
# Pubblica una release su Gitea tramite API REST e carica i file di release/ (lo zip del sito).
|
||||
# Lo usa release.yml; si può eseguire anche a mano.
|
||||
#
|
||||
# Uso:
|
||||
# FORGEJO_URL=https://forgejo.example.it \
|
||||
# FORGEJO_REPO=proprietario/repository \
|
||||
# FORGEJO_TOKEN=<token con permesso write:repository> \
|
||||
# GITEA_URL=https://gitea.encke-hake.ts.net \
|
||||
# GITEA_REPO=proprietario/repository \
|
||||
# GITEA_TOKEN=<token con permesso write:repository> \
|
||||
# scripts/release-upload.sh v1.0.0 [cartella] # cartella predefinita: release
|
||||
#
|
||||
# Prima eseguire `npm run package` con RELEASE_VERSION=v1.0.0 e pubblicare il tag
|
||||
# (git push origin v1.0.0): lo script si ferma se il tag non è sul server oppure se punta a
|
||||
# un commit diverso dal tag locale. Le note della release sono prese da CHANGELOG.md.
|
||||
#
|
||||
# Come l'action, una release nuova viene creata in bozza, riceve i file e solo alla fine viene
|
||||
# pubblicata. Se la release esiste già (anche come bozza lasciata dall'action), i file con lo
|
||||
# stesso nome vengono sostituiti (prima si carica il nuovo, poi si cancella il vecchio) e la
|
||||
# release viene pubblicata con titolo e note del CHANGELOG.
|
||||
# Una release nuova viene creata in bozza, riceve i file e solo alla fine viene pubblicata.
|
||||
# Se la release esiste già (anche come bozza rimasta a metà), i file con lo stesso nome
|
||||
# vengono sostituiti (prima si carica il nuovo, poi si cancella il vecchio) e la release viene
|
||||
# pubblicata con titolo e note del CHANGELOG.
|
||||
# =============================================================================
|
||||
set -euo pipefail
|
||||
|
||||
@@ -26,15 +26,22 @@ DIR="${2:-release}"
|
||||
die() { echo "✘ $*" >&2; exit 1; }
|
||||
|
||||
[ -n "$TAG" ] || die "indicare il tag, es.: scripts/release-upload.sh v1.0.0"
|
||||
[ -n "${FORGEJO_URL:-}" ] || die "variabile FORGEJO_URL mancante (es. https://forgejo.example.it)"
|
||||
[ -n "${FORGEJO_REPO:-}" ] || die "variabile FORGEJO_REPO mancante (es. proprietario/repository)"
|
||||
[ -n "${FORGEJO_TOKEN:-}" ] || die "variabile FORGEJO_TOKEN mancante"
|
||||
[ -n "${GITEA_URL:-}" ] || die "variabile GITEA_URL mancante (es. https://gitea.encke-hake.ts.net)"
|
||||
[ -n "${GITEA_REPO:-}" ] || die "variabile GITEA_REPO mancante (es. proprietario/repository)"
|
||||
[ -n "${GITEA_TOKEN:-}" ] || die "variabile GITEA_TOKEN mancante"
|
||||
[ -d "$DIR" ] || die "cartella $DIR assente: eseguire prima npm run package"
|
||||
command -v curl >/dev/null || die "curl non installato"
|
||||
command -v node >/dev/null || die "node non installato"
|
||||
|
||||
API="${FORGEJO_URL%/}/api/v1/repos/${FORGEJO_REPO}"
|
||||
AUTH="Authorization: token ${FORGEJO_TOKEN}"
|
||||
# nessun file da caricare = pacchetto non creato: meglio fermarsi che pubblicare una release vuota
|
||||
FILES=()
|
||||
for FILE in "$DIR"/*; do
|
||||
[ -f "$FILE" ] && FILES+=("$FILE")
|
||||
done
|
||||
[ "${#FILES[@]}" -gt 0 ] || die "nessun file in $DIR: eseguire prima npm run package"
|
||||
|
||||
API="${GITEA_URL%/}/api/v1/repos/${GITEA_REPO}"
|
||||
AUTH="Authorization: token ${GITEA_TOKEN}"
|
||||
|
||||
# Valore di un campo (anche annidato: «commit.sha») di un oggetto JSON letto da stdin.
|
||||
json_field() { node -e 'let s="";process.stdin.on("data",d=>s+=d).on("end",()=>{let v=JSON.parse(s);for(const k of process.argv[1].split("."))v=v==null?undefined:v[k];if(v===undefined)process.exit(1);console.log(typeof v==="object"?JSON.stringify(v):v)})' "$1"; }
|
||||
@@ -43,7 +50,8 @@ asset_ids() { node -e 'let s="";process.stdin.on("data",d=>s+=d).on("end",()=>{c
|
||||
urlencode() { node -e 'console.log(encodeURIComponent(process.argv[1]))' "$1"; }
|
||||
|
||||
TAG_URL="$(urlencode "$TAG")"
|
||||
NOTES="$(node scripts/changelog-notes.mjs "$TAG")"
|
||||
NOTES="$(node "$(dirname "${BASH_SOURCE[0]}")/changelog-notes.mjs" "$TAG")" \
|
||||
|| die "note della release non disponibili: manca la sezione di $TAG in CHANGELOG.md"
|
||||
PRERELEASE=false
|
||||
case "$TAG" in *-*) PRERELEASE=true ;; esac
|
||||
# Dati della release; $1 = true per la bozza, false per pubblicarla.
|
||||
@@ -52,10 +60,10 @@ payload() {
|
||||
"$TAG" "$NOTES" "$1" "$PRERELEASE"
|
||||
}
|
||||
|
||||
echo "→ Release $TAG su $FORGEJO_REPO"
|
||||
echo "→ Release $TAG su $GITEA_REPO"
|
||||
|
||||
# 1) il tag deve essere già sul server: senza, Forgejo lo creerebbe sulla punta del branch
|
||||
# predefinito (un altro commit) e avvierebbe release.yml
|
||||
# 1) il tag deve essere già sul server: senza, Gitea lo creerebbe sulla punta del branch
|
||||
# predefinito (un altro commit)
|
||||
TAG_JSON="$(curl -fsS -H "$AUTH" "$API/tags/$TAG_URL")" \
|
||||
|| die "tag $TAG assente sul server (o token senza accesso al repository): eseguire prima git push origin $TAG"
|
||||
SERVER_SHA="$(printf '%s' "$TAG_JSON" | json_field commit.sha)" || die "risposta inattesa per il tag $TAG"
|
||||
@@ -64,27 +72,34 @@ if LOCAL_SHA="$(git rev-parse --verify --quiet "refs/tags/$TAG^{commit}" 2>/dev/
|
||||
|| die "il tag $TAG sul server punta a $SERVER_SHA, quello locale a $LOCAL_SHA: pacchetto e tag non coincidono"
|
||||
fi
|
||||
|
||||
# 2) release esistente (pubblicata o bozza) oppure nuova bozza
|
||||
if EXISTING="$(curl -fsS -H "$AUTH" "$API/releases/tags/$TAG_URL" 2>/dev/null)"; then
|
||||
# 2) release esistente (pubblicata o bozza) oppure nuova bozza: solo un 404 vuol dire «non
|
||||
# esiste ancora»; qualunque altro errore (rete, 401, 403, 5xx) ferma lo script
|
||||
EXISTING_FILE="$(mktemp)"
|
||||
trap 'rm -f "$EXISTING_FILE"' EXIT
|
||||
EXISTING_CODE="$(curl -sS -o "$EXISTING_FILE" -w '%{http_code}' -H "$AUTH" "$API/releases/tags/$TAG_URL")" \
|
||||
|| die "il server non risponde ($GITEA_URL)"
|
||||
if [ "$EXISTING_CODE" = "200" ]; then
|
||||
EXISTING="$(cat "$EXISTING_FILE")"
|
||||
RELEASE_ID="$(printf '%s' "$EXISTING" | json_field id)"
|
||||
if [ "$(printf '%s' "$EXISTING" | json_field draft)" = "true" ]; then
|
||||
echo " bozza già esistente (id $RELEASE_ID): caricamento dei file e pubblicazione"
|
||||
else
|
||||
echo " release già pubblicata (id $RELEASE_ID): sostituzione dei file con lo stesso nome"
|
||||
fi
|
||||
else
|
||||
elif [ "$EXISTING_CODE" = "404" ]; then
|
||||
CREATED="$(curl -fsS -X POST -H "$AUTH" -H 'Content-Type: application/json' -d "$(payload true)" "$API/releases")" \
|
||||
|| die "creazione della release non riuscita (il token ha il permesso write:repository?)"
|
||||
RELEASE_ID="$(printf '%s' "$CREATED" | json_field id)"
|
||||
echo " bozza creata (id $RELEASE_ID)"
|
||||
else
|
||||
die "lettura della release $TAG non riuscita (HTTP $EXISTING_CODE): controllare l'indirizzo, il token e riprovare"
|
||||
fi
|
||||
|
||||
# 3) file: prima il nuovo, poi la cancellazione dell'eventuale versione precedente, così un
|
||||
# errore a metà non lascia la release senza quel file
|
||||
ASSETS="$(curl -fsS -H "$AUTH" "$API/releases/$RELEASE_ID/assets")" \
|
||||
|| die "elenco dei file della release $RELEASE_ID non disponibile"
|
||||
for FILE in "$DIR"/*; do
|
||||
[ -f "$FILE" ] || continue
|
||||
for FILE in "${FILES[@]}"; do
|
||||
NAME="$(basename "$FILE")"
|
||||
OLD_IDS="$(printf '%s' "$ASSETS" | asset_ids "$NAME")"
|
||||
curl -fsS -X POST -H "$AUTH" -F "attachment=@${FILE}" \
|
||||
@@ -101,4 +116,4 @@ done
|
||||
curl -fsS -X PATCH -H "$AUTH" -H 'Content-Type: application/json' -d "$(payload false)" \
|
||||
"$API/releases/$RELEASE_ID" >/dev/null \
|
||||
|| die "pubblicazione non riuscita: la release $RELEASE_ID potrebbe essere rimasta in bozza"
|
||||
echo "✔ Release $TAG pubblicata: ${FORGEJO_URL%/}/${FORGEJO_REPO}/releases/tag/$TAG"
|
||||
echo "✔ Release $TAG pubblicata: ${GITEA_URL%/}/${GITEA_REPO}/releases/tag/$TAG"
|
||||
Reference in new issue
Block a user