index.test.ts 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956
  1. import { afterEach, describe, test, expect } from "bun:test"
  2. import { $ } from "bun"
  3. import { Effect } from "effect"
  4. import path from "path"
  5. import fs from "fs/promises"
  6. import { File } from "../../src/file"
  7. import { Instance } from "../../src/project/instance"
  8. import { Filesystem } from "../../src/util/filesystem"
  9. import { provideInstance, tmpdir } from "../fixture/fixture"
  10. afterEach(async () => {
  11. await Instance.disposeAll()
  12. })
  13. const init = () => run(File.Service.use((svc) => svc.init()))
  14. const run = <A, E>(eff: Effect.Effect<A, E, File.Service>) =>
  15. Effect.runPromise(provideInstance(Instance.directory)(eff.pipe(Effect.provide(File.defaultLayer))))
  16. const status = () => run(File.Service.use((svc) => svc.status()))
  17. const read = (file: string) => run(File.Service.use((svc) => svc.read(file)))
  18. const list = (dir?: string) => run(File.Service.use((svc) => svc.list(dir)))
  19. const search = (input: { query: string; limit?: number; dirs?: boolean; type?: "file" | "directory" }) =>
  20. run(File.Service.use((svc) => svc.search(input)))
  21. describe("file/index Filesystem patterns", () => {
  22. describe("read() - text content", () => {
  23. test("reads text file via Filesystem.readText()", async () => {
  24. await using tmp = await tmpdir()
  25. const filepath = path.join(tmp.path, "test.txt")
  26. await fs.writeFile(filepath, "Hello World", "utf-8")
  27. await Instance.provide({
  28. directory: tmp.path,
  29. fn: async () => {
  30. const result = await read("test.txt")
  31. expect(result.type).toBe("text")
  32. expect(result.content).toBe("Hello World")
  33. },
  34. })
  35. })
  36. test("reads with Filesystem.exists() check", async () => {
  37. await using tmp = await tmpdir()
  38. await Instance.provide({
  39. directory: tmp.path,
  40. fn: async () => {
  41. // Non-existent file should return empty content
  42. const result = await read("nonexistent.txt")
  43. expect(result.type).toBe("text")
  44. expect(result.content).toBe("")
  45. },
  46. })
  47. })
  48. test("trims whitespace from text content", async () => {
  49. await using tmp = await tmpdir()
  50. const filepath = path.join(tmp.path, "test.txt")
  51. await fs.writeFile(filepath, " content with spaces \n\n", "utf-8")
  52. await Instance.provide({
  53. directory: tmp.path,
  54. fn: async () => {
  55. const result = await read("test.txt")
  56. expect(result.content).toBe("content with spaces")
  57. },
  58. })
  59. })
  60. test("handles empty text file", async () => {
  61. await using tmp = await tmpdir()
  62. const filepath = path.join(tmp.path, "empty.txt")
  63. await fs.writeFile(filepath, "", "utf-8")
  64. await Instance.provide({
  65. directory: tmp.path,
  66. fn: async () => {
  67. const result = await read("empty.txt")
  68. expect(result.type).toBe("text")
  69. expect(result.content).toBe("")
  70. },
  71. })
  72. })
  73. test("handles multi-line text files", async () => {
  74. await using tmp = await tmpdir()
  75. const filepath = path.join(tmp.path, "multiline.txt")
  76. await fs.writeFile(filepath, "line1\nline2\nline3", "utf-8")
  77. await Instance.provide({
  78. directory: tmp.path,
  79. fn: async () => {
  80. const result = await read("multiline.txt")
  81. expect(result.content).toBe("line1\nline2\nline3")
  82. },
  83. })
  84. })
  85. })
  86. describe("read() - binary content", () => {
  87. test("reads binary file via Filesystem.readArrayBuffer()", async () => {
  88. await using tmp = await tmpdir()
  89. const filepath = path.join(tmp.path, "image.png")
  90. const binaryContent = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])
  91. await fs.writeFile(filepath, binaryContent)
  92. await Instance.provide({
  93. directory: tmp.path,
  94. fn: async () => {
  95. const result = await read("image.png")
  96. expect(result.type).toBe("text") // Images return as text with base64 encoding
  97. expect(result.encoding).toBe("base64")
  98. expect(result.mimeType).toBe("image/png")
  99. expect(result.content).toBe(binaryContent.toString("base64"))
  100. },
  101. })
  102. })
  103. test("returns empty for binary non-image files", async () => {
  104. await using tmp = await tmpdir()
  105. const filepath = path.join(tmp.path, "binary.so")
  106. await fs.writeFile(filepath, Buffer.from([0x7f, 0x45, 0x4c, 0x46]), "binary")
  107. await Instance.provide({
  108. directory: tmp.path,
  109. fn: async () => {
  110. const result = await read("binary.so")
  111. expect(result.type).toBe("binary")
  112. expect(result.content).toBe("")
  113. },
  114. })
  115. })
  116. })
  117. describe("read() - Filesystem.mimeType()", () => {
  118. test("detects MIME type via Filesystem.mimeType()", async () => {
  119. await using tmp = await tmpdir()
  120. const filepath = path.join(tmp.path, "test.json")
  121. await fs.writeFile(filepath, '{"key": "value"}', "utf-8")
  122. await Instance.provide({
  123. directory: tmp.path,
  124. fn: async () => {
  125. expect(Filesystem.mimeType(filepath)).toContain("application/json")
  126. const result = await read("test.json")
  127. expect(result.type).toBe("text")
  128. },
  129. })
  130. })
  131. test("handles various image MIME types", async () => {
  132. await using tmp = await tmpdir()
  133. const testCases = [
  134. { ext: "jpg", mime: "image/jpeg" },
  135. { ext: "png", mime: "image/png" },
  136. { ext: "gif", mime: "image/gif" },
  137. { ext: "webp", mime: "image/webp" },
  138. ]
  139. for (const { ext, mime } of testCases) {
  140. const filepath = path.join(tmp.path, `test.${ext}`)
  141. await fs.writeFile(filepath, Buffer.from([0x00, 0x00, 0x00, 0x00]), "binary")
  142. await Instance.provide({
  143. directory: tmp.path,
  144. fn: async () => {
  145. expect(Filesystem.mimeType(filepath)).toContain(mime)
  146. },
  147. })
  148. }
  149. })
  150. })
  151. describe("list() - Filesystem.exists() and readText()", () => {
  152. test("reads .gitignore via Filesystem.exists() and readText()", async () => {
  153. await using tmp = await tmpdir({ git: true })
  154. await Instance.provide({
  155. directory: tmp.path,
  156. fn: async () => {
  157. const gitignorePath = path.join(tmp.path, ".gitignore")
  158. await fs.writeFile(gitignorePath, "node_modules\ndist\n", "utf-8")
  159. // This is used internally in list()
  160. expect(await Filesystem.exists(gitignorePath)).toBe(true)
  161. const content = await Filesystem.readText(gitignorePath)
  162. expect(content).toContain("node_modules")
  163. },
  164. })
  165. })
  166. test("reads .ignore file similarly", async () => {
  167. await using tmp = await tmpdir({ git: true })
  168. await Instance.provide({
  169. directory: tmp.path,
  170. fn: async () => {
  171. const ignorePath = path.join(tmp.path, ".ignore")
  172. await fs.writeFile(ignorePath, "*.log\n.env\n", "utf-8")
  173. expect(await Filesystem.exists(ignorePath)).toBe(true)
  174. expect(await Filesystem.readText(ignorePath)).toContain("*.log")
  175. },
  176. })
  177. })
  178. test("handles missing .gitignore gracefully", async () => {
  179. await using tmp = await tmpdir({ git: true })
  180. await Instance.provide({
  181. directory: tmp.path,
  182. fn: async () => {
  183. const gitignorePath = path.join(tmp.path, ".gitignore")
  184. expect(await Filesystem.exists(gitignorePath)).toBe(false)
  185. // list() should still work
  186. const nodes = await list()
  187. expect(Array.isArray(nodes)).toBe(true)
  188. },
  189. })
  190. })
  191. })
  192. describe("File.changed() - Filesystem.readText() for untracked files", () => {
  193. test("reads untracked files via Filesystem.readText()", async () => {
  194. await using tmp = await tmpdir({ git: true })
  195. await Instance.provide({
  196. directory: tmp.path,
  197. fn: async () => {
  198. const untrackedPath = path.join(tmp.path, "untracked.txt")
  199. await fs.writeFile(untrackedPath, "new content\nwith multiple lines", "utf-8")
  200. // This is how File.changed() reads untracked files
  201. const content = await Filesystem.readText(untrackedPath)
  202. const lines = content.split("\n").length
  203. expect(lines).toBe(2)
  204. },
  205. })
  206. })
  207. })
  208. describe("Error handling", () => {
  209. test("handles errors gracefully in Filesystem.readText()", async () => {
  210. await using tmp = await tmpdir()
  211. const filepath = path.join(tmp.path, "readonly.txt")
  212. await fs.writeFile(filepath, "content", "utf-8")
  213. await Instance.provide({
  214. directory: tmp.path,
  215. fn: async () => {
  216. const nonExistentPath = path.join(tmp.path, "does-not-exist.txt")
  217. // Filesystem.readText() on non-existent file throws
  218. await expect(Filesystem.readText(nonExistentPath)).rejects.toThrow()
  219. // But read() handles this gracefully
  220. const result = await read("does-not-exist.txt")
  221. expect(result.content).toBe("")
  222. },
  223. })
  224. })
  225. test("handles errors in Filesystem.readArrayBuffer()", async () => {
  226. await using tmp = await tmpdir()
  227. await Instance.provide({
  228. directory: tmp.path,
  229. fn: async () => {
  230. const nonExistentPath = path.join(tmp.path, "does-not-exist.bin")
  231. const buffer = await Filesystem.readArrayBuffer(nonExistentPath).catch(() => new ArrayBuffer(0))
  232. expect(buffer.byteLength).toBe(0)
  233. },
  234. })
  235. })
  236. test("returns empty array buffer on error for images", async () => {
  237. await using tmp = await tmpdir()
  238. const filepath = path.join(tmp.path, "broken.png")
  239. // Don't create the file
  240. await Instance.provide({
  241. directory: tmp.path,
  242. fn: async () => {
  243. // read() handles missing images gracefully
  244. const result = await read("broken.png")
  245. expect(result.type).toBe("text")
  246. expect(result.content).toBe("")
  247. },
  248. })
  249. })
  250. })
  251. describe("shouldEncode() logic", () => {
  252. test("treats .ts files as text", async () => {
  253. await using tmp = await tmpdir()
  254. const filepath = path.join(tmp.path, "test.ts")
  255. await fs.writeFile(filepath, "export const value = 1", "utf-8")
  256. await Instance.provide({
  257. directory: tmp.path,
  258. fn: async () => {
  259. const result = await read("test.ts")
  260. expect(result.type).toBe("text")
  261. expect(result.content).toBe("export const value = 1")
  262. },
  263. })
  264. })
  265. test("treats .mts files as text", async () => {
  266. await using tmp = await tmpdir()
  267. const filepath = path.join(tmp.path, "test.mts")
  268. await fs.writeFile(filepath, "export const value = 1", "utf-8")
  269. await Instance.provide({
  270. directory: tmp.path,
  271. fn: async () => {
  272. const result = await read("test.mts")
  273. expect(result.type).toBe("text")
  274. expect(result.content).toBe("export const value = 1")
  275. },
  276. })
  277. })
  278. test("treats .sh files as text", async () => {
  279. await using tmp = await tmpdir()
  280. const filepath = path.join(tmp.path, "test.sh")
  281. await fs.writeFile(filepath, "#!/usr/bin/env bash\necho hello", "utf-8")
  282. await Instance.provide({
  283. directory: tmp.path,
  284. fn: async () => {
  285. const result = await read("test.sh")
  286. expect(result.type).toBe("text")
  287. expect(result.content).toBe("#!/usr/bin/env bash\necho hello")
  288. },
  289. })
  290. })
  291. test("treats Dockerfile as text", async () => {
  292. await using tmp = await tmpdir()
  293. const filepath = path.join(tmp.path, "Dockerfile")
  294. await fs.writeFile(filepath, "FROM alpine:3.20", "utf-8")
  295. await Instance.provide({
  296. directory: tmp.path,
  297. fn: async () => {
  298. const result = await read("Dockerfile")
  299. expect(result.type).toBe("text")
  300. expect(result.content).toBe("FROM alpine:3.20")
  301. },
  302. })
  303. })
  304. test("returns encoding info for text files", async () => {
  305. await using tmp = await tmpdir()
  306. const filepath = path.join(tmp.path, "test.txt")
  307. await fs.writeFile(filepath, "simple text", "utf-8")
  308. await Instance.provide({
  309. directory: tmp.path,
  310. fn: async () => {
  311. const result = await read("test.txt")
  312. expect(result.encoding).toBeUndefined()
  313. expect(result.type).toBe("text")
  314. },
  315. })
  316. })
  317. test("returns base64 encoding for images", async () => {
  318. await using tmp = await tmpdir()
  319. const filepath = path.join(tmp.path, "test.jpg")
  320. await fs.writeFile(filepath, Buffer.from([0xff, 0xd8, 0xff, 0xe0]), "binary")
  321. await Instance.provide({
  322. directory: tmp.path,
  323. fn: async () => {
  324. const result = await read("test.jpg")
  325. expect(result.encoding).toBe("base64")
  326. expect(result.mimeType).toBe("image/jpeg")
  327. },
  328. })
  329. })
  330. })
  331. describe("Path security", () => {
  332. test("throws for paths outside project directory", async () => {
  333. await using tmp = await tmpdir()
  334. await Instance.provide({
  335. directory: tmp.path,
  336. fn: async () => {
  337. await expect(read("../outside.txt")).rejects.toThrow("Access denied")
  338. },
  339. })
  340. })
  341. test("throws for paths outside project directory", async () => {
  342. await using tmp = await tmpdir()
  343. await Instance.provide({
  344. directory: tmp.path,
  345. fn: async () => {
  346. await expect(read("../outside.txt")).rejects.toThrow("Access denied")
  347. },
  348. })
  349. })
  350. })
  351. describe("status()", () => {
  352. test("detects modified file", async () => {
  353. await using tmp = await tmpdir({ git: true })
  354. const filepath = path.join(tmp.path, "file.txt")
  355. await fs.writeFile(filepath, "original\n", "utf-8")
  356. await $`git add .`.cwd(tmp.path).quiet()
  357. await $`git commit -m "add file"`.cwd(tmp.path).quiet()
  358. await fs.writeFile(filepath, "modified\nextra line\n", "utf-8")
  359. await Instance.provide({
  360. directory: tmp.path,
  361. fn: async () => {
  362. const result = await status()
  363. const entry = result.find((f) => f.path === "file.txt")
  364. expect(entry).toBeDefined()
  365. expect(entry!.status).toBe("modified")
  366. expect(entry!.added).toBeGreaterThan(0)
  367. expect(entry!.removed).toBeGreaterThan(0)
  368. },
  369. })
  370. })
  371. test("detects untracked file as added", async () => {
  372. await using tmp = await tmpdir({ git: true })
  373. await fs.writeFile(path.join(tmp.path, "new.txt"), "line1\nline2\nline3\n", "utf-8")
  374. await Instance.provide({
  375. directory: tmp.path,
  376. fn: async () => {
  377. const result = await status()
  378. const entry = result.find((f) => f.path === "new.txt")
  379. expect(entry).toBeDefined()
  380. expect(entry!.status).toBe("added")
  381. expect(entry!.added).toBe(4) // 3 lines + trailing newline splits to 4
  382. expect(entry!.removed).toBe(0)
  383. },
  384. })
  385. })
  386. test("detects deleted file", async () => {
  387. await using tmp = await tmpdir({ git: true })
  388. const filepath = path.join(tmp.path, "gone.txt")
  389. await fs.writeFile(filepath, "content\n", "utf-8")
  390. await $`git add .`.cwd(tmp.path).quiet()
  391. await $`git commit -m "add file"`.cwd(tmp.path).quiet()
  392. await fs.rm(filepath)
  393. await Instance.provide({
  394. directory: tmp.path,
  395. fn: async () => {
  396. const result = await status()
  397. // Deleted files appear in both numstat (as "modified") and diff-filter=D (as "deleted")
  398. const entries = result.filter((f) => f.path === "gone.txt")
  399. expect(entries.some((e) => e.status === "deleted")).toBe(true)
  400. },
  401. })
  402. })
  403. test("detects mixed changes", async () => {
  404. await using tmp = await tmpdir({ git: true })
  405. await fs.writeFile(path.join(tmp.path, "keep.txt"), "keep\n", "utf-8")
  406. await fs.writeFile(path.join(tmp.path, "remove.txt"), "remove\n", "utf-8")
  407. await $`git add .`.cwd(tmp.path).quiet()
  408. await $`git commit -m "initial"`.cwd(tmp.path).quiet()
  409. // Modify one, delete one, add one
  410. await fs.writeFile(path.join(tmp.path, "keep.txt"), "changed\n", "utf-8")
  411. await fs.rm(path.join(tmp.path, "remove.txt"))
  412. await fs.writeFile(path.join(tmp.path, "brand-new.txt"), "hello\n", "utf-8")
  413. await Instance.provide({
  414. directory: tmp.path,
  415. fn: async () => {
  416. const result = await status()
  417. expect(result.some((f) => f.path === "keep.txt" && f.status === "modified")).toBe(true)
  418. expect(result.some((f) => f.path === "remove.txt" && f.status === "deleted")).toBe(true)
  419. expect(result.some((f) => f.path === "brand-new.txt" && f.status === "added")).toBe(true)
  420. },
  421. })
  422. })
  423. test("returns empty for non-git project", async () => {
  424. await using tmp = await tmpdir()
  425. await Instance.provide({
  426. directory: tmp.path,
  427. fn: async () => {
  428. const result = await status()
  429. expect(result).toEqual([])
  430. },
  431. })
  432. })
  433. test("returns empty for clean repo", async () => {
  434. await using tmp = await tmpdir({ git: true })
  435. await Instance.provide({
  436. directory: tmp.path,
  437. fn: async () => {
  438. const result = await status()
  439. expect(result).toEqual([])
  440. },
  441. })
  442. })
  443. test("parses binary numstat as 0", async () => {
  444. await using tmp = await tmpdir({ git: true })
  445. const filepath = path.join(tmp.path, "data.bin")
  446. // Write content with null bytes so git treats it as binary
  447. const binaryData = Buffer.alloc(256)
  448. for (let i = 0; i < 256; i++) binaryData[i] = i
  449. await fs.writeFile(filepath, binaryData)
  450. await $`git add .`.cwd(tmp.path).quiet()
  451. await $`git commit -m "add binary"`.cwd(tmp.path).quiet()
  452. // Modify the binary
  453. const modified = Buffer.alloc(512)
  454. for (let i = 0; i < 512; i++) modified[i] = i % 256
  455. await fs.writeFile(filepath, modified)
  456. await Instance.provide({
  457. directory: tmp.path,
  458. fn: async () => {
  459. const result = await status()
  460. const entry = result.find((f) => f.path === "data.bin")
  461. expect(entry).toBeDefined()
  462. expect(entry!.status).toBe("modified")
  463. expect(entry!.added).toBe(0)
  464. expect(entry!.removed).toBe(0)
  465. },
  466. })
  467. })
  468. })
  469. describe("list()", () => {
  470. test("returns files and directories with correct shape", async () => {
  471. await using tmp = await tmpdir({ git: true })
  472. await fs.mkdir(path.join(tmp.path, "subdir"))
  473. await fs.writeFile(path.join(tmp.path, "file.txt"), "content", "utf-8")
  474. await fs.writeFile(path.join(tmp.path, "subdir", "nested.txt"), "nested", "utf-8")
  475. await Instance.provide({
  476. directory: tmp.path,
  477. fn: async () => {
  478. const nodes = await list()
  479. expect(nodes.length).toBeGreaterThanOrEqual(2)
  480. for (const node of nodes) {
  481. expect(node).toHaveProperty("name")
  482. expect(node).toHaveProperty("path")
  483. expect(node).toHaveProperty("absolute")
  484. expect(node).toHaveProperty("type")
  485. expect(node).toHaveProperty("ignored")
  486. expect(["file", "directory"]).toContain(node.type)
  487. }
  488. },
  489. })
  490. })
  491. test("sorts directories before files, alphabetical within each", async () => {
  492. await using tmp = await tmpdir({ git: true })
  493. await fs.mkdir(path.join(tmp.path, "beta"))
  494. await fs.mkdir(path.join(tmp.path, "alpha"))
  495. await fs.writeFile(path.join(tmp.path, "zz.txt"), "", "utf-8")
  496. await fs.writeFile(path.join(tmp.path, "aa.txt"), "", "utf-8")
  497. await Instance.provide({
  498. directory: tmp.path,
  499. fn: async () => {
  500. const nodes = await list()
  501. const dirs = nodes.filter((n) => n.type === "directory")
  502. const files = nodes.filter((n) => n.type === "file")
  503. // Dirs come first
  504. const firstFile = nodes.findIndex((n) => n.type === "file")
  505. const lastDir = nodes.findLastIndex((n) => n.type === "directory")
  506. if (lastDir >= 0 && firstFile >= 0) {
  507. expect(lastDir).toBeLessThan(firstFile)
  508. }
  509. // Alphabetical within dirs
  510. expect(dirs.map((d) => d.name)).toEqual(dirs.map((d) => d.name).toSorted())
  511. // Alphabetical within files
  512. expect(files.map((f) => f.name)).toEqual(files.map((f) => f.name).toSorted())
  513. },
  514. })
  515. })
  516. test("excludes .git and .DS_Store", async () => {
  517. await using tmp = await tmpdir({ git: true })
  518. await fs.writeFile(path.join(tmp.path, ".DS_Store"), "", "utf-8")
  519. await fs.writeFile(path.join(tmp.path, "visible.txt"), "", "utf-8")
  520. await Instance.provide({
  521. directory: tmp.path,
  522. fn: async () => {
  523. const nodes = await list()
  524. const names = nodes.map((n) => n.name)
  525. expect(names).not.toContain(".git")
  526. expect(names).not.toContain(".DS_Store")
  527. expect(names).toContain("visible.txt")
  528. },
  529. })
  530. })
  531. test("marks gitignored files as ignored", async () => {
  532. await using tmp = await tmpdir({ git: true })
  533. await fs.writeFile(path.join(tmp.path, ".gitignore"), "*.log\nbuild/\n", "utf-8")
  534. await fs.writeFile(path.join(tmp.path, "app.log"), "log data", "utf-8")
  535. await fs.writeFile(path.join(tmp.path, "main.ts"), "code", "utf-8")
  536. await fs.mkdir(path.join(tmp.path, "build"))
  537. await Instance.provide({
  538. directory: tmp.path,
  539. fn: async () => {
  540. const nodes = await list()
  541. const logNode = nodes.find((n) => n.name === "app.log")
  542. const tsNode = nodes.find((n) => n.name === "main.ts")
  543. const buildNode = nodes.find((n) => n.name === "build")
  544. expect(logNode?.ignored).toBe(true)
  545. expect(tsNode?.ignored).toBe(false)
  546. expect(buildNode?.ignored).toBe(true)
  547. },
  548. })
  549. })
  550. test("lists subdirectory contents", async () => {
  551. await using tmp = await tmpdir({ git: true })
  552. await fs.mkdir(path.join(tmp.path, "sub"))
  553. await fs.writeFile(path.join(tmp.path, "sub", "a.txt"), "", "utf-8")
  554. await fs.writeFile(path.join(tmp.path, "sub", "b.txt"), "", "utf-8")
  555. await Instance.provide({
  556. directory: tmp.path,
  557. fn: async () => {
  558. const nodes = await list("sub")
  559. expect(nodes.length).toBe(2)
  560. expect(nodes.map((n) => n.name).sort()).toEqual(["a.txt", "b.txt"])
  561. // Paths should be relative to project root (normalize for Windows)
  562. expect(nodes[0].path.replaceAll("\\", "/").startsWith("sub/")).toBe(true)
  563. },
  564. })
  565. })
  566. test("throws for paths outside project directory", async () => {
  567. await using tmp = await tmpdir({ git: true })
  568. await Instance.provide({
  569. directory: tmp.path,
  570. fn: async () => {
  571. await expect(list("../outside")).rejects.toThrow("Access denied")
  572. },
  573. })
  574. })
  575. test("works without git", async () => {
  576. await using tmp = await tmpdir()
  577. await fs.writeFile(path.join(tmp.path, "file.txt"), "hi", "utf-8")
  578. await Instance.provide({
  579. directory: tmp.path,
  580. fn: async () => {
  581. const nodes = await list()
  582. expect(nodes.length).toBeGreaterThanOrEqual(1)
  583. // Without git, ignored should be false for all
  584. for (const node of nodes) {
  585. expect(node.ignored).toBe(false)
  586. }
  587. },
  588. })
  589. })
  590. })
  591. describe("search()", () => {
  592. async function setupSearchableRepo() {
  593. const tmp = await tmpdir({ git: true })
  594. await fs.writeFile(path.join(tmp.path, "index.ts"), "code", "utf-8")
  595. await fs.writeFile(path.join(tmp.path, "utils.ts"), "utils", "utf-8")
  596. await fs.writeFile(path.join(tmp.path, "readme.md"), "readme", "utf-8")
  597. await fs.mkdir(path.join(tmp.path, "src"))
  598. await fs.mkdir(path.join(tmp.path, ".hidden"))
  599. await fs.writeFile(path.join(tmp.path, "src", "main.ts"), "main", "utf-8")
  600. await fs.writeFile(path.join(tmp.path, ".hidden", "secret.ts"), "secret", "utf-8")
  601. return tmp
  602. }
  603. test("empty query returns files", async () => {
  604. await using tmp = await setupSearchableRepo()
  605. await Instance.provide({
  606. directory: tmp.path,
  607. fn: async () => {
  608. await init()
  609. const result = await search({ query: "", type: "file" })
  610. expect(result.length).toBeGreaterThan(0)
  611. },
  612. })
  613. })
  614. test("search works before explicit init", async () => {
  615. await using tmp = await setupSearchableRepo()
  616. await Instance.provide({
  617. directory: tmp.path,
  618. fn: async () => {
  619. const result = await search({ query: "main", type: "file" })
  620. expect(result.some((f) => f.includes("main"))).toBe(true)
  621. },
  622. })
  623. })
  624. test("empty query returns dirs sorted with hidden last", async () => {
  625. await using tmp = await setupSearchableRepo()
  626. await Instance.provide({
  627. directory: tmp.path,
  628. fn: async () => {
  629. await init()
  630. const result = await search({ query: "", type: "directory" })
  631. expect(result.length).toBeGreaterThan(0)
  632. // Find first hidden dir index
  633. const firstHidden = result.findIndex((d) => d.split("/").some((p) => p.startsWith(".") && p.length > 1))
  634. const lastVisible = result.findLastIndex((d) => !d.split("/").some((p) => p.startsWith(".") && p.length > 1))
  635. if (firstHidden >= 0 && lastVisible >= 0) {
  636. expect(firstHidden).toBeGreaterThan(lastVisible)
  637. }
  638. },
  639. })
  640. })
  641. test("fuzzy matches file names", async () => {
  642. await using tmp = await setupSearchableRepo()
  643. await Instance.provide({
  644. directory: tmp.path,
  645. fn: async () => {
  646. await init()
  647. const result = await search({ query: "main", type: "file" })
  648. expect(result.some((f) => f.includes("main"))).toBe(true)
  649. },
  650. })
  651. })
  652. test("type filter returns only files", async () => {
  653. await using tmp = await setupSearchableRepo()
  654. await Instance.provide({
  655. directory: tmp.path,
  656. fn: async () => {
  657. await init()
  658. const result = await search({ query: "", type: "file" })
  659. // Files don't end with /
  660. for (const f of result) {
  661. expect(f.endsWith("/")).toBe(false)
  662. }
  663. },
  664. })
  665. })
  666. test("type filter returns only directories", async () => {
  667. await using tmp = await setupSearchableRepo()
  668. await Instance.provide({
  669. directory: tmp.path,
  670. fn: async () => {
  671. await init()
  672. const result = await search({ query: "", type: "directory" })
  673. // Directories end with /
  674. for (const d of result) {
  675. expect(d.endsWith("/")).toBe(true)
  676. }
  677. },
  678. })
  679. })
  680. test("respects limit", async () => {
  681. await using tmp = await setupSearchableRepo()
  682. await Instance.provide({
  683. directory: tmp.path,
  684. fn: async () => {
  685. await init()
  686. const result = await search({ query: "", type: "file", limit: 2 })
  687. expect(result.length).toBeLessThanOrEqual(2)
  688. },
  689. })
  690. })
  691. test("query starting with dot prefers hidden files", async () => {
  692. await using tmp = await setupSearchableRepo()
  693. await Instance.provide({
  694. directory: tmp.path,
  695. fn: async () => {
  696. await init()
  697. const result = await search({ query: ".hidden", type: "directory" })
  698. expect(result.length).toBeGreaterThan(0)
  699. expect(result[0]).toContain(".hidden")
  700. },
  701. })
  702. })
  703. test("search refreshes after init when files change", async () => {
  704. await using tmp = await setupSearchableRepo()
  705. await Instance.provide({
  706. directory: tmp.path,
  707. fn: async () => {
  708. await init()
  709. expect(await search({ query: "fresh", type: "file" })).toEqual([])
  710. await fs.writeFile(path.join(tmp.path, "fresh.ts"), "fresh", "utf-8")
  711. const result = await search({ query: "fresh", type: "file" })
  712. expect(result).toContain("fresh.ts")
  713. },
  714. })
  715. })
  716. })
  717. describe("read() - diff/patch", () => {
  718. test("returns diff and patch for modified tracked file", async () => {
  719. await using tmp = await tmpdir({ git: true })
  720. const filepath = path.join(tmp.path, "file.txt")
  721. await fs.writeFile(filepath, "original content\n", "utf-8")
  722. await $`git add .`.cwd(tmp.path).quiet()
  723. await $`git commit -m "add file"`.cwd(tmp.path).quiet()
  724. await fs.writeFile(filepath, "modified content\n", "utf-8")
  725. await Instance.provide({
  726. directory: tmp.path,
  727. fn: async () => {
  728. const result = await read("file.txt")
  729. expect(result.type).toBe("text")
  730. expect(result.content).toBe("modified content")
  731. expect(result.diff).toBeDefined()
  732. expect(result.diff).toContain("original content")
  733. expect(result.diff).toContain("modified content")
  734. expect(result.patch).toBeDefined()
  735. expect(result.patch!.hunks.length).toBeGreaterThan(0)
  736. },
  737. })
  738. })
  739. test("returns diff for staged changes", async () => {
  740. await using tmp = await tmpdir({ git: true })
  741. const filepath = path.join(tmp.path, "staged.txt")
  742. await fs.writeFile(filepath, "before\n", "utf-8")
  743. await $`git add .`.cwd(tmp.path).quiet()
  744. await $`git commit -m "add file"`.cwd(tmp.path).quiet()
  745. await fs.writeFile(filepath, "after\n", "utf-8")
  746. await $`git add .`.cwd(tmp.path).quiet()
  747. await Instance.provide({
  748. directory: tmp.path,
  749. fn: async () => {
  750. const result = await read("staged.txt")
  751. expect(result.diff).toBeDefined()
  752. expect(result.patch).toBeDefined()
  753. },
  754. })
  755. })
  756. test("returns no diff for unmodified file", async () => {
  757. await using tmp = await tmpdir({ git: true })
  758. const filepath = path.join(tmp.path, "clean.txt")
  759. await fs.writeFile(filepath, "unchanged\n", "utf-8")
  760. await $`git add .`.cwd(tmp.path).quiet()
  761. await $`git commit -m "add file"`.cwd(tmp.path).quiet()
  762. await Instance.provide({
  763. directory: tmp.path,
  764. fn: async () => {
  765. const result = await read("clean.txt")
  766. expect(result.type).toBe("text")
  767. expect(result.content).toBe("unchanged")
  768. expect(result.diff).toBeUndefined()
  769. expect(result.patch).toBeUndefined()
  770. },
  771. })
  772. })
  773. })
  774. describe("InstanceState isolation", () => {
  775. test("two directories get independent file caches", async () => {
  776. await using one = await tmpdir({ git: true })
  777. await using two = await tmpdir({ git: true })
  778. await fs.writeFile(path.join(one.path, "a.ts"), "one", "utf-8")
  779. await fs.writeFile(path.join(two.path, "b.ts"), "two", "utf-8")
  780. await Instance.provide({
  781. directory: one.path,
  782. fn: async () => {
  783. await init()
  784. const results = await search({ query: "a.ts", type: "file" })
  785. expect(results).toContain("a.ts")
  786. const results2 = await search({ query: "b.ts", type: "file" })
  787. expect(results2).not.toContain("b.ts")
  788. },
  789. })
  790. await Instance.provide({
  791. directory: two.path,
  792. fn: async () => {
  793. await init()
  794. const results = await search({ query: "b.ts", type: "file" })
  795. expect(results).toContain("b.ts")
  796. const results2 = await search({ query: "a.ts", type: "file" })
  797. expect(results2).not.toContain("a.ts")
  798. },
  799. })
  800. })
  801. test("disposal gives fresh state on next access", async () => {
  802. await using tmp = await tmpdir({ git: true })
  803. await fs.writeFile(path.join(tmp.path, "before.ts"), "before", "utf-8")
  804. await Instance.provide({
  805. directory: tmp.path,
  806. fn: async () => {
  807. await init()
  808. const results = await search({ query: "before", type: "file" })
  809. expect(results).toContain("before.ts")
  810. },
  811. })
  812. await Instance.disposeAll()
  813. await fs.writeFile(path.join(tmp.path, "after.ts"), "after", "utf-8")
  814. await fs.rm(path.join(tmp.path, "before.ts"))
  815. await Instance.provide({
  816. directory: tmp.path,
  817. fn: async () => {
  818. await init()
  819. const results = await search({ query: "after", type: "file" })
  820. expect(results).toContain("after.ts")
  821. const stale = await search({ query: "before", type: "file" })
  822. expect(stale).not.toContain("before.ts")
  823. },
  824. })
  825. })
  826. })
  827. })