0.14.0:Workflow 健康檢查與 action runtime
.vscode/settings.jsonCHANGELOG.mdDocs/pages.mdDocs/usage.mdpyproject.tomlsrc/changelogkit/__init__.pysrc/changelogkit/assets/dev.csssrc/changelogkit/assets/dev.htmlsrc/changelogkit/assets/static_dev.htmlsrc/changelogkit/assets/static_workflows.htmlsrc/changelogkit/assets/workflows.htmlsrc/changelogkit/capabilities.pysrc/changelogkit/cli.pysrc/changelogkit/config.pysrc/changelogkit/export.pysrc/changelogkit/index.pysrc/changelogkit/lang/en.jsonsrc/changelogkit/lang/ja.jsonsrc/changelogkit/lang/zh-CN.jsonsrc/changelogkit/lang/zh-TW.jsonsrc/changelogkit/server.pysrc/changelogkit/workflows.pytests/test_changelogkit.py
commit 2de81b798449185cbaf052672f6b84c14d1b81bfAuthor: Nuclear0709 <agp05432@gmail.com>Date: Fri Nov 27 13:46:13 2026 +0800 0.14.0:Workflow 健康檢查與 action runtime diff --git a/.vscode/settings.json b/.vscode/settings.json--- a/.vscode/settings.json+++ b/.vscode/settings.json@@ -1,4 +1,5 @@ { "python.testing.pytestEnabled": true,- "python.testing.unittestEnabled": false+ "python.testing.unittestEnabled": false,+ "python-envs.defaultEnvManager": "ms-python.python:system" }diff --git a/CHANGELOG.md b/CHANGELOG.md--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,5 +1,21 @@ # Changelog +## 2026.11.27 13:45 changelogkit 0.14.0 發佈++**類型**: 功能 · **檔案**: `workflows.py`、`config.py`、`index.py`、`server.py`、`export.py`、`cli.py`、`assets/workflows.html`++### 問題 - GitHub Actions 的 action runtime 不在 workflow 裡,舊 Node action 難以可視化追蹤++### 修改 - Workflow 健康檢查頁與 CLI++- 新增 `/workflows` 動態頁與 `development/workflows.html` 靜態頁,列出 workflow/行號/action/ref/runtime/狀態。+- 本地掃描不需要 token;runtime 透過已登入的 `gh api` 或 CI 的 `GITHUB_TOKEN` 查詢,沒有認證時顯示 `unknown`,不中斷頁面。+- `node12`/`node16`/`node20` 標成 EOL Node;支援 composite、Docker、本地 action 與重用 workflow。+- 新增 `changelogkit workflows [--json] [--check]`;`--check` 在 EOL runtime 時回傳 1。+- `.changelog.toml` 可用 `[tool.changelog.workflows]` 設定 `enabled`/`runtime`/`path`;不提供 token 欄位。++---+ ## 2026.11.27 11:52 changelogkit 0.13.4 發佈 **類型**: 建置 · **檔案**: `.changelog.toml`、`.github/workflows/pages.yml`、`pyproject.toml`、`Docs/usage.md`diff --git a/Docs/pages.md b/Docs/pages.md--- a/Docs/pages.md+++ b/Docs/pages.md@@ -16,6 +16,7 @@ _site/ development/repos.html # 近期改動列表 development/commits/… # 單筆 commit 的完整 diff development/todo.html # 待辦快照(有 TODO 檔時)+ development/workflows.html # GitHub Actions action/runtime 健康檢查 docs/<來源>/<路徑>.html # 每份 Markdown 的檢視頁 about/index.html # 關於頁 assets/… # 網頁資產(相對路徑引用)diff --git a/Docs/usage.md b/Docs/usage.md--- a/Docs/usage.md+++ b/Docs/usage.md@@ -17,6 +17,7 @@ changelogkit community-init # 產生「社群與開發交流 changelogkit docs [--check] [--summary] # 檢查文件分類(錯誤回 1) changelogkit docs-init # 印出可貼上的 docs TOML 範本 changelogkit capabilities [--json] # 列出此安裝版本的已知功能+changelogkit workflows [--json] [--check] # 掃描 GitHub Actions action runtime ``` `add` 的標題是唯一的位置參數;內文用 `--problem`/`--cause`/`--change` 提供。各節第一行是摘要(會接在 `### 問題 - …` 等標題後),其餘行是細節;`--change` 可重複,第一筆當摘要、其餘轉成條列;`--change-detail` 在修改摘要下補一段多行說明。Web 表單分「修改摘要」(單行)、「修改細節」(段落)、「其他修改」(每行一項)。只給標題時插入空骨架。@@ -187,6 +188,24 @@ exclude = ["**/dist/**", "**/*.min.js"] # 排除(例如建置產 > > API 卡片去重:同一個 repo、同目錄且同檔名基底的 `.d.ts` 與 `.js`/`.mjs`/`.cjs`,若同名同種類,只保留 `.d.ts`;不同目錄或不同種類(例如 interface/class)不會互刪。 +## Workflow 健康檢查(GitHub Actions)++repo 有 `.github/workflows` 時會自動提供 `/workflows` 頁面與靜態站 `development/workflows.html`。本地掃描 action 參照不需要 token;runtime 查詢需要 GitHub 認證:++- 本機優先使用已登入的 `gh api`(`gh auth login` 即可)。+- CI 使用標準 `GITHUB_TOKEN`/`GH_TOKEN`。+- **不要在 `.changelog.toml` 放 token**。+- 沒有認證或查詢失敗時,runtime 顯示 `unknown`,頁面仍可用。++```toml+[tool.changelog.workflows]+enabled = true # 有 workflow 目錄時自動啟用;false 可關閉+runtime = true # 設 false 只做本地掃描,不查 runtime+# path = ".github/workflows" # 選填:自訂目錄+```++`node12`/`node16`/`node20` 會標成 EOL Node;`node24`、composite、Docker 與重用 workflow 會顯示各自狀態。CLI 可用 `changelogkit workflows --check` 在 EOL runtime 時回傳 1。+ ## 外部 API 文件(選填) 可以把 Doxygen、Sphinx、Go doc、pdoc 等產生的 HTML,或多個外部 API 站掛進 changelogkit。沒有設定時完全維持現狀;`kind` 只是未來深連結 adapter 的提示,**純掛載不需要指定**。diff --git a/pyproject.toml b/pyproject.toml--- a/pyproject.toml+++ b/pyproject.toml@@ -4,7 +4,7 @@ build-backend = "hatchling.build" [project] name = "changelogkit"-version = "0.13.4"+version = "0.14.0" description = "本機變更歷史 GUI 與開發索引:解析 ChangeHistory.md、唯讀索引 Git/文件/API 宣告" readme = "README.md" requires-python = ">=3.10"diff --git a/src/changelogkit/__init__.py b/src/changelogkit/__init__.py--- a/src/changelogkit/__init__.py+++ b/src/changelogkit/__init__.py@@ -53,4 +53,4 @@ def _installed_version(): # 版號來源優先序:原始碼 checkout 的 pyproject → 已安裝中介資料 → 字面值備援。 # 優先原始碼,讓 `PYTHONPATH=src` 直接跑時「所見即所跑」,不被環境中殘留的舊安裝誤導。-__version__ = _pyproject_version() or _installed_version() or "0.13.4"+__version__ = _pyproject_version() or _installed_version() or "0.14.0"diff --git a/src/changelogkit/assets/dev.css b/src/changelogkit/assets/dev.css--- a/src/changelogkit/assets/dev.css+++ b/src/changelogkit/assets/dev.css@@ -221,3 +221,17 @@ h3.group { .appbar .todo-index-wrap > summary::after { content: " ▾"; color: var(--mut) } .appbar .todo-index-wrap[open] > summary { border-color: var(--accent) } .appbar .todo-index-wrap #todo-index { position: absolute; top: calc(100% + 6px); right: 0; width: min(520px, calc(100vw - 24px)); max-height: 55vh; overflow: auto; background: var(--card); border: 1px solid var(--line); border-radius: 10px; box-shadow: var(--shadow); padding: 10px; margin: 0; z-index: 30 }++/* Workflow 健康檢查:本地 action 參照與 runtime 狀態。 */+.workflow-summary { margin: 12px 0 }+.workflow-summary p { margin: 6px 0 }+.workflow-table-wrap { overflow: auto; margin: 12px 0 30px }+.workflow-table { width: 100%; border-collapse: collapse; font-size: 13px }+.workflow-table th, .workflow-table td { border: 1px solid var(--line); padding: 7px 9px; text-align: left; vertical-align: top }+.workflow-table th { background: var(--code); font-weight: 600 }+.workflow-table code { overflow-wrap: anywhere }+.wf-badge { display: inline-block; padding: 2px 7px; border: 1px solid var(--line); border-radius: 999px; font-size: 12px; white-space: nowrap }+.wf-ok { color: var(--ok, #2e7d32); border-color: currentColor }+.wf-eol { color: var(--warn); border-color: currentColor }+.wf-unknown { color: var(--mut); border-color: currentColor }+.wf-local, .wf-docker, .wf-workflow { color: var(--accent); border-color: currentColor }diff --git a/src/changelogkit/assets/dev.html b/src/changelogkit/assets/dev.html--- a/src/changelogkit/assets/dev.html+++ b/src/changelogkit/assets/dev.html@@ -15,6 +15,7 @@ <a href="/about" data-i18n="nav.about">{{t.nav.about}}</a>TODO"> TODOPython API"> Python API+ {{workflows_link}} <input id="search" aria-label="{{t.dev.search}}" data-i18n-aria="dev.search" placeholder="{{t.dev.search}}" data-i18n-ph="dev.search"> <select id="repo" aria-label="{{t.dev.repo_all}}" data-i18n-aria="dev.repo_all"><option value="" data-i18n="dev.repo_all">{{t.dev.repo_all}}</option></select> <button id="reload" aria-label="{{t.dev.reload}}" data-i18n-aria="dev.reload" title="{{t.dev.reload}}" data-i18n-title="dev.reload">↻</button>diff --git a/src/changelogkit/assets/static_dev.html b/src/changelogkit/assets/static_dev.html--- a/src/changelogkit/assets/static_dev.html+++ b/src/changelogkit/assets/static_dev.html@@ -19,6 +19,7 @@ <a href="../../../about/" data-i18n="nav.about">{{t.nav.about}}</a>TODO"> TODOPython API"> Python API+ {{workflows_link}} <a href="../../../development/symbols.html" data-i18n="tab.symbols">{{t.tab.symbols}}</a> <a href="../../../development/repos.html" data-i18n="tab.repos">{{t.tab.repos}}</a> <span class="spacer"></span>diff --git a/src/changelogkit/assets/static_workflows.html b/src/changelogkit/assets/static_workflows.html--- /dev/null+++ b/src/changelogkit/assets/static_workflows.html@@ -0,0 +1,29 @@+<!doctype html>+<html lang="{{lang_html}}"><head>+<meta charset="utf-8">+<meta name="viewport" content="width=device-width,initial-scale=1">+<title>{{project}} · {{t.workflows.title}}</title>+<meta name="generator" content="changelogkit">+<script src="../../../assets/theme.js"></script>+<script>window.CK_LOCALES = {{CK_LOCALES}}; window.CK_LOCALE = "{{CK_LOCALE}}";</script>+<script src="../../../assets/i18n.js"></script>+<link rel="stylesheet" href="../../../assets/theme.css">+<link rel="stylesheet" href="../../../assets/dev.css">+</head><body>+<header class="appbar">+ <h1 data-i18n="workflows.title">{{t.workflows.title}}</h1>+ <a href="../../../" data-i18n="nav.history">{{t.nav.history}}</a>+ <a href="../../../development/" data-i18n="nav.dev">{{t.nav.dev}}</a>+ <a href="../../../about/" data-i18n="nav.about">{{t.nav.about}}</a>TODO">+ TODOPython API">+ Python API+ <span class="spacer"></span>+ <button id="locale" type="button">🌐</button>+ <button id="theme" aria-label="{{t.btn.theme}}" data-i18n-aria="btn.theme" title="{{t.btn.theme}}" data-i18n-title="btn.theme">🌙</button>+</header>+<main>+ <p class="muted" data-i18n="workflows.hint">{{hint}}</p>+ {{content}}+</main>TwhomeGH/ChangeLogKit@a42a0db · </footer>">+<footer class="built">Generated by TwhomeGH/ChangeLogKit@a42a0db · </footer>+</body></html>diff --git a/src/changelogkit/assets/workflows.html b/src/changelogkit/assets/workflows.html--- /dev/null+++ b/src/changelogkit/assets/workflows.html@@ -0,0 +1,27 @@+<!doctype html>+<html lang="{{lang_html}}"><head>+<meta charset="utf-8">+<meta name="viewport" content="width=device-width,initial-scale=1">+<title data-i18n-doc="workflows.title" data-project="{{project}}">{{project}} · {{t.workflows.title}}</title>+<script src="/assets/theme.js"></script>+<script>window.CK_LOCALES = {{CK_LOCALES}}; window.CK_LOCALE = "{{CK_LOCALE}}";</script>+<script src="/assets/i18n.js"></script>+<link rel="stylesheet" href="/assets/theme.css">+<link rel="stylesheet" href="/assets/dev.css">+</head><body>+<header class="appbar">+ <h1 data-i18n="workflows.title">{{t.workflows.title}}</h1>+ <a href="/" data-i18n="nav.history">{{t.nav.history}}</a>+ <a href="/development" data-i18n="nav.dev">{{t.nav.dev}}</a>+ <a href="/about" data-i18n="nav.about">{{t.nav.about}}</a>TODO">+ TODOPython API">+ Python API+ <span class="spacer"></span>+ <button id="locale" type="button">🌐</button>+ <button id="theme" aria-label="{{t.btn.theme}}" data-i18n-aria="btn.theme" title="{{t.btn.theme}}" data-i18n-title="btn.theme">🌙</button>+</header>+<main>+ <p class="muted" data-i18n="workflows.hint">{{hint}}</p>+ {{content}}+</main>+</body></html>diff --git a/src/changelogkit/capabilities.py b/src/changelogkit/capabilities.py--- a/src/changelogkit/capabilities.py+++ b/src/changelogkit/capabilities.py@@ -106,6 +106,14 @@ FEATURES = [ "surfaces": ["cli"], "commands": ["capabilities"], },+ {+ "id": "workflows.health",+ "since": "0.14.0",+ "summary": "Scan GitHub Actions refs and optionally check action runtimes for EOL Node.",+ "surfaces": ["cli", "web", "static"],+ "config": ["workflows"],+ "commands": ["workflows"],+ }, ] COMMANDS = [@@ -123,6 +131,7 @@ COMMANDS = [ "sort", "community-init", "capabilities",+ "workflows", ] CONFIG_KEYS = [diff --git a/src/changelogkit/cli.py b/src/changelogkit/cli.py--- a/src/changelogkit/cli.py+++ b/src/changelogkit/cli.py@@ -5,6 +5,7 @@ """ import argparse+import json import sys from . import (@@ -17,6 +18,7 @@ from . import ( history, i18n, server,+ workflows, ) @@ -30,6 +32,37 @@ def _prescan_locale(argv): return None +def cmd_workflows(args):+ """掃描 workflow actions;--check 遇到 EOL runtime 回 1。"""+ data = workflows.report(config.load())+ if args.json:+ print(json.dumps(data, ensure_ascii=False, indent=2))+ else:+ for action in data["actions"]:+ runtime = action["runtime"] or "—"+ print(+ "%-32s:%-4s %-34s %-10s %s"+ % (+ action["workflow"],+ action["line"],+ action["uses"],+ runtime,+ action["status"],+ )+ )+ print(+ "workflows: %d actions · %d EOL · %d unknown"+ % (+ len(data["actions"]),+ data["summary"].get("eol", 0),+ data["summary"].get("unknown", 0),+ )+ )+ if args.check and data["summary"].get("eol"):+ return 1+ return 0++ def cmd_capabilities(args): """印出目前版本的能力清單;``--json`` 供技能與腳本解析。""" print(capabilities.dumps() if args.json else capabilities.render())@@ -289,6 +322,10 @@ def main(argv=None): cap = sub.add_parser("capabilities", help=i18n.t("cli.capabilities.help")) cap.add_argument("--json", action="store_true", help=i18n.t("cli.capabilities.json")) + wf = sub.add_parser("workflows", help=i18n.t("cli.workflows.help"))+ wf.add_argument("--json", action="store_true", help=i18n.t("cli.workflows.json"))+ wf.add_argument("--check", action="store_true", help=i18n.t("cli.workflows.check"))+ dc = sub.add_parser("docs", help=i18n.t("cli.docs.help")) dc.add_argument("--check", action="store_true", help=i18n.t("cli.docs.check")) dc.add_argument("--summary", action="store_true", help=i18n.t("cli.docs.summary"))@@ -336,6 +373,10 @@ def main(argv=None): cmd_locales(args) elif args.cmd == "capabilities": cmd_capabilities(args)+ elif args.cmd == "workflows":+ code = cmd_workflows(args)+ if code:+ raise SystemExit(code) elif args.cmd == "docs": raise SystemExit(cmd_docs(args)) elif args.cmd == "docs-init":diff --git a/src/changelogkit/config.py b/src/changelogkit/config.py--- a/src/changelogkit/config.py+++ b/src/changelogkit/config.py@@ -100,6 +100,9 @@ class Config: todo: Path | None = None # 選填:待辦 markdown(存在才顯示入口) api: list = field(default_factory=list) # 選填:外部 API 文件站(ApiDoc) api_warnings: list = field(default_factory=list) # API 設定問題(不致命)+ workflows: Path | None = None # 選填:GitHub Actions workflow 目錄+ workflow_runtime: bool = True # 是否查詢 action runtime+ workflow_warnings: list = field(default_factory=list) # workflow 設定問題 def _find_root(start):@@ -119,6 +122,7 @@ def _default_config(root): project=root.name, timezone="local", todo=_auto_todo(root),+ workflows=_auto_workflows(root), history=root / DEFAULT_HISTORY, features=root / DEFAULT_FEATURES, community=root / DEFAULT_COMMUNITY,@@ -145,6 +149,12 @@ def _find_named(directory, name): return None +def _auto_workflows(root):+ """repo 有 GitHub Actions workflow 目錄時自動啟用。"""+ path = root / ".github" / "workflows"+ return path if path.is_dir() else None++ def _auto_todo(root): """沒有設定時自動找 ``TODO.md``:repo 根目錄 → ``Docs`` → ``docs``。""" for directory in (root, root / "Docs", root / "docs"):@@ -325,6 +335,28 @@ def _from_table(root, table): else: todo = _auto_todo(root) api, api_warnings = _api_docs(root, table.get("api", []))+ workflow_warnings = []+ workflow_table = table.get("workflows", None)+ workflow_runtime = True+ if workflow_table is False:+ workflows = None+ elif isinstance(workflow_table, str):+ workflows = _resolve(root, workflow_table.strip())+ elif isinstance(workflow_table, dict):+ enabled = workflow_table.get("enabled", True) is not False+ workflow_runtime = workflow_table.get("runtime", True) is not False+ value = workflow_table.get("path")+ if not enabled:+ workflows = None+ elif isinstance(value, str) and value.strip():+ workflows = _resolve(root, value.strip())+ else:+ workflows = _auto_workflows(root)+ else:+ workflows = _auto_workflows(root)+ if workflows is not None and not workflows.is_dir():+ workflow_warnings.append("workflow 目錄不存在或不是目錄:%s" % workflows)+ workflows = None return Config( root=root, title=table.get("title") or root.name,@@ -345,6 +377,9 @@ def _from_table(root, table): recent_commits=recent, api=api, api_warnings=api_warnings,+ workflows=workflows,+ workflow_runtime=workflow_runtime,+ workflow_warnings=workflow_warnings, ) diff --git a/src/changelogkit/export.py b/src/changelogkit/export.py--- a/src/changelogkit/export.py+++ b/src/changelogkit/export.py@@ -22,7 +22,7 @@ from pathlib import Path from typing import cast from urllib.parse import quote -from . import apidocs, assets, buildinfo, community, config, docs as docmeta, history, i18n, index+from . import apidocs, assets, buildinfo, community, config, docs as docmeta, history, i18n, index, workflows from . import todo as todo_meta # 需要複製到輸出 assets/ 的檔案(其餘為 server 動態用,不需要)。@@ -575,6 +575,15 @@ def export(out_dir, branch="main"): """靜態頁導覽的 API 文件連結;沒有可用站點時空字串。""" return apidocs.nav_html(static_api, base) + def workflows_link(base):+ """靜態頁導覽的 workflow 健康檢查連結。"""+ if not cfg.workflows:+ return ""+ return '<a href="%sdevelopment/workflows.html" data-i18n="nav.workflows">%s</a>' % (+ base,+ _esc(i18n.t("nav.workflows")),+ )+ hist_content, count = _render_history(cfg) (out / "index.html").write_text( assets.render(@@ -615,6 +624,24 @@ def export(out_dir, branch="main"): doc_repo=json.dumps(index.default_repo(), ensure_ascii=False), todo_link=todo_link("../"), api_nav=api_nav("../"),+ workflows_link=workflows_link("../"),+ ),+ encoding="utf-8",+ )++ workflow_data = workflows.report(cfg)+ (out / "development" / "workflows.html").write_text(+ assets.render(+ "static_workflows.html",+ **i18n.subs(),+ title=_esc(cfg.title),+ project=_esc(cfg.project),+ hint=_esc(i18n.t("workflows.hint")),+ content=workflows.render(workflow_data),+ footer=footer,+ base="../",+ todo_link=todo_link("../"),+ api_nav=api_nav("../"), ), encoding="utf-8", )diff --git a/src/changelogkit/index.py b/src/changelogkit/index.py--- a/src/changelogkit/index.py+++ b/src/changelogkit/index.py@@ -17,7 +17,7 @@ import subprocess from pathlib import Path, PurePosixPath from urllib.parse import parse_qs -from . import apidocs, assets, config, docs as docmeta, i18n+from . import apidocs, assets, config, docs as docmeta, i18n, workflows from .globs import regex as _glob_re from .scanners import SUPPORTED_LANGUAGES, SUPPORTED_SUFFIXES, scan_symbols from .scanners.common import link@@ -409,6 +409,32 @@ def api_nav(): return apidocs.nav_html(config.load().api, "/") +def workflows_link():+ """有 workflow 目錄時回傳健康檢查頁連結。"""+ cfg = config.load()+ if not cfg.workflows:+ return ""+ return '<a href="/workflows" data-i18n="nav.workflows">%s</a>' % html.escape(i18n.t("nav.workflows"))+++def workflows_page():+ """動態 workflow 健康檢查頁;runtime 查詢失敗不影響頁面。"""+ cfg = config.load()+ data = workflows.report(cfg)+ return assets.render(+ "workflows.html",+ title=html.escape(cfg.title),+ project=html.escape(cfg.project),+ content=workflows.render(data),+ hint=html.escape(i18n.t("workflows.hint")),+ project_title=html.escape(cfg.project),+ todo_link=todo_link(),+ api_nav=api_nav(),+ i18n_json=json.dumps(i18n.js_dict(), ensure_ascii=False),+ **i18n.subs(),+ )++ def _file_page(repo, name, line): """組出檔案檢視頁(含行號、目標行與語法上色用的 .code 容器)。""" source = safe_file(repo, name).read_text(encoding="utf-8", errors="replace")@@ -444,6 +470,7 @@ def route(path, query): project=html.escape(config.load().project), todo_link=todo_link(), api_nav=api_nav(),+ workflows_link=workflows_link(), **i18n.subs(), ), "text/html; charset=utf-8",diff --git a/src/changelogkit/lang/en.json b/src/changelogkit/lang/en.json--- a/src/changelogkit/lang/en.json+++ b/src/changelogkit/lang/en.json@@ -30,6 +30,9 @@ "cli.locales.help": "List supported UI languages", "cli.capabilities.help": "List known features supported by this installation", "cli.capabilities.json": "Machine-readable JSON (for skills and scripts)",+ "cli.workflows.help": "Scan GitHub Actions workflows for action runtime issues",+ "cli.workflows.json": "Machine-readable JSON",+ "cli.workflows.check": "Exit 1 when an action uses an EOL Node runtime", "cli.docs.help": "Check document grouping or print a starter config", "cli.docs.check": "Validate and list resolved groups (default)", "cli.docs.summary": "Only show group counts",@@ -77,6 +80,24 @@ "nav.about": "About", "nav.docs": "Documents", "nav.api": "API docs",+ "nav.workflows": "Workflow health",+ "workflows.title": "Workflow health",+ "workflows.hint": "Action references are scanned locally; runtimes are checked from each action's action.yml when GitHub auth is available.",+ "workflows.summary": "{actions} actions · {eol} EOL Node · {unknown} unknown",+ "workflows.file": "Workflow",+ "workflows.action": "Action",+ "workflows.ref": "Ref",+ "workflows.runtime": "Runtime",+ "workflows.status": "Status",+ "workflows.empty": "No actions found in this workflow directory.",+ "workflows.no_auth": "No GitHub auth found; runtime is unknown. Run gh auth login or set GITHUB_TOKEN.",+ "workflows.runtime_disabled": "Runtime lookup is disabled by configuration.",+ "workflows.ok": "OK",+ "workflows.eol": "EOL Node",+ "workflows.unknown": "Unknown",+ "workflows.local": "Local action",+ "workflows.docker": "Docker action",+ "workflows.workflow": "Reusable workflow", "btn.edit": "Edit", "btn.delete": "Delete", "btn.save": "Save",diff --git a/src/changelogkit/lang/ja.json b/src/changelogkit/lang/ja.json--- a/src/changelogkit/lang/ja.json+++ b/src/changelogkit/lang/ja.json@@ -30,6 +30,9 @@ "cli.locales.help": "対応 UI 言語を一覧", "cli.capabilities.help": "このインストールで利用できる既知の機能を一覧", "cli.capabilities.json": "機械可読 JSON(スキル/スクリプト用)",+ "cli.workflows.help": "GitHub Actions workflow の action runtime を走査",+ "cli.workflows.json": "機械可読 JSON を出力",+ "cli.workflows.check": "EOL Node の action があれば 1 を返す", "cli.docs.help": "ドキュメント分類を検査、または開始設定を出力", "cli.docs.check": "解決後のグループを検証・一覧(既定)", "cli.docs.summary": "グループ数だけ表示",@@ -77,6 +80,24 @@ "nav.about": "このツールについて", "nav.docs": "ドキュメント", "nav.api": "API ドキュメント",+ "nav.workflows": "Workflow 健全性",+ "workflows.title": "Workflow 健全性チェック",+ "workflows.hint": "action 参照はローカルで走査し、GitHub 認証がある場合は各 action の action.yml から runtime を確認します。",+ "workflows.summary": "{actions} actions · {eol} EOL Node · {unknown} unknown",+ "workflows.file": "Workflow",+ "workflows.action": "Action",+ "workflows.ref": "Ref",+ "workflows.runtime": "Runtime",+ "workflows.status": "状態",+ "workflows.empty": "この workflow ディレクトリに action はありません。",+ "workflows.no_auth": "GitHub 認証が見つかりません。runtime は unknown です。gh auth login か GITHUB_TOKEN を設定してください。",+ "workflows.runtime_disabled": "設定で runtime 検索が無効です。",+ "workflows.ok": "OK",+ "workflows.eol": "EOL Node",+ "workflows.unknown": "Unknown",+ "workflows.local": "ローカル action",+ "workflows.docker": "Docker action",+ "workflows.workflow": "再利用 workflow", "btn.edit": "編集", "btn.delete": "削除", "btn.save": "保存",diff --git a/src/changelogkit/lang/zh-CN.json b/src/changelogkit/lang/zh-CN.json--- a/src/changelogkit/lang/zh-CN.json+++ b/src/changelogkit/lang/zh-CN.json@@ -30,6 +30,9 @@ "cli.locales.help": "列出支持的 UI 语言", "cli.capabilities.help": "列出此安装版本支持的已知功能", "cli.capabilities.json": "机器可读 JSON(供技能与脚本使用)",+ "cli.workflows.help": "扫描 GitHub Actions workflow 的 action runtime",+ "cli.workflows.json": "输出机器可读 JSON",+ "cli.workflows.check": "有 action 使用 EOL Node 时返回 1", "cli.docs.help": "检查文档分类,或打印起始设置", "cli.docs.check": "验证并列出解析后的群组(默认)", "cli.docs.summary": "只显示群组数量",@@ -77,6 +80,24 @@ "nav.about": "关于", "nav.docs": "文档", "nav.api": "API 文档",+ "nav.workflows": "Workflow 健康",+ "workflows.title": "Workflow 健康检查",+ "workflows.hint": "本地扫描 action 引用;有 GitHub 认证时,从各 action 的 action.yml 查询 runtime。",+ "workflows.summary": "{actions} 个 action · {eol} 个 EOL Node · {unknown} 个未知",+ "workflows.file": "Workflow",+ "workflows.action": "Action",+ "workflows.ref": "Ref",+ "workflows.runtime": "Runtime",+ "workflows.status": "状态",+ "workflows.empty": "这个 workflow 目录没有找到 action。",+ "workflows.no_auth": "找不到 GitHub 认证;runtime 显示为未知。可执行 gh auth login 或设置 GITHUB_TOKEN。",+ "workflows.runtime_disabled": "设置已关闭 runtime 查询。",+ "workflows.ok": "正常",+ "workflows.eol": "EOL Node",+ "workflows.unknown": "未知",+ "workflows.local": "本地 action",+ "workflows.docker": "Docker action",+ "workflows.workflow": "可复用 workflow", "btn.edit": "编辑", "btn.delete": "删除", "btn.save": "保存",diff --git a/src/changelogkit/lang/zh-TW.json b/src/changelogkit/lang/zh-TW.json--- a/src/changelogkit/lang/zh-TW.json+++ b/src/changelogkit/lang/zh-TW.json@@ -30,6 +30,9 @@ "cli.locales.help": "列出支援的 UI 語系", "cli.capabilities.help": "列出此安裝版本支援的已知功能", "cli.capabilities.json": "機器可讀 JSON(供技能與腳本使用)",+ "cli.workflows.help": "掃描 GitHub Actions workflow 的 action runtime",+ "cli.workflows.json": "輸出機器可讀 JSON",+ "cli.workflows.check": "有 action 使用 EOL Node 時回傳 1", "cli.docs.help": "檢查文件分類,或印出起始設定", "cli.docs.check": "驗證並列出解析後的群組(預設)", "cli.docs.summary": "只顯示群組數量",@@ -77,6 +80,24 @@ "nav.about": "關於", "nav.docs": "文件", "nav.api": "API 文件",+ "nav.workflows": "Workflow 健康",+ "workflows.title": "Workflow 健康檢查",+ "workflows.hint": "本地掃描 action 參照;有 GitHub 認證時,從各 action 的 action.yml 查詢 runtime。",+ "workflows.summary": "{actions} 個 action · {eol} 個 EOL Node · {unknown} 個未知",+ "workflows.file": "Workflow",+ "workflows.action": "Action",+ "workflows.ref": "Ref",+ "workflows.runtime": "Runtime",+ "workflows.status": "狀態",+ "workflows.empty": "這個 workflow 目錄沒有找到 action。",+ "workflows.no_auth": "找不到 GitHub 認證;runtime 顯示為未知。可執行 gh auth login 或設定 GITHUB_TOKEN。",+ "workflows.runtime_disabled": "設定已關閉 runtime 查詢。",+ "workflows.ok": "正常",+ "workflows.eol": "EOL Node",+ "workflows.unknown": "未知",+ "workflows.local": "本地 action",+ "workflows.docker": "Docker action",+ "workflows.workflow": "可重用 workflow", "btn.edit": "編輯", "btn.delete": "刪除", "btn.save": "儲存",diff --git a/src/changelogkit/server.py b/src/changelogkit/server.py--- a/src/changelogkit/server.py+++ b/src/changelogkit/server.py@@ -155,6 +155,8 @@ class Handler(BaseHTTPRequestHandler): ), "application/json; charset=utf-8", )+ if u.path == "/workflows":+ return self._send(200, index.workflows_page(), "text/html; charset=utf-8") if u.path == "/about": # 社群區塊:未設定或無檔時為空字串(不顯示);卡片說明的連結以該檔目錄為基準。 block = community.html_block(community.load(), i18n.t("about.community_title"))diff --git a/src/changelogkit/workflows.py b/src/changelogkit/workflows.py--- /dev/null+++ b/src/changelogkit/workflows.py@@ -0,0 +1,327 @@+"""GitHub Actions workflow scan and optional action-runtime enrichment.++Local refs are always available without network. Runtime metadata lives in+each action repository's ``action.yml``; it is fetched only when a GitHub+token or an authenticated ``gh`` CLI is available. Without either, runtime is+reported as ``unknown`` rather than guessed.+"""++import base64+import html+import json+import os+import re+import shutil+import subprocess+import time+import urllib.error+import urllib.parse+import urllib.request++from . import i18n++API = "https://api.github.com"+EOL_NODES = {"node12", "node16", "node20"}+CACHE_TTL = 600+_cache = {}+_USES = re.compile(r"^\s*(?:-\s*)?uses:\s*[\"']?([^\"'\s#]+)")+++def _esc(value):+ return html.escape(str(value or ""), quote=True)+++def _auth_mode():+ """回傳 env/gh/none;不讀取或回傳 token 本身。"""+ if os.environ.get("GITHUB_TOKEN") or os.environ.get("GH_TOKEN"):+ return "env"+ if shutil.which("gh"):+ return "gh"+ return "none"+++def _http_json(endpoint, token):+ request = urllib.request.Request(+ API + endpoint,+ headers={+ "Authorization": "Bearer " + token,+ "Accept": "application/vnd.github+json",+ "User-Agent": "changelogkit-workflows",+ },+ )+ with urllib.request.urlopen(request, timeout=15) as response:+ return json.load(response)+++def _gh_json(endpoint):+ """用已登入的 gh CLI 查詢;不把 token 帶進 changelogkit process。"""+ try:+ result = subprocess.run(+ ["gh", "api", endpoint],+ capture_output=True,+ text=True,+ timeout=20,+ )+ except (OSError, subprocess.SubprocessError):+ return None+ if result.returncode:+ return None+ try:+ return json.loads(result.stdout)+ except json.JSONDecodeError:+ return None+++def _fetch_action_yml(repo, action_path, ref):+ """取得 action.yml 內容;回傳 ``(text, reason)``。"""+ mode = _auth_mode()+ if mode == "none":+ return None, "no-auth"+ token = os.environ.get("GITHUB_TOKEN") or os.environ.get("GH_TOKEN")+ names = []+ if action_path:+ names.append(action_path.rstrip("/") + "/action.yml")+ names.append(action_path.rstrip("/") + "/action.yaml")+ names += ["action.yml", "action.yaml"]+ for name in names:+ query = urllib.parse.urlencode({"ref": ref})+ endpoint = "/repos/%s/contents/%s?%s" % (repo, name, query)+ data = None+ if token:+ try:+ data = _http_json(endpoint, token)+ except urllib.error.HTTPError as error:+ if error.code == 404:+ continue+ return None, "http-%d" % error.code+ except (OSError, ValueError):+ return None, "network"+ else:+ data = _gh_json(endpoint)+ if data is None:+ return None, "gh-auth"+ if not isinstance(data, dict) or not data.get("content"):+ continue+ try:+ return base64.b64decode(data["content"]).decode("utf-8", errors="replace"), ""+ except (ValueError, TypeError):+ continue+ return None, "metadata-missing"+++def _runtime(repo, action_path, ref):+ """查詢 action runtime,回傳 ``(runtime, reason)``。"""+ key = (repo, action_path, ref)+ now = time.monotonic()+ cached = _cache.get(key)+ if cached and now - cached[0] < CACHE_TTL:+ return cached[1], cached[2]+ text, reason = _fetch_action_yml(repo, action_path, ref)+ if text is None:+ result = ("", reason)+ else:+ match = re.search(r"^\s*using:\s*['\"]?([A-Za-z0-9_-]+)", text, re.MULTILINE)+ result = ((match.group(1).lower() if match else ""), "" if match else "using-missing")+ _cache[key] = (now, result[0], result[1])+ return result+++def clear_cache():+ """測試或需要重新查詢時清空 runtime cache。"""+ _cache.clear()+++def classify(runtime, kind="action"):+ """把 runtime 轉成頁面狀態;未知值不猜測。"""+ if kind == "local":+ return "local"+ if kind == "docker":+ return "docker"+ if kind == "workflow":+ return "workflow"+ value = str(runtime or "").strip().lower()+ if value in EOL_NODES:+ return "eol"+ if value.startswith("node"):+ digits = value[4:]+ if digits.isdigit() and int(digits) >= 24:+ return "ok"+ if value in ("composite", "docker"):+ return "ok"+ return "unknown"+++def _parse_uses(uses):+ """拆解 ``owner/repo[/path]@ref``;不支援的值回傳 kind=unknown。"""+ if uses.startswith("./"):+ return {"kind": "local", "repo": "", "path": uses[2:], "ref": ""}+ if uses.startswith("docker://"):+ return {"kind": "docker", "repo": "", "path": uses[len("docker://") :], "ref": ""}+ if "@" not in uses:+ return {"kind": "unknown", "repo": "", "path": uses, "ref": ""}+ target, ref = uses.rsplit("@", 1)+ parts = target.split("/")+ if len(parts) < 2:+ return {"kind": "unknown", "repo": target, "path": "", "ref": ref}+ repo = "/".join(parts[:2])+ action_path = "/".join(parts[2:])+ kind = "workflow" if ".github/workflows/" in action_path else "action"+ return {"kind": kind, "repo": repo, "path": action_path, "ref": ref}+++def scan(cfg):+ """掃描 workflow 檔案;只做本地解析,不呼叫網路。"""+ root = cfg.workflows+ data = {"files": [], "actions": [], "auth": _auth_mode(), "warnings": list(cfg.workflow_warnings)}+ if not root:+ return data+ paths = sorted(list(root.glob("*.yml")) + list(root.glob("*.yaml")))+ for path in paths:+ try:+ lines = path.read_text(encoding="utf-8", errors="replace").splitlines()+ except OSError:+ data["warnings"].append("無法讀取 workflow:%s" % path)+ continue+ rel = path.relative_to(cfg.root).as_posix() if path.is_relative_to(cfg.root) else path.as_posix()+ data["files"].append(rel)+ for line_no, line in enumerate(lines, 1):+ if line.lstrip().startswith("#"):+ continue+ match = _USES.match(line)+ if not match:+ continue+ uses = match.group(1).strip()+ if not uses:+ continue+ parsed = _parse_uses(uses)+ data["actions"].append(+ {+ "workflow": rel,+ "line": line_no,+ "uses": uses,+ "kind": parsed["kind"],+ "repo": parsed["repo"],+ "path": parsed["path"],+ "ref": parsed["ref"],+ "runtime": "",+ "status": classify("", parsed["kind"]),+ "reason": "",+ }+ )+ return data+++def enrich(cfg, data):+ """在 scan 結果上補 runtime;沒有認證或關閉時保留 unknown。"""+ if not cfg.workflow_runtime:+ for action in data["actions"]:+ if action["kind"] == "action":+ action["reason"] = "runtime-disabled"+ data["auth"] = "disabled"+ return data+ for action in data["actions"]:+ if action["kind"] != "action":+ continue+ runtime, reason = _runtime(action["repo"], action["path"], action["ref"])+ action["runtime"] = runtime+ action["status"] = classify(runtime, action["kind"])+ action["reason"] = reason+ return data+++def report(cfg):+ data = scan(cfg)+ enrich(cfg, data)+ data["summary"] = {+ status: sum(1 for action in data["actions"] if action["status"] == status)+ for status in ("ok", "eol", "unknown", "local", "docker", "workflow")+ }+ return data+++def _status_text(status):+ key = {+ "ok": "workflows.ok",+ "eol": "workflows.eol",+ "unknown": "workflows.unknown",+ "local": "workflows.local",+ "docker": "workflows.docker",+ "workflow": "workflows.workflow",+ }.get(status, "workflows.unknown")+ return i18n.t(key)+++def _source_link(action):+ repo = action.get("repo") or ""+ ref = action.get("ref") or ""+ if not repo or not ref:+ return _esc(action.get("uses") or "")+ url = "https://github.com/%s/tree/%s" % (repo, urllib.parse.quote(ref, safe=""))+ return '<a href="%s" rel="noopener">%s</a>' % (_esc(url), _esc(action.get("uses") or ""))+++def render(data):+ """把 workflow 掃描結果轉成唯讀 HTML(動態與靜態共用)。"""+ actions = data.get("actions") or []+ summary = data.get("summary") or {}+ parts = ['<section class="workflow-summary">']+ parts.append(+ '<span class="muted">%s</span>'+ % _esc(+ i18n.t(+ "workflows.summary",+ actions=len(actions),+ eol=summary.get("eol", 0),+ unknown=summary.get("unknown", 0),+ )+ )+ )+ if data.get("auth") == "none":+ parts.append(+ '<p class="docwarn" data-i18n="workflows.no_auth">%s</p>' % _esc(i18n.t("workflows.no_auth"))+ )+ elif data.get("auth") == "disabled":+ parts.append(+ '<p class="muted" data-i18n="workflows.runtime_disabled">%s</p>'+ % _esc(i18n.t("workflows.runtime_disabled"))+ )+ parts.append("</section>")+ if not actions:+ parts.append('<p class="empty" data-i18n="workflows.empty">%s</p>' % _esc(i18n.t("workflows.empty")))+ return "\n".join(parts)+ parts.append('<div class="workflow-table-wrap"><table class="workflow-table">')+ parts.append(+ "<thead><tr><th>%s</th><th>%s</th><th>%s</th><th>%s</th><th>%s</th></tr></thead><tbody>"+ % (+ _esc(i18n.t("workflows.file")),+ _esc(i18n.t("workflows.action")),+ _esc(i18n.t("workflows.ref")),+ _esc(i18n.t("workflows.runtime")),+ _esc(i18n.t("workflows.status")),+ )+ )+ for action in actions:+ runtime = action.get("runtime") or "—"+ reason = action.get("reason") or ""+ title = (' title="%s"' % _esc(reason)) if reason else ""+ parts.append(+ "<tr>"+ "<td><code>%s:%d</code></td>"+ "<td>%s</td>"+ "<td><code>%s</code></td>"+ "<td><code>%s</code></td>"+ '<td><span class="wf-badge wf-%s"%s>%s</span></td>'+ "</tr>"+ % (+ _esc(action.get("workflow")),+ action.get("line", 0),+ _source_link(action),+ _esc(action.get("ref") or "—"),+ _esc(runtime),+ _esc(action.get("status") or "unknown"),+ title,+ _esc(_status_text(action.get("status") or "unknown")),+ )+ )+ parts.append("</tbody></table></div>")+ return "\n".join(parts)diff --git a/tests/test_changelogkit.py b/tests/test_changelogkit.py--- a/tests/test_changelogkit.py+++ b/tests/test_changelogkit.py@@ -39,6 +39,7 @@ from changelogkit import ( # noqa: E402 index, server, todo,+ workflows, ) SAMPLE = """# 變更歷史@@ -294,6 +295,21 @@ embed = true with self.assertRaises(ValueError): export.export(repo.root / "site") + def test_workflows_auto_and_disable(self):+ with TempRepo() as repo:+ workflow = repo.root / ".github" / "workflows" / "ci.yml"+ workflow.parent.mkdir(parents=True)+ workflow.write_text("name: CI\n", encoding="utf-8")+ config.reset()+ self.assertEqual(config.load(repo.root).workflows, workflow.parent)++ (repo.root / ".changelog.toml").write_text(+ TOML + "[tool.changelog.workflows]\nenabled = false\n",+ encoding="utf-8",+ )+ config.reset()+ self.assertIsNone(config.load(repo.root).workflows)+ def test_todo_path(self): with TempRepo() as repo: self.assertIsNone(config.load().todo)@@ -360,6 +376,81 @@ embed = true self.assertEqual(cfg.doc_entries[0].note, "安裝") +class WorkflowTests(unittest.TestCase):+ def test_scan_and_runtime_enrichment(self):+ with TempRepo() as repo:+ path = repo.root / ".github" / "workflows" / "ci.yml"+ path.parent.mkdir(parents=True)+ path.write_text(+ "jobs:\n"+ " build:\n"+ " steps:\n"+ " - uses: actions/checkout@v5\n"+ " - uses: owner/custom@v1\n"+ " - uses: owner/repo/.github/workflows/reuse.yml@v1\n"+ " - uses: docker://alpine:3\n"+ " # uses: ignored/commented@v1\n",+ encoding="utf-8",+ )+ config.reset()+ cfg = config.load(repo.root)+ data = workflows.scan(cfg)+ self.assertEqual(len(data["actions"]), 4)+ self.assertEqual(data["actions"][0]["kind"], "action")+ self.assertEqual(data["actions"][2]["kind"], "workflow")+ self.assertEqual(data["actions"][3]["kind"], "docker")+ original = workflows._runtime+ workflows._runtime = lambda repo, path, ref: ("node20", "")+ try:+ workflows.enrich(cfg, data)+ finally:+ workflows._runtime = original+ self.assertEqual(data["actions"][0]["status"], "eol")+ self.assertEqual(workflows.classify("node24"), "ok")+ self.assertEqual(workflows.classify("node20"), "eol")++ def test_workflows_cli_json(self):+ with TempRepo() as repo:+ workflow = repo.root / ".github" / "workflows" / "ci.yml"+ workflow.parent.mkdir(parents=True)+ workflow.write_text(+ "jobs:\n build:\n steps:\n - uses: actions/checkout@v5\n", encoding="utf-8"+ )+ (repo.root / ".changelog.toml").write_text(+ TOML + "[tool.changelog.workflows]\nruntime = false\n",+ encoding="utf-8",+ )+ config.reset()+ config.load(repo.root)+ output = io.StringIO()+ with redirect_stdout(output):+ cli.main(["workflows", "--json"])+ data = json.loads(output.getvalue())+ self.assertEqual(data["actions"][0]["uses"], "actions/checkout@v5")+ self.assertEqual(data["actions"][0]["status"], "unknown")++ def test_workflows_page_and_export(self):+ with TempRepo() as repo:+ workflow = repo.root / ".github" / "workflows" / "ci.yml"+ workflow.parent.mkdir(parents=True)+ workflow.write_text(+ "jobs:\n build:\n steps:\n - uses: actions/checkout@v5\n", encoding="utf-8"+ )+ (repo.root / ".changelog.toml").write_text(+ TOML + "[tool.changelog.workflows]\nruntime = false\n",+ encoding="utf-8",+ )+ config.reset()+ config.load(repo.root)+ page = index.workflows_page()+ self.assertIn("actions/checkout@v5", page)+ out = repo.root / "_site"+ export.export(out)+ self.assertTrue((out / "development" / "workflows.html").is_file())+ dev = (out / "development" / "index.html").read_text(encoding="utf-8")+ self.assertIn("development/workflows.html", dev)++ class DevToolTests(unittest.TestCase): def test_build_env_prepends_source(self): env = dev_tool.build_env({"PYTHONPATH": "existing"})