index.ts 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import { z } from "zod"
  2. import { Bus } from "../bus"
  3. import { $ } from "bun"
  4. import { createPatch } from "diff"
  5. import path from "path"
  6. import { status } from "isomorphic-git"
  7. import { App } from "../app/app"
  8. import fs from "fs"
  9. import { Log } from "../util/log"
  10. export namespace File {
  11. const log = Log.create({ service: "files" })
  12. export const Event = {
  13. Edited: Bus.event(
  14. "file.edited",
  15. z.object({
  16. file: z.string(),
  17. }),
  18. ),
  19. }
  20. export async function read(file: string) {
  21. using _ = log.time("read", { file })
  22. const app = App.info()
  23. const full = path.join(app.path.cwd, file)
  24. const content = await Bun.file(full).text()
  25. if (app.git) {
  26. const rel = path.relative(app.path.root, full)
  27. const diff = await status({
  28. fs,
  29. dir: app.path.root,
  30. filepath: rel,
  31. })
  32. if (diff !== "unmodified") {
  33. const original = await $`git show HEAD:${rel}`
  34. .cwd(app.path.root)
  35. .quiet()
  36. .nothrow()
  37. .text()
  38. const patch = createPatch(file, original, content)
  39. return patch
  40. }
  41. }
  42. return content.trim()
  43. }
  44. }