import { readFileSync, writeFileSync } from "node:fs"; import { getWorkflowDetail, listAllWorkflows, updateWorkflow } from "../../../domains/platform/services.js"; import { WorkflowDetailSchema } from "../../../domains/platform/types.js"; import { applyWorkflowPathPatch, beginWorkflowSave, commitWorkflowSave, createWorkflowDraft, failWorkflowSave, hasWorkflowVersionConflict, } from "../../../domains/platform/workflow/state/index.js"; import { stringOption, booleanOption } from "../../parser.js"; import { createClientsForCorp, createPiperClientForCorp } from "../../helpers.js"; import { printJson } from "../../printer.js"; import { isDryRun, mutationPreview, requireMutationConfirmation } from "../../mutation.js"; import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js"; import { PLATFORM_ID_OPTION_KEYS } from "./shared.js"; export async function handlePatch(parsed: CliParsedArgs, runtime: CliRuntime): Promise { const pipelineId = parsed.args[0] || stringOption(parsed.options, ["id", "pipelineId"]); const file = stringOption(parsed.options, ["file", "input", "from"]); const path = stringOption(parsed.options, ["path", "field"]); const rawValue = parsed.options.value; const output = stringOption(parsed.options, ["output", "output-file", "outputFile"]); const inPlace = booleanOption(parsed.options, ["in-place", "inPlace"]); if (!pipelineId || !file || !path || typeof rawValue !== "string" || (!output && !inPlace)) { return { stdout: "", stderr: "用法: hose-use workflow patch --file= --path= --value=<值> (--output=|--in-place) [--value-json]\n", exitCode: 1, }; } let source: unknown; try { source = JSON.parse(readFileSync(file, "utf8")); } catch (error) { throw new Error(`无法读取工作流 JSON 文件 [${file}]: ${error instanceof Error ? error.message : String(error)}`); } const sourceWorkflow = WorkflowDetailSchema.parse(source); if (sourceWorkflow.id !== pipelineId) { throw new Error(`工作流 ID 不匹配:参数为 [${pipelineId}],文件中为 [${sourceWorkflow.id}]`); } let value: unknown = rawValue; if (booleanOption(parsed.options, ["value-json", "valueJson"])) { try { value = JSON.parse(rawValue); } catch (error) { throw new Error(`--value-json 不是合法 JSON: ${error instanceof Error ? error.message : String(error)}`); } } const patched = applyWorkflowPathPatch(sourceWorkflow, path, value); const target = inPlace ? file : output!; requireMutationConfirmation( parsed, runtime, "写入工作流草稿文件", `hose-use workflow patch ${pipelineId} --file=${file} --path=${path} --value='${rawValue}' ${inPlace ? "--in-place" : `--output=${target}`} --yes` ); if (isDryRun(parsed, runtime)) { return mutationPreview(parsed, runtime, "写入工作流草稿文件", target, { pipelineId, path, value, tasksVersion: patched.tasksVersion, }); } writeFileSync(target, `${JSON.stringify(patched, null, 2)}\n`, "utf8"); const result = { success: true, pipelineId, path, output: target, tasksVersion: patched.tasksVersion }; if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 }; return { stdout: `✅ 已生成工作流草稿 [${target}],修改路径: ${path}\n`, stderr: "", exitCode: 0 }; } export async function handleSave(parsed: CliParsedArgs, runtime: CliRuntime): Promise { const pipelineId = parsed.args[0] || stringOption(parsed.options, ["id", "pipelineId"]); const file = stringOption(parsed.options, ["file", "input", "from"]); if (!pipelineId || !file) { return { stdout: "", stderr: "用法: hose-use workflow save --file= [--force-write]\n", exitCode: 1, }; } let draftWorkflow: unknown; try { draftWorkflow = JSON.parse(readFileSync(file, "utf8")); } catch (error) { throw new Error(`无法读取工作流 JSON 文件 [${file}]: ${error instanceof Error ? error.message : String(error)}`); } const parsedWorkflow = WorkflowDetailSchema.parse(draftWorkflow); if (parsedWorkflow.id !== pipelineId) { throw new Error(`工作流 ID 不匹配:参数为 [${pipelineId}],文件中为 [${parsedWorkflow.id}]`); } const forceWrite = booleanOption(parsed.options, ["force-write", "forceWrite"]); requireMutationConfirmation( parsed, runtime, "保存工作流草稿到远端", `hose-use workflow save ${pipelineId} --file=${file} --yes` ); if (isDryRun(parsed, runtime)) { return mutationPreview(parsed, runtime, "保存工作流草稿到远端", pipelineId, { file, tasksVersion: parsedWorkflow.tasksVersion, forceWrite, }); } const clients = await createClientsForCorp(runtime.selectedCorp!); const platformId = await resolveWorkflowPlatformId(parsed, clients, pipelineId); const piperClient = await createPiperClientForCorp(runtime.selectedCorp!, platformId); const remote = await getWorkflowDetail(piperClient, pipelineId); let state = createWorkflowDraft(parsedWorkflow); state = { ...state, revision: 1, status: "dirty", dirtyPaths: ["*"], }; if (!forceWrite && hasWorkflowVersionConflict(state, remote)) { throw new Error( `工作流版本已变化,拒绝覆盖:远端 tasksVersion=${remote.tasksVersion}, 文件 tasksVersion=${parsedWorkflow.tasksVersion}。确认来源后使用 --force-write。` ); } state = beginWorkflowSave(state); try { const payload = state.workflow.inputs?.length ? state.workflow : { ...state.workflow, inputs: [{ key: "$platformId", value: platformId }] }; const saved = await updateWorkflow(piperClient, payload); state = commitWorkflowSave(state, saved); const result = { success: true, pipelineId, status: state.status, tasksVersion: saved.tasksVersion, updateTime: saved.updateTime, }; if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 }; return { stdout: `✅ 工作流 [${pipelineId}] 草稿保存成功,tasksVersion=${saved.tasksVersion}。\n`, stderr: "", exitCode: 0, }; } catch (error) { state = failWorkflowSave(state, error); throw new Error(`工作流保存失败(${state.status}): ${state.error}`); } } async function resolveWorkflowPlatformId( parsed: CliParsedArgs, clients: Awaited>, pipelineId: string ): Promise { const explicit = stringOption(parsed.options, PLATFORM_ID_OPTION_KEYS); if (explicit) return explicit; const all = await listAllWorkflows(clients, { page: 1, pageSize: 100 }); const match = all.workflows.find((workflow) => workflow.id === pipelineId); if (!match?.platformId) { throw new Error(`无法确定工作流 [${pipelineId}] 所属自建应用,请使用 --platform-id= 或 --app-id=`); } return match.platformId; }