workflow-git-world-read-real.test.ts 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. /**
  2. * 真 git 验证:本仓库的解析器冒烟,以及隔离临时仓库的外部命令回归。
  3. *
  4. * 为什么值得单独有这么一个用例:fake 端口能证明"给定这段文本,解析出这个结构",但证明不了
  5. * "git 真的会输出这段文本"。这份实现里有三条假设**只能**由真 git falsify,而且每一条都已经
  6. * 在写代码的过程中被它纠正过一次:
  7. *
  8. * 1. `-z` 下 porcelain 的 rename 项占**两段**(NUL 分隔,不是 TAB)。
  9. * 2. `-z` 让 `status --porcelain=v2` 输出**仓库根相对**路径——不加 `-z` 时它是 cwd 相对的,
  10. * 而且没有任何 flag/config 能在 `-z` 下把它改回来。这一条直接决定了"基准统一在线上取
  11. * 根相对、由我们剥一次前缀"这个设计。
  12. * 3. `ls-files --others` 默认是 **cwd 相对**,所以必须补 `--full-name` 才能与上面两条对齐。
  13. *
  14. * 断言只钉**形状**与**一致性**,不钉内容:工作树的干净程度、分支名、commit 数都随环境变化。
  15. * 形状足够了——偏移错了路径就不再是路径(会带上 hash 前缀或整段错位),基准错了三条命令之间
  16. * 就会不一致(这正是第 2、3 条要防的那个 bug)。
  17. *
  18. * parser smoke 不在 git 仓库里(或没有 git)时跳过;外部命令回归必须有 Git,不跳过。
  19. */
  20. import { execFile, execFileSync } from "node:child_process";
  21. import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
  22. import { tmpdir } from "node:os";
  23. import { join } from "node:path";
  24. import { promisify } from "node:util";
  25. import { describe, expect, it } from "vitest";
  26. import {
  27. GIT_LOG_PRETTY,
  28. GIT_SHOW_PREFIX_ARGV,
  29. GIT_STATUS_ARGV,
  30. GIT_UNTRACKED_ARGV,
  31. gitChangedFilesPlan,
  32. gitDiffArgv,
  33. parseGitLog,
  34. parseGitPathList,
  35. parseGitShowPrefix,
  36. parseGitStatusPorcelainV2,
  37. } from "../src/app/workflow-git-world-read.js";
  38. const execGit = promisify(execFile);
  39. describe("real git diff — external commands", () => {
  40. it.each(["external", "textconv"])("does not execute a configured %s command", async (kind) => {
  41. const cwd = await mkdtemp(join(tmpdir(), "workflow-git-diff-"));
  42. const env: NodeJS.ProcessEnv = {
  43. ...process.env,
  44. GIT_CONFIG_NOSYSTEM: "1",
  45. GIT_CONFIG_GLOBAL: join(cwd, "empty.gitconfig"),
  46. GIT_CONFIG_COUNT: "0",
  47. GIT_ATTR_NOSYSTEM: "1",
  48. };
  49. for (const key of [
  50. "GIT_DIR",
  51. "GIT_WORK_TREE",
  52. "GIT_INDEX_FILE",
  53. "GIT_EXTERNAL_DIFF",
  54. "GIT_CONFIG_PARAMETERS",
  55. ]) {
  56. delete env[key];
  57. }
  58. const run = async (args: readonly string[]) =>
  59. (await execGit("git", [...args], { cwd, env })).stdout;
  60. const marker = join(cwd, ".git", "diff-probe.calls");
  61. try {
  62. await run(["init", "-q"]);
  63. await run(["config", "user.name", "Git Diff Test"]);
  64. await run(["config", "user.email", "git-diff@example.invalid"]);
  65. await run(["config", "commit.gpgsign", "false"]);
  66. await run(["config", "core.hooksPath", join(cwd, "empty-hooks")]);
  67. await writeFile(join(cwd, ".gitattributes"), "sample.txt diff=probe\n");
  68. await writeFile(join(cwd, "sample.txt"), "original before\n");
  69. await run(["add", ".gitattributes", "sample.txt"]);
  70. await run(["commit", "-qm", "baseline"]);
  71. await writeFile(join(cwd, "sample.txt"), "original after\n");
  72. await writeFile(
  73. join(cwd, ".git", "diff-probe.cjs"),
  74. [
  75. 'const { appendFile } = require("node:fs/promises");',
  76. 'appendFile(".git/diff-probe.calls", "called\\n").then(() => process.stdout.write("converted\\n"));',
  77. ].join("\n"),
  78. );
  79. await run([
  80. "config",
  81. kind === "external" ? "diff.external" : "diff.probe.textconv",
  82. "node .git/diff-probe.cjs",
  83. ]);
  84. // 先证明 fixture 的命令可执行,避免因配置失效而得到“未调用”的假通过。
  85. await run(["diff", "HEAD", "--", "sample.txt"]);
  86. expect(await readFile(marker, "utf8")).toContain("called");
  87. await rm(marker);
  88. const patch = await run(gitDiffArgv(undefined, "sample.txt"));
  89. expect(patch).toContain("-original before");
  90. expect(patch).toContain("+original after");
  91. expect(patch).not.toContain("converted");
  92. for (const base of [undefined, "HEAD"]) {
  93. const paths: string[] = [];
  94. for (const plan of gitChangedFilesPlan(base)) {
  95. paths.push(...parseGitPathList(await run(plan.argv), ""));
  96. }
  97. expect(paths).toEqual(["sample.txt"]);
  98. }
  99. await expect(readFile(marker, "utf8")).rejects.toMatchObject({ code: "ENOENT" });
  100. } finally {
  101. await rm(cwd, { recursive: true, force: true });
  102. }
  103. });
  104. });
  105. /** 跑一条 git;不可用(无 git / 非仓库)时返回 undefined 让用例跳过。 */
  106. function git(args: readonly string[]): string | undefined {
  107. try {
  108. return execFileSync("git", [...args], {
  109. cwd: process.cwd(),
  110. encoding: "utf8",
  111. stdio: ["ignore", "pipe", "ignore"],
  112. maxBuffer: 32 * 1024 * 1024,
  113. });
  114. } catch {
  115. return undefined;
  116. }
  117. }
  118. const ISO_8601 = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:Z|[+-]\d{2}:\d{2})$/;
  119. /** 交出去的路径必须是**工作区相对**的:不越界、不带仓库根前缀的残留。 */
  120. function expectWorkspaceRelative(path: string): void {
  121. expect(path.length).toBeGreaterThan(0);
  122. // 越界的路径是这套收束要防的那件事——脚本会拿它去 files.read。
  123. expect(path.startsWith("../")).toBe(false);
  124. expect(path.startsWith("/")).toBe(false);
  125. expect(path.split("/").includes("..")).toBe(false);
  126. // 路径不该以定长字段的残留开头:XY 位、mode、或一段 40 位 hash。
  127. expect(path).not.toMatch(/^[.MADRCU]{2}\s/);
  128. expect(path).not.toMatch(/^\d{6}\s/);
  129. expect(path).not.toMatch(/^[0-9a-f]{40}\s/);
  130. }
  131. describe("real git output — parser smoke", () => {
  132. it("parses this repository's actual porcelain-v2 -z status", () => {
  133. const prefixRaw = git(GIT_SHOW_PREFIX_ARGV);
  134. const raw = git(GIT_STATUS_ARGV);
  135. if (prefixRaw === undefined || raw === undefined) return;
  136. const prefix = parseGitShowPrefix(prefixRaw);
  137. const status = parseGitStatusPorcelainV2(raw, prefix);
  138. // 分支名要么缺席(detached),要么是一个非空且不含空格的名字。偏移读错时这里会拿到
  139. // 一段带 oid 的残句。
  140. if (status.branch !== undefined) {
  141. expect(status.branch.length).toBeGreaterThan(0);
  142. expect(status.branch).not.toContain(" ");
  143. }
  144. for (const bucket of [status.staged, status.unstaged, status.untracked]) {
  145. expect(Array.isArray(bucket)).toBe(true);
  146. for (const path of bucket) expectWorkspaceRelative(path);
  147. // 每个桶内部去重且已排序(journal 存的是这个值,必须只依赖内容)。
  148. expect(bucket).toEqual([...new Set(bucket)].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0)));
  149. }
  150. // clean 与三个桶必须一致——它是从桶算出来的,这条断言防的是有人改成别的来源。
  151. const empty =
  152. status.staged.length === 0 && status.unstaged.length === 0 && status.untracked.length === 0;
  153. expect(status.clean).toBe(empty);
  154. });
  155. it("agrees on one path base across all three path-producing commands", () => {
  156. // 这是第 2、3 条假设的回归防线,也是这份冒烟最有价值的一条:三条命令的 git 默认基准各不
  157. // 相同(status -z 根相对、diff 根相对、ls-files cwd 相对),所以只要有一条的 argv 少了
  158. // 对齐用的 flag,它交出的路径就会与另外两条不在同一个基准上。这里断言它们的**并集**
  159. // 整体都是工作区相对的——基准混搭时,走错基准的那一批会立刻违反它。
  160. const prefixRaw = git(GIT_SHOW_PREFIX_ARGV);
  161. if (prefixRaw === undefined) return;
  162. const prefix = parseGitShowPrefix(prefixRaw);
  163. const plans = gitChangedFilesPlan(undefined);
  164. // 无 base 时是"已跟踪 diff + 未跟踪 ls-files"两条命令,且第二条恰是那份固定 argv。
  165. expect(plans).toHaveLength(2);
  166. expect(plans[1]?.argv).toEqual(GIT_UNTRACKED_ARGV);
  167. for (const plan of plans) {
  168. const raw = git(plan.argv);
  169. if (raw === undefined) return;
  170. for (const path of parseGitPathList(raw, prefix)) expectWorkspaceRelative(path);
  171. }
  172. });
  173. it("parses this repository's actual log records", () => {
  174. const raw = git(["log", "-n3", GIT_LOG_PRETTY]);
  175. if (raw === undefined) return;
  176. const commits = parseGitLog(raw);
  177. expect(commits.length).toBeGreaterThan(0);
  178. for (const commit of commits) {
  179. // 全长 hash(`%H`),不是缩写——脚本可能拿它去比较。
  180. expect(commit.hash).toMatch(/^[0-9a-f]{40}$/);
  181. expect(commit.subject.length).toBeGreaterThan(0);
  182. // subject 里绝不该出现换行或 NUL:前者会破坏按行切分,后者会破坏按字段切分。
  183. // `%s` 按定义是单行,这也是 log 这一条不需要 `-z` 的理由。
  184. expect(commit.subject).not.toContain("\n");
  185. expect(commit.subject).not.toContain("�");
  186. expect(commit.author.length).toBeGreaterThan(0);
  187. // `%aI` 是严格 ISO 8601。日期落到 author 位(偏移错一格)会在这里失败。
  188. expect(commit.date).toMatch(ISO_8601);
  189. }
  190. });
  191. });