Initial import of streamline
This commit is contained in:
@@ -0,0 +1,61 @@
|
||||
// 「接力」:把本地 coding agent 的调研总结交给 Streamline 从头修。服务端的说明见 control-server/src/agent_handoff.ts。
|
||||
//
|
||||
// 总结是一份按固定小节写的 Markdown(模板在 skill/SKILL.md)。这里把它拆成三块:
|
||||
// 现象 → description(提交人看到了什么);复现步骤 → reproSteps;其余小节 → notes(线索,服务端加说明后进 remark)。
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { CliError } from "./http.js";
|
||||
|
||||
const SECTION_ALIASES = {
|
||||
symptom: ["现象", "问题现象", "symptom", "symptoms"],
|
||||
repro: ["复现步骤", "复现", "repro", "repro steps", "steps to reproduce"],
|
||||
facts: ["已确认的事实", "事实", "已确认事实", "facts", "confirmed facts"],
|
||||
suspects: ["怀疑点", "疑点", "可能原因", "suspects", "hypotheses"],
|
||||
ruledOut: ["已排除", "排除", "ruled out"],
|
||||
fix: ["建议修法", "修复建议", "suggested fix"],
|
||||
};
|
||||
|
||||
function kindOf(heading) {
|
||||
const h = heading.replace(/[((][^))]*[))]/g, "").trim().toLowerCase();
|
||||
for (const [kind, names] of Object.entries(SECTION_ALIASES)) if (names.includes(h)) return kind;
|
||||
return "other";
|
||||
}
|
||||
|
||||
export function parseHandoff(markdown) {
|
||||
const sections = [];
|
||||
let current = null;
|
||||
for (const line of markdown.split(/\r?\n/)) {
|
||||
const m = line.match(/^##\s+(.+?)\s*$/);
|
||||
if (m) {
|
||||
current = { heading: m[1], kind: kindOf(m[1]), body: [] };
|
||||
sections.push(current);
|
||||
} else if (current) {
|
||||
current.body.push(line);
|
||||
}
|
||||
}
|
||||
const text = (s) => s.body.join("\n").trim();
|
||||
const pick = (kind) => sections.filter((s) => s.kind === kind).map(text).filter(Boolean).join("\n\n");
|
||||
const description = pick("symptom");
|
||||
const reproSteps = pick("repro");
|
||||
if (!description) throw new CliError("总结里缺少「## 现象」小节", "按 Skill 里的模板写:现象、复现步骤、已确认的事实、怀疑点、已排除");
|
||||
const rest = sections.filter((s) => s.kind !== "symptom" && s.kind !== "repro" && text(s));
|
||||
if (!rest.some((s) => s.kind === "facts" || s.kind === "suspects"))
|
||||
throw new CliError("总结里至少要有「## 已确认的事实」或「## 怀疑点」之一", "没有调研结论的话直接用 streamline task create");
|
||||
const notes = rest.map((s) => `## ${s.heading}\n\n${text(s)}`).join("\n\n");
|
||||
return { description, reproSteps: reproSteps || null, notes };
|
||||
}
|
||||
|
||||
function git(args, cwd) {
|
||||
try {
|
||||
return execFileSync("git", args, { cwd, encoding: "utf8", timeout: 2000, stdio: ["ignore", "pipe", "ignore"] }).trim() || null;
|
||||
} catch { return null; }
|
||||
}
|
||||
|
||||
/** 调研时的代码版本:仓库、分支、提交。远端地址里的用户名口令一律去掉。不在 git 仓库里就全空。 */
|
||||
export function gitContext(cwd = process.cwd()) {
|
||||
const remote = git(["remote", "get-url", "origin"], cwd);
|
||||
return {
|
||||
repo: remote ? remote.replace(/\/\/[^@/]+@/, "//") : null,
|
||||
branch: git(["rev-parse", "--abbrev-ref", "HEAD"], cwd),
|
||||
commit: git(["rev-parse", "HEAD"], cwd),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
import { apiBase, load } from "./store.js";
|
||||
|
||||
const VERSION = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
|
||||
|
||||
/**
|
||||
* 推测是哪个 Agent 调起的命令,随请求自报给服务端做使用统计(不影响任何行为)。
|
||||
* Claude Code 设 AI_AGENT / CLAUDECODE,Cursor 的 agent 给 shell 设 CURSOR_AGENT=1;
|
||||
* Codex 没有固定的标识,看有没有 CODEX_ 开头的运行时变量(CODEX_HOME 只是配置目录,不算)。
|
||||
*/
|
||||
export function detectAgent(env = process.env) {
|
||||
const ai = (env.AI_AGENT || "").toLowerCase();
|
||||
if (ai.startsWith("claude") || env.CLAUDECODE) return "claude-code";
|
||||
if (ai.startsWith("cursor") || env.CURSOR_AGENT) return "cursor";
|
||||
if (ai.startsWith("codex") || Object.keys(env).some((k) => k.startsWith("CODEX_") && k !== "CODEX_HOME")) return "codex";
|
||||
if (ai) return "other";
|
||||
return "terminal";
|
||||
}
|
||||
|
||||
const CLIENT = `streamline-cli/${VERSION}; agent=${detectAgent()}`;
|
||||
|
||||
export class CliError extends Error {
|
||||
constructor(message, hint) {
|
||||
super(message);
|
||||
this.hint = hint;
|
||||
}
|
||||
}
|
||||
|
||||
function bearer(auth) {
|
||||
if (auth === "session") {
|
||||
const s = load().session;
|
||||
if (!s || s.expiresAt <= Date.now()) throw new CliError("还没登录,或登录已过期", "运行 streamline auth login");
|
||||
return s.token;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 调控制面。不跟随重定向:带着凭据被 30x 到别的地方去,宁可报错。
|
||||
* 非 2xx 一律抛 CliError,带上服务端给的 error / code。
|
||||
*/
|
||||
export async function call(method, path, { auth, body, query } = {}) {
|
||||
const url = new URL(apiBase() + path);
|
||||
for (const [k, v] of Object.entries(query || {})) if (v != null && v !== "") url.searchParams.set(k, String(v));
|
||||
const headers = { Accept: "application/json", "X-Streamline-Client": CLIENT };
|
||||
const token = bearer(auth);
|
||||
if (token) headers.Authorization = `Bearer ${token}`;
|
||||
if (body !== undefined) headers["Content-Type"] = "application/json";
|
||||
let res;
|
||||
try {
|
||||
res = await fetch(url, { method, headers, body: body === undefined ? undefined : JSON.stringify(body), redirect: "error" });
|
||||
} catch (err) {
|
||||
throw new CliError(`连不上 ${apiBase()}:${err.cause?.code || err.message}`, "确认在公司内网 / VPN 上");
|
||||
}
|
||||
const text = await res.text();
|
||||
let data;
|
||||
try { data = text ? JSON.parse(text) : {}; } catch { data = { error: text.slice(0, 300) }; }
|
||||
if (!res.ok) {
|
||||
const msg = `${res.status} ${data.error || res.statusText}${data.code ? ` (${data.code})` : ""}`;
|
||||
if (res.status === 401 && auth === "session") throw new CliError(msg, "登录已失效,运行 streamline auth login");
|
||||
if (Array.isArray(data.active) && data.active.length)
|
||||
throw new CliError(msg, `进行中的:${data.active.map((v) => `${v.title} ${v.panelUrl}`).join(";")}`);
|
||||
throw new CliError(msg);
|
||||
}
|
||||
return data;
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
// 把包里的 skill/ 装给本机的 Agent:Claude Code、Codex、Cursor。
|
||||
//
|
||||
// 用户级(默认):正本放 ~/.agents/skills/<name>,再从各 Agent 的 skills 目录软链过去 ——
|
||||
// 和 `npx skills` 等安装器的约定一致,升级时只换正本,几个 Agent 同时生效。
|
||||
// 项目级(--project):直接拷进仓库里各 Agent 的目录。仓库会被别人 clone,指向本人 home 的
|
||||
// 软链在别人机器上是断的,所以这里不用软链。
|
||||
import { cpSync, existsSync, lstatSync, mkdirSync, readFileSync, realpathSync, rmSync, symlinkSync, unlinkSync } from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
import { dirname, join, relative, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { CliError } from "./http.js";
|
||||
|
||||
export const SKILL_NAME = "streamline-openapi";
|
||||
const SRC = join(dirname(fileURLToPath(import.meta.url)), "..", "skill");
|
||||
|
||||
const home = homedir();
|
||||
/** 各 Agent 的用户级 skills 目录;`root` 存在才算装了这个 Agent。 */
|
||||
const AGENTS = {
|
||||
claude: { label: "Claude Code", root: join(home, ".claude"), skills: join(home, ".claude", "skills"), project: ".claude/skills" },
|
||||
codex: {
|
||||
label: "Codex", root: process.env.CODEX_HOME || join(home, ".codex"),
|
||||
skills: join(process.env.CODEX_HOME || join(home, ".codex"), "skills"), project: ".codex/skills",
|
||||
},
|
||||
cursor: { label: "Cursor", root: join(home, ".cursor"), skills: join(home, ".cursor", "skills"), project: ".cursor/skills" },
|
||||
};
|
||||
const CANONICAL = join(home, ".agents", "skills", SKILL_NAME);
|
||||
|
||||
function pickAgents(flag) {
|
||||
if (typeof flag === "string" && flag !== "auto") {
|
||||
const names = flag === "all" ? Object.keys(AGENTS) : flag.split(",").map((s) => s.trim()).filter(Boolean);
|
||||
const bad = names.filter((n) => !AGENTS[n]);
|
||||
if (bad.length) throw new CliError(`不认识的 Agent:${bad.join(", ")}`, "可选 claude、codex、cursor、all");
|
||||
return names;
|
||||
}
|
||||
const found = Object.keys(AGENTS).filter((n) => existsSync(AGENTS[n].root));
|
||||
// 一个都没检测到时至少装给 Claude Code,免得什么都没发生。
|
||||
return found.length ? found : ["claude"];
|
||||
}
|
||||
|
||||
/** 路径上有没有东西(含断掉的软链,existsSync 对它返回 false)。 */
|
||||
function present(path) {
|
||||
try { lstatSync(path); return true; } catch { return false; }
|
||||
}
|
||||
|
||||
/** 删掉路径上的东西。rmSync(force) 会把断掉的软链当成不存在而跳过,所以软链单独 unlink。 */
|
||||
function remove(path) {
|
||||
if (!present(path)) return;
|
||||
if (lstatSync(path).isSymbolicLink()) unlinkSync(path);
|
||||
else rmSync(path, { recursive: true, force: true });
|
||||
}
|
||||
|
||||
/** 目标位置上已有的东西是不是我们装的(软链,或含同名 SKILL.md 的目录)——只覆盖自己的。 */
|
||||
function ours(path) {
|
||||
if (!present(path)) return true;
|
||||
const st = lstatSync(path);
|
||||
if (st.isSymbolicLink()) return true;
|
||||
if (!st.isDirectory()) return false;
|
||||
try { return /^name:\s*streamline-openapi\s*$/m.test(readFileSync(join(path, "SKILL.md"), "utf8")); } catch { return false; }
|
||||
}
|
||||
|
||||
function place(target, linkTo) {
|
||||
if (!ours(target)) throw new CliError(`${target} 已存在且不是本 Skill,没有覆盖`, "确认后手动删除再重试");
|
||||
const existed = present(target);
|
||||
remove(target);
|
||||
mkdirSync(dirname(target), { recursive: true });
|
||||
if (linkTo) {
|
||||
try {
|
||||
// 相对路径要按真实目录算:skills 目录本身可能是软链(如 $CODEX_HOME/skills → ~/.codex/skills),
|
||||
// 按字面路径算出来的 ../.. 落到真实目录里就多跳了几层,链接是断的。
|
||||
symlinkSync(relative(realpathSync(dirname(target)), realpathSync(linkTo)), target, "dir");
|
||||
if (!existsSync(join(target, "SKILL.md"))) throw new Error("dangling");
|
||||
return { path: target, mode: "symlink", updated: existed };
|
||||
} catch {
|
||||
// 不支持软链(如 Windows 无权限)或链接没指对,就退回拷贝。
|
||||
remove(target);
|
||||
}
|
||||
}
|
||||
cpSync(linkTo || SRC, target, { recursive: true });
|
||||
return { path: target, mode: "copy", updated: existed };
|
||||
}
|
||||
|
||||
export function install(flags = {}) {
|
||||
const agents = pickAgents(flags.agent);
|
||||
let results;
|
||||
if (typeof flags.dir === "string") {
|
||||
results = [{ agent: "custom", ...place(join(resolve(flags.dir), SKILL_NAME), null) }];
|
||||
} else if (flags.project) {
|
||||
results = agents.map((a) => ({ agent: a, ...place(join(process.cwd(), AGENTS[a].project, SKILL_NAME), null) }));
|
||||
} else {
|
||||
remove(CANONICAL);
|
||||
mkdirSync(dirname(CANONICAL), { recursive: true });
|
||||
cpSync(SRC, CANONICAL, { recursive: true });
|
||||
results = agents.map((a) => ({ agent: a, ...place(join(AGENTS[a].skills, SKILL_NAME), CANONICAL) }));
|
||||
}
|
||||
for (const r of results) process.stderr.write(`${r.updated ? "已更新" : "已安装"} ${AGENTS[r.agent]?.label ?? "Skill"}:${r.path}\n`);
|
||||
process.stderr.write("新开一个 Agent 会话即可生效。下一步:streamline auth login\n");
|
||||
return { installed: true, skill: SKILL_NAME, canonical: flags.dir || flags.project ? null : CANONICAL, targets: results };
|
||||
}
|
||||
|
||||
export function uninstall(flags = {}) {
|
||||
const agents = typeof flags.agent === "string" ? pickAgents(flags.agent) : Object.keys(AGENTS);
|
||||
const removed = [];
|
||||
const base = flags.project ? (a) => join(process.cwd(), AGENTS[a].project, SKILL_NAME) : (a) => join(AGENTS[a].skills, SKILL_NAME);
|
||||
for (const a of agents) {
|
||||
const p = base(a);
|
||||
if (present(p) && ours(p)) { remove(p); removed.push(p); }
|
||||
}
|
||||
if (!flags.project && !flags.agent && present(CANONICAL)) { remove(CANONICAL); removed.push(CANONICAL); }
|
||||
return { uninstalled: true, removed };
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
// 浏览器 SSO 登录:本机 127.0.0.1 临时端口收回调 + PKCE(S256),和控制面 openapi_cli_sso.ts 是一份契约的两端。
|
||||
// 浏览器回调只带一次性授权码,SSO 的 cookie / session 从不经过命令行。
|
||||
import { createHash, randomBytes } from "node:crypto";
|
||||
import { createServer } from "node:http";
|
||||
import { spawn } from "node:child_process";
|
||||
import { call } from "./http.js";
|
||||
import { save, webBase } from "./store.js";
|
||||
|
||||
export const CALLBACK_PATH = "/streamline/sso/callback";
|
||||
const WAIT_MS = 5 * 60 * 1000;
|
||||
const b64 = (buf) => buf.toString("base64url");
|
||||
|
||||
function openBrowser(url) {
|
||||
const [cmd, args] = process.platform === "darwin" ? ["open", [url]]
|
||||
: process.platform === "win32" ? ["cmd", ["/c", "start", "", url]]
|
||||
: ["xdg-open", [url]];
|
||||
try {
|
||||
const child = spawn(cmd, args, { stdio: "ignore", detached: true });
|
||||
child.on("error", () => {});
|
||||
child.unref();
|
||||
} catch { /* 打不开就让用户自己点下面打印的链接 */ }
|
||||
}
|
||||
|
||||
const page = (title, msg) => `<!doctype html><meta charset="utf-8"><title>${title}</title>
|
||||
<body style="font:15px -apple-system,system-ui,sans-serif;max-width:420px;margin:15vh auto;text-align:center">
|
||||
<h2>${title}</h2><p>${msg}</p><script>history.replaceState(null,"",location.pathname)</script></body>`;
|
||||
|
||||
export async function login({ openBrowser: shouldOpen = true } = {}) {
|
||||
const state = b64(randomBytes(32));
|
||||
const verifier = b64(randomBytes(32));
|
||||
const challenge = b64(createHash("sha256").update(verifier).digest());
|
||||
|
||||
let settle;
|
||||
const result = new Promise((resolve, reject) => { settle = { resolve, reject }; });
|
||||
const server = createServer((req, res) => {
|
||||
const u = new URL(req.url, "http://127.0.0.1");
|
||||
if (u.pathname !== CALLBACK_PATH) { res.writeHead(404).end(); return; }
|
||||
res.setHeader("Content-Type", "text/html; charset=utf-8");
|
||||
res.setHeader("Referrer-Policy", "no-referrer");
|
||||
res.setHeader("Cache-Control", "no-store");
|
||||
if (u.searchParams.get("state") !== state || !u.searchParams.get("code")) {
|
||||
res.writeHead(400).end(page("登录失败", "回调不匹配,请回到终端重新执行 streamline auth login。"));
|
||||
return;
|
||||
}
|
||||
res.writeHead(200).end(page("已授权", "可以关闭这个页面,回到终端继续。"));
|
||||
settle.resolve(u.searchParams.get("code"));
|
||||
});
|
||||
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
|
||||
const redirectUri = `http://127.0.0.1:${server.address().port}${CALLBACK_PATH}`;
|
||||
|
||||
const authUrl = new URL(webBase() + "/cli/connect");
|
||||
authUrl.searchParams.set("redirect_uri", redirectUri);
|
||||
authUrl.searchParams.set("state", state);
|
||||
authUrl.searchParams.set("code_challenge", challenge);
|
||||
authUrl.searchParams.set("code_challenge_method", "S256");
|
||||
process.stderr.write(`在浏览器里完成授权(5 分钟内有效):\n ${authUrl.href}\n`);
|
||||
if (shouldOpen) openBrowser(authUrl.href);
|
||||
|
||||
const timer = setTimeout(() => settle.reject(new Error("等待浏览器授权超时,请重新执行 streamline auth login")), WAIT_MS);
|
||||
let code;
|
||||
try { code = await result; } finally { clearTimeout(timer); server.close(); }
|
||||
|
||||
const token = await call("POST", "/api/openapi-cli/auth/token", {
|
||||
body: { code, code_verifier: verifier, redirect_uri: redirectUri },
|
||||
});
|
||||
save((rec) => ({ ...rec, session: { token: token.access_token, email: token.email, expiresAt: token.expires_at } }));
|
||||
return { email: token.email, expiresAt: token.expires_at };
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
// 本机凭据:~/.config/streamline/credentials.json(目录 0700、文件 0600,先写临时文件再改名)。
|
||||
// 按 API 地址分开存,同一台电脑可以同时连生产和自建环境。
|
||||
// 里面有登录会话的明文 —— 命令的输出里永远不打印它。
|
||||
import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
|
||||
export const DEFAULT_API = "https://streamline-internal-api.bytedance.net";
|
||||
export const DEFAULT_WEB = "https://streamline.bytedance.net";
|
||||
|
||||
export function apiBase() {
|
||||
return (process.env.STREAMLINE_API_URL || DEFAULT_API).replace(/\/+$/, "");
|
||||
}
|
||||
|
||||
export function webBase() {
|
||||
return (process.env.STREAMLINE_WEB_URL || DEFAULT_WEB).replace(/\/+$/, "");
|
||||
}
|
||||
|
||||
function dir() {
|
||||
const base = process.env.XDG_CONFIG_HOME || join(homedir(), ".config");
|
||||
return join(base, "streamline");
|
||||
}
|
||||
|
||||
function file() {
|
||||
return join(dir(), "credentials.json");
|
||||
}
|
||||
|
||||
function readAll() {
|
||||
if (!existsSync(file())) return {};
|
||||
try { return JSON.parse(readFileSync(file(), "utf8")) || {}; } catch { return {}; }
|
||||
}
|
||||
|
||||
function writeAll(all) {
|
||||
mkdirSync(dir(), { recursive: true, mode: 0o700 });
|
||||
chmodSync(dir(), 0o700);
|
||||
const tmp = `${file()}.${process.pid}.tmp`;
|
||||
writeFileSync(tmp, JSON.stringify(all, null, 2) + "\n", { mode: 0o600 });
|
||||
renameSync(tmp, file());
|
||||
}
|
||||
|
||||
/** 当前 API 地址下的记录:{ session?: {token,email,expiresAt} }(老版本存过的 keys 字段不再使用,原样留着无害)。 */
|
||||
export function load() {
|
||||
return readAll()[apiBase()] || {};
|
||||
}
|
||||
|
||||
export function save(update) {
|
||||
const all = readAll();
|
||||
all[apiBase()] = update(all[apiBase()] || {});
|
||||
writeAll(all);
|
||||
}
|
||||
|
||||
export function credentialsPath() {
|
||||
return file();
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
// 改动验证:本地分支改完、推上去之后,让 Streamline 从这个提交编译出包、在真机上按用例执行、交付报告。
|
||||
// 这里做两件事:解析用例文件;确认被测提交已经在远端(平台只能拿到推上去的代码)。
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { CliError } from "./http.js";
|
||||
|
||||
function git(args) {
|
||||
try {
|
||||
return execFileSync("git", args, { encoding: "utf8", timeout: 5000, stdio: ["ignore", "pipe", "ignore"] }).trim();
|
||||
} catch { return null; }
|
||||
}
|
||||
|
||||
/**
|
||||
* 被测提交:当前目录的 HEAD。要求工作区干净、且这个提交已经推到远端 —— 否则平台验的不是用户以为的代码。
|
||||
* 用本地记录的远端引用判断(推送时会更新),不额外联网;节点检出时还会再从远端核对一次。
|
||||
*/
|
||||
export function changeUnderTest({ allowDirty = false } = {}) {
|
||||
if (git(["rev-parse", "--is-inside-work-tree"]) !== "true") throw new CliError("当前目录不是 git 仓库", "在被测代码所在的仓库目录里执行");
|
||||
const commit = git(["rev-parse", "HEAD"]);
|
||||
if (!commit) throw new CliError("读不到当前提交");
|
||||
let branch = git(["rev-parse", "--abbrev-ref", "HEAD"]);
|
||||
if (branch === "HEAD") branch = null;
|
||||
const dirty = git(["status", "--porcelain", "--untracked-files=no"]);
|
||||
if (dirty && !allowDirty) {
|
||||
throw new CliError("有还没提交的改动:平台只能验证已经推送的提交,这些改动不会被验证",
|
||||
"先 commit 并 push;确实只想验证已推送的部分,加 --allow-dirty");
|
||||
}
|
||||
// 以「有没有远端分支包含这个提交」为准,而不是和上游比:从 develop 拉出的分支上游常常就是
|
||||
// origin/develop,比它领先是正常的,提交其实早就推到了自己的远端分支上。
|
||||
const onRemote = !!git(["branch", "-r", "--contains", "HEAD"]);
|
||||
if (!onRemote) {
|
||||
throw new CliError("当前提交还不在任何远端分支上(以本地记录的远端分支为准)",
|
||||
branch ? `先推送:git push -u origin ${branch}(推过了的话先 git fetch 再试)` : "先把这个提交推到远端分支");
|
||||
}
|
||||
const remote = git(["remote", "get-url", "origin"]);
|
||||
return { commit, branch, repo: remote ? remote.replace(/\/\/[^@/]+@/, "//") : null };
|
||||
}
|
||||
|
||||
/**
|
||||
* 用例文件(模板在 skill/SKILL.md):
|
||||
* ## 背景 改了什么、原本要解决什么
|
||||
* ## 用例
|
||||
* ### <用例标题>
|
||||
* 前置:… (可多行)
|
||||
* 步骤:… (可多行)
|
||||
* 检查点:
|
||||
* - 预期 1
|
||||
* - 预期 2
|
||||
*/
|
||||
export function parseVerifyCases(markdown) {
|
||||
let background = [];
|
||||
const cases = [];
|
||||
let section = null, cur = null, field = null;
|
||||
for (const raw of markdown.split(/\r?\n/)) {
|
||||
const line = raw.replace(/\s+$/, "");
|
||||
const h2 = line.match(/^##\s+(.+)$/);
|
||||
if (h2) {
|
||||
const name = h2[1].trim();
|
||||
section = /背景|background/i.test(name) ? "bg" : /用例|cases?/i.test(name) ? "cases" : null;
|
||||
cur = null; field = null;
|
||||
continue;
|
||||
}
|
||||
if (section === "bg") { background.push(line); continue; }
|
||||
if (section !== "cases") continue;
|
||||
const h3 = line.match(/^###\s+(.+)$/);
|
||||
if (h3) { cur = { title: h3[1].trim(), pre: [], step: [], checkpoints: [] }; cases.push(cur); field = null; continue; }
|
||||
if (!cur) continue;
|
||||
const label = line.match(/^\s*(前置(?:条件)?|步骤|操作步骤|检查点|预期)\s*[::]\s*(.*)$/);
|
||||
if (label) {
|
||||
field = /前置/.test(label[1]) ? "pre" : /步骤/.test(label[1]) ? "step" : "checkpoints";
|
||||
if (label[2]) (field === "checkpoints" ? cur.checkpoints : cur[field]).push(label[2]);
|
||||
continue;
|
||||
}
|
||||
if (!field || !line.trim()) continue;
|
||||
if (field === "checkpoints") {
|
||||
const bullet = line.match(/^\s*(?:[-*]|\d+[.)、])\s+(.*)$/);
|
||||
if (bullet) cur.checkpoints.push(bullet[1]);
|
||||
else if (cur.checkpoints.length) cur.checkpoints[cur.checkpoints.length - 1] += ` ${line.trim()}`;
|
||||
} else {
|
||||
cur[field].push(line);
|
||||
}
|
||||
}
|
||||
if (!cases.length) throw new CliError("用例文件里没有用例", "在「## 用例」下面用「### 用例标题」开始每一条,按 Skill 里的模板写");
|
||||
const empty = cases.find((c) => !c.checkpoints.length);
|
||||
if (empty) throw new CliError(`用例「${empty.title}」没有检查点`, "每条用例在「检查点:」下面用「- 」列出要看到的结果");
|
||||
return {
|
||||
background: background.join("\n").trim(),
|
||||
cases: cases.map((c) => ({ title: c.title, pre: c.pre.join("\n").trim() || null, step: c.step.join("\n").trim() || null, checkpoints: c.checkpoints.map((x) => x.trim()) })),
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user