prebuilt-binary-extract.mjs 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141
  1. import { createHash } from "node:crypto";
  2. import {
  3. chmodSync,
  4. copyFileSync,
  5. mkdirSync,
  6. mkdtempSync,
  7. readFileSync,
  8. readdirSync,
  9. rmSync,
  10. } from "node:fs";
  11. import { tmpdir } from "node:os";
  12. import { dirname, join, relative } from "node:path";
  13. import process from "node:process";
  14. import { runCommand } from "./spawn-command.mjs";
  15. // Bugfix: Windows GNU tar(Git Bash)会把绝对路径里的盘符冒号(C:)当成远程主机名,
  16. // 反斜杠路径也会被 MSYS 参数转换破坏。tar 参数统一转正斜杠,归档路径优先改用
  17. // 相对 cwd 的形式避开盘符冒号;对 bsdtar 与 Linux/macOS CI 无影响。
  18. function toTarPosixPath(pathValue) {
  19. return pathValue.replaceAll("\\", "/");
  20. }
  21. function resolveTarArchiveArg(archivePath, cwd) {
  22. if (process.platform === "win32") {
  23. try {
  24. const relativeArchivePath = relative(cwd, archivePath);
  25. if (relativeArchivePath && !relativeArchivePath.startsWith("..")) {
  26. return toTarPosixPath(relativeArchivePath);
  27. }
  28. } catch {
  29. // 跨盘符时 relative 会抛错,退回正斜杠绝对路径(bsdtar 可用)。
  30. }
  31. }
  32. return toTarPosixPath(archivePath);
  33. }
  34. export function extractPrebuiltArchive({ archivePath, archiveExt, extractDir, cwd }) {
  35. mkdirSync(extractDir, { recursive: true });
  36. if (archiveExt === "zip") {
  37. if (process.platform === "win32") {
  38. runCommand("powershell.exe", [
  39. "-NoProfile",
  40. "-NonInteractive",
  41. "-ExecutionPolicy",
  42. "Bypass",
  43. "-Command",
  44. `Expand-Archive -LiteralPath '${archivePath.replaceAll("'", "''")}' -DestinationPath '${extractDir.replaceAll("'", "''")}' -Force`,
  45. ]);
  46. return;
  47. }
  48. runCommand("unzip", ["-q", archivePath, "-d", extractDir], { cwd });
  49. return;
  50. }
  51. const tarCwd = cwd ?? process.cwd();
  52. runCommand(
  53. "tar",
  54. ["-xzf", resolveTarArchiveArg(archivePath, tarCwd), "-C", toTarPosixPath(extractDir)],
  55. { cwd: tarCwd },
  56. );
  57. }
  58. export function findPrebuiltBinary(rootDir, binaryName) {
  59. const entries = readdirSync(rootDir, { withFileTypes: true });
  60. for (const entry of entries) {
  61. const fullPath = join(rootDir, entry.name);
  62. if (entry.isDirectory()) {
  63. const nested = findPrebuiltBinary(fullPath, binaryName);
  64. if (nested) return nested;
  65. continue;
  66. }
  67. if (entry.isFile() && entry.name === binaryName) return fullPath;
  68. }
  69. return undefined;
  70. }
  71. export function assertPrebuiltArchiveSha256(expectedSha256) {
  72. const normalizedExpectedSha256 = String(expectedSha256 ?? "")
  73. .trim()
  74. .toLowerCase();
  75. if (!/^[a-f0-9]{64}$/u.test(normalizedExpectedSha256)) {
  76. throw new Error("missing prebuilt archive SHA-256");
  77. }
  78. return normalizedExpectedSha256;
  79. }
  80. export function verifyPrebuiltArchiveSha256(archivePath, expectedSha256) {
  81. const normalizedExpectedSha256 = assertPrebuiltArchiveSha256(expectedSha256);
  82. const actualSha256 = createHash("sha256").update(readFileSync(archivePath)).digest("hex");
  83. if (actualSha256 !== normalizedExpectedSha256) {
  84. throw new Error(
  85. `Archive SHA-256 mismatch: expected ${normalizedExpectedSha256}, received ${actualSha256}`,
  86. );
  87. }
  88. }
  89. export async function extractPrebuiltBinary({
  90. archiveExt,
  91. archivePath,
  92. archiveSha256,
  93. binaryName,
  94. binaryPath,
  95. cwd,
  96. targetPlatform,
  97. validateBinary,
  98. }) {
  99. verifyPrebuiltArchiveSha256(archivePath, archiveSha256);
  100. mkdirSync(dirname(binaryPath), { recursive: true });
  101. mkdirSync(tmpdir(), { recursive: true });
  102. const tempDir = mkdtempSync(join(tmpdir(), "zcode-prebuilt-binary-"));
  103. const extractDir = join(tempDir, "extract");
  104. try {
  105. extractPrebuiltArchive({ archivePath, archiveExt, extractDir, cwd });
  106. const extractedBinaryPath = findPrebuiltBinary(extractDir, binaryName);
  107. if (!extractedBinaryPath) {
  108. throw new Error(`Failed to locate ${binaryName} in extracted archive`);
  109. }
  110. // foreign target 不能靠执行目标文件验真,必须在覆盖正式路径前校验临时产物。
  111. await validateBinary?.(extractedBinaryPath);
  112. copyFileSync(extractedBinaryPath, binaryPath);
  113. if (targetPlatform !== "win32") {
  114. chmodSync(binaryPath, 0o755);
  115. }
  116. } finally {
  117. // Bugfix: Windows 下解压产物可能被杀毒/索引器或尚未退出的解压子进程短暂持有句柄,
  118. // rmSync 立即删除会 EPERM,且 finally 里抛出的异常会掩盖真正的解压错误。
  119. // 带重试删除,失败时仅告警,让原始错误正常抛出。
  120. try {
  121. rmSync(tempDir, { force: true, recursive: true, maxRetries: 10, retryDelay: 500 });
  122. } catch (error) {
  123. console.warn(`[warn] 清理临时目录失败(可忽略): ${tempDir}`);
  124. console.warn(`[warn] ${String(error)}`);
  125. }
  126. }
  127. }