reference.ts 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. export * as ConfigReferencePlugin from "./reference"
  2. import { define } from "../../plugin/internal"
  3. import path from "path"
  4. import { Effect } from "effect"
  5. import { Config } from "../../config"
  6. import { ConfigReference } from "../reference"
  7. import { Reference } from "../../reference"
  8. import { AbsolutePath } from "../../schema"
  9. import { Global } from "../../global"
  10. import { Location } from "../../location"
  11. export const Plugin = define({
  12. id: "core/config-reference",
  13. effect: Effect.fn(function* (ctx) {
  14. const config = yield* Config.Service
  15. const location = yield* Location.Service
  16. const global = yield* Global.Service
  17. yield* ctx.reference.transform(
  18. Effect.fn(function* (draft) {
  19. const entries = new Map<string, Reference.Source>()
  20. for (const doc of (yield* config.entries()).filter(
  21. (entry): entry is Config.Document => entry.type === "document",
  22. )) {
  23. const directory = doc.path ? path.dirname(doc.path) : location.directory
  24. for (const [name, entry] of Object.entries(doc.info.references ?? {})) {
  25. if (!validAlias(name)) continue
  26. entries.set(
  27. name,
  28. local(entry)
  29. ? Reference.LocalSource.make({
  30. type: "local",
  31. path: AbsolutePath.make(
  32. localPath(directory, global.home, typeof entry === "string" ? entry : entry.path),
  33. ),
  34. description: typeof entry === "string" ? undefined : entry.description,
  35. hidden: typeof entry === "string" ? undefined : entry.hidden,
  36. })
  37. : Reference.GitSource.make({
  38. type: "git",
  39. repository: typeof entry === "string" ? entry : entry.repository,
  40. branch: typeof entry === "string" ? undefined : entry.branch,
  41. description: typeof entry === "string" ? undefined : entry.description,
  42. hidden: typeof entry === "string" ? undefined : entry.hidden,
  43. }),
  44. )
  45. }
  46. }
  47. for (const [name, source] of entries) draft.add(name, source)
  48. }),
  49. )
  50. }),
  51. })
  52. function validAlias(name: string) {
  53. return name.length > 0 && !/[\/\s`,]/.test(name)
  54. }
  55. function local(entry: ConfigReference.Entry): entry is string | ConfigReference.Local {
  56. return typeof entry === "string"
  57. ? entry.startsWith(".") || entry.startsWith("/") || entry.startsWith("~")
  58. : "path" in entry
  59. }
  60. function localPath(directory: string, home: string, value: string) {
  61. if (value.startsWith("~/")) return path.join(home, value.slice(2))
  62. return path.isAbsolute(value) ? value : path.resolve(directory, value)
  63. }