snapshot.ts 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. export * as Snapshot from "./snapshot"
  2. import { makeLocationNode } from "./effect/app-node"
  3. import path from "path"
  4. import { Context, Effect, Layer, Schema } from "effect"
  5. import { Config } from "./config"
  6. import { File } from "./file"
  7. import { FSUtil } from "./fs-util"
  8. import { Git } from "./git"
  9. import { Global } from "./global"
  10. import { Location } from "./location"
  11. import { AbsolutePath, RelativePath } from "./schema"
  12. import { Hash } from "./util/hash"
  13. export const ID = Schema.String.pipe(Schema.brand("Snapshot.ID"))
  14. export type ID = typeof ID.Type
  15. export class Error extends Schema.TaggedErrorClass<Error>()("Snapshot.Error", {
  16. operation: Schema.Literals(["capture", "files", "diff", "preview", "restore"]),
  17. message: Schema.String,
  18. cause: Schema.optional(Schema.Defect()),
  19. }) {}
  20. export interface CompareInput {
  21. readonly from: ID
  22. readonly to: ID
  23. }
  24. export interface DiffInput extends CompareInput {
  25. readonly context?: number
  26. readonly paths?: readonly RelativePath[]
  27. }
  28. export interface RestoreInput {
  29. /** Paths are relative to the project root. */
  30. readonly files: ReadonlyMap<RelativePath, ID>
  31. }
  32. export interface PreviewInput extends RestoreInput {
  33. readonly context?: number
  34. }
  35. export interface Interface {
  36. /**
  37. * Capture the current Location-scoped filesystem state as a content-addressed
  38. * tree. Returns `undefined` when snapshots are disabled, unsupported, or the
  39. * best-effort capture fails.
  40. */
  41. readonly capture: () => Effect.Effect<ID | undefined>
  42. /**
  43. * List project-relative paths changed between two captured trees without
  44. * loading file contents or generating patches.
  45. */
  46. readonly files: (input: CompareInput) => Effect.Effect<readonly RelativePath[], Error>
  47. /**
  48. * Generate structured per-file diffs between two captured trees. `context`
  49. * controls unchanged lines around each unified diff hunk.
  50. */
  51. readonly diff: (input: DiffInput) => Effect.Effect<readonly File.Diff[], Error>
  52. /**
  53. * Preview the filesystem result of a selective restore without modifying the
  54. * worktree. Each project-relative path maps to the tree it would be restored
  55. * from.
  56. */
  57. readonly preview: (input: PreviewInput) => Effect.Effect<readonly File.Diff[], Error>
  58. /**
  59. * Restore selected project-relative paths from their associated trees. A path
  60. * absent from its selected tree is removed; paths outside the map are untouched.
  61. */
  62. readonly restore: (input: RestoreInput) => Effect.Effect<void, Error>
  63. /**
  64. * Replace the snapshot index with a captured tree and check out all its entries.
  65. * Files absent from the tree remain untouched. Prefer selective `restore` when
  66. * only known paths should change.
  67. */
  68. readonly checkout: (snapshot: ID) => Effect.Effect<void, Error>
  69. }
  70. export class Service extends Context.Service<Service, Interface>()("@opencode/v2/Snapshot") {}
  71. const layer = Layer.effect(
  72. Service,
  73. Effect.gen(function* () {
  74. const config = yield* Config.Service
  75. const fs = yield* FSUtil.Service
  76. const git = yield* Git.Service
  77. const global = yield* Global.Service
  78. const location = yield* Location.Service
  79. const source = yield* git.repo.discover(location.project.directory)
  80. const worktree = source
  81. ? AbsolutePath.make(yield* fs.realPath(source.worktree).pipe(Effect.orDie))
  82. : location.project.directory
  83. const gitDirectory = AbsolutePath.make(path.join(global.data, "snapshot", location.project.id, Hash.fast(worktree)))
  84. const scope = Effect.fnUntraced(function* () {
  85. const relative = path.relative(worktree, location.directory)
  86. if (relative.startsWith("..") || path.isAbsolute(relative))
  87. return yield* new Error({ operation: "capture", message: "Location is outside the project" })
  88. return RelativePath.make(relative.replaceAll("\\", "/") || ".")
  89. })
  90. const repository = Effect.fnUntraced(function* () {
  91. if (!source) return yield* new Error({ operation: "capture", message: "Project is not a Git repository" })
  92. if (yield* fs.existsSafe(path.join(gitDirectory, "HEAD")))
  93. return new Git.Repository({
  94. worktree,
  95. gitDirectory,
  96. commonDirectory: gitDirectory,
  97. })
  98. return yield* git.repo
  99. .create({
  100. worktree,
  101. gitDirectory,
  102. seed: source,
  103. })
  104. .pipe(Effect.mapError((cause) => failure("capture", cause)))
  105. })
  106. const enabled = Effect.fnUntraced(function* () {
  107. if (location.vcs?.type !== "git") return false
  108. return Config.latest(yield* config.entries(), "snapshots") !== false
  109. })
  110. const capture = Effect.fn("Snapshot.capture")(function* () {
  111. if (!(yield* enabled())) return undefined
  112. return yield* Effect.gen(function* () {
  113. const repo = yield* repository()
  114. return ID.make(
  115. yield* git.tree.capture({
  116. repository: repo,
  117. scopes: [yield* scope()],
  118. ignores: source,
  119. maximumUntrackedFileBytes: 2 * 1024 * 1024,
  120. }),
  121. )
  122. }).pipe(
  123. Effect.catch((cause) => Effect.logWarning("failed to capture snapshot", { cause }).pipe(Effect.as(undefined))),
  124. )
  125. })
  126. const compare = Effect.fnUntraced(function* (operation: "files" | "diff", input: CompareInput) {
  127. const repo = yield* repository().pipe(Effect.mapError((cause) => failure(operation, cause)))
  128. return { repository: repo, from: Git.TreeID.make(input.from), to: Git.TreeID.make(input.to) }
  129. })
  130. const files = Effect.fn("Snapshot.files")(function* (input: CompareInput) {
  131. const comparison = yield* compare("files", input)
  132. const files = yield* git.tree.files(comparison).pipe(Effect.mapError((cause) => failure("files", cause)))
  133. if (!source) return files
  134. const ignored = yield* git.index
  135. .ignored({ repository: source, paths: files })
  136. .pipe(Effect.mapError((cause) => failure("files", cause)))
  137. return files.filter((file) => !ignored.has(file))
  138. })
  139. const diff = Effect.fn("Snapshot.diff")(function* (input: DiffInput) {
  140. const comparison = yield* compare("diff", input)
  141. const files = yield* git.tree.files(comparison).pipe(Effect.mapError((cause) => failure("diff", cause)))
  142. const ignored = source
  143. ? yield* git.index
  144. .ignored({ repository: source, paths: files })
  145. .pipe(Effect.mapError((cause) => failure("diff", cause)))
  146. : new Set<RelativePath>()
  147. return yield* git.tree
  148. .diff({
  149. ...comparison,
  150. context: input.context,
  151. paths: (input.paths ?? files).filter((file) => !ignored.has(file)),
  152. })
  153. .pipe(Effect.mapError((cause) => failure("diff", cause)))
  154. })
  155. const plan = Effect.fnUntraced(function* (operation: "preview" | "restore", input: RestoreInput) {
  156. const files = new Map<RelativePath, Git.TreeID>()
  157. for (const [file, snapshot] of input.files) {
  158. const absolute = path.resolve(worktree, file)
  159. if (!FSUtil.contains(worktree, absolute))
  160. return yield* new Error({ operation, message: `Path escapes the project: ${file}` })
  161. files.set(file, Git.TreeID.make(snapshot))
  162. }
  163. return files
  164. })
  165. const preview = Effect.fn("Snapshot.preview")(function* (input: PreviewInput) {
  166. if (!(yield* enabled())) return yield* new Error({ operation: "preview", message: "Snapshots are disabled" })
  167. const repo = yield* repository().pipe(Effect.mapError((cause) => failure("preview", cause)))
  168. const files = yield* plan("preview", input)
  169. const current = yield* git.tree
  170. .capture({
  171. repository: repo,
  172. scopes: Array.from(files.keys()),
  173. ignores: source,
  174. maximumUntrackedFileBytes: 2 * 1024 * 1024,
  175. })
  176. .pipe(Effect.mapError((cause) => failure("preview", cause)))
  177. return yield* git.tree
  178. .preview({
  179. repository: repo,
  180. current,
  181. files,
  182. context: input.context,
  183. })
  184. .pipe(Effect.mapError((cause) => failure("preview", cause)))
  185. })
  186. const restore = Effect.fn("Snapshot.restore")(function* (input: RestoreInput) {
  187. if (!(yield* enabled())) return yield* new Error({ operation: "restore", message: "Snapshots are disabled" })
  188. const repo = yield* repository().pipe(Effect.mapError((cause) => failure("restore", cause)))
  189. yield* git.tree
  190. .restore({ repository: repo, files: yield* plan("restore", input) })
  191. .pipe(Effect.mapError((cause) => failure("restore", cause)))
  192. })
  193. const checkout = Effect.fn("Snapshot.checkout")(function* (snapshot: ID) {
  194. const repo = yield* repository().pipe(Effect.mapError((cause) => failure("restore", cause)))
  195. yield* git.tree
  196. .checkout({ repository: repo, tree: Git.TreeID.make(snapshot) })
  197. .pipe(Effect.mapError((cause) => failure("restore", cause)))
  198. })
  199. return Service.of({ capture, files, diff, preview, restore, checkout })
  200. }),
  201. )
  202. export const locationLayer = layer.pipe(Layer.provideMerge(Config.locationLayer))
  203. export const node = makeLocationNode({
  204. service: Service,
  205. layer,
  206. deps: [Config.node, FSUtil.node, Git.node, Global.node, Location.node],
  207. })
  208. export const noopLayer = Layer.succeed(
  209. Service,
  210. Service.of({
  211. capture: () => Effect.succeed(undefined),
  212. files: () => Effect.succeed([]),
  213. diff: () => Effect.succeed([]),
  214. preview: () => Effect.succeed([]),
  215. restore: () => Effect.void,
  216. checkout: () => Effect.void,
  217. }),
  218. )
  219. function failure(operation: Error["operation"], cause: unknown) {
  220. if (cause instanceof Error && cause.operation === operation) return cause
  221. return new Error({
  222. operation,
  223. message: cause instanceof globalThis.Error ? cause.message : String(cause),
  224. cause,
  225. })
  226. }
  227. /** Legacy persisted session diff shape. */
  228. export type LegacyFileDiff = {
  229. file?: string
  230. patch?: string
  231. additions: number
  232. deletions: number
  233. status?: "added" | "deleted" | "modified"
  234. }