fix(cleanup-release): 重新整理 release 清理流程與輸出格式
This commit is contained in:
+349
-10
@@ -1,15 +1,354 @@
|
||||
const fs = require('fs');
|
||||
const http = require('http');
|
||||
const https = require('https');
|
||||
|
||||
function main() {
|
||||
const message = process.env.INPUT_MESSAGE || '';
|
||||
const outputPath = process.env.GITHUB_OUTPUT;
|
||||
const line = `message=${message}\n`;
|
||||
let currentStage = '';
|
||||
|
||||
if (outputPath) {
|
||||
fs.appendFileSync(outputPath, line);
|
||||
} else {
|
||||
process.stdout.write(line);
|
||||
/**
|
||||
* 格式化台灣時區時間,供 log 使用。
|
||||
*
|
||||
* @param {Date} [date=new Date()] 要格式化的時間。
|
||||
* @returns {string} `yyyy/MM/dd HH:mm:ss` 格式時間字串。
|
||||
*/
|
||||
function formatTaipeiTimestamp(date = new Date()) {
|
||||
const parts = new Intl.DateTimeFormat('en-CA', {
|
||||
timeZone: 'Asia/Taipei',
|
||||
year: 'numeric',
|
||||
month: '2-digit',
|
||||
day: '2-digit',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
second: '2-digit',
|
||||
hourCycle: 'h23',
|
||||
}).formatToParts(date);
|
||||
|
||||
const lookup = {};
|
||||
for (const part of parts) {
|
||||
if (part.type !== 'literal') {
|
||||
lookup[part.type] = part.value;
|
||||
}
|
||||
}
|
||||
|
||||
return `${lookup.year}/${lookup.month}/${lookup.day} ${lookup.hour}:${lookup.minute}:${lookup.second}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 組合統一格式的 log 字串。
|
||||
*
|
||||
* @param {string} level 訊息等級。
|
||||
* @param {string} message 訊息內容。
|
||||
* @returns {string} 已格式化的 log 字串。
|
||||
*/
|
||||
function formatLog(level, message) {
|
||||
const stagePrefix = currentStage ? `[${currentStage}]` : '';
|
||||
return `${stagePrefix}[${level}][${formatTaipeiTimestamp()}]: ${message}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 輸出標準輸出訊息。
|
||||
*
|
||||
* @param {string} level 訊息等級。
|
||||
* @param {string} message 訊息內容。
|
||||
*/
|
||||
function writeStdout(level, message) {
|
||||
process.stdout.write(`${formatLog(level, message)}\n`);
|
||||
}
|
||||
|
||||
/**
|
||||
* 輸出標準錯誤訊息。
|
||||
*
|
||||
* @param {string} level 訊息等級。
|
||||
* @param {string} message 訊息內容。
|
||||
*/
|
||||
function writeStderr(level, message) {
|
||||
process.stderr.write(`${formatLog(level, message)}\n`);
|
||||
}
|
||||
|
||||
/**
|
||||
* 保留舊介面以維持草稿對應,實際上不再輸出橫幅。
|
||||
*/
|
||||
function separator() {}
|
||||
|
||||
/**
|
||||
* 切換目前訊息所屬區塊,供 log 前綴使用。
|
||||
*
|
||||
* @param {string} title 區塊名稱。
|
||||
*/
|
||||
function section(title) {
|
||||
currentStage = title;
|
||||
}
|
||||
|
||||
/**
|
||||
* 輸出一般資訊訊息。
|
||||
*
|
||||
* @param {string} message 訊息內容。
|
||||
*/
|
||||
function info(message) {
|
||||
writeStdout('INF', message);
|
||||
}
|
||||
|
||||
/**
|
||||
* 輸出成功訊息。
|
||||
*
|
||||
* @param {string} message 訊息內容。
|
||||
*/
|
||||
function success(message) {
|
||||
writeStdout('INF', message);
|
||||
}
|
||||
|
||||
/**
|
||||
* 輸出警告訊息。
|
||||
*
|
||||
* @param {string} message 訊息內容。
|
||||
*/
|
||||
function warn(message) {
|
||||
writeStdout('WRN', message);
|
||||
}
|
||||
|
||||
/**
|
||||
* 輸出錯誤訊息。
|
||||
*
|
||||
* @param {string} message 訊息內容。
|
||||
*/
|
||||
function fail(message) {
|
||||
writeStderr('ERR', message);
|
||||
}
|
||||
|
||||
/**
|
||||
* 判斷值是否視為空值。
|
||||
*
|
||||
* @param {*} value 要檢查的值。
|
||||
* @returns {boolean} 如果是空值則回傳 `true`。
|
||||
*/
|
||||
function isEmptyOrNull(value) {
|
||||
return value === undefined || value === null || value === '' || value === 'null';
|
||||
}
|
||||
|
||||
/**
|
||||
* 驗證必要值是否存在。
|
||||
*
|
||||
* @param {string} name 參數名稱。
|
||||
* @param {*} value 參數值。
|
||||
*/
|
||||
function requireValue(name, value) {
|
||||
info(`${name}=${value}`);
|
||||
|
||||
if (isEmptyOrNull(value)) {
|
||||
fail(`${name} is required`);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
main();
|
||||
/**
|
||||
* 驗證字串是否為非負整數。
|
||||
*
|
||||
* @param {string} name 參數名稱。
|
||||
* @param {string} value 參數值。
|
||||
*/
|
||||
function requireInteger(name, value) {
|
||||
if (!/^[0-9]+$/.test(value)) {
|
||||
fail(`${name} must be a non-negative integer`);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 對指定 URL 發送 request,回傳狀態碼與 body。
|
||||
*
|
||||
* @param {string} url 完整目標網址。
|
||||
* @param {{ method?: string, headers?: Record<string, string> }} [options] request 設定。
|
||||
* @returns {Promise<{ statusCode: number, body: string }>} 回應狀態碼與內容。
|
||||
*/
|
||||
function requestJson(url, { method = 'GET', headers = {} } = {}) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const target = new URL(url);
|
||||
const client = target.protocol === 'http:' ? http : https;
|
||||
|
||||
const req = client.request(
|
||||
target,
|
||||
{
|
||||
method,
|
||||
headers,
|
||||
},
|
||||
(res) => {
|
||||
const chunks = [];
|
||||
|
||||
res.setEncoding('utf8');
|
||||
res.on('data', (chunk) => {
|
||||
chunks.push(chunk);
|
||||
});
|
||||
res.on('end', () => {
|
||||
resolve({
|
||||
statusCode: res.statusCode || 0,
|
||||
body: chunks.join(''),
|
||||
});
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
req.on('error', reject);
|
||||
req.end();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 逐頁抓取 JSON 陣列資料,直到回傳空頁為止。
|
||||
*
|
||||
* @param {string} baseUrl 不含 page 參數的 API URL。
|
||||
* @param {Record<string, string>} headers request 標頭。
|
||||
* @returns {Promise<any[]>} 合併後的陣列資料。
|
||||
*/
|
||||
async function fetchAllPages(baseUrl, headers) {
|
||||
const all = [];
|
||||
|
||||
for (let page = 1; ; page += 1) {
|
||||
const pageUrl = `${baseUrl}?page=${page}`;
|
||||
const { statusCode, body } = await requestJson(pageUrl, { headers });
|
||||
|
||||
if (statusCode < 200 || statusCode >= 300) {
|
||||
throw new Error(`GET ${pageUrl} failed with HTTP ${statusCode}: ${body}`);
|
||||
}
|
||||
|
||||
const data = JSON.parse(body || '[]');
|
||||
if (!Array.isArray(data)) {
|
||||
throw new Error(`GET ${pageUrl} did not return a JSON array`);
|
||||
}
|
||||
|
||||
if (data.length === 0) {
|
||||
break;
|
||||
}
|
||||
|
||||
all.push(...data);
|
||||
}
|
||||
|
||||
return all;
|
||||
}
|
||||
|
||||
/**
|
||||
* 對指定 URL 發送 DELETE request。
|
||||
*
|
||||
* @param {string} url 要刪除的資源網址。
|
||||
* @param {Record<string, string>} headers request 標頭。
|
||||
* @returns {Promise<{ statusCode: number, body: string }>} 回應狀態碼與內容。
|
||||
*/
|
||||
async function deleteResource(url, headers) {
|
||||
return requestJson(url, {
|
||||
method: 'DELETE',
|
||||
headers,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 執行 release 與 tag 清理流程。
|
||||
*/
|
||||
async function main() {
|
||||
const { GITEA_SERVER_URL, GITEA_REPOSITORY, RUNNER_TOKEN = '', KEEP_COUNT = '' } =
|
||||
process.env;
|
||||
|
||||
section('參數檢查');
|
||||
requireValue('GITEA_SERVER_URL', GITEA_SERVER_URL);
|
||||
requireValue('GITEA_REPOSITORY', GITEA_REPOSITORY);
|
||||
requireValue('KEEP_COUNT', KEEP_COUNT);
|
||||
requireInteger('KEEP_COUNT', KEEP_COUNT);
|
||||
|
||||
const keepCount = Number(KEEP_COUNT);
|
||||
const authHeaders = {};
|
||||
if (isEmptyOrNull(RUNNER_TOKEN)) {
|
||||
warn('RUNNER_TOKEN is empty; release API calls will be anonymous');
|
||||
} else {
|
||||
info('RUNNER_TOKEN=[redacted]');
|
||||
authHeaders.Authorization = `token ${RUNNER_TOKEN}`;
|
||||
}
|
||||
|
||||
const releaseApiUrl = `${GITEA_SERVER_URL}/api/v1/repos/${GITEA_REPOSITORY}/releases`;
|
||||
|
||||
section('取得成品資訊');
|
||||
info(`GET ${releaseApiUrl}`);
|
||||
|
||||
const releaseJson = await fetchAllPages(releaseApiUrl, authHeaders);
|
||||
releaseJson.sort((left, right) => {
|
||||
if (left.created_at < right.created_at) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (left.created_at > right.created_at) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
return 0;
|
||||
});
|
||||
|
||||
const releaseCount = releaseJson.length;
|
||||
info(`RELEASE_COUNT=${releaseCount}`);
|
||||
info(`KEEP_COUNT=${KEEP_COUNT}`);
|
||||
|
||||
if (releaseCount <= keepCount) {
|
||||
success('沒有需要清理的舊版本成品');
|
||||
} else {
|
||||
section('刪除舊版本成品');
|
||||
|
||||
const releaseToDelete = releaseJson.slice(keepCount);
|
||||
for (const releaseItem of releaseToDelete) {
|
||||
if (!releaseItem || isEmptyOrNull(releaseItem.id)) {
|
||||
warn(`略過沒有 id 的成品: ${releaseItem?.tag_name || ''} (${releaseItem?.name || ''})`);
|
||||
continue;
|
||||
}
|
||||
|
||||
const releaseTag = releaseItem.tag_name || '';
|
||||
const releaseName = releaseItem.name || '';
|
||||
const deleteUrl = `${releaseApiUrl}/${releaseItem.id}`;
|
||||
info(`DELETE ${releaseTag} (${releaseName})`);
|
||||
|
||||
const { statusCode } = await deleteResource(deleteUrl, authHeaders);
|
||||
if (statusCode === 204) {
|
||||
success(`成功刪除: ${releaseTag} (${releaseName})`);
|
||||
} else {
|
||||
fail(`刪除失敗: ${releaseTag} (${releaseName}), HTTP ${statusCode}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
section('刪除未指定 release 的 tag');
|
||||
|
||||
const currentReleaseJson = await fetchAllPages(releaseApiUrl, authHeaders);
|
||||
const releaseTags = new Set();
|
||||
for (const item of currentReleaseJson) {
|
||||
if (!isEmptyOrNull(item?.tag_name)) {
|
||||
releaseTags.add(item.tag_name);
|
||||
}
|
||||
}
|
||||
|
||||
const tagApiUrl = `${GITEA_SERVER_URL}/api/v1/repos/${GITEA_REPOSITORY}/tags`;
|
||||
info(`GET ${tagApiUrl}`);
|
||||
|
||||
const tagJson = await fetchAllPages(tagApiUrl, authHeaders);
|
||||
info(`TAG_COUNT=${tagJson.length}`);
|
||||
|
||||
for (const tagItem of tagJson) {
|
||||
const tagName = tagItem?.name;
|
||||
if (isEmptyOrNull(tagName)) {
|
||||
warn('略過沒有名稱的 tag');
|
||||
continue;
|
||||
}
|
||||
|
||||
if (releaseTags.has(tagName)) {
|
||||
info(`保留指定 release 的 tag: ${tagName}`);
|
||||
continue;
|
||||
}
|
||||
|
||||
const deleteUrl = `${tagApiUrl}/${encodeURIComponent(tagName)}`;
|
||||
info(`DELETE tag ${tagName}`);
|
||||
|
||||
const { statusCode } = await deleteResource(deleteUrl, authHeaders);
|
||||
if (statusCode === 204) {
|
||||
success(`成功刪除未指定 release 的 tag: ${tagName}`);
|
||||
} else {
|
||||
fail(`刪除 tag 失敗: ${tagName}, HTTP ${statusCode}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
main().catch((error) => {
|
||||
currentStage = '';
|
||||
fail(error instanceof Error ? error.stack || error.message : String(error));
|
||||
process.exit(1);
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user