git-product-invocation.test.ts 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  1. import assert from "node:assert/strict";
  2. import { execFile } from "node:child_process";
  3. import { mkdtemp, readFile, rm, writeFile, mkdir } from "node:fs/promises";
  4. import { tmpdir } from "node:os";
  5. import { join } from "node:path";
  6. import { promisify } from "node:util";
  7. import { after, before, describe, it } from "node:test";
  8. import { buildProductGitArgs, createGitCommandProvider } from "../../packages/services/src/git/providers/gitCommandProvider.ts";
  9. import { getGitNullDevicePath } from "../../packages/services/src/git/config.ts";
  10. // 运行时验收:仓库内的 .gitattributes 与 .git/config 可以安排 external diff、textconv、fsmonitor
  11. // 三条外部命令通道(ZP-20261105-08)。这里用真实 git 与临时仓库确认产品 Git 入口不会启动它们。
  12. // 脚本只追加一行通道名到标记文件,textconv 额外输出可区分的文本,用于断言 patch 来自原文。
  13. const execFileAsync = promisify(execFile);
  14. const GIT_IDENTITY = ["-c", "user.name=zcode-test", "-c", "user.email=zcode-test@example.com"];
  15. let root: string;
  16. let repo: string;
  17. let markerPath: string;
  18. async function git(args: string[]): Promise<string> {
  19. const { stdout } = await execFileAsync("git", [...GIT_IDENTITY, ...args], { cwd: repo });
  20. return stdout;
  21. }
  22. async function readMarkers(): Promise<string> {
  23. return await readFile(markerPath, "utf8").catch((error: NodeJS.ErrnoException) => {
  24. if (error.code === "ENOENT") return "";
  25. throw error;
  26. });
  27. }
  28. async function clearMarkers(): Promise<void> {
  29. await rm(markerPath, { force: true });
  30. }
  31. describe("产品 Git 子进程不执行仓库配置的外部命令", () => {
  32. before(async () => {
  33. root = await mkdtemp(join(tmpdir(), "zcode-git-invocation-"));
  34. repo = join(root, "repo");
  35. markerPath = join(root, "markers.log");
  36. const payloadPath = join(root, "payload", "channel.mjs");
  37. await mkdir(join(root, "payload"));
  38. await writeFile(
  39. payloadPath,
  40. [
  41. 'import { appendFileSync } from "node:fs";',
  42. "const channel = process.argv[2];",
  43. `appendFileSync(${JSON.stringify(markerPath)}, channel + "\\n");`,
  44. 'if (channel === "textconv") process.stdout.write("CONVERTED\\n");',
  45. "",
  46. ].join("\n"),
  47. );
  48. const command = (channel: string) => `"${process.execPath}" "${payloadPath}" ${channel}`;
  49. await mkdir(repo);
  50. await git(["init", "-q"]);
  51. await writeFile(join(repo, ".gitattributes"), "data.txt diff=evil\n");
  52. await writeFile(join(repo, "data.txt"), "hello\n");
  53. await git(["add", "."]);
  54. await git(["commit", "-q", "-m", "init"]);
  55. await writeFile(join(repo, "data.txt"), "hello world\n");
  56. await git(["config", "diff.external", command("external")]);
  57. await git(["config", "diff.evil.textconv", command("textconv")]);
  58. await git(["config", "core.fsmonitor", command("fsmonitor")]);
  59. });
  60. after(async () => {
  61. await rm(root, { recursive: true, force: true });
  62. });
  63. it("对照:原生 git 确实会执行三条通道,证明负载可运行", async () => {
  64. await clearMarkers();
  65. await execFileAsync("git", ["diff"], { cwd: repo }).catch(() => undefined);
  66. assert.match(await readMarkers(), /^external$/m);
  67. await clearMarkers();
  68. await execFileAsync("git", ["diff", "--no-ext-diff"], { cwd: repo });
  69. assert.match(await readMarkers(), /^textconv$/m, "--no-ext-diff 不禁止 textconv");
  70. await clearMarkers();
  71. await execFileAsync("git", ["status", "--porcelain"], { cwd: repo });
  72. assert.match(await readMarkers(), /^fsmonitor$/m);
  73. });
  74. // 调用方即使自带 --no-ext-diff,也只禁止了 external 通道;入口必须补上 textconv 与 fsmonitor 的禁用。
  75. const cases: Array<{ name: string; args: string[]; exitCodes: number[]; patch: boolean }> = [
  76. {
  77. name: "diff 带 --no-ext-diff",
  78. args: ["diff", "--no-ext-diff", "--binary"],
  79. exitCodes: [0],
  80. patch: true,
  81. },
  82. { name: "diff 不带调用方防护", args: ["diff", "--binary"], exitCodes: [0], patch: true },
  83. { name: "show", args: ["show", "--no-ext-diff", "HEAD"], exitCodes: [0], patch: true },
  84. { name: "log -p", args: ["log", "--no-ext-diff", "-p", "-1"], exitCodes: [0], patch: true },
  85. {
  86. name: "diff --no-index(未跟踪文件)",
  87. args: ["diff", "--no-index", "--binary", getGitNullDevicePath(), "data.txt"],
  88. exitCodes: [1],
  89. patch: true,
  90. },
  91. {
  92. name: "status",
  93. args: ["status", "--porcelain=v2", "--branch", "-z"],
  94. exitCodes: [0],
  95. patch: false,
  96. },
  97. ];
  98. for (const { name, args, exitCodes, patch } of cases) {
  99. it(`经产品入口执行 ${name} 不启动任何外部命令`, async () => {
  100. const provider = createGitCommandProvider();
  101. await clearMarkers();
  102. const result = await provider.run({ cwd: repo, args });
  103. assert.ok(
  104. exitCodes.includes(result.exitCode ?? -1),
  105. `退出码异常:${result.exitCode} ${result.stderr}`,
  106. );
  107. assert.equal(await readMarkers(), "", "不得启动 external / textconv / fsmonitor 负载");
  108. if (patch) {
  109. assert.doesNotMatch(result.stdout, /CONVERTED/, "patch 必须来自原始文件内容");
  110. assert.match(result.stdout, /\+hello/, "输出应包含原始文本");
  111. }
  112. });
  113. }
  114. });
  115. // 参数组装是纯函数,不需要 git 进程:防护参数必须紧跟子命令,并且只按 args[0] 识别子命令。
  116. describe("buildProductGitArgs", () => {
  117. const prefix = ["-c", "core.fsmonitor="];
  118. const guard = ["--no-ext-diff", "--no-textconv"];
  119. it("show、log、diff 紧跟子命令带上防护参数,调用方参数原样保留", () => {
  120. assert.deepEqual(buildProductGitArgs(["diff", "--stat", "HEAD"]), [...prefix, "diff", ...guard, "--stat", "HEAD"]);
  121. assert.deepEqual(buildProductGitArgs(["show", "HEAD:README.md"]), [...prefix, "show", ...guard, "HEAD:README.md"]);
  122. assert.deepEqual(buildProductGitArgs(["log", "-p", "-n", "1"]), [...prefix, "log", ...guard, "-p", "-n", "1"]);
  123. });
  124. it("不输出 patch 的子命令不加防护参数", () => {
  125. assert.deepEqual(buildProductGitArgs(["status", "--porcelain"]), [...prefix, "status", "--porcelain"]);
  126. });
  127. it("子命令前置全局选项时防护不生效:这是调用方约定,不是修复目标", () => {
  128. // 若将来改为解析全局选项,应同步更新本断言与 buildProductGitArgs 注释。
  129. assert.deepEqual(buildProductGitArgs(["-c", "color.ui=never", "diff"]), [
  130. ...prefix,
  131. "-c",
  132. "color.ui=never",
  133. "diff",
  134. ]);
  135. });
  136. });