project.ts 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  1. export * as ProjectV2 from "./project"
  2. export * as Project from "./project"
  3. import { Context, Effect, Layer, Schema } from "effect"
  4. import { eq } from "drizzle-orm"
  5. import path from "path"
  6. import { AbsolutePath, withStatics } from "./schema"
  7. import { FSUtil } from "./fs-util"
  8. import { Database } from "./database/database"
  9. import { Git } from "./git"
  10. import { Hash } from "./util/hash"
  11. import { ProjectDirectoryTable } from "./project/sql"
  12. export const ID = Schema.String.pipe(
  13. Schema.brand("Project.ID"),
  14. withStatics((schema) => ({
  15. global: schema.make("global"),
  16. })),
  17. )
  18. export type ID = typeof ID.Type
  19. export const Vcs = Schema.Union([
  20. Schema.Struct({
  21. type: Schema.Literal("git"),
  22. store: AbsolutePath,
  23. }),
  24. ])
  25. export type Vcs = typeof Vcs.Type
  26. export class Info extends Schema.Class<Info>("Project.Info")({
  27. id: ID,
  28. }) {}
  29. export const DirectoriesInput = Schema.Struct({
  30. projectID: ID,
  31. }).annotate({ identifier: "Project.DirectoriesInput" })
  32. export type DirectoriesInput = typeof DirectoriesInput.Type
  33. export const Directories = Schema.Array(AbsolutePath).annotate({ identifier: "Project.Directories" })
  34. export type Directories = typeof Directories.Type
  35. export interface Interface {
  36. readonly directories: (input: DirectoriesInput) => Effect.Effect<Directories>
  37. readonly resolve: (input: AbsolutePath) => Effect.Effect<
  38. {
  39. previous?: ID
  40. id: ID
  41. directory: AbsolutePath
  42. vcs?: Vcs
  43. },
  44. never
  45. >
  46. /**
  47. * Temporary bridge method for writing the resolved project ID to the repo-local cache.
  48. *
  49. * This exists while the old opencode project service and this core project
  50. * service work together: core resolves the ID, while the old service still owns
  51. * database migration and persistence. The old service should call this after it
  52. * finishes migrating from `resolve().previous` to `resolve().id`; once project
  53. * persistence moves into core, this separate bridge method can go away.
  54. */
  55. readonly commit: (input: { store: AbsolutePath; id: ID }) => Effect.Effect<void>
  56. }
  57. export class Service extends Context.Service<Service, Interface>()("@opencode/ProjectV2") {}
  58. export const layer = Layer.effect(
  59. Service,
  60. Effect.gen(function* () {
  61. const db = (yield* Database.Service).db
  62. const fs = yield* FSUtil.Service
  63. const git = yield* Git.Service
  64. const directories = Effect.fn("Project.directories")(function* (input: DirectoriesInput) {
  65. const rows = yield* db
  66. .select({ directory: ProjectDirectoryTable.directory })
  67. .from(ProjectDirectoryTable)
  68. .where(eq(ProjectDirectoryTable.project_id, input.projectID))
  69. .all()
  70. .pipe(Effect.orDie)
  71. return rows
  72. .toSorted((a, b) => a.directory.localeCompare(b.directory))
  73. .map((row) => AbsolutePath.make(row.directory))
  74. })
  75. const cached = Effect.fnUntraced(function* (dir: string) {
  76. return yield* fs.readFileString(path.join(dir, "opencode")).pipe(
  77. Effect.map((value) => value.trim()),
  78. Effect.map((value) => (value ? ID.make(value) : undefined)),
  79. Effect.catch(() => Effect.succeed(undefined)),
  80. )
  81. })
  82. const remote = Effect.fnUntraced(function* (repo: Git.Repo) {
  83. const origin = yield* git.remote(repo)
  84. if (!origin) return undefined
  85. const normalized = url(origin)
  86. if (!normalized) return undefined
  87. return ID.make(Hash.fast(`git-remote:${normalized}`))
  88. })
  89. function url(input: string) {
  90. const value = input.trim()
  91. if (!value) return undefined
  92. try {
  93. const parsed = new URL(value)
  94. if (parsed.protocol === "file:") return undefined
  95. return parts(parsed.hostname, parsed.pathname)
  96. } catch {
  97. const scp = value.match(/^([^@/:]+@)?([^/:]+):(.+)$/)
  98. if (scp) return parts(scp[2], scp[3])
  99. return undefined
  100. }
  101. }
  102. function parts(host: string, name: string) {
  103. const pathname = name
  104. .replace(/^\/+/, "")
  105. .replace(/\.git\/?$/, "")
  106. .replace(/\/+$/, "")
  107. if (!host || !pathname) return undefined
  108. return `${host.toLowerCase()}/${pathname}`
  109. }
  110. const root = Effect.fnUntraced(function* (repo: Git.Repo) {
  111. const root = (yield* git.roots(repo))[0]
  112. return root ? ID.make(root) : undefined
  113. })
  114. const resolve = Effect.fn("Project.resolve")(function* (input: AbsolutePath) {
  115. const repo = yield* git.find(input)
  116. if (!repo) return { id: ID.global, directory: AbsolutePath.make(path.parse(input).root), vcs: undefined }
  117. const previous = yield* cached(repo.store)
  118. const id = (yield* remote(repo)) ?? previous ?? (yield* root(repo))
  119. return {
  120. previous,
  121. id: id ?? ID.global,
  122. directory: repo.directory,
  123. vcs: { type: "git" as const, store: repo.store },
  124. }
  125. })
  126. const commit = Effect.fn("Project.commit")(function* (input: { store: AbsolutePath; id: ID }) {
  127. yield* fs.writeFileString(path.join(input.store, "opencode"), input.id).pipe(Effect.ignore)
  128. })
  129. return Service.of({ directories, resolve, commit })
  130. }),
  131. )
  132. export const defaultLayer = layer.pipe(
  133. Layer.provide(Database.defaultLayer),
  134. Layer.provide(FSUtil.defaultLayer),
  135. Layer.provide(Git.defaultLayer),
  136. )