anchor.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. #!/usr/bin/env node
  2. const { spawn, spawnSync } = require("child_process");
  3. const path = require("path");
  4. const { arch, platform } = require("os");
  5. const { version } = require("./package.json");
  6. const PACKAGE_VERSION = `anchor-cli ${version}`;
  7. const PACKAGE_ANCHOR_PATH = path.join(__dirname, "anchor");
  8. function getBinaryVersion(location) {
  9. const result = spawnSync(location, ["--version"]);
  10. const error =
  11. (result.error && result.error.toString()) ||
  12. (result.stderr.length > 0 && result.stderr.toString().trim()) ||
  13. null;
  14. return [error, result.stdout && result.stdout.toString().trim()];
  15. }
  16. function runAnchor(location) {
  17. const args = process.argv.slice(2);
  18. const anchor = spawn(location, args, { stdio: "inherit" });
  19. anchor.on("exit", (code, signal) => {
  20. process.on("exit", () => {
  21. if (signal) {
  22. process.kill(process.pid, signal);
  23. } else {
  24. process.exit(code);
  25. }
  26. });
  27. });
  28. process.on("SIGINT", function () {
  29. anchor.kill("SIGINT");
  30. anchor.kill("SIGTERM");
  31. });
  32. }
  33. function tryPackageAnchor() {
  34. if (arch() !== "x64" || platform() !== "linux") {
  35. console.error(`Only x86_64 / Linux distributed in NPM package right now.`);
  36. return false;
  37. }
  38. const [error, binaryVersion] = getBinaryVersion(PACKAGE_ANCHOR_PATH);
  39. if (error !== null) {
  40. console.error(`Failed to get version of local binary: ${error}`);
  41. return false;
  42. }
  43. if (binaryVersion !== PACKAGE_VERSION) {
  44. console.error(
  45. `Package binary version is not correct. Expected "${PACKAGE_VERSION}", found "${binaryVersion}".`
  46. );
  47. return false;
  48. }
  49. runAnchor(PACKAGE_ANCHOR_PATH);
  50. return true;
  51. }
  52. function trySystemAnchor() {
  53. console.error("Trying globally installed anchor.");
  54. const added = path.dirname(process.argv[1]);
  55. const directories = process.env.PATH.split(":").filter(
  56. (dir) => dir !== added
  57. );
  58. process.env.PATH = directories.join(":");
  59. const [error, binaryVersion] = getBinaryVersion("anchor");
  60. if (error !== null) {
  61. console.error(`Failed to get version of global binary: ${error}`);
  62. return;
  63. }
  64. if (binaryVersion !== PACKAGE_VERSION) {
  65. console.error(
  66. `Globally installed anchor version is not correct. Expected "${PACKAGE_VERSION}", found "${binaryVersion}".`
  67. );
  68. return;
  69. }
  70. runAnchor("anchor");
  71. }
  72. tryPackageAnchor() || trySystemAnchor();