global.ts 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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 { makeGlobalNode } from "./effect/app-node"
  9. const app = "kirincode"
  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.KIRINCODE_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>()("@kirincode/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.KIRINCODE_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. const layer = Layer.effect(
  66. Service,
  67. Effect.sync(() => Service.of(make())),
  68. )
  69. export const node = makeGlobalNode({ service: Service, layer: layer, deps: [] })
  70. export const layerWith = (input: Partial<Interface>) =>
  71. Layer.effect(
  72. Service,
  73. Effect.sync(() => Service.of(make(input))),
  74. )
  75. export * as Global from "./global"