import type { ExtensionAPI, ExtensionCommandContext } from "@earendil-works/pi-coding-agent"; import { setActiveTemplate } from "../config/update-config.ts"; import { tryResolveGitRepositoryRoot } from "../git/collect-changes.ts"; import { GitClient } from "../git/git-client.ts"; import { isValidTemplateName } from "../templates/load-template.ts"; import { saveUserTemplate, userTemplateExists } from "../templates/save-template.ts"; const CANCELLED_MESSAGE = "Cancelled. No template was saved."; /** * 执行 /git-commit add 的模板创建工作流: * 输入名称、编辑内容、写入用户模板目录,并按需立即启用。 */ export async function runAddTemplateFlow( pi: ExtensionAPI, ctx: ExtensionCommandContext, ): Promise { const input = await ctx.ui.input("Template name (letters, digits, . _ -)"); // Esc 取消输入不是失败,保持与提交工作流一致的普通提示。 if (input === undefined) { ctx.ui.notify(CANCELLED_MESSAGE, "info"); return; } const name = input.trim(); if (!isValidTemplateName(name)) { throw new Error( `Template name "${name}" is invalid. Use letters, digits, dots, hyphens, or underscores, starting with a letter or digit.`, ); } const exists = await userTemplateExists(name); let overwrite = false; if (exists) { overwrite = await ctx.ui.confirm( "Overwrite template", `Template "${name}" already exists in your templates directory. Overwrite it?`, ); if (!overwrite) { ctx.ui.notify(CANCELLED_MESSAGE, "info"); return; } } const content = await ctx.ui.editor(`Template content for "${name}"`); if (content === undefined || !content.trim()) { ctx.ui.notify(CANCELLED_MESSAGE, "info"); return; } const path = await saveUserTemplate(name, content, { overwrite }); const useNow = await ctx.ui.confirm( "Activate template", `Template "${name}" was saved. Use it for future generations?`, ); if (useNow) { // 与 list 一致:项目配置存在时写项目层,否则写全局配置。 const projectDir = await tryResolveGitRepositoryRoot(new GitClient(pi), ctx.cwd); const target = await setActiveTemplate(name, projectDir); const scopeText = target.scope === "project" ? "project configuration" : "global configuration"; ctx.ui.notify(`Template "${name}" saved and activated in the ${scopeText}.\n${path}`, "info"); return; } ctx.ui.notify(`Template "${name}" saved.\n${path}`, "info"); }