diff --git a/.gitea/workflows/ci.yaml b/.gitea/workflows/ci.yaml index e7c6a45..828d52c 100644 --- a/.gitea/workflows/ci.yaml +++ b/.gitea/workflows/ci.yaml @@ -1,47 +1,125 @@ +# 檔案用途:在 pull request 階段先建立版本、發佈 release,並在 beta 情境下執行後續工具鏈 +# 更新日期:2026/07/11 21:02:25 + +# Workflow 名稱,用來辨識這條 CI 流程 name: CI + +# 觸發條件設定 on: + # 只有在 pull request 時才會執行 pull_request: + # 只針對 master 與 develop 分支 branches: - master - develop + # 僅在 PR 開啟或同步更新時觸發 types: [opened, synchronize] + +# 工作流程中的各個 job jobs: + # 第一階段:建立版本與發佈 release build: + # Job 名稱,會顯示在 UI 中 name: 1. BUILD + # 執行環境為 Ubuntu runner runs-on: ubuntu + # 提供後續 job 使用的環境變數 env: + # 版本格式使用 beta 加上 run number VERSION: "0.0.0-beta.${{ gitea.run_number }}" + # 若 PR 來源分支是 develop,則標記為 beta IS_BETA: ${{ gitea.base_ref == 'develop' }} + # 對外輸出的 job 結果 outputs: + # 輸出版本號,供後續 job 使用 version: ${{ env.VERSION }} + # 輸出是否為 beta,供後續 job 判斷 is_beta: ${{ env.IS_BETA }} + # 具體步驟 steps: - - name: Publishing Release - uses: akkuman/gitea-release-action@${{ vars.ACTION_GITEA_RELEASE_VERSION }} - with: - name: "${{ gitea.event.repository.name }} v${{ env.VERSION }}" - tag_name: "v${{ env.VERSION }}" - target_commitish: ${{ gitea.sha }} - prerelease: ${{ env.IS_BETA }} + # 先依 repo 狀態計算版本號。 + - name: Calculate Version + # 供後續步驟讀取輸出用的 step id。 + id: calculate-version + # 使用版本計算 action。 + uses: https://gitea.jsc.idv.tw/actions/calculate-version@${{ vars.ACTION_CALCULATE_VERSION }} + # 傳入 action 參數。 + with: + # 告知 action 是否為 beta 分支情境。 + is_beta: ${{ env.IS_BETA }} + # 發佈 release。 + - name: Publishing Release + # 使用 release action 發佈版本。 + uses: akkuman/gitea-release-action@${{ vars.ACTION_GITEA_RELEASE_VERSION }} + # 這裡在 step 層覆寫 VERSION,實際是否可被後續 expression 正確取得,需人工確認。 + env: + # 取前一步算出的版本號。 + VERSION: ${{ steps.calculate-version.outputs.version }} + with: + # release 名稱包含 repository 名稱與版本號。 + name: "${{ gitea.event.repository.name }} v${{ env.VERSION }}" + # tag 名稱與版本號保持一致。 + tag_name: "v${{ env.VERSION }}" + # 指定這次 release 對應的 commit。 + target_commitish: ${{ gitea.sha }} + # beta 分支才標記為 prerelease。 + prerelease: ${{ env.IS_BETA }} + # 第二階段:在 beta 情況下執行工具鏈與清理動作 test: + # Job 名稱,會顯示在 UI 中 name: 2. TEST + # 執行環境為 Ubuntu runner runs-on: ubuntu + # 依賴 build job 的輸出 needs: [build] + # 只有 build 判定為 beta 時才執行 if: ${{ needs.build.outputs.is_beta == 'true' }} + # 由 build job 傳入版本號 env: VERSION: ${{ needs.build.outputs.version }} + # 對外輸出的 job 結果 outputs: + # 目前 workflow 內沒有名為 docker-template 的 step;此輸出是否可取得需人工確認。 message: ${{ steps.docker-template.outputs.message }} + # 具體步驟 steps: - - name: Run Docker Template - id: docker-template - uses: https://gitea.jsc.idv.tw/actions/docker-template@v${{ env.VERSION }} + # 安裝或設定 LLM CLI。 + - name: Setup LLM CLI + # 使用對應的 setup action。 + uses: https://gitea.jsc.idv.tw/actions/setup-${{ vars.ACTION_SETUP_LLM_CLI }} + # 傳入設定。 + with: + # LLM CLI 的 OAuth 憑證。 + oauth: ${{ secrets.LLM_OAUTH }} + # 執行 AI Code Review action。 + - name: Run AI Code Review + # step id,方便追蹤。 + id: ai-code-review + # 使用本 repo 發佈的 action。 + uses: https://gitea.jsc.idv.tw/actions/ai-code-review@${{ vars.ACTION_AI_CODE_REVIEW_VERSION }} + # action 參數。 + with: + # 存取 Gitea API 的 token。 + token: ${{ secrets.TOKEN }} + # 指定 LLM 模型名稱。 + model: ${{ vars.LLM_NAME }} + # 執行 cleanup-release action。 + - name: Run Cleanup Release + # 這裡使用 build job 的版本輸出組出 tag;若版本來源不同,需人工確認。 + uses: https://gitea.jsc.idv.tw/actions/cleanup-release@v${{ env.VERSION }} + # 第三階段:輸出結果 result: + # Job 名稱,會顯示在 UI 中 name: 3. RESULT + # 執行環境為 Ubuntu runner runs-on: ubuntu + # 依賴 build 與 test job 完成 needs: [build,test] + # 取得 build job 輸出的版本 env: - MESSAGE: ${{ needs.test.outputs.message }} + VERSION: ${{ needs.build.outputs.version }} + # 具體步驟 steps: - - name: Show Message - run: echo "$MESSAGE" + # 顯示版本,讓執行紀錄可直接查看。 + - name: Show Version + run: echo "$VERSION" diff --git a/.gitea/workflows/master.yaml b/.gitea/workflows/master.yaml index cfce70f..1166b38 100644 --- a/.gitea/workflows/master.yaml +++ b/.gitea/workflows/master.yaml @@ -1,21 +1,39 @@ +# 檔案用途:在 master 分支推送後進行部署相關檢查與標籤顯示 +# 更新日期:2026/07/11 21:02:25 + +# Workflow 名稱,代表這條 CD 流程 name: CD + +# 觸發條件設定 on: + # 只有 push 到 master 分支時才執行 push: branches: - master + +# 工作流程中的 jobs jobs: + # 部署階段,負責取 commit tag 並輸出 deploy: + # Job 名稱,會顯示在 UI 中 name: DEPLOY + # 執行環境為 Ubuntu runner runs-on: ubuntu + # 設定環境變數,取出第二個 commit 的 id env: COMMIT_SHA: ${{ gitea.event.commits[1].id }} + # 具體步驟 steps: - - name: Source Code Checkout - uses: actions/checkout@${{ vars.ACTION_CHECKOUT_VERSION }} - with: - fetch-depth: 0 - - name: Get Commit Tag - id: commit - run: echo "tag=$(git describe --contains ${{ env.COMMIT_SHA }})" >> $GITEA_OUTPUT - - name: Show Tag - run: echo "${{ steps.commit.outputs.tag }}" + # checkout source code,供後續 git describe 使用 + - name: Source Code Checkout + uses: actions/checkout@${{ vars.ACTION_CHECKOUT_VERSION }} + with: + # 保留完整歷史,讓 git describe 可運作 + fetch-depth: 0 + # 取出包含目前 commit 的 tag + - name: Get Commit Tag + id: commit + run: echo "tag=$(git describe --contains ${{ env.COMMIT_SHA }})" >> $GITEA_OUTPUT + # 顯示 tag,讓執行紀錄可直接查看 + - name: Show Tag + run: echo "${{ steps.commit.outputs.tag }}" diff --git a/Dockerfile b/Dockerfile index 6e02ce4..74dad61 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,11 +1,23 @@ +# 檔案用途:建立執行 cleanup-release action 的 Node.js 容器映像 +# 更新日期:2026/07/11 21:02:25 + +# 允許在建置時指定 Node.js 版本標籤 ARG NODE_VERSION=alpine +# 使用指定版本的 Node.js 基底映像 FROM node:${NODE_VERSION} + +# 設定 action 容器內的工作目錄 WORKDIR /action +# 複製程式碼到容器內,讓 entrypoint 可以執行主程式 COPY src/ /action/src/ + +# 複製入口腳本到容器內 COPY entrypoint.sh /action/entrypoint.sh +# 確保入口腳本可執行 RUN chmod +x /action/entrypoint.sh +# 容器啟動時固定執行入口腳本 ENTRYPOINT ["/action/entrypoint.sh"] diff --git a/action.yml b/action.yml index 2a29e09..dc7f20f 100644 --- a/action.yml +++ b/action.yml @@ -1,14 +1,41 @@ -name: 'Gitea Docker Template' -description: 'Gitea Docker 範本' +# 檔案用途:定義 CLEANUP OLD RELEASES 這個 Docker action 的輸入參數與執行環境 +# 更新日期:2026/07/11 21:02:25 + +# Action 名稱,會顯示在 action 市集與文件中 +name: 'CLEANUP OLD RELEASES' + +# Action 描述,簡短說明這個 action 的目的 +description: '清理舊版成品' + +# 作者資訊,標示此 action 的維護者 author: 'Jeffery' + +# 定義可由使用者或呼叫端傳入的輸入參數 inputs: - message: - description: '輸入訊息' - required: false - default: 'Hello, World!' -outputs: - message: - description: '輸出訊息' + # RUNNER_TOKEN 用於授權呼叫 Gitea API;未提供時會改用 secrets + RUNNER_TOKEN: + # 參數說明,讓呼叫端知道這是 Runner Token + description: 'GitHub Runner Token' + # KEEP_COUNT 用於控制保留的 release 數量 + KEEP_COUNT: + # 參數說明,這裡表示保留的版本數量 + description: '保留的版本數量' + # 預設保留 2 個版本,避免完全刪除歷史 release + default: '2' + +# 定義 action 的執行方式 runs: + # 使用 Docker image 作為執行環境 using: docker + # Dockerfile 位於 repo 根目錄 image: Dockerfile + # 將 Gitea 與輸入參數映射為容器環境變數 + env: + # GITEA_SERVER_URL 由 Gitea runtime 注入,供程式組 API URL + GITEA_SERVER_URL: ${{ gitea.server_url }} + # GITEA_REPOSITORY 由 Gitea runtime 注入,供程式指定目標 repo + GITEA_REPOSITORY: ${{ gitea.repository }} + # 優先使用傳入的 RUNNER_TOKEN,否則退回 Gitea token secrets + RUNNER_TOKEN: ${{ inputs.RUNNER_TOKEN || secrets.GITEA_TOKEN || secrets.RUNNER_TOKEN }} + # KEEP_COUNT 直接沿用輸入值,交由程式驗證 + KEEP_COUNT: ${{ inputs.KEEP_COUNT }} diff --git a/entrypoint.sh b/entrypoint.sh old mode 100755 new mode 100644 index db76083..2fb94bc --- a/entrypoint.sh +++ b/entrypoint.sh @@ -1,10 +1,12 @@ #!/bin/sh +# 檔案用途:啟動 action 容器時輸出識別資訊,並交由 Node 主程式執行 +# 更新日期:2026/07/11 21:02:25 + set -e -echo "================================================" -echo "Action : Gitea Docker Template" -echo "用途 : Gitea Docker 範本" -echo "更新時間: 2026/07/02 09:41:31" -echo "================================================" +ts=$(TZ='Asia/Taipei' date +'%Y/%m/%d %H:%M:%S') +printf '[INF][%s]: Action: CLEANUP OLD RELEASES\n' "$ts" +printf '[INF][%s]: 用途: 清理舊版成品\n' "$ts" +printf '[INF][%s]: 更新時間: 2026/07/11\n' "$ts" exec node /action/src/index.js "$@" diff --git a/src/index.js b/src/index.js index 3727edc..f7f5ab6 100644 --- a/src/index.js +++ b/src/index.js @@ -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 }} [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} headers request 標頭。 + * @returns {Promise} 合併後的陣列資料。 + */ +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} 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); +});