global.ts 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. import path from "path"
  2. import fs from "fs/promises"
  3. import { xdgData, xdgCache, xdgConfig, xdgState } from "xdg-basedir"
  4. import os from "os"
  5. import { Context, Effect, Layer } from "effect"
  6. import { Flock } from "./util/flock"
  7. import { Flag } from "./flag/flag"
  8. import { LayerNode } from "./effect/layer-node"
  9. const app = "opencode"
  10. const data = path.join(xdgData!, app)
  11. const cache = path.join(xdgCache!, app)
  12. const config = path.join(xdgConfig!, app)
  13. const state = path.join(xdgState!, app)
  14. const tmp = path.join(os.tmpdir(), app)
  15. const paths = {
  16. get home() {
  17. return process.env.OPENCODE_TEST_HOME ?? os.homedir()
  18. },
  19. data,
  20. bin: path.join(cache, "bin"),
  21. log: path.join(data, "log"),
  22. repos: path.join(data, "repos"),
  23. cache,
  24. config,
  25. state,
  26. tmp,
  27. }
  28. export const Path = paths
  29. Flock.setGlobal({ state })
  30. await Promise.all([
  31. fs.mkdir(Path.data, { recursive: true }),
  32. fs.mkdir(Path.config, { recursive: true }),
  33. fs.mkdir(Path.state, { recursive: true }),
  34. fs.mkdir(Path.tmp, { recursive: true }),
  35. fs.mkdir(Path.log, { recursive: true }),
  36. fs.mkdir(Path.bin, { recursive: true }),
  37. fs.mkdir(Path.repos, { recursive: true }),
  38. ])
  39. export class Service extends Context.Service<Service, Interface>()("@opencode/Global") {}
  40. export interface Interface {
  41. readonly home: string
  42. readonly data: string
  43. readonly cache: string
  44. readonly config: string
  45. readonly state: string
  46. readonly tmp: string
  47. readonly bin: string
  48. readonly log: string
  49. readonly repos: string
  50. }
  51. export function make(input: Partial<Interface> = {}): Interface {
  52. return {
  53. home: Path.home,
  54. data: Path.data,
  55. cache: Path.cache,
  56. config: Flag.OPENCODE_CONFIG_DIR ?? Path.config,
  57. state: Path.state,
  58. tmp: Path.tmp,
  59. bin: Path.bin,
  60. log: Path.log,
  61. repos: Path.repos,
  62. ...input,
  63. }
  64. }
  65. export const layer = Layer.effect(
  66. Service,
  67. Effect.sync(() => Service.of(make())),
  68. )
  69. export const defaultLayer = layer
  70. export const node = LayerNode.make(layer, [])
  71. export const layerWith = (input: Partial<Interface>) =>
  72. Layer.effect(
  73. Service,
  74. Effect.sync(() => Service.of(make(input))),
  75. )
  76. export * as Global from "./global"