opencode 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. #!/usr/bin/env node
  2. const childProcess = require("child_process")
  3. const fs = require("fs")
  4. const path = require("path")
  5. const os = require("os")
  6. function run(target) {
  7. const result = childProcess.spawnSync(target, process.argv.slice(2), {
  8. stdio: "inherit",
  9. })
  10. if (result.error) {
  11. console.error(result.error.message)
  12. process.exit(1)
  13. }
  14. const code = typeof result.status === "number" ? result.status : 0
  15. process.exit(code)
  16. }
  17. const envPath = process.env.OPENCODE_BIN_PATH
  18. if (envPath) {
  19. run(envPath)
  20. }
  21. const scriptPath = fs.realpathSync(__filename)
  22. const scriptDir = path.dirname(scriptPath)
  23. const platformMap = {
  24. darwin: "darwin",
  25. linux: "linux",
  26. win32: "windows",
  27. }
  28. const archMap = {
  29. x64: "x64",
  30. arm64: "arm64",
  31. arm: "arm",
  32. }
  33. let platform = platformMap[os.platform()]
  34. if (!platform) {
  35. platform = os.platform()
  36. }
  37. let arch = archMap[os.arch()]
  38. if (!arch) {
  39. arch = os.arch()
  40. }
  41. const base = "opencode-" + platform + "-" + arch
  42. const binary = platform === "windows" ? "opencode.exe" : "opencode"
  43. function findBinary(startDir) {
  44. let current = startDir
  45. for (;;) {
  46. const modules = path.join(current, "node_modules")
  47. if (fs.existsSync(modules)) {
  48. const entries = fs.readdirSync(modules)
  49. for (const entry of entries) {
  50. if (!entry.startsWith(base)) {
  51. continue
  52. }
  53. const candidate = path.join(modules, entry, "bin", binary)
  54. if (fs.existsSync(candidate)) {
  55. return candidate
  56. }
  57. }
  58. }
  59. const parent = path.dirname(current)
  60. if (parent === current) {
  61. return
  62. }
  63. current = parent
  64. }
  65. }
  66. const resolved = findBinary(scriptDir)
  67. if (!resolved) {
  68. console.error(
  69. 'It seems that your package manager failed to install the right version of the opencode CLI for your platform. You can try manually installing the "' +
  70. base +
  71. '" package',
  72. )
  73. process.exit(1)
  74. }
  75. run(resolved)