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