project.test.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  1. import { describe, expect } from "bun:test"
  2. import { $ } from "bun"
  3. import fs from "fs/promises"
  4. import path from "path"
  5. import { Effect, Layer, Schema } from "effect"
  6. import { AppNodeBuilder } from "@opencode-ai/core/effect/app-node-builder"
  7. import { Database } from "@opencode-ai/core/database/database"
  8. import { Project } from "@opencode-ai/core/project"
  9. import { ProjectTable } from "@opencode-ai/core/project/sql"
  10. import { AbsolutePath } from "@opencode-ai/core/schema"
  11. import { Hash } from "@opencode-ai/util/hash"
  12. import { tmpdir } from "./fixture/tmpdir"
  13. import { testEffect } from "./lib/effect"
  14. const it = testEffect(Layer.merge(AppNodeBuilder.build(Project.node), AppNodeBuilder.build(Database.node)))
  15. describe("Project.list", () => {
  16. it.effect("returns complete projects ordered by recent update", () =>
  17. Effect.gen(function* () {
  18. const db = (yield* Database.Service).db
  19. const project = yield* Project.Service
  20. yield* db
  21. .insert(ProjectTable)
  22. .values([
  23. {
  24. id: Project.ID.make("older"),
  25. worktree: abs("/older"),
  26. vcs: "git",
  27. name: "Older",
  28. icon_color: "#000000",
  29. commands: { start: "bun dev" },
  30. sandboxes: [abs("/older/sandbox")],
  31. time_created: 1,
  32. time_updated: 1,
  33. },
  34. {
  35. id: Project.ID.make("newer"),
  36. worktree: abs("/newer"),
  37. sandboxes: [],
  38. time_created: 2,
  39. time_updated: 2,
  40. time_initialized: 3,
  41. },
  42. ])
  43. .run()
  44. expect(yield* project.list()).toEqual([
  45. {
  46. id: Project.ID.make("newer"),
  47. canonical: abs("/newer"),
  48. time: { created: 2, updated: 2, initialized: 3 },
  49. sandboxes: [],
  50. },
  51. {
  52. id: Project.ID.make("older"),
  53. canonical: abs("/older"),
  54. vcs: "git",
  55. name: "Older",
  56. icon: { color: "#000000" },
  57. commands: { start: "bun dev" },
  58. time: { created: 1, updated: 1 },
  59. sandboxes: [abs("/older/sandbox")],
  60. },
  61. ])
  62. }),
  63. )
  64. })
  65. function remoteID(remote: string) {
  66. return Project.ID.make(Hash.fast(`git-remote:${remote}`))
  67. }
  68. function abs(value: string) {
  69. return AbsolutePath.make(value)
  70. }
  71. function real(value: string) {
  72. return Effect.promise(() => fs.realpath(value)).pipe(Effect.map((value) => AbsolutePath.make(value)))
  73. }
  74. async function initRepo(dir: string, opts?: { commit?: boolean; remote?: string }) {
  75. await $`git init`.cwd(dir).quiet()
  76. await $`git config core.fsmonitor false`.cwd(dir).quiet()
  77. await $`git config commit.gpgsign false`.cwd(dir).quiet()
  78. await $`git config user.email test@opencode.test`.cwd(dir).quiet()
  79. await $`git config user.name Test`.cwd(dir).quiet()
  80. if (opts?.commit) await $`git commit --allow-empty -m root`.cwd(dir).quiet()
  81. if (opts?.remote) await $`git remote add origin ${opts.remote}`.cwd(dir).quiet()
  82. }
  83. async function rootCommit(dir: string) {
  84. return (await $`git rev-list --max-parents=0 HEAD`.cwd(dir).text()).trim()
  85. }
  86. describe("Project.resolve", () => {
  87. it.live("returns global for non-git directory", () =>
  88. Effect.gen(function* () {
  89. const tmp = yield* Effect.acquireRelease(
  90. Effect.promise(() => tmpdir()),
  91. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  92. )
  93. const project = yield* Project.Service
  94. const result = yield* project.resolve(abs(tmp.path))
  95. expect(result.id).toBe(Project.ID.make("global"))
  96. expect(path.resolve(result.directory)).toBe(path.parse(tmp.path).root)
  97. expect(result.canonical).toBe(result.directory)
  98. expect(result.previous).toBeUndefined()
  99. expect(result.vcs).toBeUndefined()
  100. }),
  101. )
  102. it.live("returns git global for repo with no commits and no remote", () =>
  103. Effect.gen(function* () {
  104. const tmp = yield* Effect.acquireRelease(
  105. Effect.promise(() => tmpdir()),
  106. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  107. )
  108. yield* Effect.promise(() => initRepo(tmp.path))
  109. const project = yield* Project.Service
  110. const result = yield* project.resolve(abs(tmp.path))
  111. expect(result.id).toBe(Project.ID.make("global"))
  112. expect(result.directory).toBe(yield* real(tmp.path))
  113. expect(result.canonical).toBe(result.directory)
  114. expect(result.previous).toBeUndefined()
  115. expect(result.vcs?.type).toBe("git")
  116. }),
  117. )
  118. it.live("falls back to root commit when origin is missing", () =>
  119. Effect.gen(function* () {
  120. const tmp = yield* Effect.acquireRelease(
  121. Effect.promise(() => tmpdir()),
  122. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  123. )
  124. yield* Effect.promise(() => initRepo(tmp.path, { commit: true }))
  125. const project = yield* Project.Service
  126. const result = yield* project.resolve(abs(tmp.path))
  127. expect(result.id).toBe(Project.ID.make(yield* Effect.promise(() => rootCommit(tmp.path))))
  128. expect(result.directory).toBe(yield* real(tmp.path))
  129. expect(result.previous).toBeUndefined()
  130. expect(result.vcs?.type).toBe("git")
  131. }),
  132. )
  133. it.live("prefers normalized origin over root commit", () =>
  134. Effect.gen(function* () {
  135. const tmp = yield* Effect.acquireRelease(
  136. Effect.promise(() => tmpdir()),
  137. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  138. )
  139. yield* Effect.promise(() => initRepo(tmp.path, { commit: true, remote: "git@github.com:Acme/App.git" }))
  140. const project = yield* Project.Service
  141. const result = yield* project.resolve(abs(tmp.path))
  142. expect(result.id).toBe(remoteID("github.com/Acme/App"))
  143. expect(result.id).not.toBe(Project.ID.make(yield* Effect.promise(() => rootCommit(tmp.path))))
  144. expect(result.directory).toBe(yield* real(tmp.path))
  145. expect(result.vcs?.type).toBe("git")
  146. }),
  147. )
  148. it.live("normalizes ssh and https remotes to the same id", () =>
  149. Effect.gen(function* () {
  150. const ssh = yield* Effect.acquireRelease(
  151. Effect.promise(() => tmpdir()),
  152. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  153. )
  154. const https = yield* Effect.acquireRelease(
  155. Effect.promise(() => tmpdir()),
  156. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  157. )
  158. yield* Effect.promise(() => initRepo(ssh.path, { commit: true, remote: "git@github.com:owner/repo.git" }))
  159. yield* Effect.promise(() => initRepo(https.path, { commit: true, remote: "https://github.com/owner/repo.git" }))
  160. const project = yield* Project.Service
  161. const a = yield* project.resolve(abs(ssh.path))
  162. const b = yield* project.resolve(abs(https.path))
  163. expect(a.id).toBe(remoteID("github.com/owner/repo"))
  164. expect(b.id).toBe(a.id)
  165. }),
  166. )
  167. it.live("ignores file remotes and falls back to root commit", () =>
  168. Effect.gen(function* () {
  169. const tmp = yield* Effect.acquireRelease(
  170. Effect.promise(() => tmpdir()),
  171. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  172. )
  173. yield* Effect.promise(() => initRepo(tmp.path, { commit: true, remote: `file://${tmp.path}` }))
  174. const project = yield* Project.Service
  175. const result = yield* project.resolve(abs(tmp.path))
  176. expect(result.id).toBe(Project.ID.make(yield* Effect.promise(() => rootCommit(tmp.path))))
  177. }),
  178. )
  179. it.live("returns previous cached id from common dir", () =>
  180. Effect.gen(function* () {
  181. const tmp = yield* Effect.acquireRelease(
  182. Effect.promise(() => tmpdir()),
  183. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  184. )
  185. yield* Effect.promise(() => initRepo(tmp.path, { commit: true, remote: "git@github.com:owner/repo.git" }))
  186. yield* Effect.promise(() => Bun.write(path.join(tmp.path, ".git", "opencode"), "old-id"))
  187. const project = yield* Project.Service
  188. const result = yield* project.resolve(abs(tmp.path))
  189. expect(result.previous).toBe(Project.ID.make("old-id"))
  190. expect(result.id).toBe(remoteID("github.com/owner/repo"))
  191. }),
  192. )
  193. it.live("does not write the cache while resolving", () =>
  194. Effect.gen(function* () {
  195. const tmp = yield* Effect.acquireRelease(
  196. Effect.promise(() => tmpdir()),
  197. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  198. )
  199. yield* Effect.promise(() => initRepo(tmp.path, { commit: true, remote: "git@github.com:owner/repo.git" }))
  200. const project = yield* Project.Service
  201. yield* project.resolve(abs(tmp.path))
  202. expect(yield* Effect.promise(() => Bun.file(path.join(tmp.path, ".git", "opencode")).exists())).toBe(false)
  203. }),
  204. )
  205. it.live("resolves from nested directories to repo root", () =>
  206. Effect.gen(function* () {
  207. const tmp = yield* Effect.acquireRelease(
  208. Effect.promise(() => tmpdir()),
  209. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  210. )
  211. yield* Effect.promise(() => initRepo(tmp.path, { commit: true }))
  212. yield* Effect.promise(() => fs.mkdir(path.join(tmp.path, "a", "b"), { recursive: true }))
  213. const project = yield* Project.Service
  214. const result = yield* project.resolve(abs(path.join(tmp.path, "a", "b")))
  215. expect(result.directory).toBe(yield* real(tmp.path))
  216. }),
  217. )
  218. const itHg = Bun.which("hg") ? it : { live: it.live.skip }
  219. itHg.live("detects mercurial repositories from nested directories", () =>
  220. Effect.gen(function* () {
  221. const tmp = yield* Effect.acquireRelease(
  222. Effect.promise(() => tmpdir()),
  223. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  224. )
  225. yield* Effect.promise(async () => {
  226. await $`hg init`.cwd(tmp.path).quiet()
  227. await Bun.write(path.join(tmp.path, "file.txt"), "one\n")
  228. await $`hg addremove -q`
  229. .cwd(tmp.path)
  230. .env({ ...process.env, HGPLAIN: "1" })
  231. .quiet()
  232. await $`hg commit -q -m initial -u test`
  233. .cwd(tmp.path)
  234. .env({ ...process.env, HGPLAIN: "1" })
  235. .quiet()
  236. await fs.mkdir(path.join(tmp.path, "a", "b"), { recursive: true })
  237. })
  238. const project = yield* Project.Service
  239. const result = yield* project.resolve(abs(path.join(tmp.path, "a", "b")))
  240. expect(result.vcs?.type).toBe("hg")
  241. expect(result.directory).toBe(abs(tmp.path))
  242. expect(result.id).not.toBe(Project.ID.make("global"))
  243. expect(result.previous).toBeUndefined()
  244. }),
  245. )
  246. it.live("prefers git when both git and mercurial metadata exist", () =>
  247. Effect.gen(function* () {
  248. const tmp = yield* Effect.acquireRelease(
  249. Effect.promise(() => tmpdir()),
  250. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  251. )
  252. yield* Effect.promise(() => initRepo(tmp.path, { commit: true }))
  253. yield* Effect.promise(() => fs.mkdir(path.join(tmp.path, ".hg")))
  254. const project = yield* Project.Service
  255. const result = yield* project.resolve(abs(tmp.path))
  256. expect(result.vcs?.type).toBe("git")
  257. }),
  258. )
  259. it.live("returns global id for unreadable mercurial metadata", () =>
  260. Effect.gen(function* () {
  261. const tmp = yield* Effect.acquireRelease(
  262. Effect.promise(() => tmpdir()),
  263. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  264. )
  265. yield* Effect.promise(() => fs.mkdir(path.join(tmp.path, ".hg")))
  266. const project = yield* Project.Service
  267. const result = yield* project.resolve(abs(tmp.path))
  268. expect(result.vcs?.type).toBe("hg")
  269. expect(result.id).toBe(Project.ID.make("global"))
  270. }),
  271. )
  272. it.live("linked worktree returns opened worktree directory and previous from common dir", () =>
  273. Effect.gen(function* () {
  274. const tmp = yield* Effect.acquireRelease(
  275. Effect.promise(() => tmpdir()),
  276. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  277. )
  278. const worktree = `${tmp.path}-worktree`
  279. yield* Effect.addFinalizer(() =>
  280. Effect.promise(() => $`rm -rf ${worktree}`.quiet().nothrow()).pipe(Effect.ignore),
  281. )
  282. yield* Effect.promise(() => initRepo(tmp.path, { commit: true, remote: "git@github.com:owner/repo.git" }))
  283. yield* Effect.promise(() => Bun.write(path.join(tmp.path, ".git", "opencode"), "old-id"))
  284. yield* Effect.promise(() => $`git worktree add ${worktree} -b test-${Date.now()}`.cwd(tmp.path).quiet())
  285. const project = yield* Project.Service
  286. const db = (yield* Database.Service).db
  287. const id = remoteID("github.com/owner/repo")
  288. yield* db
  289. .insert(ProjectTable)
  290. .values({
  291. id,
  292. worktree: abs("/stale-worktree"),
  293. vcs: "hg",
  294. name: "Preserved name",
  295. icon_color: "#123456",
  296. commands: { start: "bun dev" },
  297. sandboxes: [abs("/preserved-sandbox")],
  298. time_created: 1,
  299. time_updated: 1,
  300. time_initialized: 2,
  301. })
  302. .run()
  303. const result = yield* project.resolve(abs(worktree))
  304. expect(result.directory).toBe(yield* real(worktree))
  305. expect(result.canonical).toBe(yield* real(tmp.path))
  306. expect(result.previous).toBe(Project.ID.make("old-id"))
  307. expect(result.id).toBe(id)
  308. expect(result.vcs?.type).toBe("git")
  309. expect((yield* project.list()).find((item) => item.id === id)).toMatchObject({
  310. canonical: yield* real(tmp.path),
  311. vcs: "git",
  312. name: "Preserved name",
  313. icon: { color: "#123456" },
  314. commands: { start: "bun dev" },
  315. sandboxes: [abs("/preserved-sandbox")],
  316. time: { created: 1, initialized: 2 },
  317. })
  318. expect(
  319. (yield* project.directories({ projectID: id })).toSorted((a, b) => a.directory.localeCompare(b.directory)),
  320. ).toEqual([
  321. { directory: yield* real(tmp.path) },
  322. { directory: yield* real(worktree), strategy: "git_worktree" },
  323. ])
  324. }),
  325. )
  326. })