internal-search.node-test.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. import assert from "node:assert/strict";
  2. import { spawn } from "node:child_process";
  3. import { chmod, mkdtemp, mkdir, readFile, writeFile } from "node:fs/promises";
  4. import { tmpdir } from "node:os";
  5. import { delimiter, join } from "node:path";
  6. import { PassThrough, Readable } from "node:stream";
  7. import { test } from "node:test";
  8. import { setTimeout as delay } from "node:timers/promises";
  9. import { fileURLToPath } from "node:url";
  10. import type { RunContext } from "@zcode/shared-types";
  11. import {
  12. resolveNativeSearchArgs,
  13. runEmbeddedSearchCli,
  14. } from "../src/internal-search/embedded-search-cli.js";
  15. import { run } from "../src/run.js";
  16. const nativeSearchTest = process.platform === "win32" ? test.skip : test;
  17. function createIo(cwd: string, stdin?: NodeJS.ReadableStream) {
  18. let stdout = "";
  19. let stderr = "";
  20. return {
  21. io: {
  22. cwd,
  23. ...(stdin ? { stdin } : {}),
  24. stderr: {
  25. write: (chunk: string | Uint8Array) =>
  26. void (stderr += typeof chunk === "string" ? chunk : chunk.toString()),
  27. },
  28. stdout: {
  29. write: (chunk: string | Uint8Array) =>
  30. void (stdout += typeof chunk === "string" ? chunk : chunk.toString()),
  31. },
  32. },
  33. read() {
  34. return { stderr, stdout };
  35. },
  36. };
  37. }
  38. type CapturedWriteStream = NodeJS.WriteStream & {
  39. output: () => string;
  40. };
  41. function createWriteStream(): CapturedWriteStream {
  42. let output = "";
  43. return {
  44. output: () => output,
  45. write: (chunk: string | Uint8Array): boolean => {
  46. output += typeof chunk === "string" ? chunk : chunk.toString();
  47. return true;
  48. },
  49. } as CapturedWriteStream;
  50. }
  51. function createContext(argv: string[]): RunContext & {
  52. stderr: CapturedWriteStream;
  53. stdout: CapturedWriteStream;
  54. } {
  55. const stdin = Readable.from([]) as NodeJS.ReadStream;
  56. stdin.isTTY = false;
  57. return {
  58. argv,
  59. stderr: createWriteStream(),
  60. stdin,
  61. stdout: createWriteStream(),
  62. };
  63. }
  64. async function fixture() {
  65. const root = await mkdtemp(join(tmpdir(), "zcode-embedded-search-"));
  66. await mkdir(join(root, "src"), { recursive: true });
  67. await mkdir(join(root, "src", "ignored"), { recursive: true });
  68. await mkdir(join(root, ".git"), { recursive: true });
  69. await writeFile(join(root, "src", "a.ts"), "const needle = true;\n");
  70. await writeFile(join(root, "src", "b.ts"), "const hay = false;\n");
  71. await writeFile(join(root, "src", "ignored", "c.ts"), "const needle = 'ignored';\n");
  72. await writeFile(join(root, ".git", "packed-refs"), "needle from vcs metadata\n");
  73. await writeFile(join(root, "README.md"), "Needle in docs\n");
  74. return root;
  75. }
  76. function shellQuote(value: string): string {
  77. return `'${value.replaceAll("'", "'\\''")}'`;
  78. }
  79. async function writeIgnoringSigtermCommand(path: string, pidFile: string): Promise<void> {
  80. await writeFile(
  81. path,
  82. `#!/usr/bin/env node
  83. const { writeFileSync } = require("node:fs");
  84. writeFileSync(${JSON.stringify(pidFile)}, String(process.pid));
  85. process.on("SIGTERM", () => {});
  86. setInterval(() => {}, 1000);
  87. `,
  88. );
  89. await chmod(path, 0o755);
  90. }
  91. async function readPidFile(path: string): Promise<number> {
  92. const deadline = Date.now() + 2_000;
  93. while (Date.now() < deadline) {
  94. try {
  95. const pid = Number((await readFile(path, "utf8")).trim());
  96. if (Number.isInteger(pid) && pid > 0) {
  97. return pid;
  98. }
  99. } catch {
  100. // 子进程启动后才写 pid 文件;轮询能让测试稳定等待到真实 native child。
  101. }
  102. await delay(20);
  103. }
  104. throw new Error(`Timed out waiting for pid file: ${path}`);
  105. }
  106. function isProcessRunning(pid: number): boolean {
  107. try {
  108. process.kill(pid, 0);
  109. return true;
  110. } catch {
  111. return false;
  112. }
  113. }
  114. async function waitForProcessExit(pid: number): Promise<void> {
  115. const deadline = Date.now() + 3_000;
  116. while (Date.now() < deadline) {
  117. if (!isProcessRunning(pid)) {
  118. return;
  119. }
  120. await delay(20);
  121. }
  122. assert.fail(`Expected process ${pid} to exit`);
  123. }
  124. function runShell(
  125. command: string,
  126. cwd: string,
  127. ): Promise<{
  128. code: number | null;
  129. stderr: string;
  130. stdout: string;
  131. }> {
  132. return new Promise((resolve, reject) => {
  133. const child = spawn("bash", ["-lc", command], {
  134. cwd,
  135. stdio: ["ignore", "pipe", "pipe"],
  136. });
  137. let stdout = "";
  138. let stderr = "";
  139. child.stdout.setEncoding("utf8");
  140. child.stderr.setEncoding("utf8");
  141. child.stdout.on("data", (chunk: string) => {
  142. stdout += chunk;
  143. });
  144. child.stderr.on("data", (chunk: string) => {
  145. stderr += chunk;
  146. });
  147. child.on("error", reject);
  148. child.on("close", (code) => {
  149. resolve({ code, stderr, stdout });
  150. });
  151. });
  152. }
  153. test("internal grep prepends default VCS excludes for normal searches", () => {
  154. assert.deepEqual(resolveNativeSearchArgs("grep", ["needle", "."]), [
  155. "-G",
  156. "-I",
  157. "--exclude-dir=.git",
  158. "--exclude-dir=.svn",
  159. "--exclude-dir=.hg",
  160. "--exclude-dir=.bzr",
  161. "--exclude-dir=.jj",
  162. "--exclude-dir=.sl",
  163. "needle",
  164. ".",
  165. ]);
  166. });
  167. test("internal grep leaves special arguments without defaults", () => {
  168. assert.deepEqual(resolveNativeSearchArgs("grep", ["--config", "grep.toml", "needle", "."]), [
  169. "--config",
  170. "grep.toml",
  171. "needle",
  172. ".",
  173. ]);
  174. assert.deepEqual(resolveNativeSearchArgs("grep", ["--format-open", "vim", "needle", "."]), [
  175. "--format-open",
  176. "vim",
  177. "needle",
  178. ".",
  179. ]);
  180. assert.deepEqual(resolveNativeSearchArgs("grep", ["---debug", "needle", "."]), [
  181. "---debug",
  182. "needle",
  183. ".",
  184. ]);
  185. assert.deepEqual(resolveNativeSearchArgs("grep", ["-@profile", "needle", "."]), [
  186. "-@profile",
  187. "needle",
  188. ".",
  189. ]);
  190. });
  191. test("internal grep bypasses null-data and z compatibility flags", () => {
  192. for (const args of [
  193. ["-z", "needle", "."],
  194. ["-Z", "needle", "."],
  195. ["-Rz", "needle", "."],
  196. ["-nZ", "needle", "."],
  197. ["--null", "needle", "."],
  198. ["--null-data", "needle", "."],
  199. ]) {
  200. assert.deepEqual(resolveNativeSearchArgs("grep", args), args);
  201. }
  202. });
  203. test("internal find keeps native arguments unchanged", () => {
  204. assert.deepEqual(resolveNativeSearchArgs("find", [".", "-type", "f"]), [".", "-type", "f"]);
  205. });
  206. nativeSearchTest("internal grep prints matching lines", async () => {
  207. const root = await fixture();
  208. const { io, read } = createIo(root);
  209. const exitCode = await runEmbeddedSearchCli(["grep", "needle", "src/a.ts"], io);
  210. assert.equal(exitCode, 0);
  211. assert.equal(read().stdout, "const needle = true;\n");
  212. assert.equal(read().stderr, "");
  213. });
  214. nativeSearchTest("internal grep passes through common native grep flags", async () => {
  215. const root = await fixture();
  216. const { io, read } = createIo(root);
  217. const exitCode = await runEmbeddedSearchCli(["grep", "-e", "needle", "src/a.ts"], io);
  218. assert.equal(exitCode, 0);
  219. assert.equal(read().stdout, "const needle = true;\n");
  220. assert.equal(read().stderr, "");
  221. });
  222. nativeSearchTest("internal grep supports -n and -i", async () => {
  223. const root = await fixture();
  224. const { io, read } = createIo(root);
  225. const exitCode = await runEmbeddedSearchCli(["grep", "-R", "-n", "-i", "needle", "."], io);
  226. assert.equal(exitCode, 0);
  227. assert.match(read().stdout, /^\.\/README\.md:1:Needle in docs$/m);
  228. assert.match(read().stdout, /^\.\/src\/a\.ts:1:const needle = true;$/m);
  229. assert.doesNotMatch(read().stdout, /\.\/\.git\/packed-refs/m);
  230. });
  231. nativeSearchTest("internal grep preserves stdin for pipeline-style commands", async () => {
  232. const root = await fixture();
  233. const stdin = Readable.from(["before\nneedle from stdin\nafter\n"]);
  234. const { io, read } = createIo(root, stdin);
  235. const exitCode = await runEmbeddedSearchCli(["grep", "needle"], io);
  236. assert.equal(exitCode, 0);
  237. assert.equal(read().stdout, "needle from stdin\n");
  238. assert.equal(read().stderr, "");
  239. });
  240. nativeSearchTest("internal grep exits quietly when downstream pipe closes early", async () => {
  241. const root = await fixture();
  242. const inputPath = join(root, "many.txt");
  243. await writeFile(inputPath, "needle\n".repeat(200_000));
  244. const cliMainPath = fileURLToPath(new URL("../src/main.ts", import.meta.url));
  245. const tsxLoaderPath = fileURLToPath(import.meta.resolve("tsx"));
  246. const result = await runShell(
  247. [
  248. // Bug 根因:硬编码 workspace 层的 tsx shim 会在 pnpm filtered install 下不存在;
  249. // 复用当前 Node 与相同 loader,测试才不依赖 node_modules 的物理铺设方式。
  250. shellQuote(process.execPath),
  251. "--import",
  252. shellQuote(tsxLoaderPath),
  253. shellQuote(cliMainPath),
  254. "__internal-search",
  255. "grep",
  256. "needle",
  257. shellQuote(inputPath),
  258. "|",
  259. "head",
  260. "-5",
  261. ].join(" "),
  262. root,
  263. );
  264. assert.equal(result.stdout, "needle\n".repeat(5));
  265. assert.equal(result.stderr, "");
  266. assert.equal(result.code, 0);
  267. });
  268. nativeSearchTest("internal grep abort signal force kills the native child", async () => {
  269. const root = await fixture();
  270. const binDir = await mkdtemp(join(tmpdir(), "zcode-embedded-search-bin-"));
  271. const pidFile = join(root, "fake-grep.pid");
  272. await writeIgnoringSigtermCommand(join(binDir, "grep"), pidFile);
  273. const previousPath = process.env.PATH;
  274. const stdin = new PassThrough();
  275. const controller = new AbortController();
  276. const { io } = createIo(root, stdin);
  277. process.env.PATH = previousPath ? `${binDir}${delimiter}${previousPath}` : binDir;
  278. try {
  279. const searchPromise = runEmbeddedSearchCli(["grep", "needle"], {
  280. ...io,
  281. signal: controller.signal,
  282. });
  283. const childPid = await readPidFile(pidFile);
  284. controller.abort();
  285. assert.equal(await searchPromise, 130);
  286. await waitForProcessExit(childPid);
  287. } finally {
  288. stdin.destroy();
  289. if (previousPath === undefined) {
  290. delete process.env.PATH;
  291. } else {
  292. process.env.PATH = previousPath;
  293. }
  294. }
  295. });
  296. nativeSearchTest(
  297. "internal grep supports combined flags and separated include filters",
  298. async () => {
  299. const root = await fixture();
  300. const { io, read } = createIo(root);
  301. const exitCode = await runEmbeddedSearchCli(
  302. ["grep", "-Rni", "--include", "*.ts", "--exclude-dir", "ignored", "needle", "."],
  303. io,
  304. );
  305. assert.equal(exitCode, 0);
  306. assert.equal(read().stdout, "./src/a.ts:1:const needle = true;\n");
  307. },
  308. );
  309. nativeSearchTest("internal grep returns one for no matches", async () => {
  310. const root = await fixture();
  311. const { io, read } = createIo(root);
  312. const exitCode = await runEmbeddedSearchCli(["grep", "missing", "src/a.ts"], io);
  313. assert.equal(exitCode, 1);
  314. assert.equal(read().stdout, "");
  315. });
  316. test("internal search rejects unsupported commands", async () => {
  317. const root = await fixture();
  318. const { io, read } = createIo(root);
  319. const exitCode = await runEmbeddedSearchCli(["rg", "needle", "."], io);
  320. assert.equal(exitCode, 2);
  321. assert.equal(read().stdout, "");
  322. assert.equal(read().stderr, "unsupported embedded search command: rg\n");
  323. });
  324. nativeSearchTest("internal find supports name and type predicates", async () => {
  325. const root = await fixture();
  326. const { io, read } = createIo(root);
  327. const exitCode = await runEmbeddedSearchCli(["find", ".", "-type", "f", "-name", "*.ts"], io);
  328. assert.equal(exitCode, 0);
  329. assert.deepEqual(read().stdout.trim().split("\n").sort(), [
  330. "./src/a.ts",
  331. "./src/b.ts",
  332. "./src/ignored/c.ts",
  333. ]);
  334. });
  335. nativeSearchTest("internal find passes through common native find predicates", async () => {
  336. const root = await fixture();
  337. const { io, read } = createIo(root);
  338. const exitCode = await runEmbeddedSearchCli(
  339. ["find", ".", "-type", "f", "-name", "*.ts", "-print"],
  340. io,
  341. );
  342. assert.equal(exitCode, 0);
  343. assert.deepEqual(read().stdout.trim().split("\n").sort(), [
  344. "./src/a.ts",
  345. "./src/b.ts",
  346. "./src/ignored/c.ts",
  347. ]);
  348. assert.equal(read().stderr, "");
  349. });
  350. nativeSearchTest("internal find returns the native error for invalid predicates", async () => {
  351. const root = await fixture();
  352. const { io, read } = createIo(root);
  353. const exitCode = await runEmbeddedSearchCli(["find", ".", "-definitely-not-real"], io);
  354. assert.notEqual(exitCode, 0);
  355. assert.match(read().stderr, /definitely-not-real/);
  356. });
  357. nativeSearchTest("CLI dispatch runs internal search before global option parsing", async () => {
  358. const root = await fixture();
  359. const ctx = createContext(["__internal-search", "grep", "-n", "needle", "src/a.ts"]);
  360. const exitCode = await run(ctx, { cwd: () => root });
  361. assert.equal(exitCode, 0);
  362. assert.equal(ctx.stdout.output(), "1:const needle = true;\n");
  363. assert.equal(ctx.stderr.output(), "");
  364. });