spawn.ts 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import { cmd } from "@/cli/cmd/cmd"
  2. import { Instance } from "@/project/instance"
  3. import path from "path"
  4. import { Server } from "@/server/server"
  5. import { upgrade } from "@/cli/upgrade"
  6. export const TuiSpawnCommand = cmd({
  7. command: "spawn [project]",
  8. builder: (yargs) =>
  9. yargs
  10. .positional("project", {
  11. type: "string",
  12. describe: "path to start opencode in",
  13. })
  14. .option("port", {
  15. type: "number",
  16. describe: "port to listen on",
  17. default: 0,
  18. })
  19. .option("hostname", {
  20. type: "string",
  21. describe: "hostname to listen on",
  22. default: "127.0.0.1",
  23. }),
  24. handler: async (args) => {
  25. upgrade()
  26. const server = Server.listen({
  27. port: args.port,
  28. hostname: "127.0.0.1",
  29. })
  30. const bin = process.execPath
  31. const cmd = []
  32. let cwd = process.cwd()
  33. if (bin.endsWith("bun")) {
  34. cmd.push(
  35. process.execPath,
  36. "run",
  37. "--conditions",
  38. "browser",
  39. new URL("../../../index.ts", import.meta.url).pathname,
  40. )
  41. cwd = new URL("../../../../", import.meta.url).pathname
  42. } else cmd.push(process.execPath)
  43. cmd.push("attach", server.url.toString(), "--dir", args.project ? path.resolve(args.project) : process.cwd())
  44. const proc = Bun.spawn({
  45. cmd,
  46. cwd,
  47. stdout: "inherit",
  48. stderr: "inherit",
  49. stdin: "inherit",
  50. env: {
  51. ...process.env,
  52. BUN_OPTIONS: "",
  53. },
  54. })
  55. await proc.exited
  56. await Instance.disposeAll()
  57. await server.stop(true)
  58. },
  59. })