import type { ExtensionAPI, ExtensionCommandContext } from "@earendil-works/pi-coding-agent"; import { loadCommitConfig } from "../config/load-config.ts"; import { setActiveTemplate } from "../config/update-config.ts"; import { tryResolveGitRepositoryRoot } from "../git/collect-changes.ts"; import { GitClient } from "../git/git-client.ts"; import { listTemplates } from "../templates/list-templates.ts"; const CANCELLED_MESSAGE = "Cancelled. The active template was not changed."; /** 构建选择器条目文本,模板名后追加来源与激活标记。 */ function buildTemplateLabel(name: string, source: "user" | "builtin", active: boolean): string { const markers: string[] = []; if (source === "builtin") { markers.push("built-in"); } if (active) { markers.push("active"); } return markers.length > 0 ? `${name} (${markers.join(", ")})` : name; } /** * 执行 /git-commit list 的模板切换工作流: * 列出全部模板供上下键选择,确认后按项目优先、全局兜底的顺序写入配置。 */ export async function runListTemplatesFlow( pi: ExtensionAPI, ctx: ExtensionCommandContext, ): Promise { // 模板管理不要求处于 Git 仓库中;不在仓库时仅操作全局配置。 const projectDir = await tryResolveGitRepositoryRoot(new GitClient(pi), ctx.cwd); const config = await loadCommitConfig(projectDir); const templates = await listTemplates(); if (templates.length === 0) { ctx.ui.notify("No templates were found. Create one with /git-commit add.", "warning"); return; } const labels = templates.map((template) => buildTemplateLabel(template.name, template.source, template.name === config.template), ); const choice = await ctx.ui.select("Select commit message template", labels); if (choice === undefined) { ctx.ui.notify(CANCELLED_MESSAGE, "info"); return; } // 模板名不含空格,标记后缀直接按首个空格截断即可还原。 const name = choice.split(" ", 1)[0] as string; if (name === config.template) { ctx.ui.notify(`Template "${name}" is already active.`, "info"); return; } const target = await setActiveTemplate(name, projectDir); const scopeText = target.scope === "project" ? "project configuration" : "global configuration"; ctx.ui.notify(`Template "${name}" activated in the ${scopeText}.\n${target.path}`, "info"); }