- action.yml 移除 RUNNER_TOKEN input 與 secrets 回退鏈,env 簡化為 GITEA_TOKEN: ${{ gitea.token }}
- src/index.js 環境變數與 log 訊息同步改名為 GITEA_TOKEN,遮罩行為不變
- 自動 token 權限僅限當前 repo 且 job 結束即失效,已足夠本 action 的 release/tag 清理需求
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
551 lines
16 KiB
JavaScript
551 lines
16 KiB
JavaScript
const https = require('https');
|
|
|
|
const DELETE_CONCURRENCY = 4;
|
|
const DEFAULT_MAX_PAGES = 1000;
|
|
|
|
const keepAliveAgent = new https.Agent({ keepAlive: true });
|
|
|
|
const taipeiFormatter = 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',
|
|
});
|
|
|
|
let currentStage = '';
|
|
let cachedTimestampKey = '';
|
|
let cachedTimestampValue = '';
|
|
|
|
/**
|
|
* 格式化台灣時區時間,供 log 使用。
|
|
*
|
|
* @param {Date} [date=new Date()] 要格式化的時間。
|
|
* @returns {string} `yyyy/MM/dd HH:mm:ss` 格式時間字串。
|
|
*/
|
|
function formatTaipeiTimestamp(date = new Date()) {
|
|
const timestampKey = date.toISOString().slice(0, 19);
|
|
if (timestampKey === cachedTimestampKey) {
|
|
return cachedTimestampValue;
|
|
}
|
|
|
|
const parts = taipeiFormatter.formatToParts(date);
|
|
|
|
const lookup = {};
|
|
for (const part of parts) {
|
|
if (part.type !== 'literal') {
|
|
lookup[part.type] = part.value;
|
|
}
|
|
}
|
|
|
|
cachedTimestampKey = timestampKey;
|
|
cachedTimestampValue = `${lookup.year}/${lookup.month}/${lookup.day} ${lookup.hour}:${lookup.minute}:${lookup.second}`;
|
|
return cachedTimestampValue;
|
|
}
|
|
|
|
/**
|
|
* 將未信任內容整理成適合記錄到 log 或錯誤訊息的文字。
|
|
*
|
|
* @param {*} value 原始值。
|
|
* @returns {string} 已去除控制字元的文字。
|
|
*/
|
|
function sanitizeLogText(value) {
|
|
return String(value).replace(/[\u0000-\u001f\u007f]/g, ' ');
|
|
}
|
|
|
|
/**
|
|
* 將回應內容整理成適合放進例外訊息的摘要。
|
|
*
|
|
* @param {*} body 回應內容。
|
|
* @param {number} [maxLength=200] 最長保留長度。
|
|
* @returns {string} 已整理的回應摘要。
|
|
*/
|
|
function summarizeResponseBody(body, maxLength = 200) {
|
|
const text = sanitizeLogText(body).replace(/\s+/g, ' ').trim();
|
|
if (text.length <= maxLength) {
|
|
return text;
|
|
}
|
|
|
|
return `${text.slice(0, maxLength)}…`;
|
|
}
|
|
|
|
/**
|
|
* 組合統一格式的 log 字串。
|
|
*
|
|
* @param {string} level 訊息等級。
|
|
* @param {string} message 訊息內容。
|
|
* @returns {string} 已格式化的 log 字串。
|
|
*/
|
|
function formatLog(level, message) {
|
|
const stagePrefix = currentStage ? `[${sanitizeLogText(currentStage)}]` : '';
|
|
return `${stagePrefix}[${level}][${formatTaipeiTimestamp()}]: ${sanitizeLogText(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`);
|
|
}
|
|
|
|
/**
|
|
* 切換目前訊息所屬區塊,供 log 前綴使用。
|
|
*
|
|
* @param {string} title 區塊名稱。
|
|
*/
|
|
function section(title) {
|
|
currentStage = title;
|
|
}
|
|
|
|
/**
|
|
* 輸出一般資訊訊息。
|
|
*
|
|
* @param {string} message 訊息內容。
|
|
*/
|
|
function info(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 === '';
|
|
}
|
|
|
|
/**
|
|
* 正規化環境變數值;workflow 模板缺值時可能代入字面值 `'null'`,一律視為未提供。
|
|
*
|
|
* @param {string | undefined} value 環境變數原始值。
|
|
* @returns {string | undefined} 正規化後的值。
|
|
*/
|
|
function normalizeEnvValue(value) {
|
|
return value === 'null' ? undefined : value;
|
|
}
|
|
|
|
/**
|
|
* 將 URL 遮罩成只含 origin 的文字,供 log 使用。
|
|
*
|
|
* @param {*} value 原始 URL 值。
|
|
* @returns {string} 遮罩後的 origin,無法解析時回傳提示文字。
|
|
*/
|
|
function maskUrlForLog(value) {
|
|
try {
|
|
return new URL(String(value)).origin;
|
|
} catch (error) {
|
|
return '[invalid URL]';
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 驗證必要值是否存在。
|
|
*
|
|
* @param {string} name 參數名稱。
|
|
* @param {*} value 參數值。
|
|
* @param {*} [displayValue=value] 寫進 log 的顯示值,敏感內容可先遮罩。
|
|
*/
|
|
function requireValue(name, value, displayValue = value) {
|
|
info(`${name}=${displayValue}`);
|
|
|
|
if (isEmptyOrNull(value)) {
|
|
fail(`${name} is required`);
|
|
process.exit(1);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 驗證字串是否為正整數,且落在安全整數範圍內;下限 1 可避免把保留數設成 0 而清空所有 release。
|
|
*
|
|
* @param {string} name 參數名稱。
|
|
* @param {string} value 參數值。
|
|
*/
|
|
function requirePositiveInteger(name, value) {
|
|
if (!/^[0-9]+$/.test(value) || !Number.isSafeInteger(Number(value)) || Number(value) < 1) {
|
|
fail(`${name} must be a positive integer within the safe integer range`);
|
|
process.exit(1);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 驗證值是否為合法的 HTTPS 絕對 URL,避免 URL 解析失敗留到主流程中途才拋出。
|
|
*
|
|
* @param {string} name 參數名稱。
|
|
* @param {*} value 參數值。
|
|
*/
|
|
function requireHttpsUrl(name, value) {
|
|
let parsed;
|
|
try {
|
|
parsed = new URL(String(value));
|
|
} catch (error) {
|
|
fail(`${name} must be a valid absolute URL`);
|
|
process.exit(1);
|
|
}
|
|
|
|
if (parsed.protocol !== 'https:') {
|
|
fail(`${name} must use HTTPS`);
|
|
process.exit(1);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 驗證 repository 是否為 `owner/repo` 格式且僅含安全字元,拒絕 `.`、`..` 等路徑片段。
|
|
*
|
|
* @param {string} name 參數名稱。
|
|
* @param {*} value 參數值。
|
|
*/
|
|
function requireRepository(name, value) {
|
|
const segments = String(value).split('/');
|
|
const isValidSegment = (segment) =>
|
|
/^[A-Za-z0-9_.-]+$/.test(segment) && segment !== '.' && segment !== '..';
|
|
|
|
if (segments.length !== 2 || !segments.every(isValidSegment)) {
|
|
fail(`${name} must be in owner/repo format`);
|
|
process.exit(1);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 對指定 URL 發送 request,回傳狀態碼與 body。
|
|
*
|
|
* @param {string} url 完整目標網址。
|
|
* @param {{ method?: string, headers?: Record<string, string>, collectBody?: boolean }} [options] request 設定;`collectBody` 為 `false` 時丟棄回應內容、只保留狀態碼。
|
|
* @returns {Promise<{ statusCode: number, body: string }>} 回應狀態碼與內容。
|
|
*/
|
|
function request(url, { method = 'GET', headers = {}, collectBody = true } = {}) {
|
|
return new Promise((resolve, reject) => {
|
|
const target = new URL(url);
|
|
if (target.protocol !== 'https:') {
|
|
reject(new Error(`Refusing to send request to non-HTTPS URL: ${target.origin}`));
|
|
return;
|
|
}
|
|
|
|
const req = https.request(
|
|
target,
|
|
{
|
|
method,
|
|
headers,
|
|
agent: keepAliveAgent,
|
|
},
|
|
(res) => {
|
|
const statusCode = res.statusCode || 0;
|
|
|
|
if (!collectBody) {
|
|
res.resume();
|
|
res.on('end', () => {
|
|
resolve({ statusCode, body: '' });
|
|
});
|
|
return;
|
|
}
|
|
|
|
const chunks = [];
|
|
|
|
res.setEncoding('utf8');
|
|
res.on('data', (chunk) => {
|
|
chunks.push(chunk);
|
|
});
|
|
res.on('end', () => {
|
|
resolve({
|
|
statusCode,
|
|
body: chunks.join(''),
|
|
});
|
|
});
|
|
},
|
|
);
|
|
|
|
req.on('error', reject);
|
|
req.end();
|
|
});
|
|
}
|
|
|
|
/**
|
|
* 逐頁抓取 JSON 陣列資料,直到回傳空頁為止;超過 `maxPages` 即中止並回報異常。
|
|
*
|
|
* @param {string} baseUrl 不含 page 參數的 API URL。
|
|
* @param {Record<string, string>} headers request 標頭。
|
|
* @param {number} [maxPages=DEFAULT_MAX_PAGES] 分頁上限,可由環境變數 `MAX_PAGES` 覆寫。
|
|
* @returns {Promise<any[]>} 合併後的陣列資料。
|
|
*/
|
|
async function fetchAllPages(baseUrl, headers, maxPages = DEFAULT_MAX_PAGES) {
|
|
const all = [];
|
|
|
|
for (let page = 1; ; page += 1) {
|
|
if (page > maxPages) {
|
|
throw new Error(`GET ${baseUrl} 分頁超過 ${maxPages} 頁上限,中止抓取以避免無限迴圈;資料量更大時可用 MAX_PAGES 環境變數調高上限`);
|
|
}
|
|
|
|
const pageUrl = `${baseUrl}?page=${page}`;
|
|
const { statusCode, body } = await request(pageUrl, { headers });
|
|
|
|
if (statusCode < 200 || statusCode >= 300) {
|
|
throw new Error(`GET ${pageUrl} failed with HTTP ${statusCode}: ${summarizeResponseBody(body)}`);
|
|
}
|
|
|
|
let data;
|
|
try {
|
|
data = JSON.parse(body || '[]');
|
|
} catch (error) {
|
|
throw new Error(`GET ${pageUrl} returned invalid JSON: ${summarizeResponseBody(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 request(url, {
|
|
method: 'DELETE',
|
|
headers,
|
|
collectBody: false,
|
|
});
|
|
}
|
|
|
|
/**
|
|
* 以固定批次大小處理項目,降低逐筆等待造成的延遲;單筆例外不會中止同批其他項目。
|
|
*
|
|
* @param {any[]} items 要處理的項目。
|
|
* @param {number} batchSize 每批同時處理的數量。
|
|
* @param {(item: any) => Promise<boolean>} handler 單筆處理函式,回傳該筆是否成功。
|
|
* @returns {Promise<PromiseSettledResult<boolean>[]>} 依原始順序排列的處理結果。
|
|
*/
|
|
async function processInBatches(items, batchSize, handler) {
|
|
const results = [];
|
|
|
|
for (let index = 0; index < items.length; index += batchSize) {
|
|
const batch = items.slice(index, index + batchSize);
|
|
results.push(...(await Promise.allSettled(batch.map((item) => handler(item)))));
|
|
}
|
|
|
|
return results;
|
|
}
|
|
|
|
/**
|
|
* 彙總批次結果;記錄被 reject 的例外,並回傳是否有任何一筆失敗。
|
|
*
|
|
* @param {PromiseSettledResult<boolean>[]} results 批次處理結果。
|
|
* @returns {boolean} 只要有任一筆失敗即回傳 `true`。
|
|
*/
|
|
function hasBatchFailure(results) {
|
|
let failed = false;
|
|
|
|
for (const result of results) {
|
|
if (result.status === 'rejected') {
|
|
failed = true;
|
|
const reason = result.reason;
|
|
fail(`批次處理發生例外: ${reason instanceof Error ? reason.message : String(reason)}`);
|
|
} else if (result.value === false) {
|
|
failed = true;
|
|
}
|
|
}
|
|
|
|
return failed;
|
|
}
|
|
|
|
/**
|
|
* 執行 release 與 tag 清理流程。
|
|
*/
|
|
async function main() {
|
|
const GITEA_SERVER_URL = normalizeEnvValue(process.env.GITEA_SERVER_URL);
|
|
const GITEA_REPOSITORY = normalizeEnvValue(process.env.GITEA_REPOSITORY);
|
|
const GITEA_TOKEN = normalizeEnvValue(process.env.GITEA_TOKEN) ?? '';
|
|
const KEEP_COUNT = normalizeEnvValue(process.env.KEEP_COUNT) ?? '';
|
|
const MAX_PAGES = normalizeEnvValue(process.env.MAX_PAGES) ?? '';
|
|
|
|
section('參數檢查');
|
|
requireValue('GITEA_SERVER_URL', GITEA_SERVER_URL, maskUrlForLog(GITEA_SERVER_URL));
|
|
requireHttpsUrl('GITEA_SERVER_URL', GITEA_SERVER_URL);
|
|
requireValue('GITEA_REPOSITORY', GITEA_REPOSITORY);
|
|
requireRepository('GITEA_REPOSITORY', GITEA_REPOSITORY);
|
|
requireValue('KEEP_COUNT', KEEP_COUNT);
|
|
requirePositiveInteger('KEEP_COUNT', KEEP_COUNT);
|
|
|
|
let maxPages = DEFAULT_MAX_PAGES;
|
|
if (!isEmptyOrNull(MAX_PAGES)) {
|
|
info(`MAX_PAGES=${MAX_PAGES}`);
|
|
requirePositiveInteger('MAX_PAGES', MAX_PAGES);
|
|
maxPages = Number(MAX_PAGES);
|
|
}
|
|
|
|
const keepCount = Number(KEEP_COUNT);
|
|
const authHeaders = {};
|
|
if (isEmptyOrNull(GITEA_TOKEN)) {
|
|
warn('GITEA_TOKEN is empty; release API calls will be anonymous');
|
|
} else {
|
|
info('GITEA_TOKEN=[redacted]');
|
|
authHeaders.Authorization = `token ${GITEA_TOKEN}`;
|
|
}
|
|
|
|
const serverBase = new URL(GITEA_SERVER_URL);
|
|
serverBase.username = '';
|
|
serverBase.password = '';
|
|
serverBase.search = '';
|
|
serverBase.hash = '';
|
|
const serverBaseUrl = serverBase.toString().replace(/\/+$/, '');
|
|
|
|
const repositoryPath = GITEA_REPOSITORY.split('/').map(encodeURIComponent).join('/');
|
|
const releaseApiUrl = `${serverBaseUrl}/api/v1/repos/${repositoryPath}/releases`;
|
|
|
|
section('取得成品資訊');
|
|
info(`GET ${releaseApiUrl}`);
|
|
|
|
const releaseJson = await fetchAllPages(releaseApiUrl, authHeaders, maxPages);
|
|
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) {
|
|
info('沒有需要清理的舊版本成品');
|
|
} else {
|
|
section('刪除舊版本成品');
|
|
|
|
const releaseToDelete = releaseJson.slice(keepCount);
|
|
const releaseResults = await processInBatches(releaseToDelete, DELETE_CONCURRENCY, async (releaseItem) => {
|
|
const releaseId = releaseItem?.id;
|
|
if (!Number.isSafeInteger(releaseId) || releaseId <= 0) {
|
|
fail(
|
|
`成品 id 不是正整數,視為資料異常: ${sanitizeLogText(releaseItem?.tag_name || '')} (${sanitizeLogText(releaseItem?.name || '')})`,
|
|
);
|
|
return false;
|
|
}
|
|
|
|
const releaseTag = sanitizeLogText(releaseItem.tag_name || '');
|
|
const releaseName = sanitizeLogText(releaseItem.name || '');
|
|
const deleteUrl = `${releaseApiUrl}/${releaseId}`;
|
|
info(`DELETE ${releaseTag} (${releaseName})`);
|
|
|
|
const { statusCode } = await deleteResource(deleteUrl, authHeaders);
|
|
if (statusCode === 204) {
|
|
info(`成功刪除: ${releaseTag} (${releaseName})`);
|
|
return true;
|
|
}
|
|
|
|
fail(`刪除失敗: ${releaseTag} (${releaseName}), HTTP ${statusCode}`);
|
|
return false;
|
|
});
|
|
|
|
if (hasBatchFailure(releaseResults)) {
|
|
throw new Error('至少有一筆 release 刪除失敗');
|
|
}
|
|
}
|
|
|
|
section('刪除未指定 release 的 tag');
|
|
|
|
const releaseTags = new Set(
|
|
releaseJson
|
|
.slice(0, keepCount)
|
|
.map((item) => item?.tag_name)
|
|
.filter((tag) => !isEmptyOrNull(tag)),
|
|
);
|
|
|
|
const tagApiUrl = `${serverBaseUrl}/api/v1/repos/${repositoryPath}/tags`;
|
|
info(`GET ${tagApiUrl}`);
|
|
|
|
const tagJson = await fetchAllPages(tagApiUrl, authHeaders, maxPages);
|
|
info(`TAG_COUNT=${tagJson.length}`);
|
|
|
|
const tagResults = await processInBatches(tagJson, DELETE_CONCURRENCY, async (tagItem) => {
|
|
const tagName = tagItem?.name;
|
|
if (isEmptyOrNull(tagName)) {
|
|
fail('tag 缺少名稱,視為資料異常');
|
|
return false;
|
|
}
|
|
|
|
const safeTagName = sanitizeLogText(tagName);
|
|
if (releaseTags.has(tagName)) {
|
|
info(`保留指定 release 的 tag: ${safeTagName}`);
|
|
return true;
|
|
}
|
|
|
|
const deleteUrl = `${tagApiUrl}/${encodeURIComponent(tagName)}`;
|
|
info(`DELETE tag ${safeTagName}`);
|
|
|
|
const { statusCode } = await deleteResource(deleteUrl, authHeaders);
|
|
if (statusCode === 204) {
|
|
info(`成功刪除未指定 release 的 tag: ${safeTagName}`);
|
|
return true;
|
|
}
|
|
|
|
fail(`刪除 tag 失敗: ${safeTagName}, HTTP ${statusCode}`);
|
|
return false;
|
|
});
|
|
|
|
if (hasBatchFailure(tagResults)) {
|
|
throw new Error('至少有一筆 tag 刪除失敗');
|
|
}
|
|
}
|
|
|
|
main()
|
|
.catch((error) => {
|
|
const showStack = process.env.RUNNER_DEBUG === '1';
|
|
fail(error instanceof Error ? (showStack && error.stack) || error.message : String(error));
|
|
process.exitCode = 1;
|
|
})
|
|
.finally(() => {
|
|
keepAliveAgent.destroy();
|
|
});
|