feat(workflow): implement declarative node editing commands

This commit is contained in:
gitea committed 2026-10-15 16:24:25 +08:00
1 parent 61123ad550
commit 3261b6ebdb
9 files changed
+1415 -6

No files matched your search

+428
View File
@@ -0,0 +1,428 @@
import {
getWorkflowDetail,
updateWorkflow,
flattenWorkflowTaskTree,
findWorkflowTask,
addWorkflowTask,
editWorkflowTask,
removeWorkflowTask,
} from "../../../domains/platform/services.js";
import { stringOption } from "../../parser.js";
import { printJson, printTable, printKeyValue } from "../../printer.js";
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../../mutation.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
import { createWorkflowDetailClient } from "./shared.js";
const SUB_ACTIONS = new Set(["list", "ls", "get", "show", "info", "add", "append", "insert", "edit", "update", "set", "rm", "remove", "delete", "del"]);
export async function handleNodeCommand(
parsed: CliParsedArgs,
runtime: CliRuntime
): Promise<CliResult> {
const firstArg = parsed.args[0]?.toLowerCase();
let subAction = "list";
let pipelineId = "";
let nodeTarget = "";
if (firstArg && SUB_ACTIONS.has(firstArg)) {
subAction = firstArg;
pipelineId = parsed.args[1] || stringOption(parsed.options, ["id", "pipelineId", "workflowId"]) || "";
nodeTarget = parsed.args[2] || stringOption(parsed.options, ["node", "target", "name"]) || "";
} else if (firstArg) {
// 允许缩写直接跟 pipelineId: hose-use workflow node <pipelineId>
pipelineId = firstArg;
nodeTarget = parsed.args[1] || stringOption(parsed.options, ["node", "target", "name"]) || "";
} else {
pipelineId = stringOption(parsed.options, ["id", "pipelineId", "workflowId"]) || "";
nodeTarget = stringOption(parsed.options, ["node", "target", "name"]) || "";
}
if (!pipelineId) {
return {
stdout: "",
stderr: [
"用法: hose-use workflow node <子命令> <pipelineId> [选项]",
"",
"子命令:",
" list <pipelineId> 列出工作流所有任务节点 (别名: ls, 默认)",
" get <pipelineId> <节点标识> 查看指定节点的完整配置 (别名: show, info)",
" add <pipelineId> [选项] 声明式追加或插入新任务节点 (别名: append, insert)",
" edit <pipelineId> <节点标识> 定向修改指定节点配置 (别名: update, set)",
" rm <pipelineId> <节点标识> 安全移除指定任务节点 (别名: remove, delete)",
"",
"示例:",
" hose-use workflow node list 896398895352487950",
" hose-use workflow node get 896398895352487950 action_dx9cci",
" hose-use workflow node add 896398895352487950 --type=code-js2 --label='数据清洗' --code='return items;' --yes",
" hose-use workflow node edit 896398895352487950 action_dx9cci --label='新清洗逻辑' --yes",
" hose-use workflow node rm 896398895352487950 action_dx9cci --yes",
].join("\n") + "\n",
exitCode: 1,
};
}
switch (subAction) {
case "list":
case "ls":
return handleListNodes(pipelineId, parsed, runtime);
case "get":
case "show":
case "info":
return handleGetNode(pipelineId, nodeTarget, parsed, runtime);
case "add":
case "append":
case "insert":
return handleAddNode(pipelineId, parsed, runtime);
case "edit":
case "update":
case "set":
return handleEditNode(pipelineId, nodeTarget, parsed, runtime);
case "rm":
case "remove":
case "delete":
case "del":
return handleRemoveNode(pipelineId, nodeTarget, parsed, runtime);
default:
return {
stdout: "",
stderr: `未知 workflow node 子命令: ${subAction}。支持: list, get, add, edit, rm\n`,
exitCode: 1,
};
}
}
async function handleListNodes(
pipelineId: string,
parsed: CliParsedArgs,
runtime: CliRuntime
): Promise<CliResult> {
const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
const detail = await getWorkflowDetail(client, pipelineId);
const tasks = detail.tasks || [];
const flattened = flattenWorkflowTaskTree(tasks);
if (runtime.jsonMode) {
return {
stdout: printJson({ pipelineId, label: detail.label, totalNodes: flattened.length, nodes: flattened }, runtime.outputOptions),
stderr: "",
exitCode: 0,
};
}
if (flattened.length === 0) {
return {
stdout: `工作流 [${detail.label || pipelineId}] 暂无任何任务节点。\n`,
stderr: "",
exitCode: 0,
};
}
const rows = flattened.map((item) => [
item.hierarchicalIndex,
item.task.name,
item.task.type,
item.task.label || "-",
item.task.groupName || "-",
item.summary,
]);
const table = printTable(
["#", "节点标识 (name)", "类型 (type)", "标题 (label)", "分组", "配置摘要"],
rows
);
const out = [
`====== 工作流 [${detail.label || pipelineId}] 任务节点树 (共 ${flattened.length} 个节点) ======`,
table,
].join("\n");
return { stdout: `${out}\n`, stderr: "", exitCode: 0 };
}
async function handleGetNode(
pipelineId: string,
nodeTarget: string,
parsed: CliParsedArgs,
runtime: CliRuntime
): Promise<CliResult> {
if (!nodeTarget) {
return {
stdout: "",
stderr: "请提供节点标识 (name 或层级序号): hose-use workflow node get <pipelineId> <nodeNameOrIndex>\n",
exitCode: 1,
};
}
const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
const detail = await getWorkflowDetail(client, pipelineId);
const located = findWorkflowTask(detail.tasks || [], nodeTarget);
if (!located) {
return {
stdout: "",
stderr: `在工作流 [${pipelineId}] 中未找到节点: ${nodeTarget}\n`,
exitCode: 1,
};
}
if (runtime.jsonMode) {
return {
stdout: printJson({ pipelineId, ...located }, runtime.outputOptions),
stderr: "",
exitCode: 0,
};
}
const { task, hierarchicalIndex, path, parentName } = located;
const kv: Record<string, string> = {
"工作流 ID": pipelineId,
"节点标识 (name)": task.name,
"层级编号 (#)": hierarchicalIndex,
"JSON 路径": path,
"父容器节点": parentName || "顶级节点 (root)",
"节点类型 (type)": task.type,
"节点标题 (label)": task.label || "-",
"节点分组 (group)": task.groupName || "-",
"状态 (status)": task.status || "active",
};
if ((task as any).code !== undefined) {
kv["代码行数"] = String((task as any).code.split("\n").length);
}
const outLines = [
`====== 节点详情 [${task.name}] (${task.label || task.type}) ======`,
printKeyValue(kv),
];
if ((task as any).code) {
outLines.push("\n--- 脚本内容 ---");
outLines.push((task as any).code);
}
return { stdout: `${outLines.join("\n")}\n`, stderr: "", exitCode: 0 };
}
async function handleAddNode(
pipelineId: string,
parsed: CliParsedArgs,
runtime: CliRuntime
): Promise<CliResult> {
const type = stringOption(parsed.options, ["type", "t"]);
if (!type) {
return {
stdout: "",
stderr: [
"请指定新增节点类型: --type=<类型>",
"常见类型: code-js2 (JS脚本), code (MVEL代码), http (HTTP请求), stop (终止流程), every (循环遍历), condition (分支条件)",
"示例: hose-use workflow node add 896398895352487950 --type=code-js2 --label='数据清洗' --yes",
].join("\n") + "\n",
exitCode: 1,
};
}
const label = stringOption(parsed.options, ["label", "name", "l"]);
const parent = stringOption(parsed.options, ["parent", "container", "p"]);
const after = stringOption(parsed.options, ["after", "insert-after"]);
const desc = stringOption(parsed.options, ["desc", "description", "d"]);
const codeFile = stringOption(parsed.options, ["code-file", "file"]);
let code = stringOption(parsed.options, ["code", "c"]);
if (codeFile) {
const fs = await import("fs/promises");
code = await fs.readFile(codeFile, "utf-8");
}
requireMutationConfirmation(
parsed,
runtime,
"追加工作流节点",
`hose-use workflow node add ${pipelineId} --type=${type}${label ? ` --label="${label}"` : ""}${parent ? ` --parent="${parent}"` : ""}${after ? ` --after="${after}"` : ""} --yes`
);
const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
const detail = await getWorkflowDetail(client, pipelineId);
const { workflow: updatedWorkflow, newTask } = addWorkflowTask(detail, {
type,
label,
desc,
code,
parent,
after,
});
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "追加工作流节点", pipelineId, {
pipelineId,
newNodeName: newTask.name,
type: newTask.type,
label: newTask.label,
targetLocation: parent ? `容器 [${parent}] 内部` : after ? `节点 [${after}] 之后` : "工作流末尾",
totalTasksCount: updatedWorkflow.tasks?.length || 0,
});
}
const saveResult = await updateWorkflow(client, updatedWorkflow);
if (runtime.jsonMode) {
return {
stdout: printJson({ success: true, pipelineId, newTask, workflow: saveResult }, runtime.outputOptions),
stderr: "",
exitCode: 0,
};
}
const out = [
`✨ 节点 [${newTask.name}] (${newTask.label}) 已成功添加至工作流 [${pipelineId}]:`,
printKeyValue({
"节点标识 (name)": newTask.name,
"节点类型 (type)": newTask.type,
"节点标题 (label)": newTask.label || "-",
"所属位置": parent ? `容器 [${parent}] 内部` : after ? `节点 [${after}] 之后` : "工作流顶级末尾",
"节点总数": String(saveResult.tasks?.length || updatedWorkflow.tasks?.length || 0),
}),
].join("\n");
return { stdout: `${out}\n`, stderr: "", exitCode: 0 };
}
async function handleEditNode(
pipelineId: string,
nodeTarget: string,
parsed: CliParsedArgs,
runtime: CliRuntime
): Promise<CliResult> {
if (!nodeTarget) {
return {
stdout: "",
stderr: "请提供节点标识 (name 或层级序号): hose-use workflow node edit <pipelineId> <nodeNameOrIndex> [选项]\n",
exitCode: 1,
};
}
const label = stringOption(parsed.options, ["label", "l"]);
const desc = stringOption(parsed.options, ["desc", "description", "d"]);
const codeFile = stringOption(parsed.options, ["code-file", "file"]);
let code = stringOption(parsed.options, ["code", "c"]);
if (codeFile) {
const fs = await import("fs/promises");
code = await fs.readFile(codeFile, "utf-8");
}
const rawSet = stringOption(parsed.options, ["set", "value"]);
const customSet: Record<string, any> = {};
if (rawSet) {
const eqIdx = rawSet.indexOf("=");
if (eqIdx !== -1) {
const k = rawSet.slice(0, eqIdx).trim();
const v = rawSet.slice(eqIdx + 1).trim();
try {
customSet[k] = JSON.parse(v);
} catch {
customSet[k] = v;
}
}
}
requireMutationConfirmation(
parsed,
runtime,
"修改工作流节点",
`hose-use workflow node edit ${pipelineId} ${nodeTarget}${label ? ` --label="${label}"` : ""} --yes`
);
const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
const detail = await getWorkflowDetail(client, pipelineId);
const { workflow: updatedWorkflow, editedTask } = editWorkflowTask(detail, nodeTarget, {
label,
desc,
code,
set: Object.keys(customSet).length > 0 ? customSet : undefined,
});
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "修改工作流节点", `${pipelineId}:${editedTask.name}`, {
pipelineId,
nodeName: editedTask.name,
label: editedTask.label,
updatedFields: {
...(label ? { label } : {}),
...(desc ? { desc } : {}),
...(code !== undefined ? { code: `${code.length} 字符` } : {}),
...customSet,
},
});
}
const saveResult = await updateWorkflow(client, updatedWorkflow);
if (runtime.jsonMode) {
return {
stdout: printJson({ success: true, pipelineId, editedTask, workflow: saveResult }, runtime.outputOptions),
stderr: "",
exitCode: 0,
};
}
return {
stdout: `✅ 节点 [${editedTask.name}] (${editedTask.label}) 修改已保存至工作流 [${pipelineId}]。\n`,
stderr: "",
exitCode: 0,
};
}
async function handleRemoveNode(
pipelineId: string,
nodeTarget: string,
parsed: CliParsedArgs,
runtime: CliRuntime
): Promise<CliResult> {
if (!nodeTarget) {
return {
stdout: "",
stderr: "请提供待删除节点标识 (name 或层级序号): hose-use workflow node rm <pipelineId> <nodeNameOrIndex>\n",
exitCode: 1,
};
}
requireMutationConfirmation(
parsed,
runtime,
"移除工作流节点",
`hose-use workflow node rm ${pipelineId} ${nodeTarget} --yes`
);
const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
const detail = await getWorkflowDetail(client, pipelineId);
const { workflow: updatedWorkflow, removedTask } = removeWorkflowTask(detail, nodeTarget);
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "移除工作流节点", `${pipelineId}:${removedTask.name}`, {
pipelineId,
nodeName: removedTask.name,
type: removedTask.type,
label: removedTask.label || "-",
remainingTasksCount: updatedWorkflow.tasks?.length || 0,
});
}
const saveResult = await updateWorkflow(client, updatedWorkflow);
if (runtime.jsonMode) {
return {
stdout: printJson({ success: true, pipelineId, removedTask, workflow: saveResult }, runtime.outputOptions),
stderr: "",
exitCode: 0,
};
}
return {
stdout: `🗑️ 节点 [${removedTask.name}] (${removedTask.label || removedTask.type}) 已从工作流 [${pipelineId}] 中安全移除。\n`,
stderr: "",
exitCode: 0,
};
}