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