arms-patch-install-contract.test.mjs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import assert from "node:assert/strict";
  2. import { createHash } from "node:crypto";
  3. import { readFile } from "node:fs/promises";
  4. import test from "node:test";
  5. const repositoryRoot = new URL("../../", import.meta.url);
  6. async function readJson(relativePath) {
  7. return JSON.parse(await readFile(new URL(relativePath, repositoryRoot), "utf8"));
  8. }
  9. function gitBlobHash(content) {
  10. return createHash("sha1")
  11. .update(`blob ${content.byteLength}\0`)
  12. .update(content)
  13. .digest("hex");
  14. }
  15. function assertCoherentHunkOffsets(patch) {
  16. const hunkPattern = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/gmu;
  17. let accumulatedDelta = 0;
  18. let hunkCount = 0;
  19. for (const match of patch.matchAll(hunkPattern)) {
  20. const sourceStart = Number(match[1]);
  21. const sourceCount = Number(match[2] ?? 1);
  22. const targetStart = Number(match[3]);
  23. const targetCount = Number(match[4] ?? 1);
  24. assert.equal(
  25. targetStart,
  26. sourceStart + accumulatedDelta,
  27. `第 ${hunkCount + 1} 个 hunk 目标行号未累计前序偏移`,
  28. );
  29. accumulatedDelta += targetCount - sourceCount;
  30. hunkCount += 1;
  31. }
  32. assert.ok(hunkCount > 1, "ARMS patch 应包含多个连续 hunk");
  33. }
  34. test("ARMS patch 固定 0.0.3 且目标 blob 与安装产物一致", async () => {
  35. const [rootManifest, desktopManifest, npmrc, patch, installedEntry] = await Promise.all([
  36. readJson("package.json"),
  37. readJson("packages/desktop/package.json"),
  38. readFile(new URL(".npmrc", repositoryRoot), "utf8"),
  39. readFile(new URL("patches/@arms__rum-electron@0.0.3.patch", repositoryRoot), "utf8"),
  40. readFile(new URL("node_modules/@arms/rum-electron/dist/index.mjs", repositoryRoot)),
  41. ]);
  42. assert.match(npmrc, /^node-linker=hoisted$/mu);
  43. const armsSpecifier = desktopManifest.dependencies?.["@arms/rum-electron"];
  44. assert.equal(armsSpecifier, "^0.0.3");
  45. const armsVersion = "0.0.3";
  46. assert.equal(
  47. rootManifest.pnpm?.patchedDependencies?.[`@arms/rum-electron@${armsVersion}`],
  48. `patches/@arms__rum-electron@${armsVersion}.patch`,
  49. );
  50. assert.equal(rootManifest.pnpm?.patchedDependencies?.["@arms/rum-electron@0.0.7"], undefined);
  51. // Bugfix:旧 patch 分次追加 hunk 后仍保留旧目标 hash,pnpm hoisted 第二次安装会误判并重复打补丁。
  52. const patchIndex = patch.match(/^index ([0-9a-f]{40})\.\.([0-9a-f]{40}) 100644$/mu);
  53. assert.ok(patchIndex, "patch 必须保留完整的 source/target blob hash");
  54. assertCoherentHunkOffsets(patch);
  55. assert.equal(gitBlobHash(installedEntry), patchIndex[2]);
  56. });