native-search-tools-process.mjs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. import { spawnSync } from "node:child_process";
  2. import { createHash } from "node:crypto";
  3. import { mkdirSync, readFileSync } from "node:fs";
  4. import { join } from "node:path";
  5. function formatCommand(command, args) {
  6. return [command, ...args].join(" ");
  7. }
  8. export function run(command, args, { cwd, env, quiet = false, input } = {}) {
  9. const result = spawnSync(command, args, {
  10. cwd,
  11. env,
  12. input,
  13. encoding: "utf8",
  14. maxBuffer: 64 * 1024 * 1024,
  15. stdio: quiet ? [input === undefined ? "ignore" : "pipe", "pipe", "pipe"] : "inherit",
  16. });
  17. if (result.error) {
  18. throw result.error;
  19. }
  20. if (result.status !== 0) {
  21. const details = quiet
  22. ? `\nstdout:\n${result.stdout ?? ""}\nstderr:\n${result.stderr ?? ""}`
  23. : "";
  24. throw new Error(`${formatCommand(command, args)} failed with code ${result.status}${details}`);
  25. }
  26. return result;
  27. }
  28. export function runCapture(command, args, options = {}) {
  29. const result = spawnSync(command, args, {
  30. ...options,
  31. encoding: "utf8",
  32. maxBuffer: 64 * 1024 * 1024,
  33. stdio: ["ignore", "pipe", "pipe"],
  34. });
  35. if (result.error) {
  36. throw result.error;
  37. }
  38. if (result.status !== 0) {
  39. throw new Error(
  40. `${formatCommand(command, args)} failed with code ${result.status}\nstdout:\n${result.stdout}\nstderr:\n${result.stderr}`,
  41. );
  42. }
  43. return result.stdout;
  44. }
  45. function sha256(path) {
  46. return createHash("sha256").update(readFileSync(path)).digest("hex");
  47. }
  48. export function downloadAndExtractSources({ sources, workDir, env, quiet }) {
  49. const archivesDir = join(workDir, "archives");
  50. const sourcesDir = join(workDir, "sources");
  51. mkdirSync(archivesDir, { recursive: true });
  52. mkdirSync(sourcesDir, { recursive: true });
  53. const sourcePaths = {};
  54. for (const source of sources) {
  55. console.log(`==> Download ${source.id} ${source.version}`);
  56. const archivePath = join(archivesDir, `${source.id}.tar.gz`);
  57. run("curl", ["-L", "--fail", "--retry", "3", "-o", archivePath, source.url], {
  58. env,
  59. quiet,
  60. });
  61. const actualSha256 = sha256(archivePath);
  62. if (actualSha256 !== source.sha256) {
  63. throw new Error(
  64. `${source.id} archive checksum mismatch: expected ${source.sha256}, received ${actualSha256}`,
  65. );
  66. }
  67. const sourcePath = join(sourcesDir, source.id);
  68. mkdirSync(sourcePath, { recursive: true });
  69. run("tar", ["-xzf", archivePath, "-C", sourcePath, "--strip-components=1"], {
  70. env,
  71. quiet,
  72. });
  73. sourcePaths[source.id] = sourcePath;
  74. }
  75. return sourcePaths;
  76. }