@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/land.js ADDED
@@ -0,0 +1,788 @@
1
+ import * as system from "@yaks/process/system";
2
+ import { command as processCommand } from "@yaks/process/command";
3
+ import { formatConfig, formatting } from "./format.js";
4
+ export { formatting } from "./format.js";
5
+ // Landing a branch: the plain Git operation, and the guard that keeps a rebase
6
+ // from quietly reverting the base. It reads nothing from a graph — the
7
+ // checkout you are standing in and `git worktree list` supply every
8
+ // coordinate: the primary worktree is the shared checkout to merge into, and
9
+ // the branch that checkout has checked out is the base every linked worktree
10
+ // lands onto. Landing runs no test suite and hides nothing; its output stays
11
+ // Git's own, so whoever ran it can see exactly what happened. Git exit codes
12
+ // decide every branch in the control flow; Git's prose is diagnostics only.
13
+ //
14
+ // One invocation does at most one thing:
15
+ // - Fast-forward the current branch into the base. This succeeds exactly
16
+ // when the base is still an ancestor of the branch — the common case, and
17
+ // the whole job when it works. If the base has an upstream (config `@{u}`,
18
+ // nothing configured anywhere else), the branch is pushed to it first.
19
+ // - If the base moved (it is no longer an ancestor), or its upstream moved
20
+ // (the push was refused and a fetch shows commits the branch lacks, which
21
+ // the base then catches up to), the fast-forward is refused: rebase
22
+ // the branch onto the base and return without merging, printing what
23
+ // happened, a `git diff --stat` of what the base pulled in (so the caller
24
+ // can judge whether re-running its tests matters — docs-only versus code
25
+ // it touches), and, on a rebase conflict, Git's conflict output verbatim. The caller re-runs its tests if needed and lands again, which
26
+ // then fast-forwards cleanly.
27
+ //
28
+ // A landing is also guarded: before the fast-forward, land refuses a branch
29
+ // whose files carry content no commit on it wrote — the rebase artifact that
30
+ // quietly reverts the base (see {@link reverts}). `allow` names the files
31
+ // whose rewind is deliberate.
32
+ //
33
+ // The `--ff-only` merge is the compare-and-swap that serializes concurrent
34
+ // landers: a lander whose base moved is refused, rebases, and comes back.
35
+ // Everything land writes in the shared checkout (its index, its files, the
36
+ // base) happens under that checkout's land lock ({@link hold}), held
37
+ // exclusively, so two landers never take its index at once and a reader that
38
+ // holds the lock shared (a runtime snapshot) never meets a landing half done.
39
+ // Landing means landing in the shared checkout — the one that is actually
40
+ // used; pushing to a remote only publishes bytes and is never what makes work
41
+ // take effect, so a remote that cannot be reached still lands the work
42
+ // locally. But the push runs under the same lock, before the fast-forward, so
43
+ // the remote's own compare-and-swap serializes this checkout's landers with
44
+ // anything else that moved the upstream: a base that took commits the
45
+ // upstream refused would split the two. A base holding unpublished commits
46
+ // catches up by replaying them onto the fetched upstream under the lock;
47
+ // conflicts abort that replay before releasing the checkout. Landing is the
48
+ // only path that writes the base or pushes it.
49
+ //
50
+ // Running a test suite is the caller's job, not this operation's — before
51
+ // landing, and again after a rebase if the incoming diff could affect it. Land
52
+ // neither runs tests nor knows of any. It runs `git` as a subprocess, so like
53
+ // ./host.ts it is kept out of this package's portable entry point (./mod.ts).
54
+ import { backoff, sleep } from "@yaks/fp";
55
+ import { CallError } from "@yaks/tools/errors";
56
+ import { hold } from "./hold.js";
57
+ /** A landing refused for the caller's own state: not in a linked worktree on
58
+ * a branch, a dirty worktree, a revert the guard caught, or commits the base's
59
+ * upstream declined. It is a `CallError`,
60
+ * so whatever tool lands, a refusal reaches its caller as an answer and never
61
+ * as a fault. An unexpected Git command failure is a plain `Error`, a fault
62
+ * somebody has to hear about. */ export class LandError extends CallError {
63
+ constructor(message){
64
+ super('land', message);
65
+ this.name = 'LandError';
66
+ }
67
+ }
68
+ let dec = new TextDecoder();
69
+ // No terminal prompts, ever: this may run with nobody there to answer, and a
70
+ // credential prompt would hang the caller instead of failing it.
71
+ let quiet = {
72
+ GIT_TERMINAL_PROMPT: '0',
73
+ GIT_ASKPASS: '',
74
+ SSH_ASKPASS: ''
75
+ };
76
+ // A subprocess that failed to start (no git, no such directory, EAGAIN under
77
+ // load) is returned as a failed run carrying the reason, never thrown: every
78
+ // caller here already handles a git that failed, and none handles an
79
+ // exception.
80
+ // One generic process boundary for Git and the formatter; output stays raw.
81
+ let execute = async (command, args, cwd)=>{
82
+ try {
83
+ let out = await processCommand(command, {
84
+ args,
85
+ cwd,
86
+ env: quiet,
87
+ stdout: 'piped',
88
+ stderr: 'piped'
89
+ }).output();
90
+ return {
91
+ ok: out.success,
92
+ code: out.code,
93
+ out: dec.decode(out.stdout),
94
+ err: dec.decode(out.stderr)
95
+ };
96
+ } catch (e) {
97
+ return {
98
+ ok: false,
99
+ code: -1,
100
+ out: '',
101
+ err: `${command} ${args.join(' ')} in ${cwd}: ${e}`
102
+ };
103
+ }
104
+ };
105
+ /** Run git without a terminal prompt. */ export let run = (args, cwd)=>execute('git', args, cwd);
106
+ let format = async (files, cwd)=>{
107
+ try {
108
+ let found = await formatConfig(cwd);
109
+ if (!found) return {
110
+ ok: true,
111
+ code: 0,
112
+ out: '',
113
+ err: ''
114
+ };
115
+ return execute(system.execPath(), formatting(files, found.config, found.file), cwd);
116
+ } catch (e) {
117
+ return {
118
+ ok: false,
119
+ code: 1,
120
+ out: '',
121
+ err: String(e)
122
+ };
123
+ }
124
+ };
125
+ // Resolves the manifests into the lockfile without linking node_modules: the
126
+ // checkout's own install (packages/cli/dependencies.ts) follows the lockfile.
127
+ let lock = (cwd)=>execute('pnpm', [
128
+ 'install',
129
+ '--lockfile-only',
130
+ '--prefer-offline',
131
+ '--ignore-scripts'
132
+ ], cwd);
133
+ let lockfile = 'pnpm-lock.yaml';
134
+ /// commits('a\0One\n\nwhy\n\x01\nb\0Two\n\x01')
135
+ /// -> [{ sha: 'a', message: 'One\n\nwhy' }, { sha: 'b', message: 'Two' }]
136
+ /** Commits from `git log --format=%H%x00%B%x01`. */ export let commits = (log)=>log.split('\x01').map((c)=>c.trim()).filter(Boolean).map((c)=>{
137
+ let at = c.indexOf('\0');
138
+ return {
139
+ sha: c.slice(0, at),
140
+ message: c.slice(at + 1).trim()
141
+ };
142
+ });
143
+ let defaultWrite = (text, error = false)=>{
144
+ text = text.trimEnd();
145
+ if (text) (error ? console.error : console.log)(text);
146
+ };
147
+ let message = (label, r)=>{
148
+ let detail = (r.err || r.out).trim().split('\n').find(Boolean);
149
+ return `${label} failed with exit ${r.code}${detail ? `: ${detail}` : ''}`;
150
+ };
151
+ // Git prints absolute paths in both outputs, so the only difference between
152
+ // them can be a trailing slash.
153
+ let same = (a, b)=>a.replace(/\/+$/, '') == b.replace(/\/+$/, '');
154
+ let lines = (out)=>out.split('\n').filter(Boolean);
155
+ // How far back down the base the blob scan looks: the base's recent history,
156
+ // not its whole history.
157
+ let DEPTH = 200;
158
+ // `git log --raw` names the blob each commit left at a path
159
+ // (`:mode mode src dst status\tpath`), so one walk of the base's recent history
160
+ // yields every content each path has held — no `rev-parse` per file per
161
+ // commit. Merge commits print no raw lines and contribute nothing, which is
162
+ // right: a merge introduces no content of its own. The base TIP is included
163
+ // harmlessly — its blob for a path is `base:path`, which a file in the
164
+ // `base...HEAD` diff cannot equal.
165
+ let held = (log)=>{
166
+ let past = new Map();
167
+ for (let line of lines(log)){
168
+ let m = /^:\S+ \S+ \S+ (\S+) \S+\t(.+)$/.exec(line);
169
+ if (!m) continue;
170
+ if (!past.has(m[2])) past.set(m[2], new Set());
171
+ past.get(m[2]).add(m[1]);
172
+ }
173
+ return past;
174
+ };
175
+ // path → whether the landing diff adds anything there. `--numstat` reports
176
+ // added and deleted counts per path in the same walk that names the paths, so
177
+ // the guard learns both from one command. A binary file reports `-`: its added
178
+ // line count is unknowable, which the guard treats as content added.
179
+ // `--no-renames` keeps every path plain, so a rename reads as the deletion and
180
+ // the addition it is rather than as an `old => new` name that nothing else
181
+ // here would match.
182
+ let adding = (out)=>new Map(lines(out).flatMap((l)=>{
183
+ let m = /^(\d+|-)\t(?:\d+|-)\t(.+)$/.exec(l);
184
+ return m ? [
185
+ [
186
+ m[2],
187
+ m[1] != '0'
188
+ ]
189
+ ] : [];
190
+ }));
191
+ // path → blob for the whole landing tree, from one `ls-tree -r`: cheaper than
192
+ // a `rev-parse` per file, and immune to a pathspec longer than argv allows.
193
+ let blobs = (out)=>new Map(lines(out).flatMap((l)=>{
194
+ let m = /^\S+ blob (\S+)\t(.+)$/.exec(l);
195
+ return m ? [
196
+ [
197
+ m[2],
198
+ m[1]
199
+ ]
200
+ ] : [];
201
+ }));
202
+ /** Every file this landing would change that the branch did not author. Asked
203
+ * only when the base is an ancestor of the branch, so that `base...HEAD` is
204
+ * exactly the landing diff. How it runs git is a parameter, which is how a
205
+ * test answers without a repository. */ export let reverts = async (ask, base)=>{
206
+ let adds = adding(await ask([
207
+ 'diff',
208
+ '--numstat',
209
+ '--no-renames',
210
+ `${base}...HEAD`
211
+ ]));
212
+ if (!adds.size) return [];
213
+ let changed = [
214
+ ...adds.keys()
215
+ ];
216
+ // Three reads that need nothing from each other, asked at once: what the
217
+ // branch's commits touch, what the base's history held, and the landing
218
+ // tree. `--no-renames` as the diff above: a move names both paths, or the
219
+ // old one reads as the rebase's.
220
+ let [log, raw, tree] = await Promise.all([
221
+ ask([
222
+ 'log',
223
+ '--format=',
224
+ '--name-only',
225
+ '--no-renames',
226
+ `${base}..HEAD`
227
+ ]),
228
+ ask([
229
+ 'log',
230
+ `-${DEPTH}`,
231
+ '--format=',
232
+ '--raw',
233
+ // Full object names: `--raw` abbreviates by default, and the tree these
234
+ // are compared against does not.
235
+ '--no-abbrev',
236
+ '--no-renames',
237
+ base
238
+ ]),
239
+ ask([
240
+ 'ls-tree',
241
+ '-r',
242
+ 'HEAD'
243
+ ])
244
+ ]);
245
+ let touched = new Set(lines(log));
246
+ let found = changed.filter((f)=>!touched.has(f)).map((file)=>({
247
+ file,
248
+ rewound: false
249
+ }));
250
+ let rest = changed.filter((f)=>touched.has(f));
251
+ let past = held(raw);
252
+ let now = blobs(tree);
253
+ for (let file of rest){
254
+ let blob = now.get(file);
255
+ // A file the branch deletes has no landing blob and nothing to rewind to,
256
+ // and a diff that adds no line put nothing back to rewind to it.
257
+ if (blob && adds.get(file) && past.get(file)?.has(blob)) {
258
+ found.push({
259
+ file,
260
+ rewound: true
261
+ });
262
+ }
263
+ }
264
+ return found;
265
+ };
266
+ let why = (r, base, at)=>` ${r.file} — ${r.rewound ? `lands at content ${base} already moved past` : `changed by the rebase, not by any commit on the branch`}${at ? `; ${base} last touched it at ${at}` : ''}`;
267
+ // The refusal names the files and gives the caller the pointers it needs: the
268
+ // base commit that last touched each one, the diff to read, and the flag that
269
+ // lands anyway.
270
+ let refusal = async (ask, base, found)=>{
271
+ let at = await Promise.all(found.map((r)=>ask([
272
+ 'log',
273
+ '-1',
274
+ '--format=%h %s',
275
+ base,
276
+ '--',
277
+ r.file
278
+ ]).then((s)=>s.split('\n')[0].trim())));
279
+ let names = found.map((r)=>r.file);
280
+ return [
281
+ `land: refusing — the rebase left ${names.length} file${names.length == 1 ? '' : 's'} at content no commit on this branch wrote:`,
282
+ ...found.map((r, i)=>why(r, base, at[i])),
283
+ ` inspect: git diff ${base}...HEAD -- ${names.join(' ')}`,
284
+ ` deliberate: land --allow-revert=${names.join(',')}`
285
+ ].join('\n');
286
+ };
287
+ // Raw, NUL-delimited diff records keep unusual names intact. Only regular
288
+ // files go to fmt: a symlink or submodule must never lead it outside the diff.
289
+ let regular = (raw)=>{
290
+ let fields = raw.split('\0');
291
+ let files = [];
292
+ for(let i = 0; i + 1 < fields.length; i += 2){
293
+ if (/^:\d+ 100(?:644|755) /.test(fields[i])) files.push(fields[i + 1]);
294
+ }
295
+ return files;
296
+ };
297
+ /// named(':100644 000000 a b D\0gone.ts\0:000000 100644 a b A\0new.ts\0')
298
+ /// -> ['gone.ts', 'new.ts']
299
+ /** Every path in raw, NUL-delimited diff records. */ export let named = (raw)=>raw.split('\0').filter((_, i)=>i % 2);
300
+ /// manifest('packages/a/package.json') -> true
301
+ /// manifest('pnpm-workspace.yaml') -> true
302
+ /// manifest('packages/a/mod.ts') -> false
303
+ /** Whether a path is one the pnpm lockfile is resolved from. */ export let manifest = (path)=>/(^|\/)package\.json$/.test(path) || path == 'pnpm-workspace.yaml';
304
+ /** Land the branch you are standing on: fast-forward it into the base, or
305
+ * rebase onto a base that moved and return, for the caller to re-run its tests
306
+ * and land again. */ export let land = async (ops = {})=>{
307
+ let command = ops.run ?? run;
308
+ let write = ops.write ?? defaultWrite;
309
+ let cwd = ops.cwd ?? system.cwd();
310
+ let git = async (at, args, show = true)=>{
311
+ let r = await command(args, at);
312
+ if (show) {
313
+ write(r.out);
314
+ write(r.err, true);
315
+ }
316
+ return r;
317
+ };
318
+ let must = (label, r)=>{
319
+ if (r.code) throw new Error(message(label, r));
320
+ return r.out.trim();
321
+ };
322
+ let need = async (label, at, args)=>must(label, await git(at, args, false));
323
+ // What the guard reads: a git command run in this worktree whose output is
324
+ // raw lines — a failure here is a broken read, never an answer.
325
+ let read = async (args)=>{
326
+ let r = await git(tree, args, false);
327
+ if (r.code) throw new Error(message(`git ${args[0]}`, r));
328
+ return r.out;
329
+ };
330
+ // Every coordinate from git alone. `git worktree list --porcelain` lists the
331
+ // primary worktree first, whichever worktree you run it in, since worktrees
332
+ // share one ref store — and the branch that primary worktree has checked out
333
+ // is the base. A primary worktree with a detached HEAD has no base to land
334
+ // onto, so refuse rather than guess. A directory git does not know is where
335
+ // the caller stood, and so is a worktree with no branch checked out. The
336
+ // worktree's branch, the list and its status need nothing from each other,
337
+ // so they are asked at once and judged in that order.
338
+ let top = await git(cwd, [
339
+ 'rev-parse',
340
+ '--show-toplevel'
341
+ ], false);
342
+ if (top.code) throw new LandError(message('land: find worktree', top));
343
+ let tree = top.out.trim();
344
+ // The common Git directory is the shared checkout's own, where its lock
345
+ // lives.
346
+ let [on, listed, status, common] = await Promise.all([
347
+ git(tree, [
348
+ 'symbolic-ref',
349
+ '-q',
350
+ '--short',
351
+ 'HEAD'
352
+ ], false),
353
+ git(tree, [
354
+ 'worktree',
355
+ 'list',
356
+ '--porcelain'
357
+ ], false),
358
+ git(tree, [
359
+ 'status',
360
+ '--porcelain=v1',
361
+ '--untracked-files=all'
362
+ ], false),
363
+ git(tree, [
364
+ 'rev-parse',
365
+ '--path-format=absolute',
366
+ '--git-common-dir'
367
+ ], false)
368
+ ]);
369
+ if (on.code == 1) throw new LandError('land: the worktree is detached');
370
+ if (on.code) throw new Error(message('read branch', on));
371
+ let branch = on.out.trim();
372
+ let list = must('list worktrees', listed);
373
+ let head = list.split('\n\n')[0].split('\n');
374
+ let root = head.find((l)=>l.startsWith('worktree '))?.slice(9) ?? '';
375
+ let base = (head.find((l)=>l.startsWith('branch '))?.slice(7) ?? '').replace(/^refs\/heads\//, '');
376
+ if (!base) {
377
+ throw new LandError('land: the shared checkout is detached — no base to land onto');
378
+ }
379
+ if (same(tree, root)) {
380
+ throw new LandError('land: run it inside a linked worktree, not the shared checkout');
381
+ }
382
+ if (branch == base) {
383
+ throw new LandError('land: the worktree is on the base branch');
384
+ }
385
+ // Uncommitted work would not land and would break a rebase, so a dirty
386
+ // worktree is refused: what you land must be what you tested.
387
+ let dirty = must('git status', status);
388
+ if (dirty) {
389
+ let writer = ops.writer ? `\n writer: ${ops.writer}` : '';
390
+ throw new LandError(`land: worktree is dirty:\n${dirty}\n branch: ${branch}\n checkout: ${tree}${writer}`);
391
+ }
392
+ let gitdir = must('find the shared checkout', common);
393
+ // Ancestry decides which of the two things this invocation does, and it is
394
+ // asked before the merge because the guard's refusal has to come before the
395
+ // merge too: once the base has fast-forwarded, the bad content has landed.
396
+ let ancestry = async ()=>{
397
+ let r = await git(tree, [
398
+ 'merge-base',
399
+ '--is-ancestor',
400
+ base,
401
+ branch
402
+ ], false);
403
+ if (r.code != 0 && r.code != 1) {
404
+ throw new Error(message('read merge contention', r));
405
+ }
406
+ return r.code;
407
+ };
408
+ if (await ancestry() == 0) {
409
+ // The base has not moved: the branch is rebased onto it (or never left it),
410
+ // so `base...HEAD` is the landing diff and the guard can read it.
411
+ let found = await reverts(read, base);
412
+ let allow = new Set(ops.allow ?? []);
413
+ let refuse = found.filter((r)=>!allow.has(r.file));
414
+ if (refuse.length) throw new LandError(await refusal(read, base, refuse));
415
+ for (let r of found){
416
+ write(`land: --allow-revert — landing anyway:${why(r, base, '')}`, true);
417
+ }
418
+ let changed = await read([
419
+ 'diff',
420
+ '--raw',
421
+ '-z',
422
+ '--no-renames',
423
+ '--diff-filter=ACDMT',
424
+ `${base}...HEAD`
425
+ ]);
426
+ let files = regular(changed);
427
+ let edited = new Set(files);
428
+ if (files.length) {
429
+ let formatted = await (ops.format ?? format)(files.map((f)=>`./${f}`), tree);
430
+ write(formatted.out);
431
+ write(formatted.err, true);
432
+ // A parser failure can still leave other files formatted. Keep those
433
+ // changes and land; formatting is an edit, never a new gate.
434
+ if (formatted.code) write(message('land: format', formatted), true);
435
+ }
436
+ // A manifest the branch changed lands with the lockfile resolved from it,
437
+ // so a frozen install of the base never meets a stale lockfile. Only a
438
+ // checkout that tracks one is asked.
439
+ if (named(changed).some(manifest) && (await read([
440
+ 'ls-files',
441
+ '--',
442
+ lockfile
443
+ ])).trim()) {
444
+ let locked = await (ops.lock ?? lock)(tree);
445
+ write(locked.out);
446
+ write(locked.err, true);
447
+ if (locked.code) {
448
+ let said = message(`land: update ${lockfile}`, locked);
449
+ write(said, true);
450
+ await ops.report?.(new Error(said), {
451
+ tags: {
452
+ step: 'land: lock'
453
+ }
454
+ });
455
+ }
456
+ edited.add(lockfile);
457
+ }
458
+ if (edited.size) {
459
+ let paths = [
460
+ ...edited
461
+ ];
462
+ let diff = await git(tree, [
463
+ '--literal-pathspecs',
464
+ 'diff',
465
+ '--quiet',
466
+ '--',
467
+ ...paths
468
+ ], false);
469
+ if (diff.code != 0 && diff.code != 1) {
470
+ must('read landing edits', diff);
471
+ }
472
+ if (diff.code == 1) {
473
+ await need('stage landing edits', tree, [
474
+ '--literal-pathspecs',
475
+ 'add',
476
+ '--',
477
+ ...paths
478
+ ]);
479
+ await need('commit landing edits', tree, ops.formatCommit ? [
480
+ 'commit',
481
+ '--no-verify',
482
+ '-m',
483
+ ops.formatCommit
484
+ ] : [
485
+ 'commit',
486
+ '--amend',
487
+ '--no-edit',
488
+ '--allow-empty'
489
+ ]);
490
+ }
491
+ }
492
+ let up = await upstream(git, root, base);
493
+ let release = await (ops.hold ?? ((dir)=>hold(dir, true)))(gitdir);
494
+ let sha;
495
+ let landing = [];
496
+ try {
497
+ let moved = await ancestry() == 1;
498
+ if (!moved) {
499
+ await prepare(git, root, branch);
500
+ landing = commits(await need('list landing commits', root, [
501
+ 'log',
502
+ '--format=%H%x00%B%x01',
503
+ `HEAD..${branch}`
504
+ ]));
505
+ }
506
+ // Under the lock nothing that lands moves the base, so what is pushed
507
+ // contains it, and the fast-forward after the push follows it.
508
+ if (!moved && up) {
509
+ let to = await publish(git, write, ops, root, branch, up);
510
+ if (to) await catchUp(git, write, root, base, up, to);
511
+ moved = !!to;
512
+ }
513
+ if (!moved) {
514
+ let merged = await git(root, [
515
+ 'merge',
516
+ '--ff-only',
517
+ branch
518
+ ]);
519
+ if (merged.code) {
520
+ if (await ancestry() != 1) {
521
+ throw new Error(message('git merge', merged));
522
+ }
523
+ } else {
524
+ sha = await need('read landed commit', root, [
525
+ 'rev-parse',
526
+ 'HEAD'
527
+ ]);
528
+ }
529
+ }
530
+ } finally{
531
+ release();
532
+ }
533
+ if (sha) {
534
+ // The worktree and its branch survive landing: the caller does its own
535
+ // cleanup afterwards, and a command whose working directory was unlinked
536
+ // under it is refused by the kernel. Unlock it instead — whoever handed the
537
+ // worktree out locked it to mark it as in use, and this is that worker
538
+ // reporting it has finished. The unlock's exit code decides nothing: the
539
+ // only failure reachable is "not locked".
540
+ await git(root, [
541
+ 'worktree',
542
+ 'unlock',
543
+ tree
544
+ ], false);
545
+ return {
546
+ landed: sha,
547
+ root,
548
+ commits: landing
549
+ };
550
+ }
551
+ }
552
+ // The base moved; rebase onto it and return, for the caller to re-run its
553
+ // tests and land again. The guard runs on that second landing, once the
554
+ // rebase is finished.
555
+ write(`land: ${base} moved — rebasing ${branch} onto it, not merging.`);
556
+ write(`land: changes pulled in from ${base}:`);
557
+ // Three dots: from where the branch forked to the base.
558
+ await git(tree, [
559
+ 'diff',
560
+ '--stat',
561
+ `${branch}...${base}`
562
+ ]);
563
+ let rebased = await git(tree, [
564
+ 'rebase',
565
+ base
566
+ ]);
567
+ if (rebased.code) {
568
+ // The rebase is left in progress on purpose: the caller resolves the
569
+ // conflict, runs `git rebase --continue`, then lands again. Git printed
570
+ // the conflict above; this only names the next step.
571
+ write('land: rebase hit conflicts — resolve them, `git rebase --continue`, ' + 'then land again.', true);
572
+ return {
573
+ diverged: true,
574
+ conflict: true
575
+ };
576
+ }
577
+ write('land: rebased cleanly. Run affected tests if the diff above reaches them, then ' + 'land again.');
578
+ return {
579
+ diverged: true,
580
+ conflict: false
581
+ };
582
+ };
583
+ let sharedEdits = async (git, root)=>{
584
+ let status = await git(root, [
585
+ 'status',
586
+ '--porcelain=v1',
587
+ '-z',
588
+ '--untracked-files=all',
589
+ '--no-renames'
590
+ ], false);
591
+ if (status.code) throw new Error(message('read shared checkout', status));
592
+ return status.out.split('\0').filter(Boolean).map((entry)=>entry.slice(3));
593
+ };
594
+ let saveEdits = async (git, root, target, paths = [])=>{
595
+ let saved = await git(root, [
596
+ '--literal-pathspecs',
597
+ 'stash',
598
+ 'push',
599
+ '--include-untracked',
600
+ '-m',
601
+ `yak land: shared checkout edits before ${target}`,
602
+ ...paths.length ? [
603
+ '--',
604
+ ...paths
605
+ ] : []
606
+ ]);
607
+ if (saved.code) throw new Error(message('save shared checkout edits', saved));
608
+ };
609
+ let overlaps = (a, b)=>a == b || a.startsWith(`${b}/`) || b.startsWith(`${a}/`);
610
+ // Run Git's fast-forward safety check before publishing. Save edits on paths
611
+ // it needs to replace, including a file in the way of an incoming directory.
612
+ // A conflicting edit stays in the stash, so the shared index remains usable.
613
+ let prepare = async (git, root, target)=>{
614
+ await git(root, [
615
+ 'update-index',
616
+ '-q',
617
+ '--refresh'
618
+ ], false);
619
+ let check = ()=>git(root, [
620
+ 'read-tree',
621
+ '-n',
622
+ '-m',
623
+ '-u',
624
+ 'HEAD',
625
+ target
626
+ ], false);
627
+ let ready = await check();
628
+ if (!ready.code) return;
629
+ let changed = await git(root, [
630
+ 'diff',
631
+ '--name-only',
632
+ '-z',
633
+ '--no-renames',
634
+ 'HEAD',
635
+ target
636
+ ], false);
637
+ if (changed.code) throw new Error(message('read incoming paths', changed));
638
+ let incoming = changed.out.split('\0').filter(Boolean);
639
+ let paths = (await sharedEdits(git, root)).filter((edit)=>incoming.some((path)=>overlaps(edit, path)));
640
+ if (paths.length) {
641
+ await saveEdits(git, root, target, paths);
642
+ ready = await check();
643
+ }
644
+ if (ready.code) throw new Error(message('prepare shared checkout', ready));
645
+ };
646
+ // The base's upstream: just `@{u}`, nothing configured anywhere else.
647
+ let upstream = async (git, root, base)=>{
648
+ let up = await git(root, [
649
+ 'rev-parse',
650
+ '--abbrev-ref',
651
+ `${base}@{u}`
652
+ ], false);
653
+ if (up.code) return;
654
+ let ref = up.out.trim();
655
+ let cut = ref.indexOf('/');
656
+ return {
657
+ remote: ref.slice(0, cut),
658
+ branch: ref.slice(cut + 1)
659
+ };
660
+ };
661
+ // Push the landing branch to the base's upstream, under the land lock and
662
+ // before the base takes it. The remote's fast-forward check is the
663
+ // compare-and-swap: a refusal followed by a fetch that finds commits the
664
+ // branch lacks means the upstream moved, and what it moved to is returned, for
665
+ // the landing to rebase onto rather than merge. A push the remote answers with
666
+ // a 5xx, or whose connection drops, is tried again after a backoff, up to
667
+ // {@link tries} times: a retry of a push that did reach the remote finds it
668
+ // up to date. A push the remote declined (`[remote rejected]` with no server
669
+ // fault: a secret it found, a rule of the repository) refuses the landing, and
670
+ // the base stays where it was: the remote read those commits and will decline
671
+ // every later landing that carries them, so landing them here would stop
672
+ // everyone's pushes, not just this one. Any other failure, an unreachable
673
+ // remote included, leaves the work to land locally: the push only publishes
674
+ // bytes. It is still a failure,
675
+ // so it is reported with the remote's whole account, once. The push runs to
676
+ // completion with no deadline: its exit code is the only report of whether the
677
+ // remote has the commit, and a killed push may already have reached it.
678
+ let publish = async (git, write, ops, root, branch, up)=>{
679
+ let push = ()=>git(root, [
680
+ 'push',
681
+ '--quiet',
682
+ up.remote,
683
+ `${branch}:${up.branch}`
684
+ ], false);
685
+ let sent = await push();
686
+ for(let n = 1; sent.code && n < tries && transient(sent); n++){
687
+ await sleep(backoff(n), undefined, ops.clock);
688
+ sent = await push();
689
+ }
690
+ if (!sent.code) return;
691
+ // FETCH_HEAD is read once, at once: anything fetching in the shared
692
+ // checkout rewrites it.
693
+ let fetched = await git(root, [
694
+ 'fetch',
695
+ '--quiet',
696
+ up.remote,
697
+ up.branch
698
+ ], false);
699
+ let to = fetched.code ? undefined : await git(root, [
700
+ 'rev-parse',
701
+ '--verify',
702
+ 'FETCH_HEAD^{commit}'
703
+ ], false);
704
+ if (to && !to.code) {
705
+ let sha = to.out.trim();
706
+ let behind = await git(root, [
707
+ 'merge-base',
708
+ '--is-ancestor',
709
+ sha,
710
+ branch
711
+ ], false);
712
+ if (behind.code == 1) return sha;
713
+ }
714
+ let label = `land: publish to ${up.remote}/${up.branch}`;
715
+ if (declined(sent)) {
716
+ throw new LandError(`${label} was declined, so nothing landed. Rewrite the commits it ` + `names, then land again:\n${(sent.err || sent.out).trim()}`);
717
+ }
718
+ write(`${message(label, sent)} — landed locally, publish separately`, true);
719
+ let said = (sent.err || sent.out).trim();
720
+ await ops.report?.(new Error(`${label} failed with exit ${sent.code}${said ? `:\n${said}` : ''}`), {
721
+ tags: {
722
+ step: 'land: publish',
723
+ remote: up.remote
724
+ }
725
+ });
726
+ };
727
+ // How many times a push is tried while the remote's answers are transient.
728
+ let tries = 4;
729
+ // A refusal that says nothing about the push itself: the remote's server
730
+ // failed (a 5xx) or the connection dropped. Git exits 1 or 128 for these and
731
+ // for refusals that mean something, so only its words tell them apart.
732
+ let transient = (r)=>/(error|HTTP)[: ]+5\d\d\b|internal server error|bad gateway|service unavailable|gateway time-?out|the remote end hung up|early eof|connection (reset|timed out|refused)|RPC failed/i.test(r.err + r.out);
733
+ // The remote received the push and declined it, for a reason no retry
734
+ // changes.
735
+ let declined = (r)=>!transient(r) && /\[remote rejected\]/.test(r.err + r.out);
736
+ // Bring the base up to the fetched commit under its land lock. A failed push
737
+ // can leave locally landed commits the upstream lacks; replay those rather
738
+ // than treating the divergence as a fault. Unlike a caller's rebase, a shared
739
+ // checkout's replay must be aborted on conflict before readers get it back.
740
+ let catchUp = async (git, write, root, base, up, to)=>{
741
+ let at = `${up.remote}/${up.branch}`;
742
+ let contained = await git(root, [
743
+ 'merge-base',
744
+ '--is-ancestor',
745
+ base,
746
+ to
747
+ ], false);
748
+ if (contained.code != 0 && contained.code != 1) {
749
+ throw new Error(message('read upstream', contained));
750
+ }
751
+ if (contained.code == 1) {
752
+ await replay(git, write, root, base, at, to);
753
+ return;
754
+ }
755
+ write(`land: ${at} moved — bringing ${base} up to it.`);
756
+ await prepare(git, root, to);
757
+ let merged = await git(root, [
758
+ 'merge',
759
+ '--ff-only',
760
+ to
761
+ ]);
762
+ if (merged.code) {
763
+ throw new Error(message('fast-forward shared checkout', merged));
764
+ }
765
+ };
766
+ let replay = async (git, write, root, base, at, to)=>{
767
+ if ((await sharedEdits(git, root)).length) await saveEdits(git, root, to);
768
+ write(`land: ${at} moved — rebasing unpublished ${base} commits onto it.`);
769
+ // Ignore config that would stash shared edits or rewrite other branches.
770
+ let rebased = await git(root, [
771
+ '-c',
772
+ 'rebase.autoStash=false',
773
+ 'rebase',
774
+ '--no-update-refs',
775
+ to
776
+ ]);
777
+ if (!rebased.code) return;
778
+ let aborted = await git(root, [
779
+ 'rebase',
780
+ '--abort'
781
+ ]);
782
+ let said = message('land: shared checkout blocks catching up', rebased);
783
+ if (aborted.code) {
784
+ throw new Error(`${said}\n${message('restore shared checkout', aborted)}`);
785
+ }
786
+ throw new LandError(`${said}\nland: restored ${base}; nothing landed.`);
787
+ };
788
+ //# sourceMappingURL=land.js.map