@yaks/git 0.0.0-stage → 0.2.36

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (183) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +754 -2
  3. package/_dist/address.d.ts +6 -0
  4. package/_dist/address.d.ts.map +1 -0
  5. package/_dist/checkout_vocab.d.ts +3 -0
  6. package/_dist/checkout_vocab.d.ts.map +1 -0
  7. package/_dist/cites.d.ts +48 -0
  8. package/_dist/cites.d.ts.map +1 -0
  9. package/_dist/commit.d.ts +36 -0
  10. package/_dist/commit.d.ts.map +1 -0
  11. package/_dist/comp.d.ts +29 -0
  12. package/_dist/comp.d.ts.map +1 -0
  13. package/_dist/door.d.ts +29 -0
  14. package/_dist/door.d.ts.map +1 -0
  15. package/_dist/format.d.ts +2 -0
  16. package/_dist/format.d.ts.map +1 -0
  17. package/_dist/hold.d.ts +6 -0
  18. package/_dist/hold.d.ts.map +1 -0
  19. package/_dist/host.d.ts +126 -0
  20. package/_dist/host.d.ts.map +1 -0
  21. package/_dist/http.d.ts +33 -0
  22. package/_dist/http.d.ts.map +1 -0
  23. package/_dist/import.d.ts +13 -0
  24. package/_dist/import.d.ts.map +1 -0
  25. package/_dist/index.d.ts +80 -0
  26. package/_dist/index.d.ts.map +1 -0
  27. package/_dist/land.d.ts +77 -0
  28. package/_dist/land.d.ts.map +1 -0
  29. package/_dist/mod.d.ts +73 -0
  30. package/_dist/mod.d.ts.map +1 -0
  31. package/_dist/objects.d.ts +40 -0
  32. package/_dist/objects.d.ts.map +1 -0
  33. package/_dist/oid.d.ts +24 -0
  34. package/_dist/oid.d.ts.map +1 -0
  35. package/_dist/pack-store.d.ts +9 -0
  36. package/_dist/pack-store.d.ts.map +1 -0
  37. package/_dist/pack.d.ts +26 -0
  38. package/_dist/pack.d.ts.map +1 -0
  39. package/_dist/pkt.d.ts +14 -0
  40. package/_dist/pkt.d.ts.map +1 -0
  41. package/_dist/placement.d.ts +4 -0
  42. package/_dist/placement.d.ts.map +1 -0
  43. package/_dist/plugin.d.ts +43 -0
  44. package/_dist/plugin.d.ts.map +1 -0
  45. package/_dist/project.d.ts +20 -0
  46. package/_dist/project.d.ts.map +1 -0
  47. package/_dist/push.d.ts +42 -0
  48. package/_dist/push.d.ts.map +1 -0
  49. package/_dist/refs.d.ts +81 -0
  50. package/_dist/refs.d.ts.map +1 -0
  51. package/_dist/rewrite.d.ts +35 -0
  52. package/_dist/rewrite.d.ts.map +1 -0
  53. package/_dist/service.d.ts +35 -0
  54. package/_dist/service.d.ts.map +1 -0
  55. package/_dist/sha1.d.ts +11 -0
  56. package/_dist/sha1.d.ts.map +1 -0
  57. package/_dist/source.d.ts +12 -0
  58. package/_dist/source.d.ts.map +1 -0
  59. package/_dist/tools.d.ts +11 -0
  60. package/_dist/tools.d.ts.map +1 -0
  61. package/_dist/tree.d.ts +28 -0
  62. package/_dist/tree.d.ts.map +1 -0
  63. package/_dist/unpack.d.ts +5 -0
  64. package/_dist/unpack.d.ts.map +1 -0
  65. package/_dist/vocab.d.ts +8 -0
  66. package/_dist/vocab.d.ts.map +1 -0
  67. package/_dist/workspace.d.ts +17 -0
  68. package/_dist/workspace.d.ts.map +1 -0
  69. package/address.js +9 -0
  70. package/address.js.map +1 -0
  71. package/address.ts +15 -0
  72. package/cache.js +9 -0
  73. package/cache.js.map +1 -0
  74. package/cache.ts +6 -0
  75. package/checkout.js +18 -0
  76. package/checkout.js.map +1 -0
  77. package/checkout.ts +24 -0
  78. package/checkout_vocab.js +14 -0
  79. package/checkout_vocab.js.map +1 -0
  80. package/checkout_vocab.ts +11 -0
  81. package/cites.js +189 -0
  82. package/cites.js.map +1 -0
  83. package/cites.ts +206 -0
  84. package/commit.js +128 -0
  85. package/commit.js.map +1 -0
  86. package/commit.ts +183 -0
  87. package/comp.js +94 -0
  88. package/comp.js.map +1 -0
  89. package/comp.ts +111 -0
  90. package/deno.json +1 -0
  91. package/door.js +88 -0
  92. package/door.js.map +1 -0
  93. package/door.ts +142 -0
  94. package/format.js +43 -0
  95. package/format.js.map +1 -0
  96. package/format.ts +49 -0
  97. package/hold.js +17 -0
  98. package/hold.js.map +1 -0
  99. package/hold.ts +21 -0
  100. package/host.js +1024 -0
  101. package/host.js.map +1 -0
  102. package/host.ts +1140 -0
  103. package/http.js +268 -0
  104. package/http.js.map +1 -0
  105. package/http.ts +329 -0
  106. package/import.js +141 -0
  107. package/import.js.map +1 -0
  108. package/import.ts +128 -0
  109. package/index.js +496 -0
  110. package/index.js.map +1 -0
  111. package/index.ts +634 -0
  112. package/land.js +788 -0
  113. package/land.js.map +1 -0
  114. package/land.ts +871 -0
  115. package/mod.js +73 -0
  116. package/mod.js.map +1 -0
  117. package/mod.ts +74 -0
  118. package/objects.js +331 -0
  119. package/objects.js.map +1 -0
  120. package/objects.ts +390 -0
  121. package/oid.js +50 -0
  122. package/oid.js.map +1 -0
  123. package/oid.ts +83 -0
  124. package/pack-index.js +103 -0
  125. package/pack-index.js.map +1 -0
  126. package/pack-index.ts +104 -0
  127. package/pack-store.js +216 -0
  128. package/pack-store.js.map +1 -0
  129. package/pack-store.ts +292 -0
  130. package/pack.js +121 -0
  131. package/pack.js.map +1 -0
  132. package/pack.ts +146 -0
  133. package/package.json +78 -4
  134. package/pkt.js +73 -0
  135. package/pkt.js.map +1 -0
  136. package/pkt.ts +93 -0
  137. package/placement.js +44 -0
  138. package/placement.js.map +1 -0
  139. package/placement.ts +38 -0
  140. package/plugin.js +66 -0
  141. package/plugin.js.map +1 -0
  142. package/plugin.ts +88 -0
  143. package/process-cwd.py +57 -0
  144. package/project.js +142 -0
  145. package/project.js.map +1 -0
  146. package/project.ts +151 -0
  147. package/push.js +401 -0
  148. package/push.js.map +1 -0
  149. package/push.ts +451 -0
  150. package/refs.js +176 -0
  151. package/refs.js.map +1 -0
  152. package/refs.ts +285 -0
  153. package/rewrite.js +176 -0
  154. package/rewrite.js.map +1 -0
  155. package/rewrite.ts +173 -0
  156. package/service.js +104 -0
  157. package/service.js.map +1 -0
  158. package/service.ts +194 -0
  159. package/sha1.js +115 -0
  160. package/sha1.js.map +1 -0
  161. package/sha1.ts +146 -0
  162. package/source.js +100 -0
  163. package/source.js.map +1 -0
  164. package/source.ts +116 -0
  165. package/spare.js +108 -0
  166. package/spare.js.map +1 -0
  167. package/spare.ts +94 -0
  168. package/tools.js +278 -0
  169. package/tools.js.map +1 -0
  170. package/tools.ts +310 -0
  171. package/tree.js +105 -0
  172. package/tree.js.map +1 -0
  173. package/tree.ts +132 -0
  174. package/unpack.js +207 -0
  175. package/unpack.js.map +1 -0
  176. package/unpack.ts +210 -0
  177. package/vocab.js +20 -0
  178. package/vocab.js.map +1 -0
  179. package/vocab.json +386 -0
  180. package/vocab.ts +22 -0
  181. package/workspace.js +449 -0
  182. package/workspace.js.map +1 -0
  183. package/workspace.ts +445 -0
package/host.ts ADDED
@@ -0,0 +1,1140 @@
1
+ import { trash } from '@yaks/process/trash'
2
+ import * as io from '@yaks/file/io'
3
+ import { line } from '@yaks/query'
4
+ import * as system from '@yaks/process/system'
5
+ import { command as processCommand } from '@yaks/process/command'
6
+ // Git checkouts on the machine this process runs on: find one, record what Git
7
+ // reports about it, create a new worktree, take one back once it holds
8
+ // nothing, and create it again where it stood.
9
+ //
10
+ // Git is authoritative here. The graph holds an observation of what Git
11
+ // reports, and writing that observation again changes nothing, so discovery
12
+ // can be run at any time. These functions run `git` as a subprocess, so they
13
+ // are kept out of ./mod.ts, which type-checks with only the web platform in
14
+ // scope.
15
+
16
+ import type { Bundle, Comp, Graph } from 'jsr:@yaks/graph@0.2.36'
17
+ import { derivedEid, identityEid } from '@yaks/graph/identity'
18
+ import { token } from '@yaks/graph/sha256'
19
+ import { and, distinct, eq, fields, list, present } from '@yaks/query'
20
+ import { refEid } from './comp.js'
21
+ import { localFilesystem } from './placement.js'
22
+ import { checkoutBase } from './checkout.js'
23
+ import { spares } from './spare.js'
24
+ import { cache } from './cache.js'
25
+ export { filesystemEid, localFilesystem } from './placement.js'
26
+
27
+ export { checkoutDoc } from './checkout_vocab.js'
28
+
29
+ /** The entity id of a repository: its declared identity, the canonical common
30
+ * Git directory. */
31
+ export let repositoryEid = (common: string, workspace: string): string =>
32
+ identityEid('repository', [workspace, common])
33
+ /** The entity id of a checkout, derived from its repository and its canonical
34
+ * root path. */
35
+ export let worktreeEid = (repository: string, path: string): string =>
36
+ derivedEid('worktree|' + repository + '|' + path)
37
+
38
+ let git = async (cwd: string, args: string[], optional = false) => {
39
+ let p = await processCommand('git', {
40
+ cwd,
41
+ args,
42
+ stdout: 'piped',
43
+ stderr: 'piped',
44
+ }).output()
45
+ let text = new TextDecoder().decode(p.stdout).trimEnd()
46
+ if (!p.success && !optional) {
47
+ throw new Error(
48
+ 'git ' + args.join(' ') + ': ' +
49
+ new TextDecoder().decode(p.stderr).trim(),
50
+ )
51
+ }
52
+ return p.success ? text : undefined
53
+ }
54
+ let row = async (g: Graph, eid: string) => (await g.get([eid]))[0]
55
+ let canonical = async (path: string): Promise<string> => {
56
+ // The parent directories that do exist are canonicalized, so a path can be
57
+ // canonicalized before the checkout at the end of it has been created.
58
+ try {
59
+ return await io.realPath(path)
60
+ } catch (e) {
61
+ if (!io.isNotFound(e)) throw e
62
+ let absolute = path.startsWith('/') ? path : system.cwd() + '/' + path
63
+ let parts: string[] = []
64
+ for (let part of absolute.split('/')) {
65
+ if (part == '..') parts.pop()
66
+ else if (part && part != '.') parts.push(part)
67
+ }
68
+ let normalized = '/' + parts.join('/')
69
+ let at = normalized.lastIndexOf('/')
70
+ return await canonical(normalized.slice(0, at) || '/') + '/' +
71
+ normalized.slice(at + 1)
72
+ }
73
+ }
74
+
75
+ let exists = (path: string): Promise<boolean> =>
76
+ io.lstat(path).then(() => true, (error) => {
77
+ if (io.isNotFound(error)) return false
78
+ throw error
79
+ })
80
+
81
+ // Serialize creation and restoration at one worktree path, including requests
82
+ // through different graph clients. The advisory lock holds across processes,
83
+ // and the kernel releases it if this one dies. Lock files stay: unlinking one
84
+ // races with processes waiting on it.
85
+ let pending = new Map<string, Promise<unknown>>()
86
+ let locked = async <T>(
87
+ common: string,
88
+ path: string,
89
+ change: () => Promise<T>,
90
+ ): Promise<T> => {
91
+ let before = pending.get(path) ?? Promise.resolve()
92
+ let run = before.catch(() => {}).then(async () => {
93
+ let dir = common + '/yaks-locks'
94
+ await io.mkdir(dir, { recursive: true })
95
+ let file = await io.open(
96
+ dir + '/' + derivedEid('worktree lock|' + common + '|' + path),
97
+ { create: true, write: true },
98
+ )
99
+ try {
100
+ await file.lock(true)
101
+ return await change()
102
+ } finally {
103
+ file.close()
104
+ }
105
+ })
106
+ pending.set(path, run)
107
+ try {
108
+ return await run
109
+ } finally {
110
+ if (pending.get(path) === run) pending.delete(path)
111
+ }
112
+ }
113
+
114
+ /** Canonical Git directories for the checkout containing `cwd`, or nothing
115
+ * when that directory is gone or is not a checkout. Other filesystem and
116
+ * subprocess failures remain errors. This observation writes no graph rows. */
117
+ export let locate = async (cwd: string): Promise<
118
+ { path: string; common: string; gitdir: string } | undefined
119
+ > => {
120
+ let dirs: string | undefined
121
+ try {
122
+ dirs = await git(cwd, [
123
+ 'rev-parse',
124
+ '--path-format=absolute',
125
+ '--show-toplevel',
126
+ '--git-common-dir',
127
+ '--absolute-git-dir',
128
+ ])
129
+ } catch (error) {
130
+ if (
131
+ error instanceof Error &&
132
+ error.message.includes('fatal: not a git repository')
133
+ ) {
134
+ try {
135
+ await io.lstat(`${cwd}/.git`)
136
+ } catch (missing) {
137
+ if (io.isNotFound(missing)) return undefined
138
+ throw missing
139
+ }
140
+ }
141
+ if (!io.isNotFound(error)) {
142
+ throw new Error(`Git checkout ${cwd}: ${String(error)}`, {
143
+ cause: error,
144
+ })
145
+ }
146
+ // ENOENT can also mean the git executable is missing. Only a missing
147
+ // checkout directory is an absent observation.
148
+ try {
149
+ await io.stat(cwd)
150
+ } catch (missing) {
151
+ if (io.isNotFound(missing)) return undefined
152
+ throw missing
153
+ }
154
+ throw new Error(`Git checkout ${cwd}: ${String(error)}`, { cause: error })
155
+ }
156
+ if (!dirs) return undefined
157
+ let [path, common, gitdir] = await Promise.all(
158
+ dirs.split('\n').map((dir) => io.realPath(dir)),
159
+ )
160
+ return { path, common, gitdir }
161
+ }
162
+
163
+ /** Current primary checkouts on this filesystem. Historical observations and
164
+ * managed restore records do not stand in for a checkout that Git can open. */
165
+ export let primary = async (g: Graph): Promise<string[]> => {
166
+ let filesystem = await localFilesystem(g)
167
+ let refs = await g.rows(and(
168
+ present('worktree'),
169
+ eq('worktree.repository.repository.workspace', filesystem.entity.eid),
170
+ distinct('worktree.repository'),
171
+ ))
172
+ let ids = refs.map((r) => r.value).filter((id): id is string =>
173
+ typeof id == 'string'
174
+ )
175
+ let repos = ids.length ? await g.get(ids, ['repository']) : []
176
+ let dirs = repos.flatMap((b) => {
177
+ let common = (b.repository as Comp | undefined)?.common
178
+ return typeof common == 'string' ? [common] : []
179
+ })
180
+ if (!dirs.length) return []
181
+ let rows = await g.read(and(
182
+ present('worktree'),
183
+ eq('worktree.repository.repository.workspace', filesystem.entity.eid),
184
+ eq('worktree.repository', list(...ids)),
185
+ eq('worktree.gitdir', list(...dirs)),
186
+ fields(
187
+ 'worktree.repository',
188
+ 'worktree.gitdir',
189
+ 'workspace.root',
190
+ 'worktree.repository.repository.common',
191
+ ),
192
+ ))
193
+ let common = new Map(
194
+ rows.filter((b) => b.repository).map((b) => [
195
+ b.entity.eid,
196
+ (b.repository as Comp).common,
197
+ ]),
198
+ )
199
+ let trees = rows.filter((b) => b.worktree)
200
+ let roots: string[] = []
201
+ for (let b of trees) {
202
+ let tree = b.worktree as Comp
203
+ let root = (b.workspace as Comp | undefined)?.root
204
+ let dir = common.get(String(tree.repository))
205
+ if (
206
+ typeof dir != 'string' || tree.gitdir != dir || typeof root != 'string'
207
+ ) {
208
+ continue
209
+ }
210
+ let current = await locate(root)
211
+ if (
212
+ current && current.gitdir == dir && current.common == dir &&
213
+ current.path == root
214
+ ) roots.push(root)
215
+ }
216
+ return [...new Set(roots)].sort()
217
+ }
218
+
219
+ /** Retire obsolete unmanaged checkout observations of the repository at
220
+ * `common`, keeping the entity and its other components. Managed rows retain
221
+ * the history required by restore, and are not read: a repository keeps
222
+ * thousands. */
223
+ export let reconcile = async (
224
+ g: Graph,
225
+ common: string,
226
+ repository: string,
227
+ ): Promise<void> => {
228
+ for (
229
+ let tree of await g.read(
230
+ line`.worktree.repository=${repository}&.worktree.managed!=true ?workspace`,
231
+ )
232
+ ) {
233
+ let w = tree.worktree as Comp
234
+ let path = (tree.workspace as Comp | undefined)?.root
235
+ if (w.managed || typeof path != 'string') continue
236
+ let current = await locate(path)
237
+ if (
238
+ current?.path == path && current.common == common &&
239
+ current.gitdir == w.gitdir
240
+ ) continue
241
+ await g.apply([{
242
+ entity: { eid: tree.entity.eid },
243
+ worktree: null,
244
+ $was: {
245
+ worktree: Object.fromEntries(
246
+ Object.entries(w).map(([key, value]) => [key, token(value)]),
247
+ ),
248
+ },
249
+ }])
250
+ }
251
+ }
252
+
253
+ /** Find the checkout containing `cwd`, and update the repository's refs from
254
+ * Git. A ref that Git no longer has keeps its row, marked absent. With
255
+ * `refs: false`, only the checkout's own row: a pass over many checkouts of
256
+ * one repository would otherwise read and compare every ref it has (a
257
+ * thousand and more) once for each. */
258
+ export let discover = async (
259
+ g: Graph,
260
+ cwd: string,
261
+ o: { refs?: boolean } = {},
262
+ ): Promise<Bundle> => {
263
+ // Git is asked everything at once: each answer is about the checkout that
264
+ // holds `cwd`, from wherever in it `cwd` is, and a session opening pays for
265
+ // one round of processes rather than six in a row.
266
+ let [dirs, head, branch, refs] = await Promise.all([
267
+ locate(cwd),
268
+ git(cwd, ['rev-parse', '--verify', 'HEAD'], true),
269
+ git(cwd, ['symbolic-ref', '-q', 'HEAD'], true),
270
+ o.refs == false ? undefined : git(cwd, [
271
+ 'for-each-ref',
272
+ '--format=%(refname)%09%(objectname)%09%(symref)',
273
+ ]).catch((error: Error) => error),
274
+ ])
275
+ // Outside a checkout every command fails; that it is not one is the answer.
276
+ if (!dirs) throw new Error('not a checkout: ' + cwd)
277
+ if (refs instanceof Error) throw refs
278
+ let { path, common, gitdir } = dirs
279
+ let filesystem = await localFilesystem(g)
280
+ let repository = repositoryEid(common, filesystem.entity.eid)
281
+ let eid = worktreeEid(repository, path)
282
+ let bundles: Bundle[] = [{
283
+ entity: { eid: repository },
284
+ repository: { common, workspace: filesystem.entity.eid },
285
+ }]
286
+ let found = new Set<string>()
287
+ for (let line of (refs ?? '').split('\n').filter(Boolean)) {
288
+ let [name, oid, target] = line.split('\t')
289
+ let id = refEid(repository, name)
290
+ found.add(id)
291
+ bundles.push({
292
+ entity: { eid: id },
293
+ ref: {
294
+ app: repository,
295
+ name,
296
+ oid,
297
+ target: target || null,
298
+ present: true,
299
+ },
300
+ })
301
+ }
302
+ // A branch with no commits yet still gets an entity, even though Git has no
303
+ // ref for it.
304
+ if (refs != null && branch && !found.has(refEid(repository, branch))) {
305
+ let id = refEid(repository, branch)
306
+ found.add(id)
307
+ bundles.push({
308
+ entity: { eid: id },
309
+ ref: {
310
+ app: repository,
311
+ name: branch,
312
+ oid: null,
313
+ target: null,
314
+ present: false,
315
+ },
316
+ })
317
+ }
318
+ // Only a ref still marked present can have gone: the repository's absent
319
+ // ones, every branch a session ever cut, are many times the present.
320
+ let present = refs == null ? [] : await g.rows(
321
+ line`.ref.app=${repository}&.ref.present=true .fields=entity.eid`,
322
+ ) as { eid: string }[]
323
+ for (let { eid } of present) {
324
+ if (!found.has(eid)) {
325
+ bundles.push({
326
+ entity: { eid },
327
+ ref: { present: false, oid: null, target: null },
328
+ })
329
+ }
330
+ }
331
+ let old = await row(g, eid)
332
+ let tree: Bundle = {
333
+ entity: { eid },
334
+ worktree: {
335
+ repository,
336
+ gitdir,
337
+ head: head ?? null,
338
+ branch: branch ? refEid(repository, branch) : null,
339
+ managed: Boolean((old?.worktree as Comp | undefined)?.managed),
340
+ },
341
+ }
342
+ tree.workspace = {
343
+ machine: (filesystem.workspace as Comp).machine,
344
+ root: path,
345
+ }
346
+ bundles.push(tree)
347
+ // Write only the rows whose values actually changed, so that discovering an
348
+ // unchanged checkout updates no timestamps and notifies nobody.
349
+ let previous = await g.get(
350
+ bundles.map((b) => b.entity.eid),
351
+ ['repository', 'ref', 'worktree', 'workspace'],
352
+ )
353
+ let byId = new Map(previous.map((b) => [b.entity.eid, b]))
354
+ let changed = bundles.filter((b) =>
355
+ Object.entries(b).some(([k, v]) =>
356
+ k != 'entity' &&
357
+ Object.entries(v as Comp).some(([prop, value]) =>
358
+ (typeof value == 'boolean'
359
+ ? Boolean((byId.get(b.entity.eid)?.[k] as Comp | undefined)?.[prop])
360
+ : ((byId.get(b.entity.eid)?.[k] as Comp | undefined)?.[prop] ??
361
+ null)) !== (value ?? null)
362
+ )
363
+ )
364
+ )
365
+ if (changed.length) await g.apply(changed)
366
+ return (await row(g, eid))!
367
+ }
368
+
369
+ /** Repeating the same base request uses its original commit, even after a
370
+ * branch moves. A different base must still name that pinned commit. With
371
+ * `spare`, the checkout is made from the spare beside it ({@link keepSpare}) when
372
+ * there is one. */
373
+ export type CheckoutRequest = {
374
+ path: string
375
+ base?: string
376
+ branch?: string
377
+ spare?: boolean
378
+ }
379
+ let resolve = async (source: string, base: string): Promise<string> =>
380
+ (await git(source, [
381
+ 'rev-parse',
382
+ '--verify',
383
+ '--end-of-options',
384
+ base + '^{commit}',
385
+ ]))!
386
+ /** Create a worktree, safely repeatable after a failure. A path that already
387
+ * exists must be a checkout of the same repository. HEAD is detached unless a
388
+ * branch is named, and the base is resolved to a commit, so uncommitted files
389
+ * are never copied. Git's own worktree and ref locks settle races between
390
+ * processes. */
391
+ let create = async (g: Graph, source: string, request: CheckoutRequest) => {
392
+ let home = await discover(g, source)
393
+ let repository = String((home.worktree as Comp).repository)
394
+ let path = await canonical(request.path)
395
+ let eid = worktreeEid(repository, path)
396
+ let old = await row(g, eid)
397
+ let intent = old?.checkout as Comp | undefined
398
+ let resolved = intent
399
+ ? await checkoutBase(intent, request.base, (name) => resolve(source, name))
400
+ : undefined
401
+ if (intent && (intent.branch ?? null) !== (request.branch ?? null)) {
402
+ throw new Error('checkout request conflicts with existing branch intent')
403
+ }
404
+ if (old?.worktree && !intent) {
405
+ throw new Error(
406
+ 'existing checkout must be attached by home, not created again',
407
+ )
408
+ }
409
+ if (old?.worktree && intent?.state == 'ready') {
410
+ await replace(g, path, old.worktree as Comp, request.spare)
411
+ let current = await discover(g, path)
412
+ if ((current.worktree as Comp).repository != repository) {
413
+ throw new Error('worktree repository mismatch')
414
+ }
415
+ return current
416
+ }
417
+ if (!intent) {
418
+ try {
419
+ await io.stat(path)
420
+ throw new Error('checkout path already exists; attach with home instead')
421
+ } catch (e) {
422
+ if (!io.isNotFound(e)) throw e
423
+ }
424
+ }
425
+ await g.apply([{
426
+ entity: { eid },
427
+ checkout: {
428
+ repository,
429
+ path,
430
+ requested: intent?.requested ?? request.base ?? 'HEAD',
431
+ branch: request.branch ?? null,
432
+ state: 'preparing',
433
+ error: null,
434
+ },
435
+ }])
436
+ let base: string
437
+ try {
438
+ base = resolved ?? await resolve(source, request.base ?? 'HEAD')
439
+ await g.apply([{ entity: { eid }, checkout: { base } }])
440
+ } catch (error) {
441
+ await g.apply([{
442
+ entity: { eid },
443
+ checkout: { state: 'failed', error: String(error) },
444
+ }])
445
+ throw error
446
+ }
447
+ try {
448
+ await add(
449
+ source,
450
+ path,
451
+ request.branch ? ['-b', request.branch] : ['--detach'],
452
+ base,
453
+ request.spare,
454
+ )
455
+ } catch (failure) {
456
+ // Another process, or a crash after `git worktree add` succeeded, may have
457
+ // already done this; check before reporting a failure.
458
+ try {
459
+ let current = await discover(g, path)
460
+ let c = current.worktree as Comp
461
+ let desiredBranch = request.branch
462
+ ? refEid(repository, 'refs/heads/' + request.branch)
463
+ : null
464
+ if (
465
+ c.repository != repository || c.head != base ||
466
+ (c.branch ?? null) != desiredBranch
467
+ ) throw failure
468
+ } catch {
469
+ await g.apply([{
470
+ entity: { eid },
471
+ checkout: { state: 'failed', error: String(failure) },
472
+ }])
473
+ throw failure
474
+ }
475
+ }
476
+ let current = await discover(g, path)
477
+ await g.apply([{
478
+ entity: { eid: current.entity.eid },
479
+ worktree: { managed: true },
480
+ checkout: { state: 'ready', error: null },
481
+ }])
482
+ return (await row(g, current.entity.eid))!
483
+ }
484
+
485
+ /** The checkout containing `cwd`, or undefined when `cwd` is not inside one.
486
+ * Creating a worktree always goes through `discover`, which refuses that. */
487
+ export let checkoutAt = async (
488
+ g: Graph,
489
+ cwd: string,
490
+ ): Promise<Bundle | undefined> => {
491
+ if (!await locate(cwd)) {
492
+ return undefined
493
+ }
494
+ return discover(g, cwd)
495
+ }
496
+
497
+ export let createWorktree = async (
498
+ g: Graph,
499
+ source: string,
500
+ request: CheckoutRequest,
501
+ ): Promise<Bundle> => {
502
+ let path = await canonical(request.path)
503
+ return locked(
504
+ await commonOf(source),
505
+ path,
506
+ () => create(g, source, { ...request, path }),
507
+ )
508
+ }
509
+
510
+ let commonOf = async (source: string): Promise<string> =>
511
+ io.realPath(
512
+ (await git(source, [
513
+ 'rev-parse',
514
+ '--path-format=absolute',
515
+ '--git-common-dir',
516
+ ]))!,
517
+ )
518
+
519
+ let { add, keep } = spares({
520
+ git,
521
+ exists,
522
+ entries: io.readDir,
523
+ remove: (path) =>
524
+ io.remove(path, { recursive: true }).catch((error) => {
525
+ if (!io.isNotFound(error)) throw error
526
+ }),
527
+ lock: async (source, path, change) =>
528
+ locked(await commonOf(source), path, change),
529
+ })
530
+
531
+ /**
532
+ * Cut the spare checkout beside `path` from `base` (a commit or ref of the
533
+ * repository `source` is a checkout of), unless one is there: a checkout
534
+ * created in that directory with `spare` is made from it in about a second,
535
+ * where one cut whole writes every file and installs its dependencies. It is
536
+ * cut under a name of its own and moved once whole, so nothing takes it half
537
+ * made. Its Git registration stays locked through publication and claim; a
538
+ * concurrent prune cannot remove it. Unfinished cuts are removed first.
539
+ *
540
+ * ```ts ignore
541
+ * import { createWorktree, keepSpare } from '@yaks/git/host'
542
+ *
543
+ * let path = '/srv/runs/S-1'
544
+ * await createWorktree(graph, '/srv/repo', { path, branch: 'b', spare: true })
545
+ * await keepSpare('/srv/repo', path, 'refs/heads/main') // for the next one
546
+ * ```
547
+ */
548
+ export let keepSpare = async (
549
+ source: string,
550
+ path: string,
551
+ base = 'HEAD',
552
+ ): Promise<void> => {
553
+ await keep(source, await canonical(path), base)
554
+ }
555
+
556
+ /** Why a worktree was kept: uncommitted files, commits that exist nowhere
557
+ * else, an unfinished Git operation or lock, a failed removal, or a run
558
+ * that took it up again. */
559
+ export type Held = 'dirty' | 'unlanded' | 'busy' | 'failed' | 'taken'
560
+
561
+ /** What the scan reads of this host's processes, each read failing as procfs
562
+ * does: `procfs` reads Linux's, and a test hands the scan its own. */
563
+ export type Procs = {
564
+ /** Every process listed, by pid. */
565
+ pids: () => Promise<string[]>
566
+ /** The uid that owns a process. */
567
+ owner: (pid: string) => Promise<number>
568
+ /** A process's canonical working directory. */
569
+ cwd: (pid: string) => Promise<string>
570
+ /** Where a process's open descriptors point; one that closed reads `''`. */
571
+ links: (pid: string) => Promise<string[]>
572
+ /** The cwd and absolute open file paths of each same-user process ptrace
573
+ * hides, keyed by PID. Processes that cannot be read are absent. */
574
+ privileged: (pids: string[]) => Promise<Record<string, string[]>>
575
+ }
576
+
577
+ // Linux's ptrace checks can hide even a same-user cwd (a capability-bearing
578
+ // manager or a non-dumpable PAM helper). Ask the user manager for a privileged
579
+ // reader in one launch. The root-owned helper and sudo permission are
580
+ // installed as described in README.md.
581
+ let readPrivileged = async (pids: string[]): Promise<unknown> => {
582
+ let read = await processCommand('systemd-run', {
583
+ args: [
584
+ '--user',
585
+ '--quiet',
586
+ '--wait',
587
+ '--pipe',
588
+ '--collect',
589
+ '/usr/bin/sudo',
590
+ '-n',
591
+ '/usr/local/libexec/yak-process-cwd',
592
+ ...pids,
593
+ ],
594
+ env: {
595
+ XDG_RUNTIME_DIR: `/run/user/${system.uid()}`,
596
+ DBUS_SESSION_BUS_ADDRESS: `unix:path=/run/user/${system.uid()}/bus`,
597
+ },
598
+ stdout: 'piped',
599
+ stderr: 'piped',
600
+ }).output()
601
+ if (!read.success) return
602
+ try {
603
+ return JSON.parse(new TextDecoder().decode(read.stdout))
604
+ } catch {
605
+ return
606
+ }
607
+ }
608
+
609
+ let absolutePaths = (value: unknown): value is string[] =>
610
+ Array.isArray(value) && value.length > 0 &&
611
+ value.every((path) => typeof path == 'string' && path.startsWith('/'))
612
+
613
+ let privileged: Procs['privileged'] = async (pids) => {
614
+ let found = await readPrivileged(pids)
615
+ if (found && typeof found == 'object' && !Array.isArray(found)) {
616
+ let rows = found as Record<string, unknown>
617
+ return Object.fromEntries(
618
+ pids.filter((pid) => absolutePaths(rows[pid])).map((pid) => [
619
+ pid,
620
+ rows[pid] as string[],
621
+ ]),
622
+ )
623
+ }
624
+ if (pids.length == 1) {
625
+ return absolutePaths(found) ? { [pids[0]]: found } : {}
626
+ }
627
+ // The original installed helper accepts a single PID.
628
+ return Object.assign(
629
+ {},
630
+ ...await Promise.all(pids.map((pid) => privileged([pid]))),
631
+ )
632
+ }
633
+
634
+ /** This Linux host's processes, read from `/proc`. */
635
+ export let procfs: Procs = {
636
+ pids: async () => {
637
+ if (system.os != 'linux') {
638
+ throw new Error('Worktree collection requires a local process scan')
639
+ }
640
+ return (await Array.fromAsync(io.readDir('/proc')))
641
+ .map((entry) => entry.name).filter((name) => /^\d+$/.test(name))
642
+ },
643
+ owner: async (pid) => (await io.stat(`/proc/${pid}`)).uid,
644
+ cwd: (pid) => io.realPath(`/proc/${pid}/cwd`),
645
+ links: async (pid) => {
646
+ let fd = `/proc/${pid}/fd`
647
+ return await Promise.all(
648
+ (await Array.fromAsync(io.readDir(fd))).map((entry) =>
649
+ io.readLink(`${fd}/${entry.name}`).catch((error) => {
650
+ if (io.isNotFound(error)) return ''
651
+ throw error
652
+ })
653
+ ),
654
+ )
655
+ },
656
+ privileged,
657
+ }
658
+
659
+ // Ask procfs about this user's processes, then give the privileged reader
660
+ // the PIDs ptrace hid. The helper checks their owner again.
661
+ let scan = async (
662
+ procs: Procs,
663
+ read: (pid: string) => Promise<string[]>,
664
+ hidden = (paths: string[]) => paths,
665
+ ): Promise<string[]> => {
666
+ let denied: string[] = []
667
+ let paths = await Promise.all((await procs.pids()).map(async (pid) => {
668
+ try {
669
+ if (await procs.owner(pid) != system.uid()) return []
670
+ try {
671
+ return await read(pid)
672
+ } catch (error) {
673
+ if (!io.isPermissionDenied(error)) throw error
674
+ denied.push(pid)
675
+ }
676
+ } catch { /* The process went away before it could be read. */ }
677
+ return []
678
+ }))
679
+ if (denied.length) {
680
+ let found = await procs.privileged(denied).catch(() => ({}))
681
+ paths.push(...Object.values(found).map(hidden))
682
+ }
683
+ return paths.flat()
684
+ }
685
+
686
+ /** Canonical directories occupied by this user's live local processes,
687
+ * including agents outside the graph. A process that cannot be read holds
688
+ * nothing. */
689
+ export let processCwds = async (procs = procfs): Promise<Set<string>> =>
690
+ new Set([
691
+ await io.realPath(system.cwd()),
692
+ ...await scan(
693
+ procs,
694
+ async (pid) => [await procs.cwd(pid)],
695
+ (paths) => paths.slice(0, 1),
696
+ ),
697
+ ])
698
+
699
+ /** Paths occupied by this user's processes: their directories and open files.
700
+ * Procfs links name the canonical file even when it was opened through a
701
+ * symlink. A process that cannot be read holds nothing. */
702
+ export let processPaths = async (procs = procfs): Promise<Set<string>> =>
703
+ new Set(
704
+ await scan(procs, async (pid) => [
705
+ await procs.cwd(pid),
706
+ ...(await procs.links(pid)).filter((path) => path.startsWith('/'))
707
+ .map((path) => path.replace(/ \(deleted\)$/, '')),
708
+ ]),
709
+ )
710
+
711
+ /** A process using any path inside a worktree keeps the whole checkout. */
712
+ export let inUse = (path: string, cwds: Set<string>): boolean =>
713
+ cwds.has(path) || cwds.values().some((cwd) => cwd.startsWith(path + '/'))
714
+
715
+ // A git command's output, or nothing when it failed or could not run at all —
716
+ // a path that is not a checkout is an answer here, not an error.
717
+ let quiet = (cwd: string, args: string[]): Promise<string | undefined> =>
718
+ git(cwd, args, true).catch(() => undefined)
719
+
720
+ // The gitdir a linked worktree's `.git` file names, or nothing for a primary
721
+ // checkout or a path that is not a checkout at all. A worktree linked with
722
+ // `--relative-paths` names it relative to itself, never to this process.
723
+ let gitdirOf = async (path: string): Promise<string | undefined> => {
724
+ let named = /^gitdir:\s*(.+)$/m.exec(
725
+ await io.readTextFile(path + '/.git').catch(() => ''),
726
+ )?.[1]?.trim()
727
+ return named && !named.startsWith('/') ? `${path}/${named}` : named
728
+ }
729
+
730
+ // Git keeps operation state with the worktree, even after the process exits.
731
+ let BUSY = new Set([
732
+ 'rebase-merge',
733
+ 'rebase-apply',
734
+ 'MERGE_HEAD',
735
+ 'CHERRY_PICK_HEAD',
736
+ 'REVERT_HEAD',
737
+ 'sequencer',
738
+ 'BISECT_START',
739
+ 'locked',
740
+ 'index.lock',
741
+ ])
742
+
743
+ let busy = async (path: string): Promise<boolean> => {
744
+ let dir = await gitdirOf(path)
745
+ if (!dir) return false
746
+ try {
747
+ for await (let entry of io.readDir(dir)) {
748
+ if (BUSY.has(entry.name)) return true
749
+ }
750
+ } catch (error) {
751
+ if (!io.isNotFound(error)) throw error
752
+ }
753
+ return false
754
+ }
755
+
756
+ /** A worktree Git has already lost: the gitdir its `.git` file names is gone,
757
+ * so nothing can be committed from it and nothing read out of it. */
758
+ export let lost = async (path: string): Promise<boolean> => {
759
+ let named = await gitdirOf(path)
760
+ return !!named && !await io.stat(named).then(() => true, () => false)
761
+ }
762
+
763
+ /// moved('a b J <j@x> 1700000000 -0400\tcommit: x\n') -> 1700000000000
764
+ /// moved('') -> 0
765
+ /** When a reflog's last entry moved HEAD, in milliseconds: the time written
766
+ * in the entry, not the file's. `git gc` expires every worktree's reflog,
767
+ * rewriting each file whole with the same entries, so its mtime says when
768
+ * gc last ran. */
769
+ export let moved = (reflog: string): number => {
770
+ let last = reflog.trimEnd().split('\n').at(-1) ?? ''
771
+ let at = Number(/ (\d+) [+-]\d{4}\t/.exec(last)?.[1])
772
+ return Number.isSafeInteger(at) ? at * 1000 : 0
773
+ }
774
+
775
+ /** How long, in milliseconds, since Git last moved this linked worktree's
776
+ * HEAD: a commit, checkout, rebase or reset, by its reflog's last entry, or
777
+ * HEAD's own write. Editing or staging a file moves neither, but it makes the
778
+ * worktree dirty, and a dirty worktree is kept at any age. Zero for anything
779
+ * that is not a linked worktree. */
780
+ export let idleFor = async (
781
+ path: string,
782
+ now: number = Date.now(),
783
+ ): Promise<number> => {
784
+ let dir = await gitdirOf(path)
785
+ if (!dir) return 0
786
+ let [head, reflog] = await Promise.all([
787
+ io.stat(dir + '/HEAD').then((s) => s.mtime?.getTime() ?? 0, () => 0),
788
+ io.readTextFile(dir + '/logs/HEAD').then(moved, () => 0),
789
+ ])
790
+ return Math.max(0, now - Math.max(head, reflog))
791
+ }
792
+
793
+ /** The linked worktrees of the repository whose common Git directory is
794
+ * `common`: every checkout `git worktree list` names but the primary one.
795
+ * Git's records of worktrees whose directory is already gone are pruned
796
+ * first, so none of those is named. */
797
+ export let linked = async (common: string): Promise<string[]> => {
798
+ let at = ['--git-dir=' + common, 'worktree']
799
+ await quiet(common, [...at, 'prune'])
800
+ let list = await quiet(common, [...at, 'list', '--porcelain']) ?? ''
801
+ return list.split('\n')
802
+ .filter((line) => line.startsWith('worktree '))
803
+ .map((line) => line.slice('worktree '.length))
804
+ .slice(1)
805
+ }
806
+
807
+ // What `git status` says of a checkout, from one process: whether it has
808
+ // uncommitted files, the commit it stands at and the branch it is on, by its
809
+ // short name. Nothing when the path is not a checkout.
810
+ let standing = async (path: string) => {
811
+ let said = await quiet(path, ['status', '--porcelain=v2', '--branch'])
812
+ if (said == null) return undefined
813
+ let lines = said.split('\n')
814
+ let header = (key: string) =>
815
+ lines.find((l) => l.startsWith(`# branch.${key} `))?.split(' ')[2]
816
+ let head = header('oid')
817
+ let branch = header('head')
818
+ return {
819
+ dirty: lines.some((l) => l && !l.startsWith('#')),
820
+ head: head == '(initial)' ? undefined : head,
821
+ branch: branch == '(detached)' ? undefined : branch,
822
+ }
823
+ }
824
+
825
+ // Containment on main proves landing only after the branch wrote work of its
826
+ // own. Reflogs retain commits through a rebase; a creation or a fast-forward
827
+ // alone is not work. Missing/expired evidence keeps the checkout.
828
+ let committed = async (path: string, branch: string, head: string) => {
829
+ let log = await quiet(path, [
830
+ 'reflog',
831
+ 'show',
832
+ '--format=%H%x09%gs',
833
+ branch,
834
+ ])
835
+ let entries = log?.split('\n').filter(Boolean) ?? []
836
+ let start = entries.at(-1)?.split('\t')[0]
837
+ if (!start) return false
838
+ let headLog = await quiet(path, [
839
+ 'reflog',
840
+ 'show',
841
+ '--format=%H%x09%gs',
842
+ 'HEAD',
843
+ ])
844
+ for (let entry of [...entries, ...headLog?.split('\n') ?? []]) {
845
+ let [hash, message] = entry.split('\t')
846
+ if (
847
+ !/^(commit(?: \([^)]*\))?|cherry-pick|rebase \(pick\)):/.test(
848
+ message ?? '',
849
+ )
850
+ ) continue
851
+ if (
852
+ await quiet(path, ['merge-base', '--is-ancestor', hash, start]) == null &&
853
+ await quiet(path, ['merge-base', '--is-ancestor', hash, head]) != null
854
+ ) return true
855
+ }
856
+ return false
857
+ }
858
+
859
+ // What a checkout holds, beside the branch it stands on.
860
+ let holding = async (
861
+ path: string,
862
+ landed?: string,
863
+ base?: string,
864
+ ): Promise<{ held?: Held; branch?: string }> => {
865
+ if (await busy(path)) return { held: 'busy' }
866
+ let at = await standing(path)
867
+ if (at?.dirty) return { held: 'dirty' }
868
+ if (!at?.head) return { held: 'unlanded' }
869
+ let own = at.branch && `refs/heads/${at.branch}`
870
+ if (landed) {
871
+ let merged = !!own && own != landed &&
872
+ (at.head == base || await committed(path, own, at.head)) &&
873
+ await quiet(path, [
874
+ 'merge-base',
875
+ '--is-ancestor',
876
+ at.head,
877
+ landed,
878
+ ]) != null
879
+ return { held: merged ? undefined : 'unlanded', branch: at.branch }
880
+ }
881
+ let elsewhere = (await quiet(path, [
882
+ 'for-each-ref',
883
+ '--contains',
884
+ at.head,
885
+ '--format=%(refname)',
886
+ 'refs/heads/',
887
+ ]) ?? '').split('\n').filter((ref) => ref && ref != own)
888
+ return { held: elsewhere.length ? undefined : 'unlanded', branch: at.branch }
889
+ }
890
+
891
+ /** What this worktree still holds, `undefined` when it holds nothing: a clean
892
+ * working tree whose HEAD already exists on some other branch — the base it was
893
+ * created from, a parent's branch, main. Its own branch never counts; that is
894
+ * what "unlanded" means. A path that is not a worktree at all is reported as
895
+ * `unlanded` — kept, never guessed at. With `landed`, only that full local
896
+ * branch ref counts as a landing (for example `refs/heads/main`), and the
897
+ * branch reflog must prove it committed work still contained in HEAD. A fresh
898
+ * branch or missing reflog evidence is kept. A lock or unfinished Git
899
+ * operation keeps a linked worktree as `busy`. A caller supplying the checkout's
900
+ * pinned `base` can also take back a clean checkout still at that commit. */
901
+ export let holds = async (
902
+ path: string,
903
+ landed?: string,
904
+ base?: string,
905
+ ): Promise<Held | undefined> => (await holding(path, landed, base)).held
906
+
907
+ // Git silently discards ignored files on worktree removal. Dependency/build
908
+ // caches and declared scratch are reproducible; every other ignored path is
909
+ // kept separately before the checkout goes.
910
+ let keepIgnored = async (path: string) => {
911
+ let files = await git(path, [
912
+ 'ls-files',
913
+ '--others',
914
+ '--ignored',
915
+ '--exclude-standard',
916
+ '--directory',
917
+ '-z',
918
+ ])
919
+ for (let file of files!.split('\0').filter(Boolean)) {
920
+ if (cache(file)) continue
921
+ await trash(`${path}/${file}`)
922
+ }
923
+ }
924
+
925
+ /** Remove one worktree — the directory and the branch it was created on —
926
+ * unless it still holds something. Returns what kept it, or nothing. A worktree
927
+ * Git has lost is kept: its unique contents cannot be proved absent. Nothing
928
+ * here passes `--force`, so Git's own
929
+ * refusal is a second guard behind `holds`. It is removed under the lock
930
+ * creation takes at its path, after `free` (asked under that lock) says
931
+ * nobody took it up again: a checkout created there meanwhile waits for the
932
+ * removal to finish and cuts it again, rather than finding it half gone. */
933
+ export let reclaim = async (
934
+ path: string,
935
+ landed?: string,
936
+ base?: string,
937
+ free: () => Promise<boolean> = () => Promise.resolve(true),
938
+ ): Promise<Held | undefined> => {
939
+ if (await lost(path)) {
940
+ // Without Git's index and HEAD, cleanliness and landing cannot be proved.
941
+ return 'unlanded'
942
+ }
943
+ let common = await commonOf(path).catch(() => undefined)
944
+ if (!common) return 'failed'
945
+ return locked(common, await canonical(path), async () => {
946
+ let { held, branch } = await holding(path, landed, base)
947
+ if (held == 'busy') return held
948
+ let caches = ['.scratch', 'node_modules']
949
+ let ignored = (await quiet(path, [
950
+ 'ls-files',
951
+ '--others',
952
+ '--ignored',
953
+ '--exclude-standard',
954
+ '--directory',
955
+ '-z',
956
+ '--',
957
+ ...caches.map((dir) => dir + '/'),
958
+ ]))?.split('\0')
959
+ let disposable = caches.filter((dir) => ignored?.includes(dir + '/'))
960
+ if (held && !disposable.length) return held
961
+ if (!await free()) return 'taken'
962
+ if (await busy(path)) return 'busy'
963
+ // Release reproducible dependencies and scratch database copies even
964
+ // when uncommitted files or unlanded commits keep the checkout.
965
+ for (let dir of disposable) {
966
+ await io.remove(`${path}/${dir}`, { recursive: true })
967
+ }
968
+ if (held) return held
969
+ await keepIgnored(path)
970
+ if (await quiet(path, ['worktree', 'remove', path]) == null) {
971
+ return 'failed'
972
+ }
973
+ // The branch outlives its worktree, and only the repository can delete
974
+ // it. `-D` is safe here: the commits were proved to exist on another
975
+ // branch.
976
+ if (branch) {
977
+ await quiet(common, ['--git-dir=' + common, 'branch', '-D', branch])
978
+ }
979
+ return undefined
980
+ })
981
+ }
982
+
983
+ /** The size of an untracked file too large to commit when shelving: a
984
+ * megabyte. A checkout holding one is kept, as an asset never goes in Git. */
985
+ export let LARGE = 1_000_000
986
+
987
+ /** Put a worktree its agent left on its shelf: its uncommitted files are
988
+ * committed onto its branch, a detached HEAD gets a `shelf/` branch of its
989
+ * own, and the checkout is removed while the branch stays. Every commit stays
990
+ * on a branch, so `restore` cuts it again where it stood once `onBranch` (run
991
+ * with the work committed and the checkout still there) has recorded it.
992
+ * Returns what kept it, or nothing: `dirty` for an untracked file of
993
+ * {@link LARGE} or more, `busy` for a lock or unfinished Git operation,
994
+ * `failed` when Git refused a step. It is removed
995
+ * under the lock creation takes at its path, as `reclaim` removes one. */
996
+ export let shelve = async (
997
+ path: string,
998
+ onBranch: () => Promise<unknown> = async () => {},
999
+ free: () => Promise<boolean> = () => Promise.resolve(true),
1000
+ ): Promise<Held | undefined> => {
1001
+ if (await lost(path)) return 'unlanded'
1002
+ let common = await commonOf(path).catch(() => undefined)
1003
+ if (!common) return 'failed'
1004
+ return locked(common, await canonical(path), () => put(path, onBranch, free))
1005
+ }
1006
+
1007
+ // Shelve, under the lock creation takes at `path`.
1008
+ let put = async (
1009
+ path: string,
1010
+ onBranch: () => Promise<unknown>,
1011
+ free: () => Promise<boolean>,
1012
+ ): Promise<Held | undefined> => {
1013
+ if (await busy(path)) return 'busy'
1014
+ let at = await standing(path)
1015
+ if (!at) return 'unlanded'
1016
+ if (at.dirty) {
1017
+ let untracked = (await quiet(path, [
1018
+ 'ls-files',
1019
+ '--others',
1020
+ '--exclude-standard',
1021
+ '-z',
1022
+ ]) ?? '').split('\0').filter(Boolean)
1023
+ for (let file of untracked) {
1024
+ let size = await io.lstat(`${path}/${file}`).then((s) => s.size, () => 0)
1025
+ if (size >= LARGE) return 'dirty'
1026
+ }
1027
+ }
1028
+ if (!await free()) return 'taken'
1029
+ if (await busy(path)) return 'busy'
1030
+ if (at.dirty) {
1031
+ let shelved = await quiet(path, ['add', '-A']) != null &&
1032
+ await quiet(path, [
1033
+ '-c',
1034
+ 'core.hooksPath=/dev/null',
1035
+ 'commit',
1036
+ '--no-verify',
1037
+ '--quiet',
1038
+ '-m',
1039
+ `Shelved: what was left uncommitted in ${path}`,
1040
+ ]) != null
1041
+ if (!shelved) return 'failed'
1042
+ }
1043
+ if (!at.branch) {
1044
+ let name = 'shelf/' + path.replace(/\/+$/, '').split('/').at(-1)
1045
+ if (await quiet(path, ['switch', '--quiet', '-c', name]) == null) {
1046
+ return 'failed'
1047
+ }
1048
+ }
1049
+ await onBranch()
1050
+ await keepIgnored(path)
1051
+ return await quiet(path, ['worktree', 'remove', path]) == null
1052
+ ? 'failed'
1053
+ : undefined
1054
+ }
1055
+
1056
+ /** The path this worktree is checked out at, creating it again if it was
1057
+ * removed — same path, same branch, at the commit its row recorded — so work
1058
+ * taken back by `reclaim` comes back where it stood. Nothing new has to be
1059
+ * recorded for that: `workspace{root}` and `worktree{head, branch}` already holds it, as long
1060
+ * as `discover` brought it up to date before the files went. */
1061
+ export let restore = async (g: Graph, tree: Bundle): Promise<string> => {
1062
+ let w = tree.worktree as Comp | undefined
1063
+ let place = tree.workspace as Comp | undefined
1064
+ if (!w || typeof place?.root != 'string') {
1065
+ throw new Error('worktree has no workspace root')
1066
+ }
1067
+ let local = (await localFilesystem(g)).workspace as Comp
1068
+ if (place.machine != local.machine || place.sandbox) {
1069
+ throw new Error('Worktree is not on the explicitly local filesystem')
1070
+ }
1071
+ let path = place.root
1072
+ let repo = (await row(g, String(w.repository)))?.repository as
1073
+ | Comp
1074
+ | undefined
1075
+ if (repo?.workspace != (await localFilesystem(g)).entity.eid) {
1076
+ throw new Error('Repository is not on the local filesystem')
1077
+ }
1078
+ let common = repo.common
1079
+ if (typeof common != 'string') {
1080
+ if (await io.stat(path).then(() => true, () => false)) return path
1081
+ throw new Error('nothing recorded to cut ' + path + ' again from')
1082
+ }
1083
+ return locked(common, path, () => replace(g, path, w))
1084
+ }
1085
+
1086
+ // Called with the checkout path locked by create or restore. A peer may have
1087
+ // restored it while this request waited; a checkout standing at the path is
1088
+ // never replaced. A directory there without its `.git` is what a removal
1089
+ // killed partway leaves: it goes to trash and the checkout grows again.
1090
+ let replace = async (
1091
+ g: Graph,
1092
+ path: string,
1093
+ w: Comp,
1094
+ spare?: boolean,
1095
+ ): Promise<string> => {
1096
+ let there = await exists(path)
1097
+ if (there && await exists(path + '/.git')) return path
1098
+ let common = ((await row(g, String(w.repository)))?.repository as Comp)
1099
+ ?.common
1100
+ if (there && typeof common == 'string') await gone(common, path)
1101
+ let head = w.head
1102
+ if (typeof head != 'string' || typeof common != 'string') {
1103
+ throw new Error('nothing recorded to cut ' + path + ' again from')
1104
+ }
1105
+ let name = w.branch
1106
+ ? String(
1107
+ ((await row(g, String(w.branch)))?.ref as Comp | undefined)?.name ?? '',
1108
+ )
1109
+ : ''
1110
+ let branch = name.replace(/^refs\/heads\//, '')
1111
+ // Removing a worktree deletes its branch too, but a branch somebody else
1112
+ // kept is where that work actually is, not a stale copy of it.
1113
+ let standing = !!branch &&
1114
+ await quiet(common, ['rev-parse', '--verify', '--quiet', name]) != null
1115
+ await add(
1116
+ common,
1117
+ path,
1118
+ branch ? standing ? [] : ['-b', branch] : ['--detach'],
1119
+ standing ? branch : head,
1120
+ spare,
1121
+ )
1122
+ await discover(g, path)
1123
+ return path
1124
+ }
1125
+
1126
+ // Trash what a killed `git worktree remove` left of the checkout at `path`:
1127
+ // the directory, which Git empties before its registration, and the
1128
+ // registration, which still claims the path and its branch.
1129
+ let gone = async (common: string, path: string) => {
1130
+ let admin = common + '/worktrees'
1131
+ let names = await Array.fromAsync(io.readDir(admin)).catch((error) => {
1132
+ if (io.isNotFound(error)) return []
1133
+ throw error
1134
+ })
1135
+ for (let { name } of names) {
1136
+ let at = await io.readTextFile(`${admin}/${name}/gitdir`).catch(() => '')
1137
+ if (at.trim() == path + '/.git') await trash(`${admin}/${name}`)
1138
+ }
1139
+ await trash(path)
1140
+ }