embedded-search-native.e2e.test.ts 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  1. import { spawnSync } from "node:child_process";
  2. import { createWriteStream } from "node:fs";
  3. import { chmod, mkdir, mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises";
  4. import { tmpdir } from "node:os";
  5. import { basename, delimiter, dirname, join } from "node:path";
  6. import { pipeline } from "node:stream/promises";
  7. import { brotliCompressSync, gzipSync, zstdCompressSync } from "node:zlib";
  8. import { afterAll, beforeAll, describe, expect, it } from "vitest";
  9. import { ZipFile } from "yazl";
  10. import { NodeExecutionAdapter, resolveEffectiveBashShellSelection } from "@zcode/adapters/exec";
  11. import {
  12. createSessionId,
  13. createTraceId,
  14. createTurnId,
  15. type BashOutput,
  16. type EmbeddedSearchBackend,
  17. windowsPathToGitBashPath,
  18. } from "@zcode/contracts";
  19. import { builtInTools, type ToolExecutionContext } from "@zcode/core";
  20. import { resolveDefaultEmbeddedSearchBackend } from "../src/app/embedded-search-backend.js";
  21. const bfsPath = process.env.ZCODE_BFS_BINARY;
  22. const rgPath = process.env.ZCODE_RG_BINARY;
  23. const ugrepPath = process.env.ZCODE_UGREP_BINARY;
  24. const windowsShellResolution =
  25. process.platform === "win32"
  26. ? resolveEffectiveBashShellSelection({ env: process.env, platform: "win32" })
  27. : undefined;
  28. const windowsGitBashPath =
  29. windowsShellResolution?.selection.dialect === "git-bash"
  30. ? windowsShellResolution.selection.path
  31. : undefined;
  32. const nativeE2eEnabled = Boolean(
  33. rgPath && ugrepPath && (process.platform === "win32" ? windowsGitBashPath : bfsPath),
  34. );
  35. const outputSectionPattern = /^__ZCODE_[A-Z0-9_]+__$/u;
  36. if (process.env.ZCODE_REQUIRE_NATIVE_SEARCH_E2E === "1" && !nativeE2eEnabled) {
  37. throw new Error(
  38. "native embedded search E2E prerequisites are missing (bfs on Unix, ugrep, rg, or Windows Git Bash)",
  39. );
  40. }
  41. describe.skipIf(!nativeE2eEnabled)("native embedded search E2E", () => {
  42. let adapter: NodeExecutionAdapter;
  43. let backend: EmbeddedSearchBackend;
  44. let fixtureRoot: string;
  45. let systemRgAdapter: NodeExecutionAdapter;
  46. beforeAll(async () => {
  47. fixtureRoot = await mkdtemp(join(tmpdir(), "zcode-native-embedded-search-"));
  48. const home = join(fixtureRoot, "home");
  49. const isolatedBin = join(fixtureRoot, "isolated-bin");
  50. const systemBin = join(fixtureRoot, "system-bin");
  51. await mkdir(home, { recursive: true });
  52. await mkdir(join(fixtureRoot, "src", "deep"), { recursive: true });
  53. await mkdir(join(fixtureRoot, "ignored"), { recursive: true });
  54. await mkdir(join(fixtureRoot, ".git"), { recursive: true });
  55. await mkdir(join(fixtureRoot, "binary"), { recursive: true });
  56. await mkdir(join(fixtureRoot, "compressed"), { recursive: true });
  57. await mkdir(isolatedBin, { recursive: true });
  58. await mkdir(systemBin, { recursive: true });
  59. await writeFile(join(fixtureRoot, "src", "alpha.ts"), "before\nneedle alpha\nafter\n");
  60. await writeFile(join(fixtureRoot, "src", "deep", "beta.ts"), "needle beta\n");
  61. await writeFile(join(fixtureRoot, ".hidden.ts"), "needle hidden\n");
  62. await writeFile(join(fixtureRoot, "ignored", "skip.ts"), "needle ignored\n");
  63. await writeFile(join(fixtureRoot, ".git", "config"), "needle vcs\n");
  64. await writeFile(join(fixtureRoot, ".gitignore"), "ignored/\n");
  65. await writeFile(join(fixtureRoot, "binary", "data.ts"), Buffer.from("needle\0binary\n"));
  66. await writeFile(join(fixtureRoot, "many.txt"), "needle\n".repeat(100_000));
  67. await writeCompressedFixtures(join(fixtureRoot, "compressed"));
  68. const systemGrepPath = join(isolatedBin, "grep");
  69. await writeFile(systemGrepPath, "#!/bin/sh\nprintf 'system-grep-bypass:%s\\n' \"$*\"\n");
  70. await chmod(systemGrepPath, 0o755);
  71. const systemRgPath = join(systemBin, "rg");
  72. await writeFile(systemRgPath, "#!/bin/sh\nprintf 'system-rg\\n'\n");
  73. await chmod(systemRgPath, 0o755);
  74. backend = resolveDefaultEmbeddedSearchBackend({
  75. env: {
  76. ...(bfsPath ? { ZCODE_BFS_BINARY: bfsPath } : {}),
  77. ZCODE_RG_BINARY: rgPath!,
  78. ZCODE_UGREP_BINARY: ugrepPath!,
  79. },
  80. });
  81. const shellPath = nativeShellPathEntries();
  82. // Bugfix:Unix bundled 用例必须隔离系统 rg,否则 /usr/bin/rg 会绕过 ZCODE_RG_BINARY。
  83. const bundledShellPath = process.platform === "win32" ? shellPath : [];
  84. adapter = createAdapter([isolatedBin, ...bundledShellPath].join(delimiter), "bundled", home);
  85. systemRgAdapter = createAdapter([systemBin, ...shellPath].join(delimiter), "system-rg", home);
  86. });
  87. afterAll(async () => {
  88. // Bugfix:fixture 初始化失败时 adapter 尚未创建,清理阶段不能覆盖最初的环境错误。
  89. await Promise.all([adapter?.close(), systemRgAdapter?.close()]);
  90. if (fixtureRoot) await rm(fixtureRoot, { recursive: true, force: true });
  91. });
  92. // Bugfix:Windows Git Bash 会串行启动多次原生进程,完整契约用例不能受 Vitest 5 秒单测默认值限制。
  93. it("covers the complete platform native search contract through one Bash toolcall", async () => {
  94. const isolatedBinShellPath =
  95. process.platform === "win32"
  96. ? windowsPathToGitBashPath(join(fixtureRoot, "isolated-bin"))
  97. : join(fixtureRoot, "isolated-bin");
  98. expect(backend).toEqual({
  99. kind: "native-binaries",
  100. findCommand: bfsPath ?? "bfs",
  101. grepCommand: ugrepPath,
  102. rgCommand: rgPath,
  103. });
  104. const result = await runBashToolCall(
  105. [
  106. "printf '%s\\n' __ZCODE_VERSIONS__",
  107. "find --version",
  108. "grep --version",
  109. "rg --version",
  110. "printf '%s\\n' __ZCODE_BFS_NAME__",
  111. "find . -maxdepth 3 -type f -name '*.ts' | /usr/bin/sort",
  112. "printf '%s\\n' __ZCODE_BFS_REGEX__",
  113. "find . -type f -regex '.*\\(alpha\\|beta\\)\\.ts' | /usr/bin/sort",
  114. "printf '%s\\n' __ZCODE_UGREP_RECURSIVE__",
  115. "grep -Rni --include='*.ts' needle . | /usr/bin/sort",
  116. "printf '%s\\n' __ZCODE_UGREP_STDIN__",
  117. "printf 'before\\nneedle from stdin\\nafter\\n' | grep needle",
  118. "printf '%s\\n' __ZCODE_UGREP_MATCHERS__",
  119. "grep -E 'needle (alpha|beta)' src/alpha.ts",
  120. "grep -F 'needle alpha' src/alpha.ts",
  121. "grep -P '(?<=needle )alpha' src/alpha.ts",
  122. "printf '%s\\n' __ZCODE_UGREP_BYPASS__",
  123. // Bugfix:Git Bash 登录初始化会把 /usr/bin 放回 PATH 前部,绕过分支必须仍命中测试 grep。
  124. // Bugfix:GNU grep 的 -z/-Z、组合短参数和 null-data 长参数必须绕回 system grep;
  125. // 解压路径改用 ugrep 的显式 --decompress,避免与 GNU grep 的 -z 语义混淆。
  126. `(export PATH=${quoteShellValue(isolatedBinShellPath)}:"$PATH"; for _arg in --file-filter=stub --pager=stub --view=stub --format-open=stub --config=stub ---stub -@stub --save-config=stub -z -Z -Rz -nZ --null --null-data; do grep "$_arg"; done)`,
  127. "printf '%s\\n' __ZCODE_UGREP_COMPRESSED__",
  128. "for _file in compressed/sample.txt.gz compressed/sample.txt.bz2 compressed/sample.txt.zst compressed/sample.txt.br compressed/sample.zip compressed/sample.tar; do printf 'FILE:%s\\n' \"$_file\"; grep --decompress 'archive needle' \"$_file\"; done",
  129. "printf '%s\\n' __ZCODE_UGREP_EARLY_CLOSE__",
  130. "grep needle many.txt | /usr/bin/head -n 5",
  131. "printf '%s\\n' __ZCODE_UGREP_EXIT_CODES__",
  132. "grep absent src/alpha.ts >/dev/null; printf 'no-match=%s\\n' \"$?\"",
  133. "grep '[' src/alpha.ts >/dev/null 2>&1; printf 'invalid-regex=%s\\n' \"$?\"",
  134. "printf '%s\\n' __ZCODE_RG_FILES__",
  135. "rg -n -g '*.ts' needle src | /usr/bin/sort",
  136. "printf '%s\\n' __ZCODE_RG_HIDDEN__",
  137. "rg --hidden -Hn needle .hidden.ts",
  138. "printf '%s\\n' __ZCODE_RG_STDIN__",
  139. "printf 'before\\nneedle from rg stdin\\nafter\\n' | rg needle",
  140. "printf '%s\\n' __ZCODE_RG_MATCHERS__",
  141. "rg -F 'needle alpha' src/alpha.ts",
  142. "rg -P '(?<=needle )alpha' src/alpha.ts",
  143. "printf '%s\\n' __ZCODE_RG_EARLY_CLOSE__",
  144. "rg needle many.txt | /usr/bin/head -n 5",
  145. "printf '%s\\n' __ZCODE_RG_EXIT_CODES__",
  146. "rg absent src/alpha.ts >/dev/null; printf 'no-match=%s\\n' \"$?\"",
  147. "rg '[' src/alpha.ts >/dev/null 2>&1; printf 'invalid-regex=%s\\n' \"$?\"",
  148. "printf '%s\\n' __ZCODE_DONE__",
  149. "printf 'ok\\n'",
  150. ].join("\n"),
  151. );
  152. expectToolCallExit(result, 0);
  153. expect(result.stderr).toBe("");
  154. const versions = outputSection(result.stdout, "VERSIONS");
  155. if (process.platform === "win32") {
  156. expect(versions).toContain("GNU findutils");
  157. } else {
  158. expect(versions).toContain("bfs 4.1.1");
  159. expect(versions).not.toContain("GNU findutils");
  160. }
  161. expect(versions).toContain("ugrep 7.8.4");
  162. expect(versions).toContain(process.platform === "darwin" ? "-P:pcre2" : "-P:pcre2jit");
  163. expect(versions).toContain("-z:zlib,bzip2,zstd,brotli,7z,tar/pax/cpio/zip");
  164. expect(versions).toContain("ripgrep 14.1.1");
  165. expect(versions).toContain("features:+pcre2");
  166. expect(versions).toContain("PCRE2 10.43 is available");
  167. expect(outputLines(outputSection(result.stdout, "BFS_NAME"))).toEqual([
  168. "./.hidden.ts",
  169. "./binary/data.ts",
  170. "./ignored/skip.ts",
  171. "./src/alpha.ts",
  172. "./src/deep/beta.ts",
  173. ]);
  174. expect(outputLines(outputSection(result.stdout, "BFS_REGEX"))).toEqual([
  175. "./src/alpha.ts",
  176. "./src/deep/beta.ts",
  177. ]);
  178. const recursive = normalizeNativeSearchResultPaths(
  179. outputSection(result.stdout, "UGREP_RECURSIVE"),
  180. );
  181. expect(recursive).toContain(".hidden.ts:1:needle hidden");
  182. expect(recursive).toContain("src/alpha.ts:2:needle alpha");
  183. expect(recursive).toContain("src/deep/beta.ts:1:needle beta");
  184. expect(recursive).not.toContain("ignored/skip.ts");
  185. expect(recursive).not.toContain(".git/config");
  186. expect(recursive).not.toContain("binary/data.ts");
  187. expect(outputSection(result.stdout, "UGREP_STDIN")).toBe("needle from stdin");
  188. expect(outputLines(outputSection(result.stdout, "UGREP_MATCHERS"))).toEqual([
  189. "needle alpha",
  190. "needle alpha",
  191. "needle alpha",
  192. ]);
  193. expect(outputLines(outputSection(result.stdout, "UGREP_BYPASS"))).toEqual([
  194. "system-grep-bypass:--file-filter=stub",
  195. "system-grep-bypass:--pager=stub",
  196. "system-grep-bypass:--view=stub",
  197. "system-grep-bypass:--format-open=stub",
  198. "system-grep-bypass:--config=stub",
  199. "system-grep-bypass:---stub",
  200. "system-grep-bypass:-@stub",
  201. "system-grep-bypass:--save-config=stub",
  202. "system-grep-bypass:-z",
  203. "system-grep-bypass:-Z",
  204. "system-grep-bypass:-Rz",
  205. "system-grep-bypass:-nZ",
  206. "system-grep-bypass:--null",
  207. "system-grep-bypass:--null-data",
  208. ]);
  209. const compressed = outputSection(result.stdout, "UGREP_COMPRESSED");
  210. for (const fileName of [
  211. "sample.txt.gz",
  212. "sample.txt.bz2",
  213. "sample.txt.zst",
  214. "sample.txt.br",
  215. "sample.zip",
  216. "sample.tar",
  217. ]) {
  218. expect(compressed).toContain(`FILE:compressed/${fileName}`);
  219. }
  220. expect(compressed.match(/archive needle/gu)).toHaveLength(6);
  221. expect(outputSection(result.stdout, "UGREP_EARLY_CLOSE")).toBe(
  222. "needle\nneedle\nneedle\nneedle\nneedle",
  223. );
  224. expect(outputLines(outputSection(result.stdout, "UGREP_EXIT_CODES"))).toEqual([
  225. "no-match=1",
  226. "invalid-regex=2",
  227. ]);
  228. expect(
  229. outputLines(normalizeNativeSearchResultPaths(outputSection(result.stdout, "RG_FILES"))),
  230. ).toEqual(["src/alpha.ts:2:needle alpha", "src/deep/beta.ts:1:needle beta"]);
  231. expect(outputSection(result.stdout, "RG_HIDDEN")).toBe(".hidden.ts:1:needle hidden");
  232. expect(outputSection(result.stdout, "RG_STDIN")).toBe("needle from rg stdin");
  233. expect(outputLines(outputSection(result.stdout, "RG_MATCHERS"))).toEqual([
  234. "needle alpha",
  235. "needle alpha",
  236. ]);
  237. expect(outputSection(result.stdout, "RG_EARLY_CLOSE")).toBe(
  238. "needle\nneedle\nneedle\nneedle\nneedle",
  239. );
  240. expect(outputLines(outputSection(result.stdout, "RG_EXIT_CODES"))).toEqual([
  241. "no-match=1",
  242. "invalid-regex=2",
  243. ]);
  244. expect(outputSection(result.stdout, "DONE")).toBe("ok");
  245. }, 30_000);
  246. it("keeps an existing executable rg instead of shadowing it", async () => {
  247. const result = await runBashToolCall("rg --version", backend, systemRgAdapter);
  248. expectToolCallExit(result, 0);
  249. expect(result.stdout).toBe("system-rg\n");
  250. expect(result.stderr).toBe("");
  251. });
  252. it("falls back to system find and grep when native binaries are unavailable", async () => {
  253. const missingBackend: EmbeddedSearchBackend = {
  254. kind: "native-binaries",
  255. findCommand: join(fixtureRoot, "missing-bfs"),
  256. grepCommand: join(fixtureRoot, "missing-ugrep"),
  257. rgCommand: join(fixtureRoot, "missing-rg"),
  258. };
  259. const result = await runBashToolCall(
  260. [
  261. "find src -type f -name '*.ts' | /usr/bin/sort",
  262. "printf '%s\\n' ---",
  263. "printf 'before\\nneedle fallback\\nafter\\n' | grep needle",
  264. ].join("\n"),
  265. missingBackend,
  266. systemRgAdapter,
  267. );
  268. expectToolCallExit(result, 0);
  269. expect(result.stdout).toBe("src/alpha.ts\nsrc/deep/beta.ts\n---\nneedle fallback\n");
  270. expect(result.stderr).toBe("");
  271. });
  272. it.each(["ugrep-direct", "ugrep-pipe", "system-grep-pipe"])(
  273. "isolates live output from recursive search (%s)",
  274. async (mode) => {
  275. const searchRoot = join(fixtureRoot, `self-search-${mode}`);
  276. const tempParent = join(fixtureRoot, `temporary-${mode}`);
  277. await mkdir(searchRoot);
  278. await mkdir(tempParent);
  279. await writeFile(join(searchRoot, "00-seed.txt"), "self_search_needle\n".repeat(200_000));
  280. const shellPath = (path: string) =>
  281. process.platform === "win32" ? windowsPathToGitBashPath(path) : path;
  282. // 只允许读回种子输出及一条嵌套匹配;另设大小和时长保护,不能把测试变成磁盘耗尽事故。
  283. const grep =
  284. mode === "system-grep-pipe"
  285. ? "command grep -rn -m200001 self_search_needle ."
  286. : "grep -J1 --sort=name -rn -m200001 self_search_needle .";
  287. const command = `cd ${quoteShellValue(shellPath(searchRoot))} && ${grep}${mode.endsWith("pipe") ? " | cut -c 1-4096" : ""}`;
  288. for (const useTmp of [false, true]) {
  289. const outputRoot = join(searchRoot, "zz-output");
  290. const execution = new NodeExecutionAdapter({
  291. outputRootDir: outputRoot,
  292. ...(useTmp ? { bashOutputTempDir: tempParent } : {}),
  293. processEnv: { ...process.env, PATH: nativeShellPathEntries().join(delimiter) },
  294. });
  295. const deadline = setTimeout(() => void execution.close(), 10_000);
  296. const controlPath = join(
  297. outputRoot,
  298. "native-search-e2e",
  299. "tool_native_search_e2e-stdout.log",
  300. );
  301. const sizeGuard = setInterval(() => {
  302. void stat(controlPath).then(
  303. (file) => {
  304. if (file.size >= 64 * 1024 * 1024) return execution.close();
  305. },
  306. () => undefined,
  307. );
  308. }, 25);
  309. try {
  310. const result = await runBashToolCall(command, backend, execution);
  311. expectToolCallExit(result, 0);
  312. const outputPath = result.persistedOutputPath!;
  313. expect(outputPath).toBeTruthy();
  314. expect((await stat(outputPath)).size).toBeLessThan(64 * 1024 * 1024);
  315. const text = await readFile(outputPath, "utf8");
  316. const nested = /stdout\.log:\d+:/u.test(text);
  317. if (useTmp) {
  318. expect(outputPath.startsWith(tempParent)).toBe(true);
  319. expect(nested).toBe(false);
  320. expect(text.match(/self_search_needle/g)).toHaveLength(200_000);
  321. } else if (
  322. mode === "ugrep-pipe" ||
  323. process.platform === "win32" ||
  324. (mode === "system-grep-pipe" && process.platform === "linux")
  325. ) {
  326. expect(nested).toBe(true);
  327. }
  328. } finally {
  329. clearTimeout(deadline);
  330. clearInterval(sizeGuard);
  331. await execution.close();
  332. await rm(outputRoot, { recursive: true, force: true });
  333. }
  334. }
  335. },
  336. 30_000,
  337. );
  338. async function runBashToolCall(
  339. command: string,
  340. selectedBackend: EmbeddedSearchBackend = backend,
  341. selectedAdapter: NodeExecutionAdapter = adapter,
  342. ): Promise<BashOutput> {
  343. const bashTool = builtInTools.find((entry) => entry.metadata.name === "Bash");
  344. if (!bashTool) throw new Error("Bash tool entry is not registered");
  345. const context: ToolExecutionContext = {
  346. toolCallId: "tool_native_search_e2e",
  347. traceId: createTraceId(),
  348. abortSignal: new AbortController().signal,
  349. bashShellSelection: windowsShellResolution?.selection ?? {
  350. dialect: "posix",
  351. display: { name: "bash" },
  352. path: "/bin/bash",
  353. source: "auto-detected",
  354. },
  355. embeddedSearch: {
  356. backend: selectedBackend,
  357. enabled: true,
  358. },
  359. executionPort: selectedAdapter,
  360. runtimeScope: "main",
  361. workingDirectory: fixtureRoot,
  362. workspaceRoot: fixtureRoot,
  363. sessionId: createSessionId("native-search-e2e"),
  364. turnId: createTurnId("native-search-e2e"),
  365. };
  366. return (await bashTool.handler(
  367. {
  368. command,
  369. dangerouslyDisableSandbox: true,
  370. timeout: 30_000,
  371. },
  372. context,
  373. )) as BashOutput;
  374. }
  375. function createAdapter(path: string, id: string, home: string): NodeExecutionAdapter {
  376. return new NodeExecutionAdapter({
  377. outputRootDir: join(fixtureRoot, `exec-output-${id}`),
  378. processEnv: {
  379. ...process.env,
  380. HOME: home,
  381. PATH: path,
  382. SHELL: "/bin/bash",
  383. },
  384. });
  385. }
  386. function nativeShellPathEntries(): string[] {
  387. if (process.platform !== "win32" || !windowsGitBashPath) return ["/usr/bin", "/bin"];
  388. const gitRoot = dirname(dirname(windowsGitBashPath));
  389. const comSpec = process.env.ComSpec?.trim() || process.env.COMSPEC?.trim();
  390. return [
  391. dirname(windowsGitBashPath),
  392. join(gitRoot, "usr", "bin"),
  393. join(gitRoot, "mingw64", "bin"),
  394. // Bugfix:E2E 会覆盖 PATH,但仍需保留 cmd/chcp 所在目录以执行 Windows 编码探测。
  395. ...(comSpec ? [dirname(comSpec)] : []),
  396. ];
  397. }
  398. });
  399. function quoteShellValue(value: string): string {
  400. return `'${value.replaceAll("'", "'\\''")}'`;
  401. }
  402. async function writeCompressedFixtures(compressedDir: string): Promise<void> {
  403. const archiveText = Buffer.from("archive needle\n");
  404. const rawPath = join(compressedDir, "raw.txt");
  405. await writeFile(rawPath, archiveText);
  406. await writeFile(join(compressedDir, "sample.txt.gz"), gzipSync(archiveText));
  407. await writeFile(join(compressedDir, "sample.txt.zst"), zstdCompressSync(archiveText));
  408. await writeFile(join(compressedDir, "sample.txt.br"), brotliCompressSync(archiveText));
  409. // Bugfix:Linux runner 不保证安装 zip CLI;由测试依赖生成跨平台 fixture,避免环境工具污染 E2E。
  410. const zip = new ZipFile();
  411. zip.addBuffer(archiveText, basename(rawPath));
  412. zip.end();
  413. await pipeline(zip.outputStream, createWriteStream(join(compressedDir, "sample.zip")));
  414. if (process.platform === "win32" && windowsGitBashPath) {
  415. const archiveFixtures = spawnSync(
  416. windowsGitBashPath,
  417. [
  418. "--noprofile",
  419. "--norc",
  420. "-c",
  421. "bzip2 -c raw.txt > sample.txt.bz2 && tar -cf sample.tar raw.txt",
  422. ],
  423. { cwd: compressedDir, encoding: "utf8" },
  424. );
  425. expectNativeFixtureCommand(archiveFixtures, "Git Bash archive fixture creation");
  426. return;
  427. }
  428. const bzip2 = spawnSync("bzip2", ["-c", rawPath], { encoding: null });
  429. expectNativeFixtureCommand(bzip2, "bzip2 fixture creation");
  430. await writeFile(join(compressedDir, "sample.txt.bz2"), bzip2.stdout);
  431. const tar = spawnSync("tar", ["-cf", "sample.tar", basename(rawPath)], {
  432. cwd: compressedDir,
  433. encoding: "utf8",
  434. });
  435. expectNativeFixtureCommand(tar, "tar fixture creation");
  436. }
  437. function expectNativeFixtureCommand(result: ReturnType<typeof spawnSync>, label: string): void {
  438. if (result.error) throw result.error;
  439. if (result.status === 0) return;
  440. throw new Error(
  441. `${label} exited with ${result.status}\nstdout:\n${String(result.stdout ?? "")}\nstderr:\n${String(result.stderr ?? "")}`,
  442. );
  443. }
  444. function outputSection(output: string, name: string): string {
  445. const lines = output.trimEnd().split("\n");
  446. const marker = `__ZCODE_${name}__`;
  447. const start = lines.indexOf(marker);
  448. if (start < 0) throw new Error(`missing output marker: ${marker}\n${output}`);
  449. const next = lines.findIndex((line, index) => index > start && outputSectionPattern.test(line));
  450. return lines
  451. .slice(start + 1, next < 0 ? lines.length : next)
  452. .join("\n")
  453. .trimEnd();
  454. }
  455. function outputLines(output: string): string[] {
  456. return output.split("\n").filter((line) => line.length > 0);
  457. }
  458. function normalizeNativeSearchResultPaths(output: string): string {
  459. // Bugfix:Windows 原生 ugrep/rg 由 Git Bash 启动时仍输出反斜杠,路径断言统一为 shell 风格。
  460. return process.platform === "win32" ? output.replaceAll("\\", "/") : output;
  461. }
  462. function expectToolCallExit(result: BashOutput, exitCode: number): void {
  463. const diagnostic = [
  464. `status: ${result.status}`,
  465. `exitCode: ${String(result.exitCode)}`,
  466. `signal: ${String(result.signal)}`,
  467. `timedOut: ${String(result.timedOut)}`,
  468. `cancelled: ${String(result.cancelled)}`,
  469. `error: ${JSON.stringify(result.error)}`,
  470. `stdout:\n${result.stdout}`,
  471. `stderr:\n${result.stderr}`,
  472. ].join("\n");
  473. expect(result.status, diagnostic).toBe(exitCode === 0 ? "completed" : "failed");
  474. expect(result.exitCode, diagnostic).toBe(exitCode);
  475. }