plug-worker.ts 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. import path from "path"
  2. import { createPlugTask, type PlugCtx, type PlugDeps } from "../../src/cli/cmd/plug"
  3. import { Filesystem } from "../../src/util/filesystem"
  4. type Msg = {
  5. dir: string
  6. target: string
  7. mod: string
  8. global?: boolean
  9. force?: boolean
  10. globalDir?: string
  11. vcs?: string
  12. worktree?: string
  13. directory?: string
  14. holdMs?: number
  15. }
  16. function sleep(ms: number) {
  17. return new Promise<void>((resolve) => {
  18. setTimeout(resolve, ms)
  19. })
  20. }
  21. function input() {
  22. const raw = process.argv[2]
  23. if (!raw) {
  24. throw new Error("Missing plug worker input")
  25. }
  26. const msg = JSON.parse(raw) as Partial<Msg>
  27. if (!msg.dir || !msg.target || !msg.mod) {
  28. throw new Error("Invalid plug worker input")
  29. }
  30. return msg as Msg
  31. }
  32. function deps(msg: Msg): PlugDeps {
  33. return {
  34. spinner: () => ({
  35. start() {},
  36. stop() {},
  37. }),
  38. log: {
  39. error() {},
  40. info() {},
  41. success() {},
  42. },
  43. resolve: async () => msg.target,
  44. readText: (file) => Filesystem.readText(file),
  45. write: async (file, text) => {
  46. if (msg.holdMs && msg.holdMs > 0) {
  47. await sleep(msg.holdMs)
  48. }
  49. await Filesystem.write(file, text)
  50. },
  51. exists: (file) => Filesystem.exists(file),
  52. files: (dir, name) => [path.join(dir, `${name}.jsonc`), path.join(dir, `${name}.json`)],
  53. global: msg.globalDir ?? path.join(msg.dir, ".global"),
  54. }
  55. }
  56. function ctx(msg: Msg): PlugCtx {
  57. return {
  58. vcs: msg.vcs ?? "git",
  59. worktree: msg.worktree ?? msg.dir,
  60. directory: msg.directory ?? msg.dir,
  61. }
  62. }
  63. async function main() {
  64. const msg = input()
  65. const run = createPlugTask(
  66. {
  67. mod: msg.mod,
  68. global: msg.global,
  69. force: msg.force,
  70. },
  71. deps(msg),
  72. )
  73. const ok = await run(ctx(msg))
  74. if (!ok) {
  75. throw new Error("Plug task failed")
  76. }
  77. }
  78. await main().catch((err) => {
  79. const text = err instanceof Error ? (err.stack ?? err.message) : String(err)
  80. process.stderr.write(text)
  81. process.exit(1)
  82. })