upstream-snapshot.mjs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import { readFile } from "node:fs/promises";
  2. import { resolve } from "node:path";
  3. import { gitFileNames } from "./git-file-names.mjs";
  4. export function isSnapshotPath(value) {
  5. return (
  6. typeof value === "string" &&
  7. !value.includes("\\") &&
  8. value.split("/").every((part) => part && part !== "." && part !== "..") &&
  9. !value.includes(":")
  10. );
  11. }
  12. function isFileMap(files) {
  13. return (
  14. files &&
  15. typeof files === "object" &&
  16. !Array.isArray(files) &&
  17. Object.entries(files).every(
  18. ([file, blob]) =>
  19. isSnapshotPath(file) &&
  20. typeof blob === "string" &&
  21. /^(100644|100755|120000) [a-f0-9]{40}$/.test(blob),
  22. )
  23. );
  24. }
  25. /** 独立公开历史没有源仓库对象;固定内容与模式仍须同时匹配暂存区和工作区。 */
  26. export async function readUpstreamSnapshot(cwd, snapshotPath) {
  27. if (!isSnapshotPath(snapshotPath)) throw new Error("acceptedUpstreamSnapshot 路径无效");
  28. const snapshot = JSON.parse(await readFile(resolve(cwd, snapshotPath), "utf8"));
  29. if (
  30. snapshot.version !== 1 ||
  31. !isFileMap(snapshot.files) ||
  32. !isFileMap(snapshot.historicalFiles ?? {}) ||
  33. !Array.isArray(snapshot.introduced) ||
  34. !snapshot.introduced.every(isSnapshotPath)
  35. ) {
  36. throw new Error("acceptedUpstreamSnapshot 清单无效");
  37. }
  38. const [index, dirty] = await Promise.all([
  39. gitFileNames(cwd, ["ls-files", "--stage", "-z"]),
  40. gitFileNames(cwd, [
  41. "diff",
  42. "--no-ext-diff",
  43. "--no-textconv",
  44. "--no-renames",
  45. "--name-only",
  46. "-z",
  47. "--",
  48. ]),
  49. ]);
  50. const different = new Set(dirty);
  51. const accepted = new Set();
  52. const historical = new Set();
  53. for (const entry of index) {
  54. const separator = entry.indexOf("\t");
  55. const file = entry.slice(separator + 1);
  56. const [mode, blob, stage] = entry.slice(0, separator).split(" ");
  57. if (stage === "0" && !different.has(file) && snapshot.files[file] === `${mode} ${blob}`)
  58. accepted.add(file);
  59. if (
  60. stage === "0" &&
  61. !different.has(file) &&
  62. snapshot.historicalFiles?.[file] === `${mode} ${blob}`
  63. )
  64. historical.add(file);
  65. }
  66. return { accepted, historical, introduced: snapshot.introduced };
  67. }