@osdlc/typed-git 0.5.2 → 0.6.0
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.
- package/CHANGELOG.md +36 -1
- package/CONTRIBUTING.md +3 -4
- package/LICENSE-APACHE +1 -1
- package/README.md +40 -16
- package/dist/async.d.ts +3 -4
- package/dist/async.js +3 -3
- package/dist/backend.d.ts +1 -2
- package/dist/checkout-root.d.ts +0 -1
- package/dist/client.d.ts +2 -2
- package/dist/client.js +1 -0
- package/dist/failure.d.ts +64 -0
- package/dist/failure.js +126 -0
- package/dist/git-url.d.ts +0 -1
- package/dist/index.d.ts +1 -2
- package/dist/index.js +1 -1
- package/dist/outcome.d.ts +13 -18
- package/dist/outcome.js +21 -16
- package/dist/remote-url.d.ts +0 -1
- package/dist/soft.d.ts +0 -1
- package/dist/sync.d.ts +5 -5
- package/dist/sync.js +4 -3
- package/dist/testing.d.ts +0 -1
- package/dist/verbs.d.ts +5 -7
- package/dist/verbs.js +18 -11
- package/package.json +10 -23
- package/async.ts +0 -753
- package/backend.ts +0 -574
- package/checkout-root.ts +0 -164
- package/client.ts +0 -102
- package/dist/async.d.ts.map +0 -1
- package/dist/backend.d.ts.map +0 -1
- package/dist/checkout-root.d.ts.map +0 -1
- package/dist/client.d.ts.map +0 -1
- package/dist/git-url.d.ts.map +0 -1
- package/dist/index.d.ts.map +0 -1
- package/dist/outcome.d.ts.map +0 -1
- package/dist/remote-url.d.ts.map +0 -1
- package/dist/soft.d.ts.map +0 -1
- package/dist/sync.d.ts.map +0 -1
- package/dist/testing.d.ts.map +0 -1
- package/dist/verbs.d.ts.map +0 -1
- package/git-url.ts +0 -102
- package/hosted-git-info.d.ts +0 -24
- package/index.ts +0 -52
- package/outcome.ts +0 -191
- package/remote-url.ts +0 -46
- package/soft.ts +0 -60
- package/sync.ts +0 -827
- package/testing.ts +0 -291
- package/verbs.ts +0 -2300
package/verbs.ts
DELETED
|
@@ -1,2300 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* The verb table — every git invocation this library knows, as data.
|
|
3
|
-
*
|
|
4
|
-
* A {@link GitVerb} pairs the argv to run with the exit codes that mean
|
|
5
|
-
* "absent" for that invocation and the function that reads the result.
|
|
6
|
-
* Nothing here spawns anything, so the same definitions drive the synchronous
|
|
7
|
-
* `Git` client and the asynchronous CLI backend. Adding a verb means adding it
|
|
8
|
-
* here once.
|
|
9
|
-
*
|
|
10
|
-
* {@link gate} is the single place a git result becomes either a value or a
|
|
11
|
-
* `CommandFailed`. Both clients call it, so they cannot disagree.
|
|
12
|
-
*
|
|
13
|
-
* `GitVerb` and `gate` are internal: the package entries do not export them.
|
|
14
|
-
*/
|
|
15
|
-
|
|
16
|
-
import { CommandFailed, type CommandResult } from '@osdlc/command-seam'
|
|
17
|
-
|
|
18
|
-
/**
|
|
19
|
-
* One git invocation: what to run, which exits are answers, and how to read
|
|
20
|
-
* what came back.
|
|
21
|
-
*/
|
|
22
|
-
export interface GitVerb<T> {
|
|
23
|
-
argv: string[]
|
|
24
|
-
/** Written to the child's stdin when set. */
|
|
25
|
-
input?: string | undefined
|
|
26
|
-
/**
|
|
27
|
-
* Environment entries the verb needs, set over the client's and the call's
|
|
28
|
-
* `env`. The integration verbs set `LC_ALL=C` here so their parsers read
|
|
29
|
-
* English git output.
|
|
30
|
-
*/
|
|
31
|
-
env?: Readonly<Record<string, string>> | undefined
|
|
32
|
-
/**
|
|
33
|
-
* Exit codes that mean "asked and answered: not there" for this verb — not
|
|
34
|
-
* "git failed". `config --get` exits 1 for an unset key, `cat-file -e` exits
|
|
35
|
-
* 1 for a missing object. Those codes reach {@link GitVerb.parse}, which
|
|
36
|
-
* turns them into the verb's absence value; any other non-zero exit throws.
|
|
37
|
-
*
|
|
38
|
-
* A mutation declares `[]`: nothing about a failed `push` is an answer
|
|
39
|
-
* (`configRemoveSection` is the one exception). That
|
|
40
|
-
* is the whole checked/unchecked distinction, so there is no `checked` flag
|
|
41
|
-
* to contradict it.
|
|
42
|
-
*/
|
|
43
|
-
absent: readonly number[]
|
|
44
|
-
/**
|
|
45
|
-
* `argv` is the invocation that produced `result` — the verb's own argv
|
|
46
|
-
* behind whatever repository binding the client added. A parse that raises
|
|
47
|
-
* its own {@link CommandFailed} must report that, not {@link GitVerb.argv},
|
|
48
|
-
* so every failure names the command that ran.
|
|
49
|
-
*/
|
|
50
|
-
parse(result: CommandResult, argv: string[]): T
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
/**
|
|
54
|
-
* Turn one git result into a value or a `CommandFailed`.
|
|
55
|
-
*
|
|
56
|
-
* The exit-code throw site for the whole library, shared by both clients so
|
|
57
|
-
* they cannot disagree. A parse can raise its own `CommandFailed` for output
|
|
58
|
-
* it cannot read (`aheadBehind`, the integration verbs); it is handed the same
|
|
59
|
-
* argv this reports. `CommandFailed` is reused rather than wrapped in a
|
|
60
|
-
* git-specific class, so one `instanceof` matches failures from typed-git and
|
|
61
|
-
* from any other command-seam caller; a caller that must tell which git call
|
|
62
|
-
* failed reads `e.argv`.
|
|
63
|
-
*
|
|
64
|
-
* `argv` overrides what the error reports. Both clients pass the argv they
|
|
65
|
-
* actually ran, so a failure from a repository-bound client names its store.
|
|
66
|
-
*
|
|
67
|
-
* A result the seam flagged `neverExited` — `git` missing from PATH, a
|
|
68
|
-
* timeout kill, an abort — is a failure whatever the verb declares: its
|
|
69
|
-
* `exitCode` is the seam's stand-in `1`, and 1 is the absence code of half
|
|
70
|
-
* this table (`configGet`, `resolveRef`, `mergeBase`, `checkIgnore`,
|
|
71
|
-
* `isAncestor`, `grep`, `revParse`). Read as an absence it would answer "no
|
|
72
|
-
* such key / ref / match" for a git that never ran.
|
|
73
|
-
*
|
|
74
|
-
* A result flagged `outputIncomplete` is a failure too. The child exited, but
|
|
75
|
-
* the runner stopped reading at the output cap (`maxOutputBytes`) or at a
|
|
76
|
-
* timeout, so a parse would read cut-short output as the whole answer.
|
|
77
|
-
*/
|
|
78
|
-
export function gate<T>(verb: GitVerb<T>, result: CommandResult, argv?: string[]): T {
|
|
79
|
-
if (
|
|
80
|
-
result.neverExited ||
|
|
81
|
-
result.outputIncomplete ||
|
|
82
|
-
(result.exitCode !== 0 && !verb.absent.includes(result.exitCode))
|
|
83
|
-
) {
|
|
84
|
-
throw new CommandFailed(argv ?? verb.argv, result)
|
|
85
|
-
}
|
|
86
|
-
return verb.parse(result, argv ?? verb.argv)
|
|
87
|
-
}
|
|
88
|
-
|
|
89
|
-
/**
|
|
90
|
-
* A client-level environment bag under a per-call one, or `undefined` when
|
|
91
|
-
* neither is set (so the runner inherits the parent environment untouched
|
|
92
|
-
* rather than being handed an empty object).
|
|
93
|
-
*
|
|
94
|
-
* Shared by `Git` and `cliBackend` so the precedence rule has one definition.
|
|
95
|
-
*/
|
|
96
|
-
export function mergeEnv(
|
|
97
|
-
base: Record<string, string> | undefined,
|
|
98
|
-
call: Record<string, string> | undefined,
|
|
99
|
-
): Record<string, string> | undefined {
|
|
100
|
-
if (base === undefined) return call
|
|
101
|
-
if (call === undefined) return base
|
|
102
|
-
return { ...base, ...call }
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
/**
|
|
106
|
-
* Split a variadic `revParse` call into its string args and a trailing
|
|
107
|
-
* options object, when there is one. Shared by `Git` and `AsyncGit`.
|
|
108
|
-
*/
|
|
109
|
-
export function splitTrailingOptions<O extends object>(
|
|
110
|
-
args: ReadonlyArray<string | O>,
|
|
111
|
-
): [string[], O] {
|
|
112
|
-
const last = args[args.length - 1]
|
|
113
|
-
if (last !== undefined && typeof last !== 'string') {
|
|
114
|
-
return [args.slice(0, -1) as string[], last]
|
|
115
|
-
}
|
|
116
|
-
return [args as string[], {} as O]
|
|
117
|
-
}
|
|
118
|
-
|
|
119
|
-
/**
|
|
120
|
-
* The `--git-dir=` / `--work-tree=` flags that bind an invocation to one
|
|
121
|
-
* repository, or `[]` when neither is set. Shared by `Git` and `cliBackend`.
|
|
122
|
-
*/
|
|
123
|
-
export function repoPrefix(gitDir: string | undefined, workTree: string | undefined): string[] {
|
|
124
|
-
const prefix: string[] = []
|
|
125
|
-
if (gitDir !== undefined) prefix.push(`--git-dir=${gitDir}`)
|
|
126
|
-
if (workTree !== undefined) prefix.push(`--work-tree=${workTree}`)
|
|
127
|
-
return prefix
|
|
128
|
-
}
|
|
129
|
-
|
|
130
|
-
/** One row of `git worktree list --porcelain`. */
|
|
131
|
-
export interface Worktree {
|
|
132
|
-
/** Absolute path of the worktree. */
|
|
133
|
-
path: string
|
|
134
|
-
/** HEAD sha, or null for an entry that reports none (a bare store). */
|
|
135
|
-
head: string | null
|
|
136
|
-
/** Checked-out branch shortname, or null when detached. */
|
|
137
|
-
branch: string | null
|
|
138
|
-
detached: boolean
|
|
139
|
-
/**
|
|
140
|
-
* The entry is a bare repository — git printed a literal `bare` line for it.
|
|
141
|
-
*
|
|
142
|
-
* Read from that line rather than inferred from `head === null`: an
|
|
143
|
-
* unborn-HEAD checkout reports `HEAD 0000000000000000000000000000000000000000`,
|
|
144
|
-
* and a prunable entry keeps the HEAD it had.
|
|
145
|
-
*/
|
|
146
|
-
bare: boolean
|
|
147
|
-
/** `git worktree lock` was run on the entry; `prune` skips it and `remove` refuses it. */
|
|
148
|
-
locked: boolean
|
|
149
|
-
/**
|
|
150
|
-
* The reason given to `git worktree lock --reason`, or null when none was.
|
|
151
|
-
* Verbatim porcelain: git C-quotes a reason holding a newline or other
|
|
152
|
-
* special characters, and the quotes stay.
|
|
153
|
-
*/
|
|
154
|
-
lockReason: string | null
|
|
155
|
-
}
|
|
156
|
-
|
|
157
|
-
/** One row of `git ls-remote`. */
|
|
158
|
-
export interface RemoteRef {
|
|
159
|
-
sha: string
|
|
160
|
-
ref: string
|
|
161
|
-
}
|
|
162
|
-
|
|
163
|
-
/** One row of a `--name-status` diff. */
|
|
164
|
-
export interface DiffEntry {
|
|
165
|
-
/**
|
|
166
|
-
* The status token, verbatim: `M`, `A`, `D`, and the similarity-scored
|
|
167
|
-
* `R100` / `C085` a rename or copy carries. A caller that wants the letter
|
|
168
|
-
* writes `status[0]`; a truncating library would lose the score for good.
|
|
169
|
-
*/
|
|
170
|
-
status: string
|
|
171
|
-
/**
|
|
172
|
-
* The path the status is about. For a rename or copy, the destination —
|
|
173
|
-
* where the file is now.
|
|
174
|
-
*/
|
|
175
|
-
path: string
|
|
176
|
-
/**
|
|
177
|
-
* The source path of a rename or copy, and absent on every other status.
|
|
178
|
-
*
|
|
179
|
-
* An `R`/`C` record is three fields, so the source is there to report.
|
|
180
|
-
* Present iff `status` starts with `R` or `C`.
|
|
181
|
-
*/
|
|
182
|
-
from?: string
|
|
183
|
-
}
|
|
184
|
-
|
|
185
|
-
// ── parse helpers ───────────────────────────────────────────────────────────
|
|
186
|
-
|
|
187
|
-
// A parser only ever sees exit 0 or one of the verb's declared `absent` codes
|
|
188
|
-
// — the gate has already rejected everything else — so a non-zero exit here
|
|
189
|
-
// means absence, never failure.
|
|
190
|
-
|
|
191
|
-
/** Trimmed stdout, or null on a declared absence or an empty result. */
|
|
192
|
-
function trimmedOrNull(r: CommandResult): string | null {
|
|
193
|
-
if (r.exitCode !== 0) return null
|
|
194
|
-
const out = r.stdout.trim()
|
|
195
|
-
return out === '' ? null : out
|
|
196
|
-
}
|
|
197
|
-
|
|
198
|
-
/** Non-blank lines of a command's stdout, verbatim. */
|
|
199
|
-
export function splitLines(out: string): string[] {
|
|
200
|
-
return out.split('\n').filter((l) => l.trim() !== '')
|
|
201
|
-
}
|
|
202
|
-
|
|
203
|
-
/** Non-blank stdout lines, empty array on a declared absence. Verbatim. */
|
|
204
|
-
function lines(r: CommandResult): string[] {
|
|
205
|
-
if (r.exitCode !== 0) return []
|
|
206
|
-
return splitLines(r.stdout)
|
|
207
|
-
}
|
|
208
|
-
|
|
209
|
-
/** {@link lines}, with each line trimmed — for output that pads its values. */
|
|
210
|
-
function trimmedLines(r: CommandResult): string[] {
|
|
211
|
-
return lines(r).map((l) => l.trim())
|
|
212
|
-
}
|
|
213
|
-
|
|
214
|
-
/**
|
|
215
|
-
* NUL-separated fields, empties dropped — the parser for every `-z` verb.
|
|
216
|
-
*
|
|
217
|
-
* `-z` exists because git's default output quotes a path containing a space,
|
|
218
|
-
* a quote or a non-ASCII byte (`"docs/a b.md"`), and a line-splitting caller
|
|
219
|
-
* silently reads the quotes as part of the name. NUL has no such escape, so
|
|
220
|
-
* this is the only split that is right for paths.
|
|
221
|
-
*/
|
|
222
|
-
function nulFields(r: CommandResult): string[] {
|
|
223
|
-
return r.stdout.split('\x00').filter((f) => f !== '')
|
|
224
|
-
}
|
|
225
|
-
|
|
226
|
-
/**
|
|
227
|
-
* `--name-status -z` records into {@link DiffEntry} rows.
|
|
228
|
-
*
|
|
229
|
-
* A plain record is two fields — `M \0 path` — but a rename or copy is three:
|
|
230
|
-
* `R100 \0 oldPath \0 newPath`. A parser that pairs fields two at a time
|
|
231
|
-
* desynchronizes on the first rename and mislabels every record after it.
|
|
232
|
-
* Shared with `diffTree`, which emits the same records.
|
|
233
|
-
*/
|
|
234
|
-
function nameStatusEntries(r: CommandResult): DiffEntry[] {
|
|
235
|
-
const fields = nulFields(r)
|
|
236
|
-
const out: DiffEntry[] = []
|
|
237
|
-
for (let i = 0; i < fields.length;) {
|
|
238
|
-
const status = fields[i]!
|
|
239
|
-
// R/C carry a similarity score and both paths; the destination is at +2.
|
|
240
|
-
const renamed = status.startsWith('R') || status.startsWith('C')
|
|
241
|
-
const path = fields[i + (renamed ? 2 : 1)]
|
|
242
|
-
if (path === undefined) break // truncated trailing record: no path to report
|
|
243
|
-
// `from` is set only for R/C, so a plain record deep-equals `{status, path}`.
|
|
244
|
-
out.push(renamed ? { status, path, from: fields[i + 1]! } : { status, path })
|
|
245
|
-
i += renamed ? 3 : 2
|
|
246
|
-
}
|
|
247
|
-
return out
|
|
248
|
-
}
|
|
249
|
-
|
|
250
|
-
/** A mutation's result carries no value. */
|
|
251
|
-
function nothing(): void {}
|
|
252
|
-
|
|
253
|
-
/** No exit code is an answer here — the gate throws on any non-zero exit. */
|
|
254
|
-
const NONE: readonly number[] = []
|
|
255
|
-
|
|
256
|
-
/**
|
|
257
|
-
* Refuse a ref, remote, URL, path, pattern or config-key positional that
|
|
258
|
-
* starts with `-`.
|
|
259
|
-
*
|
|
260
|
-
* git reads such a value as an option. `--upload-pack=<cmd>` given as a remote
|
|
261
|
-
* runs `<cmd>`. The check throws a `TypeError` before anything spawns, so
|
|
262
|
-
* `try` and `soft` let it through. Write `./-name` for a path that starts with
|
|
263
|
-
* `-`, and `@{-1}` for the previous branch.
|
|
264
|
-
*/
|
|
265
|
-
function positional(verb: string, param: string, value: string): string {
|
|
266
|
-
if (value.startsWith('-')) {
|
|
267
|
-
throw new TypeError(
|
|
268
|
-
`typed-git: ${verb}: ${param} must not start with "-" (got ${JSON.stringify(value)})`,
|
|
269
|
-
)
|
|
270
|
-
}
|
|
271
|
-
return value
|
|
272
|
-
}
|
|
273
|
-
|
|
274
|
-
/**
|
|
275
|
-
* A config key for the `config` reads: {@link positional}, plus a section and
|
|
276
|
-
* a name.
|
|
277
|
-
*
|
|
278
|
-
* git exits 1 for a key with no `.`, or one that starts or ends with `.`. That
|
|
279
|
-
* is the code the reads take as "unset", so a typo would read as no value. The
|
|
280
|
-
* check throws a `TypeError` instead, before anything spawns.
|
|
281
|
-
*/
|
|
282
|
-
function configKey(verb: string, key: string): string {
|
|
283
|
-
positional(verb, 'key', key)
|
|
284
|
-
if (!key.includes('.') || key.startsWith('.') || key.endsWith('.')) {
|
|
285
|
-
throw new TypeError(
|
|
286
|
-
`typed-git: ${verb}: key must be <section>.<name> (got ${JSON.stringify(key)})`,
|
|
287
|
-
)
|
|
288
|
-
}
|
|
289
|
-
return key
|
|
290
|
-
}
|
|
291
|
-
|
|
292
|
-
/**
|
|
293
|
-
* A `--depth` value, refused with a `TypeError` unless it is a positive safe
|
|
294
|
-
* integer. git rejects the others too, but only after it runs.
|
|
295
|
-
*/
|
|
296
|
-
function depthArg(verb: string, depth: number): string {
|
|
297
|
-
if (!Number.isSafeInteger(depth) || depth < 1) {
|
|
298
|
-
throw new TypeError(
|
|
299
|
-
`typed-git: ${verb}: depth must be a positive integer (got ${JSON.stringify(depth)})`,
|
|
300
|
-
)
|
|
301
|
-
}
|
|
302
|
-
return `--depth=${depth}`
|
|
303
|
-
}
|
|
304
|
-
|
|
305
|
-
/** {@link positional}, for an optional value. */
|
|
306
|
-
function optionalPositional(
|
|
307
|
-
verb: string,
|
|
308
|
-
param: string,
|
|
309
|
-
value: string | undefined,
|
|
310
|
-
): string | undefined {
|
|
311
|
-
return value === undefined ? undefined : positional(verb, param, value)
|
|
312
|
-
}
|
|
313
|
-
|
|
314
|
-
/** The child env that makes git print English, whatever the caller's locale. */
|
|
315
|
-
const C_LOCALE: Readonly<Record<string, string>> = Object.freeze({ LC_ALL: 'C' })
|
|
316
|
-
|
|
317
|
-
// ── queries ─────────────────────────────────────────────────────────────────
|
|
318
|
-
|
|
319
|
-
/**
|
|
320
|
-
* A file's content at a rev (`git show <rev>:<relPath>`), null if absent.
|
|
321
|
-
*
|
|
322
|
-
* `absent: [128]` is as sharp as git allows: it spells both "no such path in
|
|
323
|
-
* that tree" and "not a repository" as 128, so this verb cannot separate
|
|
324
|
-
* absence from breakage.
|
|
325
|
-
*/
|
|
326
|
-
export function showAtRev(rev: string, relPath: string): GitVerb<string | null> {
|
|
327
|
-
return {
|
|
328
|
-
argv: ['show', `${positional('showAtRev', 'rev', rev)}:${relPath}`],
|
|
329
|
-
absent: [128],
|
|
330
|
-
// NOT trimmedOrNull: file content is returned verbatim, trailing newline
|
|
331
|
-
// included, because a caller round-tripping a blob must get its bytes.
|
|
332
|
-
parse: (r) => (r.exitCode === 0 ? r.stdout : null),
|
|
333
|
-
}
|
|
334
|
-
}
|
|
335
|
-
|
|
336
|
-
/**
|
|
337
|
-
* Trimmed `git rev-parse <args>` output — the general escape hatch, for a
|
|
338
|
-
* query no dedicated verb covers.
|
|
339
|
-
*
|
|
340
|
-
* `absent: [1]`, the code `rev-parse --verify --quiet <ref>` returns for a ref
|
|
341
|
-
* that does not resolve. {@link resolveRef} passes those flags for you; reach
|
|
342
|
-
* for it rather than spelling them here.
|
|
343
|
-
*
|
|
344
|
-
* `absent: [1]` is about refs. For a non-ref query — `--is-inside-work-tree`,
|
|
345
|
-
* `--show-toplevel`, `--git-common-dir` — git exits 128 outside a repository
|
|
346
|
-
* and this throws rather than answering `null`. Use `git.try.revParse(...)`
|
|
347
|
-
* with an explicit `!ok` branch, or {@link topLevel} / {@link gitCommonDir},
|
|
348
|
-
* for which "not a repository" is the answer.
|
|
349
|
-
*/
|
|
350
|
-
export function revParse(...args: string[]): GitVerb<string | null> {
|
|
351
|
-
return { argv: ['rev-parse', ...args], absent: [1], parse: trimmedOrNull }
|
|
352
|
-
}
|
|
353
|
-
|
|
354
|
-
/**
|
|
355
|
-
* The sha `ref` resolves to (`rev-parse --verify --quiet`), or null when it
|
|
356
|
-
* does not resolve.
|
|
357
|
-
*
|
|
358
|
-
* `absent: [1]` — an unborn HEAD, a branch that does not exist, a tag that was
|
|
359
|
-
* never fetched. An unreadable store exits 128 and throws, so absence stays
|
|
360
|
-
* separable from breakage. That is what makes `resolveRef("HEAD")` the
|
|
361
|
-
* repository-health probe — see {@link objectExists}, which is not.
|
|
362
|
-
*/
|
|
363
|
-
export function resolveRef(ref: string): GitVerb<string | null> {
|
|
364
|
-
return {
|
|
365
|
-
argv: ['rev-parse', '--verify', '--quiet', positional('resolveRef', 'ref', ref)],
|
|
366
|
-
absent: [1],
|
|
367
|
-
parse: trimmedOrNull,
|
|
368
|
-
}
|
|
369
|
-
}
|
|
370
|
-
|
|
371
|
-
/**
|
|
372
|
-
* HEAD's shortname (`rev-parse --abbrev-ref HEAD`).
|
|
373
|
-
*
|
|
374
|
-
* Reports the literal string `"HEAD"` on a detached HEAD, where
|
|
375
|
-
* {@link currentBranch} reports `null`. Pick by what the caller wants to
|
|
376
|
-
* print: a name that is always a string, or a branch or nothing.
|
|
377
|
-
*
|
|
378
|
-
* `absent: []` — an unborn HEAD exits 128, as does a non-repository, so both
|
|
379
|
-
* throw.
|
|
380
|
-
*/
|
|
381
|
-
export function headRef(): GitVerb<string | null> {
|
|
382
|
-
return {
|
|
383
|
-
argv: ['rev-parse', '--abbrev-ref', 'HEAD'],
|
|
384
|
-
absent: NONE,
|
|
385
|
-
parse: trimmedOrNull,
|
|
386
|
-
}
|
|
387
|
-
}
|
|
388
|
-
|
|
389
|
-
/**
|
|
390
|
-
* Absolute repo top-level directory, or null outside a repo.
|
|
391
|
-
*
|
|
392
|
-
* `absent: [128]`: for this question "not a repository" is a genuine answer,
|
|
393
|
-
* so `if (!git.topLevel())` is the idiomatic "am I in a repo?" check. Most
|
|
394
|
-
* other verbs throw there — see {@link lsFiles}.
|
|
395
|
-
*/
|
|
396
|
-
export function topLevel(): GitVerb<string | null> {
|
|
397
|
-
return { argv: ['rev-parse', '--show-toplevel'], absent: [128], parse: trimmedOrNull }
|
|
398
|
-
}
|
|
399
|
-
|
|
400
|
-
/**
|
|
401
|
-
* The shared `.git` dir (worktree-aware) as an absolute path, or null outside
|
|
402
|
-
* a repo.
|
|
403
|
-
*
|
|
404
|
-
* `--path-format=absolute` is passed for you: bare `--git-common-dir` answers
|
|
405
|
-
* relative to the cwd — literally `.git` from a primary checkout — which a
|
|
406
|
-
* caller then has to re-anchor.
|
|
407
|
-
*
|
|
408
|
-
* "Not a repository" is an answer here (`absent: [128]`); a variadic
|
|
409
|
-
* `revParse("--git-common-dir")` throws there. Reach for this verb.
|
|
410
|
-
*/
|
|
411
|
-
export function gitCommonDir(): GitVerb<string | null> {
|
|
412
|
-
return {
|
|
413
|
-
argv: ['rev-parse', '--path-format=absolute', '--git-common-dir'],
|
|
414
|
-
absent: [128],
|
|
415
|
-
parse: trimmedOrNull,
|
|
416
|
-
}
|
|
417
|
-
}
|
|
418
|
-
|
|
419
|
-
/**
|
|
420
|
-
* This worktree's own `.git` dir as an absolute path, or null outside a repo
|
|
421
|
-
* (`rev-parse --absolute-git-dir`).
|
|
422
|
-
*
|
|
423
|
-
* In a linked worktree it is `<common>/worktrees/<name>`, not the shared dir
|
|
424
|
-
* {@link gitCommonDir} gives. Per-worktree state lives here: a rebase in
|
|
425
|
-
* progress is a `rebase-merge` or `rebase-apply` directory in it.
|
|
426
|
-
*
|
|
427
|
-
* `absent: [128]`, as for {@link gitCommonDir}: "not a repository" is an answer.
|
|
428
|
-
*/
|
|
429
|
-
export function gitDir(): GitVerb<string | null> {
|
|
430
|
-
return { argv: ['rev-parse', '--absolute-git-dir'], absent: [128], parse: trimmedOrNull }
|
|
431
|
-
}
|
|
432
|
-
|
|
433
|
-
/**
|
|
434
|
-
* The full refname a symbolic ref points at, or null when it is not one.
|
|
435
|
-
*
|
|
436
|
-
* `absent: [128]` because "not a symbolic ref" is the common, meaningful
|
|
437
|
-
* answer, not a failure: `refs/remotes/<remote>/HEAD` is unset in any clone
|
|
438
|
-
* made before the remote had a default branch, and in every repository whose
|
|
439
|
-
* remote HEAD was never fetched. A caller asking for a default branch handles
|
|
440
|
-
* the null by probing instead.
|
|
441
|
-
*
|
|
442
|
-
* A caller wanting the branch name strips the `refs/remotes/<remote>/` prefix
|
|
443
|
-
* rather than taking the last segment: the name may contain slashes.
|
|
444
|
-
*/
|
|
445
|
-
export function symbolicRef(ref: string): GitVerb<string | null> {
|
|
446
|
-
return {
|
|
447
|
-
argv: ['symbolic-ref', positional('symbolicRef', 'ref', ref)],
|
|
448
|
-
absent: [128],
|
|
449
|
-
parse: trimmedOrNull,
|
|
450
|
-
}
|
|
451
|
-
}
|
|
452
|
-
|
|
453
|
-
/**
|
|
454
|
-
* Current branch shortname, or null when detached.
|
|
455
|
-
*
|
|
456
|
-
* `absent: []` — a detached HEAD and an empty repo both exit 0 with empty
|
|
457
|
-
* stdout, so absence never needs an exit code here. Outside a repo git exits
|
|
458
|
-
* 128, which throws. {@link headRef} is the variant that prints `"HEAD"` when
|
|
459
|
-
* detached instead of answering `null`.
|
|
460
|
-
*/
|
|
461
|
-
export function currentBranch(): GitVerb<string | null> {
|
|
462
|
-
return { argv: ['branch', '--show-current'], absent: NONE, parse: trimmedOrNull }
|
|
463
|
-
}
|
|
464
|
-
|
|
465
|
-
/** Options for {@link statusPorcelain}. */
|
|
466
|
-
export interface StatusPorcelainOptions {
|
|
467
|
-
/**
|
|
468
|
-
* Pathspecs, passed after `--`. Narrows the report to one subtree.
|
|
469
|
-
*/
|
|
470
|
-
paths?: string[] | undefined
|
|
471
|
-
}
|
|
472
|
-
|
|
473
|
-
/**
|
|
474
|
-
* `git status --porcelain` lines; empty array on a clean tree, and a throw
|
|
475
|
-
* outside a repository (exit 128).
|
|
476
|
-
*
|
|
477
|
-
* Verbatim: the first two columns are the status, so ` M f.ts` (unstaged
|
|
478
|
-
* modification) must not be trimmed down to `M f.ts` (staged one).
|
|
479
|
-
*/
|
|
480
|
-
export function statusPorcelain(opts: StatusPorcelainOptions = {}): GitVerb<string[]> {
|
|
481
|
-
const argv = ['status', '--porcelain']
|
|
482
|
-
if (opts.paths !== undefined && opts.paths.length > 0) argv.push('--', ...opts.paths)
|
|
483
|
-
return {
|
|
484
|
-
argv,
|
|
485
|
-
absent: NONE,
|
|
486
|
-
// A CRLF-terminated line keeps no stray \r for callers to strip.
|
|
487
|
-
parse: (r) => lines(r).map((l) => l.replace(/\r$/, '')),
|
|
488
|
-
}
|
|
489
|
-
}
|
|
490
|
-
|
|
491
|
-
/** One `git status --porcelain -z` record. */
|
|
492
|
-
export interface StatusEntry {
|
|
493
|
-
/** Index status column. */
|
|
494
|
-
x: string
|
|
495
|
-
/** Worktree status column. */
|
|
496
|
-
y: string
|
|
497
|
-
/** The path; for a rename or copy, the destination. */
|
|
498
|
-
path: string
|
|
499
|
-
}
|
|
500
|
-
|
|
501
|
-
/**
|
|
502
|
-
* Every changed or untracked file as a {@link StatusEntry}
|
|
503
|
-
* (`git status --porcelain -z --untracked-files=all`). Untracked directories
|
|
504
|
-
* are expanded to their files. Paths are verbatim, never quoted, and a rename
|
|
505
|
-
* or copy yields one entry (its source path is dropped). Empty on a clean
|
|
506
|
-
* tree; throws outside a repository.
|
|
507
|
-
*/
|
|
508
|
-
export function statusEntries(): GitVerb<StatusEntry[]> {
|
|
509
|
-
return {
|
|
510
|
-
argv: ['status', '--porcelain', '-z', '--untracked-files=all'],
|
|
511
|
-
absent: NONE,
|
|
512
|
-
parse(r) {
|
|
513
|
-
const fields = nulFields(r)
|
|
514
|
-
const out: StatusEntry[] = []
|
|
515
|
-
for (let i = 0; i < fields.length; i++) {
|
|
516
|
-
const f = fields[i]!
|
|
517
|
-
if (f.length < 4) continue
|
|
518
|
-
const x = f[0]!
|
|
519
|
-
out.push({ x, y: f[1]!, path: f.slice(3) })
|
|
520
|
-
if (x === 'R' || x === 'C') i++
|
|
521
|
-
}
|
|
522
|
-
return out
|
|
523
|
-
},
|
|
524
|
-
}
|
|
525
|
-
}
|
|
526
|
-
|
|
527
|
-
/** Local branch shortnames matching `pattern` (all when omitted). */
|
|
528
|
-
export function branches(pattern?: string | undefined): GitVerb<string[]> {
|
|
529
|
-
const argv = ['branch', '--list', '--format=%(refname:short)']
|
|
530
|
-
if (pattern !== undefined) argv.push(positional('branches', 'pattern', pattern))
|
|
531
|
-
return { argv, absent: NONE, parse: trimmedLines }
|
|
532
|
-
}
|
|
533
|
-
|
|
534
|
-
/** `git worktree list --porcelain`, parsed. Throws outside a repository. */
|
|
535
|
-
export function worktrees(): GitVerb<Worktree[]> {
|
|
536
|
-
return {
|
|
537
|
-
argv: ['worktree', 'list', '--porcelain'],
|
|
538
|
-
absent: NONE,
|
|
539
|
-
parse(r) {
|
|
540
|
-
const out: Worktree[] = []
|
|
541
|
-
let cur: Partial<Worktree> | null = null
|
|
542
|
-
const flush = () => {
|
|
543
|
-
if (cur?.path !== undefined) {
|
|
544
|
-
out.push({
|
|
545
|
-
path: cur.path,
|
|
546
|
-
head: cur.head ?? null,
|
|
547
|
-
branch: cur.branch ?? null,
|
|
548
|
-
detached: cur.detached ?? false,
|
|
549
|
-
bare: cur.bare ?? false,
|
|
550
|
-
locked: cur.locked ?? false,
|
|
551
|
-
lockReason: cur.lockReason ?? null,
|
|
552
|
-
})
|
|
553
|
-
}
|
|
554
|
-
}
|
|
555
|
-
for (const line of r.stdout.split('\n')) {
|
|
556
|
-
if (line.startsWith('worktree ')) {
|
|
557
|
-
flush()
|
|
558
|
-
cur = { path: line.slice('worktree '.length) }
|
|
559
|
-
} else if (cur !== null && line.startsWith('HEAD ')) {
|
|
560
|
-
cur.head = line.slice('HEAD '.length)
|
|
561
|
-
} else if (cur !== null && line.startsWith('branch ')) {
|
|
562
|
-
cur.branch = line.slice('branch '.length).replace(/^refs\/heads\//, '')
|
|
563
|
-
} else if (cur !== null && line === 'detached') {
|
|
564
|
-
cur.detached = true
|
|
565
|
-
} else if (cur !== null && line === 'bare') {
|
|
566
|
-
cur.bare = true
|
|
567
|
-
} else if (cur !== null && (line === 'locked' || line.startsWith('locked '))) {
|
|
568
|
-
cur.locked = true
|
|
569
|
-
cur.lockReason = line.slice('locked '.length) || null
|
|
570
|
-
}
|
|
571
|
-
}
|
|
572
|
-
flush()
|
|
573
|
-
return out
|
|
574
|
-
},
|
|
575
|
-
}
|
|
576
|
-
}
|
|
577
|
-
|
|
578
|
-
/**
|
|
579
|
-
* Merge base of two revs, or null when the two histories are unrelated
|
|
580
|
-
* (exit 1). A rev that does not resolve exits 128 and throws.
|
|
581
|
-
*/
|
|
582
|
-
export function mergeBase(a: string, b: string): GitVerb<string | null> {
|
|
583
|
-
return {
|
|
584
|
-
argv: ['merge-base', positional('mergeBase', 'a', a), positional('mergeBase', 'b', b)],
|
|
585
|
-
absent: [1],
|
|
586
|
-
parse: trimmedOrNull,
|
|
587
|
-
}
|
|
588
|
-
}
|
|
589
|
-
|
|
590
|
-
/**
|
|
591
|
-
* Subject line of a ref's HEAD commit (`log -1 --format=%s`), or null.
|
|
592
|
-
*
|
|
593
|
-
* `absent: [128]`, which git also uses for a broken repository — the same
|
|
594
|
-
* overload as {@link showAtRev}. A caller that must tell an empty history from
|
|
595
|
-
* a broken one probes {@link resolveRef} with `HEAD` first.
|
|
596
|
-
*/
|
|
597
|
-
export function logSubject(ref: string): GitVerb<string | null> {
|
|
598
|
-
return {
|
|
599
|
-
argv: ['log', '-1', '--format=%s', positional('logSubject', 'ref', ref)],
|
|
600
|
-
absent: [128],
|
|
601
|
-
parse(r) {
|
|
602
|
-
if (r.exitCode !== 0) return null
|
|
603
|
-
// Only trailing newlines: a subject's own leading whitespace is content.
|
|
604
|
-
const out = r.stdout.replace(/\n+$/, '')
|
|
605
|
-
return out === '' ? null : out
|
|
606
|
-
},
|
|
607
|
-
}
|
|
608
|
-
}
|
|
609
|
-
|
|
610
|
-
/** Which config file a `config` verb reads or writes. */
|
|
611
|
-
export type ConfigScope = 'local' | 'global' | 'system'
|
|
612
|
-
|
|
613
|
-
/** Options for {@link configGet}, {@link configGetAll} and {@link configGetBool}. */
|
|
614
|
-
export interface ConfigGetOptions {
|
|
615
|
-
/**
|
|
616
|
-
* Read one file only. Omitted means every file git reads, the last value
|
|
617
|
-
* winning. `local` outside a repository exits 128 and throws.
|
|
618
|
-
*/
|
|
619
|
-
scope?: ConfigScope | undefined
|
|
620
|
-
}
|
|
621
|
-
|
|
622
|
-
/** The `config` read argv: the scope flag when one is given, the flags, the checked key. */
|
|
623
|
-
function configRead(flags: string[], key: string, opts: ConfigGetOptions): string[] {
|
|
624
|
-
const argv = ['config']
|
|
625
|
-
if (opts.scope !== undefined) argv.push(`--${opts.scope}`)
|
|
626
|
-
argv.push(...flags, key)
|
|
627
|
-
return argv
|
|
628
|
-
}
|
|
629
|
-
|
|
630
|
-
/** `git config --get <key>`, or null when unset (exit 1). */
|
|
631
|
-
export function configGet(key: string, opts: ConfigGetOptions = {}): GitVerb<string | null> {
|
|
632
|
-
return {
|
|
633
|
-
argv: configRead(['--get'], configKey('configGet', key), opts),
|
|
634
|
-
absent: [1],
|
|
635
|
-
parse: trimmedOrNull,
|
|
636
|
-
}
|
|
637
|
-
}
|
|
638
|
-
|
|
639
|
-
/**
|
|
640
|
-
* Every value of a multi-valued key (`git config --get-all -z <key>`), in the
|
|
641
|
-
* order git reads them. `[]` when the key is unset (exit 1).
|
|
642
|
-
*
|
|
643
|
-
* `-z` ends each value with NUL, so a value holding a newline stays whole and
|
|
644
|
-
* an empty value is kept as `""`. Values are verbatim, not trimmed.
|
|
645
|
-
*/
|
|
646
|
-
export function configGetAll(key: string, opts: ConfigGetOptions = {}): GitVerb<string[]> {
|
|
647
|
-
return {
|
|
648
|
-
argv: configRead(['--get-all', '-z'], configKey('configGetAll', key), opts),
|
|
649
|
-
absent: [1],
|
|
650
|
-
parse(r) {
|
|
651
|
-
if (r.exitCode !== 0) return []
|
|
652
|
-
// Each value ends with NUL, so the last field is always the empty tail.
|
|
653
|
-
return r.stdout.split('\x00').slice(0, -1)
|
|
654
|
-
},
|
|
655
|
-
}
|
|
656
|
-
}
|
|
657
|
-
|
|
658
|
-
/**
|
|
659
|
-
* A key read as a boolean (`git config --type=bool --get <key>`), or null when
|
|
660
|
-
* unset (exit 1).
|
|
661
|
-
*
|
|
662
|
-
* git does the reading: `yes`, `on`, `1` and a bare key are `true`. A value
|
|
663
|
-
* git cannot read as a boolean exits 128 and throws.
|
|
664
|
-
*/
|
|
665
|
-
export function configGetBool(key: string, opts: ConfigGetOptions = {}): GitVerb<boolean | null> {
|
|
666
|
-
return {
|
|
667
|
-
argv: configRead(['--type=bool', '--get'], configKey('configGetBool', key), opts),
|
|
668
|
-
absent: [1],
|
|
669
|
-
parse(r, ranArgv) {
|
|
670
|
-
if (r.exitCode !== 0) return null
|
|
671
|
-
const out = r.stdout.trim()
|
|
672
|
-
if (out === 'true') return true
|
|
673
|
-
if (out === 'false') return false
|
|
674
|
-
throw new CommandFailed(ranArgv, r)
|
|
675
|
-
},
|
|
676
|
-
}
|
|
677
|
-
}
|
|
678
|
-
|
|
679
|
-
/**
|
|
680
|
-
* True iff `rev` resolves to an object (`cat-file -e`).
|
|
681
|
-
*
|
|
682
|
-
* A predicate, so both of git's "no" codes are absence: 1 for a well-formed
|
|
683
|
-
* name with no object behind it, 128 for a name it cannot even parse.
|
|
684
|
-
*
|
|
685
|
-
* That breadth is what makes it a predicate, and also what disqualifies it as
|
|
686
|
-
* a repository-health probe. `false` here does not mean "no history": measured
|
|
687
|
-
* against real stores, `cat-file -e HEAD` exits 128 on an empty repository, 1
|
|
688
|
-
* on a dangling HEAD ref, and 128 again with the object directory removed — so
|
|
689
|
-
* `objectExists("HEAD")` answers `false` for all three and folds a corrupt
|
|
690
|
-
* store into "nothing here yet". Ask "does this repo have history?" with
|
|
691
|
-
* `hasHistory()` ({@link resolveRef} on `HEAD`), which is `false` only for the
|
|
692
|
-
* unborn case and throws when the store is unreadable.
|
|
693
|
-
*/
|
|
694
|
-
export function objectExists(rev: string): GitVerb<boolean> {
|
|
695
|
-
return {
|
|
696
|
-
argv: ['cat-file', '-e', positional('objectExists', 'rev', rev)],
|
|
697
|
-
absent: [1, 128],
|
|
698
|
-
parse: (r) => r.exitCode === 0,
|
|
699
|
-
}
|
|
700
|
-
}
|
|
701
|
-
|
|
702
|
-
/** Options for {@link lsRemote}. */
|
|
703
|
-
export interface LsRemoteOptions {
|
|
704
|
-
/** `--heads` — branches only. */
|
|
705
|
-
heads?: boolean | undefined
|
|
706
|
-
/** `--tags` — tags only. Set with `heads` to ask for both. */
|
|
707
|
-
tags?: boolean | undefined
|
|
708
|
-
}
|
|
709
|
-
|
|
710
|
-
/**
|
|
711
|
-
* `ls-remote` rows for a remote (optionally pattern- and kind-filtered).
|
|
712
|
-
*
|
|
713
|
-
* `absent: []` — a remote with no matching refs answers with exit 0 and no
|
|
714
|
-
* output, so `[]` means "no refs". An unreachable remote exits 128 and throws.
|
|
715
|
-
*/
|
|
716
|
-
export function lsRemote(
|
|
717
|
-
remote: string,
|
|
718
|
-
pattern?: string | undefined,
|
|
719
|
-
opts: LsRemoteOptions = {},
|
|
720
|
-
): GitVerb<RemoteRef[]> {
|
|
721
|
-
const argv = ['ls-remote']
|
|
722
|
-
if (opts.heads) argv.push('--heads')
|
|
723
|
-
if (opts.tags) argv.push('--tags')
|
|
724
|
-
argv.push(positional('lsRemote', 'remote', remote))
|
|
725
|
-
if (pattern !== undefined) argv.push(positional('lsRemote', 'pattern', pattern))
|
|
726
|
-
return {
|
|
727
|
-
argv,
|
|
728
|
-
absent: NONE,
|
|
729
|
-
// Same sha-TAB-ref rows `for-each-ref` prints, so the same parser.
|
|
730
|
-
parse: (r) => parseRefRows(splitLines(r.stdout)),
|
|
731
|
-
}
|
|
732
|
-
}
|
|
733
|
-
|
|
734
|
-
/**
|
|
735
|
-
* The subset of `relPaths` that .gitignore rules ignore
|
|
736
|
-
* (`check-ignore --stdin -z`, NUL-delimited through the seam's `input`).
|
|
737
|
-
*
|
|
738
|
-
* `absent: [1]` — "none of these paths are ignored". Outside a repository git
|
|
739
|
-
* exits 128 and this throws, so a caller cannot mistake "could not ask" for
|
|
740
|
-
* "nothing is ignored".
|
|
741
|
-
*
|
|
742
|
-
* A fail-closed caller — a guard deciding whether a path may be read or
|
|
743
|
-
* published — must use `git.try.checkIgnore` with an explicit `!ok` branch
|
|
744
|
-
* that refuses. It must neither let the `CommandFailed` escape nor read it as
|
|
745
|
-
* "not ignored":
|
|
746
|
-
*
|
|
747
|
-
* ```ts
|
|
748
|
-
* const got = git.try.checkIgnore(paths);
|
|
749
|
-
* if (!got.ok) return denyEverything(got.error); // could not ask ⇒ refuse
|
|
750
|
-
* ```
|
|
751
|
-
*/
|
|
752
|
-
export function checkIgnore(relPaths: string[]): GitVerb<Set<string>> {
|
|
753
|
-
return {
|
|
754
|
-
argv: ['check-ignore', '--stdin', '-z'],
|
|
755
|
-
input: relPaths.join('\x00') + '\x00',
|
|
756
|
-
absent: [1],
|
|
757
|
-
parse: (r) => new Set(r.stdout.split('\x00').filter((c) => c !== '')),
|
|
758
|
-
}
|
|
759
|
-
}
|
|
760
|
-
|
|
761
|
-
/** One ignore rule that matched a path, as `git check-ignore -v` reports it. */
|
|
762
|
-
export interface IgnoreMatch {
|
|
763
|
-
/** The path asked about, as given. */
|
|
764
|
-
path: string
|
|
765
|
-
/** The file holding the rule (a `.gitignore`, `.git/info/exclude`, or the global excludes file). */
|
|
766
|
-
source: string
|
|
767
|
-
/** 1-based line of the rule in `source`. */
|
|
768
|
-
line: number
|
|
769
|
-
/** The pattern as written; a leading `!` marks a negation, which un-ignores the path. */
|
|
770
|
-
pattern: string
|
|
771
|
-
}
|
|
772
|
-
|
|
773
|
-
/**
|
|
774
|
-
* The rule that decides each of `relPaths`, from `git check-ignore -v --stdin -z`. Paths no rule
|
|
775
|
-
* mentions are omitted, and exit 1 (nothing matched) is an empty list. A negated pattern (`!x`)
|
|
776
|
-
* is reported too: the path is then NOT ignored, so check `pattern` before treating a match as
|
|
777
|
-
* "ignored". Like {@link checkIgnore} it throws outside a repository.
|
|
778
|
-
*/
|
|
779
|
-
export function checkIgnoreVerbose(relPaths: string[]): GitVerb<IgnoreMatch[]> {
|
|
780
|
-
return {
|
|
781
|
-
argv: ['check-ignore', '-v', '--stdin', '-z'],
|
|
782
|
-
input: relPaths.join('\x00') + '\x00',
|
|
783
|
-
absent: [1],
|
|
784
|
-
parse: (r) => {
|
|
785
|
-
// -z output is four NUL-terminated fields per match: source, line, pattern, path.
|
|
786
|
-
const f = r.stdout.split('\x00')
|
|
787
|
-
const out: IgnoreMatch[] = []
|
|
788
|
-
for (let i = 0; i + 3 < f.length; i += 4) {
|
|
789
|
-
out.push({ source: f[i]!, line: Number(f[i + 1]), pattern: f[i + 2]!, path: f[i + 3]! })
|
|
790
|
-
}
|
|
791
|
-
return out
|
|
792
|
-
},
|
|
793
|
-
}
|
|
794
|
-
}
|
|
795
|
-
|
|
796
|
-
/** Options for {@link lsFiles}. */
|
|
797
|
-
export interface LsFilesOptions {
|
|
798
|
-
/** `--cached` — files in the index. */
|
|
799
|
-
cached?: boolean | undefined
|
|
800
|
-
/** `--others` — files git is not tracking. */
|
|
801
|
-
others?: boolean | undefined
|
|
802
|
-
/** `--exclude-standard` — apply .gitignore and friends. */
|
|
803
|
-
excludeStandard?: boolean | undefined
|
|
804
|
-
/** `--directory` — list a wholly untracked directory once, as `dir/`. */
|
|
805
|
-
directory?: boolean | undefined
|
|
806
|
-
/** Pathspecs, passed after `--`. */
|
|
807
|
-
paths?: string[] | undefined
|
|
808
|
-
}
|
|
809
|
-
|
|
810
|
-
/**
|
|
811
|
-
* Tracked and/or untracked file paths (`git ls-files -z`).
|
|
812
|
-
*
|
|
813
|
-
* `absent: []` — no matching files is exit 0 with empty stdout, so `[]` means
|
|
814
|
-
* "none". Outside a repository git exits 128 and this throws: a guard that
|
|
815
|
-
* cannot read the index has not "found zero files to check".
|
|
816
|
-
*
|
|
817
|
-
* Note the asymmetry with {@link topLevel}, which guards commonly call on the
|
|
818
|
-
* adjacent line: `topLevel()` returns null outside a repository and this verb
|
|
819
|
-
* throws there. Both are correct — "not a repository" answers "where is the
|
|
820
|
-
* root?" but not "which files are here?" — but a reader who assumes the two
|
|
821
|
-
* behave alike writes `if (!git.topLevel()) return; git.lsFiles()` and is not
|
|
822
|
-
* protected. Only a `try` / catch is.
|
|
823
|
-
*/
|
|
824
|
-
export function lsFiles(opts: LsFilesOptions = {}): GitVerb<string[]> {
|
|
825
|
-
const argv = ['ls-files', '-z']
|
|
826
|
-
if (opts.cached) argv.push('--cached')
|
|
827
|
-
if (opts.others) argv.push('--others')
|
|
828
|
-
if (opts.excludeStandard) argv.push('--exclude-standard')
|
|
829
|
-
if (opts.directory) argv.push('--directory')
|
|
830
|
-
if (opts.paths !== undefined && opts.paths.length > 0) argv.push('--', ...opts.paths)
|
|
831
|
-
return { argv, absent: NONE, parse: nulFields }
|
|
832
|
-
}
|
|
833
|
-
|
|
834
|
-
/** One row of `git ls-files -v`. */
|
|
835
|
-
export interface TaggedFile {
|
|
836
|
-
/**
|
|
837
|
-
* The status tag, verbatim: `H` for an ordinary tracked file, `S` for
|
|
838
|
-
* skip-worktree, and a lowercase letter for assume-unchanged.
|
|
839
|
-
*/
|
|
840
|
-
tag: string
|
|
841
|
-
path: string
|
|
842
|
-
}
|
|
843
|
-
|
|
844
|
-
/**
|
|
845
|
-
* Tracked files with their status tag (`git ls-files -v -z`).
|
|
846
|
-
*
|
|
847
|
-
* The tag is the only place git shows the skip-worktree and assume-unchanged
|
|
848
|
-
* flags; `status` hides edits to flagged files. Throws outside a repository,
|
|
849
|
-
* as {@link lsFiles} does.
|
|
850
|
-
*/
|
|
851
|
-
export function lsFilesTagged(): GitVerb<TaggedFile[]> {
|
|
852
|
-
return {
|
|
853
|
-
argv: ['ls-files', '-v', '-z'],
|
|
854
|
-
absent: NONE,
|
|
855
|
-
parse(r) {
|
|
856
|
-
const rows: TaggedFile[] = []
|
|
857
|
-
for (const chunk of r.stdout.split('\x00')) {
|
|
858
|
-
if (chunk.length < 3 || chunk[1] !== ' ') continue
|
|
859
|
-
rows.push({ tag: chunk[0]!, path: chunk.slice(2) })
|
|
860
|
-
}
|
|
861
|
-
return rows
|
|
862
|
-
},
|
|
863
|
-
}
|
|
864
|
-
}
|
|
865
|
-
|
|
866
|
-
/** Options for {@link forEachRef}. */
|
|
867
|
-
export interface ForEachRefOptions {
|
|
868
|
-
/** `--format=` value; defaults to `%(objectname)%09%(refname)`. */
|
|
869
|
-
format?: string | undefined
|
|
870
|
-
/** `--sort=` key, e.g. `-committerdate`. */
|
|
871
|
-
sort?: string | undefined
|
|
872
|
-
/** `--count=` cap on the rows returned. */
|
|
873
|
-
count?: number | undefined
|
|
874
|
-
}
|
|
875
|
-
|
|
876
|
-
/** The `forEachRef` format {@link refs} parses: sha, TAB, full refname. */
|
|
877
|
-
export const REF_FORMAT = '%(objectname)%09%(refname)'
|
|
878
|
-
|
|
879
|
-
/**
|
|
880
|
-
* `git for-each-ref` rows, one per line, verbatim.
|
|
881
|
-
*
|
|
882
|
-
* `absent: []` — a pattern matching nothing is exit 0 with empty stdout, so
|
|
883
|
-
* `[]` means "no such refs". Outside a repository, and for an unknown format
|
|
884
|
-
* or sort field, git exits 128 and this throws.
|
|
885
|
-
*
|
|
886
|
-
* Lines rather than parsed rows because the format is the caller's: the
|
|
887
|
-
* default gives sha-TAB-refname, which {@link parseRefRows} splits.
|
|
888
|
-
*/
|
|
889
|
-
export function forEachRef(
|
|
890
|
-
pattern: string | string[],
|
|
891
|
-
opts: ForEachRefOptions = {},
|
|
892
|
-
): GitVerb<string[]> {
|
|
893
|
-
const argv = ['for-each-ref', `--format=${opts.format ?? REF_FORMAT}`]
|
|
894
|
-
if (opts.sort !== undefined) argv.push(`--sort=${opts.sort}`)
|
|
895
|
-
if (opts.count !== undefined) argv.push(`--count=${opts.count}`)
|
|
896
|
-
for (const p of typeof pattern === 'string' ? [pattern] : pattern) {
|
|
897
|
-
argv.push(positional('forEachRef', 'pattern', p))
|
|
898
|
-
}
|
|
899
|
-
return { argv, absent: NONE, parse: lines }
|
|
900
|
-
}
|
|
901
|
-
|
|
902
|
-
/**
|
|
903
|
-
* {@link forEachRef} rows in the default format, split into `{ sha, ref }`.
|
|
904
|
-
*
|
|
905
|
-
* Split at the first tab: a refname cannot contain one, but a caller-chosen
|
|
906
|
-
* format could, and splitting on every tab would silently truncate.
|
|
907
|
-
*/
|
|
908
|
-
export function parseRefRows(rows: string[]): RemoteRef[] {
|
|
909
|
-
const out: RemoteRef[] = []
|
|
910
|
-
for (const row of rows) {
|
|
911
|
-
const tab = row.indexOf('\t')
|
|
912
|
-
if (tab <= 0) continue
|
|
913
|
-
out.push({ sha: row.slice(0, tab), ref: row.slice(tab + 1) })
|
|
914
|
-
}
|
|
915
|
-
return out
|
|
916
|
-
}
|
|
917
|
-
|
|
918
|
-
/** Options for {@link diffNameOnly}. */
|
|
919
|
-
export interface DiffNameOnlyOptions {
|
|
920
|
-
/** `--cached` — diff the index against HEAD rather than the worktree. */
|
|
921
|
-
cached?: boolean | undefined
|
|
922
|
-
/** `--diff-filter=` selector, e.g. `ACMR`. */
|
|
923
|
-
diffFilter?: string | undefined
|
|
924
|
-
/**
|
|
925
|
-
* The diff range, as argv tokens rather than one string: the two-dot form is
|
|
926
|
-
* two tokens (`[base, "HEAD"]`) and the three-dot form is one
|
|
927
|
-
* (`["base...HEAD"]`), and callers need both spellings. Named `rangeArgs` to
|
|
928
|
-
* keep `range` meaning a single token everywhere else.
|
|
929
|
-
*/
|
|
930
|
-
rangeArgs?: string[] | undefined
|
|
931
|
-
/** Pathspecs, passed after `--`. */
|
|
932
|
-
paths?: string[] | undefined
|
|
933
|
-
}
|
|
934
|
-
|
|
935
|
-
/**
|
|
936
|
-
* Changed paths (`git diff --name-only -z`).
|
|
937
|
-
*
|
|
938
|
-
* `absent: []` — no changes is exit 0 with empty stdout, because this verb
|
|
939
|
-
* never passes `--exit-code`. Outside a repository `git diff` exits **129**
|
|
940
|
-
* (a usage error, not the 128 most git commands give); undeclared either way,
|
|
941
|
-
* so it throws.
|
|
942
|
-
*/
|
|
943
|
-
export function diffNameOnly(opts: DiffNameOnlyOptions = {}): GitVerb<string[]> {
|
|
944
|
-
const argv = ['diff', '--name-only', '-z']
|
|
945
|
-
if (opts.cached) argv.push('--cached')
|
|
946
|
-
if (opts.diffFilter !== undefined) argv.push(`--diff-filter=${opts.diffFilter}`)
|
|
947
|
-
for (const token of opts.rangeArgs ?? [])
|
|
948
|
-
argv.push(positional('diffNameOnly', 'rangeArgs', token))
|
|
949
|
-
if (opts.paths !== undefined && opts.paths.length > 0) argv.push('--', ...opts.paths)
|
|
950
|
-
return { argv, absent: NONE, parse: nulFields }
|
|
951
|
-
}
|
|
952
|
-
|
|
953
|
-
/** Options for {@link diffStat}. */
|
|
954
|
-
export interface DiffStatOptions {
|
|
955
|
-
/** The diff range as argv tokens, as in {@link DiffNameOnlyOptions.rangeArgs}. */
|
|
956
|
-
rangeArgs?: string[] | undefined
|
|
957
|
-
/** Pathspecs, passed after `--`. */
|
|
958
|
-
paths?: string[] | undefined
|
|
959
|
-
}
|
|
960
|
-
|
|
961
|
-
/**
|
|
962
|
-
* The per-file change summary (`git diff --stat`), as raw stdout; empty when
|
|
963
|
-
* nothing changed. A rev that does not resolve throws.
|
|
964
|
-
*/
|
|
965
|
-
export function diffStat(opts: DiffStatOptions = {}): GitVerb<string> {
|
|
966
|
-
const argv = ['diff', '--stat']
|
|
967
|
-
for (const token of opts.rangeArgs ?? []) argv.push(positional('diffStat', 'rangeArgs', token))
|
|
968
|
-
if (opts.paths !== undefined && opts.paths.length > 0) argv.push('--', ...opts.paths)
|
|
969
|
-
return { argv, absent: NONE, parse: (r) => r.stdout }
|
|
970
|
-
}
|
|
971
|
-
|
|
972
|
-
/** Result of {@link diffCheck}. */
|
|
973
|
-
export interface DiffCheckResult {
|
|
974
|
-
/** True when the diff has no whitespace errors or conflict markers. */
|
|
975
|
-
ok: boolean
|
|
976
|
-
/** git's report of the offending lines; empty when `ok`. */
|
|
977
|
-
output: string
|
|
978
|
-
}
|
|
979
|
-
|
|
980
|
-
/** Options for {@link diffCheck}. */
|
|
981
|
-
export interface DiffCheckOptions {
|
|
982
|
-
/** Pathspecs, passed after `--`. */
|
|
983
|
-
paths?: string[] | undefined
|
|
984
|
-
}
|
|
985
|
-
|
|
986
|
-
/**
|
|
987
|
-
* `git diff --check`: whitespace errors and leftover conflict markers in the
|
|
988
|
-
* unstaged changes. `absent: [1, 2]` — git signals findings through its exit
|
|
989
|
-
* code (2 on current git), so they are an answer, not a failure.
|
|
990
|
-
*/
|
|
991
|
-
export function diffCheck(opts: DiffCheckOptions = {}): GitVerb<DiffCheckResult> {
|
|
992
|
-
const argv = ['diff', '--check']
|
|
993
|
-
if (opts.paths !== undefined && opts.paths.length > 0) argv.push('--', ...opts.paths)
|
|
994
|
-
return {
|
|
995
|
-
argv,
|
|
996
|
-
absent: [1, 2],
|
|
997
|
-
parse: (r) => ({ ok: r.exitCode === 0, output: r.stdout }),
|
|
998
|
-
}
|
|
999
|
-
}
|
|
1000
|
-
|
|
1001
|
-
/** Options for {@link diffNameStatus}. */
|
|
1002
|
-
export interface DiffNameStatusOptions {
|
|
1003
|
-
/** `--cached` — diff the index against HEAD rather than the worktree. */
|
|
1004
|
-
cached?: boolean | undefined
|
|
1005
|
-
/** The diff range as a single token, e.g. `origin/main..HEAD`. */
|
|
1006
|
-
range?: string | undefined
|
|
1007
|
-
/** `--no-renames` — report a rename as a delete plus an add. */
|
|
1008
|
-
noRenames?: boolean | undefined
|
|
1009
|
-
/** Pathspecs, passed after `--`. */
|
|
1010
|
-
paths?: string[] | undefined
|
|
1011
|
-
}
|
|
1012
|
-
|
|
1013
|
-
/**
|
|
1014
|
-
* Changed paths with their status (`git diff --name-status -z`).
|
|
1015
|
-
*
|
|
1016
|
-
* `absent: []` — no changes is exit 0 with empty stdout, including before the
|
|
1017
|
-
* first commit, where `--cached` diffs against the empty tree. Outside a
|
|
1018
|
-
* repository `git diff` exits 129 and this throws.
|
|
1019
|
-
*
|
|
1020
|
-
* See {@link DiffEntry} for what a rename record costs a naive parser.
|
|
1021
|
-
*/
|
|
1022
|
-
export function diffNameStatus(opts: DiffNameStatusOptions = {}): GitVerb<DiffEntry[]> {
|
|
1023
|
-
const argv = ['diff', '--name-status', '-z']
|
|
1024
|
-
if (opts.cached) argv.push('--cached')
|
|
1025
|
-
if (opts.noRenames) argv.push('--no-renames')
|
|
1026
|
-
if (opts.range !== undefined) argv.push(positional('diffNameStatus', 'range', opts.range))
|
|
1027
|
-
if (opts.paths !== undefined && opts.paths.length > 0) argv.push('--', ...opts.paths)
|
|
1028
|
-
return { argv, absent: NONE, parse: nameStatusEntries }
|
|
1029
|
-
}
|
|
1030
|
-
|
|
1031
|
-
/** Options for {@link log}. */
|
|
1032
|
-
export interface LogOptions {
|
|
1033
|
-
/** A single starting rev. */
|
|
1034
|
-
rev?: string | undefined
|
|
1035
|
-
/** A range expression as one token, e.g. `origin/main..HEAD`. */
|
|
1036
|
-
range?: string | undefined
|
|
1037
|
-
/**
|
|
1038
|
-
* The `--format=` value, caller-chosen and passed through verbatim.
|
|
1039
|
-
*
|
|
1040
|
-
* git reads a placeholder string as `tformat:`, which terminates each
|
|
1041
|
-
* record with a newline; pass `"format:%H…"` explicitly for the older
|
|
1042
|
-
* separator semantics, which a caller framing its own records with `%x1e`
|
|
1043
|
-
* usually wants.
|
|
1044
|
-
*/
|
|
1045
|
-
format?: string | undefined
|
|
1046
|
-
/** `--max-count=`. */
|
|
1047
|
-
maxCount?: number | undefined
|
|
1048
|
-
/** `--no-merges`. */
|
|
1049
|
-
noMerges?: boolean | undefined
|
|
1050
|
-
/** `--reverse` — oldest first. */
|
|
1051
|
-
reverse?: boolean | undefined
|
|
1052
|
-
/** `--no-renames` — no rename detection in `nameStatus` / `numstat` output. */
|
|
1053
|
-
noRenames?: boolean | undefined
|
|
1054
|
-
/** `--name-status` — append each commit's changed paths and statuses. */
|
|
1055
|
-
nameStatus?: boolean | undefined
|
|
1056
|
-
/** `--numstat` — append each commit's per-file added/deleted line counts. */
|
|
1057
|
-
numstat?: boolean | undefined
|
|
1058
|
-
/** `--relative` — report paths relative to the client's cwd. */
|
|
1059
|
-
relative?: boolean | undefined
|
|
1060
|
-
/** Revs to exclude, emitted after `--not` (so after the positive revs). */
|
|
1061
|
-
notRefs?: string[] | undefined
|
|
1062
|
-
/** Pathspecs, passed after `--`. */
|
|
1063
|
-
paths?: string[] | undefined
|
|
1064
|
-
}
|
|
1065
|
-
|
|
1066
|
-
/**
|
|
1067
|
-
* `git log`, as raw stdout.
|
|
1068
|
-
*
|
|
1069
|
-
* Callers choose their own `--format`, and several frame their own records
|
|
1070
|
-
* with `%x1e` / `%x1f` separators or interleave `--name-status` blocks — so
|
|
1071
|
-
* the library returns the bytes and does not split them. A caller that wants
|
|
1072
|
-
* lines uses the client's `logLines`.
|
|
1073
|
-
*
|
|
1074
|
-
* `absent: []`, deliberately. An empty repository exits 128 — the same code a
|
|
1075
|
-
* corrupt one gives, and the same code as a rev that does not resolve — so
|
|
1076
|
-
* declaring 128 absent would hand back `""` for a broken store. A caller that
|
|
1077
|
-
* must tolerate an empty history probes `hasHistory()` first (not
|
|
1078
|
-
* `objectExists("HEAD")` — see {@link objectExists}), or uses `git.try.log()`.
|
|
1079
|
-
*
|
|
1080
|
-
* {@link logSubject} is the fixed-format convenience for the one question that
|
|
1081
|
-
* needs no format.
|
|
1082
|
-
*/
|
|
1083
|
-
export function log(opts: LogOptions = {}): GitVerb<string> {
|
|
1084
|
-
const argv = ['log']
|
|
1085
|
-
if (opts.format !== undefined) argv.push(`--format=${opts.format}`)
|
|
1086
|
-
if (opts.maxCount !== undefined) argv.push(`--max-count=${opts.maxCount}`)
|
|
1087
|
-
if (opts.noMerges) argv.push('--no-merges')
|
|
1088
|
-
if (opts.reverse) argv.push('--reverse')
|
|
1089
|
-
if (opts.noRenames) argv.push('--no-renames')
|
|
1090
|
-
if (opts.nameStatus) argv.push('--name-status')
|
|
1091
|
-
if (opts.numstat) argv.push('--numstat')
|
|
1092
|
-
if (opts.relative) argv.push('--relative')
|
|
1093
|
-
if (opts.rev !== undefined) argv.push(positional('log', 'rev', opts.rev))
|
|
1094
|
-
if (opts.range !== undefined) argv.push(positional('log', 'range', opts.range))
|
|
1095
|
-
// `--not` negates every rev after it, so the positive revs must precede it.
|
|
1096
|
-
if (opts.notRefs !== undefined && opts.notRefs.length > 0) {
|
|
1097
|
-
argv.push('--not', ...opts.notRefs.map((ref) => positional('log', 'notRefs', ref)))
|
|
1098
|
-
}
|
|
1099
|
-
if (opts.paths !== undefined && opts.paths.length > 0) argv.push('--', ...opts.paths)
|
|
1100
|
-
// Verbatim, trailing newline included: the caller's format decides where a
|
|
1101
|
-
// record ends, and trimming would eat the terminator it relies on.
|
|
1102
|
-
return { argv, absent: NONE, parse: (r) => r.stdout }
|
|
1103
|
-
}
|
|
1104
|
-
|
|
1105
|
-
/** One row of `git ls-tree`. */
|
|
1106
|
-
export interface TreeEntry {
|
|
1107
|
-
/** The six-digit mode, verbatim: `100644`, `100755`, `040000`, `160000`. */
|
|
1108
|
-
mode: string
|
|
1109
|
-
type: 'blob' | 'tree' | 'commit'
|
|
1110
|
-
sha: string
|
|
1111
|
-
/**
|
|
1112
|
-
* Blob size in bytes — set only under `long`, and only for a blob. `--long`
|
|
1113
|
-
* prints `-` for a tree or submodule, which reads back as `null` rather than
|
|
1114
|
-
* a fabricated zero.
|
|
1115
|
-
*/
|
|
1116
|
-
sizeBytes: number | null
|
|
1117
|
-
path: string
|
|
1118
|
-
}
|
|
1119
|
-
|
|
1120
|
-
/** Options for {@link lsTree}. */
|
|
1121
|
-
export interface LsTreeOptions {
|
|
1122
|
-
/** `-r` — descend into subtrees, so only blobs come back. */
|
|
1123
|
-
recursive?: boolean | undefined
|
|
1124
|
-
/** `--long` — include each blob's size. */
|
|
1125
|
-
long?: boolean | undefined
|
|
1126
|
-
/** Pathspecs, passed after `--`. */
|
|
1127
|
-
paths?: string[] | undefined
|
|
1128
|
-
}
|
|
1129
|
-
|
|
1130
|
-
/**
|
|
1131
|
-
* The entries of a tree at a rev (`git ls-tree -z`).
|
|
1132
|
-
*
|
|
1133
|
-
* `absent: []` — a pathspec matching nothing is exit 0 with empty stdout, so
|
|
1134
|
-
* `[]` means "no such entries"; a rev that does not resolve exits 128 and
|
|
1135
|
-
* throws, so an unreadable rev cannot read as "the tree is empty".
|
|
1136
|
-
*/
|
|
1137
|
-
export function lsTree(rev: string, opts: LsTreeOptions = {}): GitVerb<TreeEntry[]> {
|
|
1138
|
-
const argv = ['ls-tree', '-z']
|
|
1139
|
-
if (opts.recursive) argv.push('-r')
|
|
1140
|
-
if (opts.long) argv.push('--long')
|
|
1141
|
-
argv.push(positional('lsTree', 'rev', rev))
|
|
1142
|
-
if (opts.paths !== undefined && opts.paths.length > 0) argv.push('--', ...opts.paths)
|
|
1143
|
-
return {
|
|
1144
|
-
argv,
|
|
1145
|
-
absent: NONE,
|
|
1146
|
-
parse(r) {
|
|
1147
|
-
const out: TreeEntry[] = []
|
|
1148
|
-
for (const record of nulFields(r)) {
|
|
1149
|
-
// `<mode> <type> <sha>[ <size>]\t<path>` — the TAB is the only
|
|
1150
|
-
// separator that cannot appear in the metadata half, and a path may
|
|
1151
|
-
// contain spaces, so split there first and never on whitespace alone.
|
|
1152
|
-
const tab = record.indexOf('\t')
|
|
1153
|
-
if (tab < 0) continue
|
|
1154
|
-
const meta = record
|
|
1155
|
-
.slice(0, tab)
|
|
1156
|
-
.split(/\s+/)
|
|
1157
|
-
.filter((f) => f !== '')
|
|
1158
|
-
const [mode, type, sha, size] = meta
|
|
1159
|
-
if (mode === undefined || type === undefined || sha === undefined) continue
|
|
1160
|
-
out.push({
|
|
1161
|
-
mode,
|
|
1162
|
-
type: type as TreeEntry['type'],
|
|
1163
|
-
sha,
|
|
1164
|
-
// `--long` writes `-` where a size makes no sense (tree, submodule).
|
|
1165
|
-
sizeBytes: size === undefined || size === '-' ? null : Number(size),
|
|
1166
|
-
path: record.slice(tab + 1),
|
|
1167
|
-
})
|
|
1168
|
-
}
|
|
1169
|
-
return out
|
|
1170
|
-
},
|
|
1171
|
-
}
|
|
1172
|
-
}
|
|
1173
|
-
|
|
1174
|
-
/** Options for {@link diffTree}. */
|
|
1175
|
-
export interface DiffTreeOptions {
|
|
1176
|
-
/**
|
|
1177
|
-
* `--root` — report a root commit's contents as adds rather than nothing.
|
|
1178
|
-
*
|
|
1179
|
-
* Without it `diff-tree` on the first commit exits 0 with empty output,
|
|
1180
|
-
* because a root commit has no parent to diff against. A caller walking a
|
|
1181
|
-
* whole history and not passing this silently loses the first commit.
|
|
1182
|
-
*/
|
|
1183
|
-
root?: boolean | undefined
|
|
1184
|
-
/** `--no-renames` — report a rename as a delete plus an add. */
|
|
1185
|
-
noRenames?: boolean | undefined
|
|
1186
|
-
/**
|
|
1187
|
-
* `-M` — detect renames. Plumbing `diff-tree` does not read `diff.renames`,
|
|
1188
|
-
* so without it a move is a delete plus an add. Read by `diffTree` only;
|
|
1189
|
-
* `diffTreeNumstat` ignores it.
|
|
1190
|
-
*/
|
|
1191
|
-
findRenames?: boolean | undefined
|
|
1192
|
-
/** Pathspecs, passed after `--`. */
|
|
1193
|
-
paths?: string[] | undefined
|
|
1194
|
-
}
|
|
1195
|
-
|
|
1196
|
-
/** Options for {@link diffText}. */
|
|
1197
|
-
export interface DiffTextOptions {
|
|
1198
|
-
/** `--cached` — diff the index against `rev` (or HEAD) rather than the worktree. */
|
|
1199
|
-
staged?: boolean | undefined
|
|
1200
|
-
/** Pathspecs, passed after `--`. */
|
|
1201
|
-
paths?: string[] | undefined
|
|
1202
|
-
}
|
|
1203
|
-
|
|
1204
|
-
/**
|
|
1205
|
-
* The unified diff text (`git diff [--cached] [rev] [-- paths]`), for the same
|
|
1206
|
-
* rev and staged shape {@link diffNameOnly} selects paths for. Empty when
|
|
1207
|
-
* nothing differs.
|
|
1208
|
-
*
|
|
1209
|
-
* `absent: []`. A rev that does not resolve exits 128, and outside a
|
|
1210
|
-
* repository `git diff` exits 129. Both throw, so "git failed" never reads as
|
|
1211
|
-
* "no diff". `git.try.diffText` reports them as `{ ok: false }`.
|
|
1212
|
-
*/
|
|
1213
|
-
export function diffText(rev?: string | undefined, opts: DiffTextOptions = {}): GitVerb<string> {
|
|
1214
|
-
const argv = ['diff']
|
|
1215
|
-
if (opts.staged === true) argv.push('--cached')
|
|
1216
|
-
const from = optionalPositional('diffText', 'rev', rev)
|
|
1217
|
-
if (from !== undefined) argv.push(from)
|
|
1218
|
-
if (opts.paths !== undefined && opts.paths.length > 0) argv.push('--', ...opts.paths)
|
|
1219
|
-
return { argv, absent: NONE, parse: (r) => r.stdout }
|
|
1220
|
-
}
|
|
1221
|
-
|
|
1222
|
-
/**
|
|
1223
|
-
* One untracked file rendered as an all-added diff
|
|
1224
|
-
* (`diff --no-index -- /dev/null <path>`), so a new file reaches a consumer in
|
|
1225
|
-
* the same shape as a modified one. An empty existing file still gives a diff
|
|
1226
|
-
* header.
|
|
1227
|
-
*
|
|
1228
|
-
* `--no-index` exits 1 whenever the inputs differ, which for a real file is
|
|
1229
|
-
* always, so exit 1 is the success case. git also exits 1, with empty stdout,
|
|
1230
|
-
* for a path it cannot read; that throws `CommandFailed`. Exit 2 (a usage or
|
|
1231
|
-
* read error) throws too.
|
|
1232
|
-
*/
|
|
1233
|
-
export function diffAddedFile(relPath: string): GitVerb<string> {
|
|
1234
|
-
return {
|
|
1235
|
-
argv: ['diff', '--no-index', '--', '/dev/null', relPath],
|
|
1236
|
-
absent: [1],
|
|
1237
|
-
parse(r, ranArgv) {
|
|
1238
|
-
if (r.exitCode !== 0 && r.stdout === '') throw new CommandFailed(ranArgv, r)
|
|
1239
|
-
return r.stdout
|
|
1240
|
-
},
|
|
1241
|
-
}
|
|
1242
|
-
}
|
|
1243
|
-
|
|
1244
|
-
/**
|
|
1245
|
-
* The paths and statuses one commit changed (`git diff-tree --name-status -z`).
|
|
1246
|
-
*
|
|
1247
|
-
* `diffNameStatus` for a commit rather than the worktree or index, sharing
|
|
1248
|
-
* that verb's parser and its {@link DiffEntry} rows. `--no-commit-id` keeps
|
|
1249
|
-
* the sha out of the records.
|
|
1250
|
-
*
|
|
1251
|
-
* `absent: []` — a rev that does not resolve exits 128 and throws.
|
|
1252
|
-
*
|
|
1253
|
-
* For per-file line counts use {@link diffTreeNumstat}: git rejects
|
|
1254
|
-
* `--numstat` together with `--name-status` (exit 129), so the two shapes are
|
|
1255
|
-
* two verbs.
|
|
1256
|
-
*/
|
|
1257
|
-
export function diffTree(rev: string, opts: DiffTreeOptions = {}): GitVerb<DiffEntry[]> {
|
|
1258
|
-
const argv = ['diff-tree', '-r', '--no-commit-id']
|
|
1259
|
-
if (opts.root) argv.push('--root')
|
|
1260
|
-
if (opts.noRenames) argv.push('--no-renames')
|
|
1261
|
-
if (opts.findRenames) argv.push('-M')
|
|
1262
|
-
argv.push('--name-status', '-z', positional('diffTree', 'rev', rev))
|
|
1263
|
-
if (opts.paths !== undefined && opts.paths.length > 0) argv.push('--', ...opts.paths)
|
|
1264
|
-
return { argv, absent: NONE, parse: nameStatusEntries }
|
|
1265
|
-
}
|
|
1266
|
-
|
|
1267
|
-
/** One row of a `--numstat` diff. */
|
|
1268
|
-
export interface NumstatEntry {
|
|
1269
|
-
path: string
|
|
1270
|
-
/** Added lines, or null for a binary file, where git prints `-`. */
|
|
1271
|
-
linesAdded: number | null
|
|
1272
|
-
/** Deleted lines, or null for a binary file. */
|
|
1273
|
-
linesDeleted: number | null
|
|
1274
|
-
}
|
|
1275
|
-
|
|
1276
|
-
/**
|
|
1277
|
-
* Per-file line counts for one commit (`git diff-tree --numstat -z`).
|
|
1278
|
-
*
|
|
1279
|
-
* The counting twin of {@link diffTree}, with the same options. A binary file
|
|
1280
|
-
* has no line counts: git prints `-` for both, which reads back as `null`.
|
|
1281
|
-
*
|
|
1282
|
-
* `absent: []` — a rev that does not resolve exits 128 and throws.
|
|
1283
|
-
*/
|
|
1284
|
-
export function diffTreeNumstat(rev: string, opts: DiffTreeOptions = {}): GitVerb<NumstatEntry[]> {
|
|
1285
|
-
const argv = ['diff-tree', '-r', '--no-commit-id']
|
|
1286
|
-
if (opts.root) argv.push('--root')
|
|
1287
|
-
if (opts.noRenames) argv.push('--no-renames')
|
|
1288
|
-
argv.push('--numstat', '-z', positional('diffTreeNumstat', 'rev', rev))
|
|
1289
|
-
if (opts.paths !== undefined && opts.paths.length > 0) argv.push('--', ...opts.paths)
|
|
1290
|
-
return {
|
|
1291
|
-
argv,
|
|
1292
|
-
absent: NONE,
|
|
1293
|
-
parse(r) {
|
|
1294
|
-
const out: NumstatEntry[] = []
|
|
1295
|
-
for (const record of nulFields(r)) {
|
|
1296
|
-
// `<added>\t<deleted>\t<path>`: only the first two tabs separate, and
|
|
1297
|
-
// the rest of the record is the path — raw bytes, tabs included,
|
|
1298
|
-
// because `-z` turns off git's quoting. Splitting on every tab would
|
|
1299
|
-
// truncate a path that contains one.
|
|
1300
|
-
const firstTab = record.indexOf('\t')
|
|
1301
|
-
const secondTab = firstTab < 0 ? -1 : record.indexOf('\t', firstTab + 1)
|
|
1302
|
-
if (secondTab < 0) continue
|
|
1303
|
-
const added = record.slice(0, firstTab)
|
|
1304
|
-
const deleted = record.slice(firstTab + 1, secondTab)
|
|
1305
|
-
out.push({
|
|
1306
|
-
path: record.slice(secondTab + 1),
|
|
1307
|
-
linesAdded: added === '-' ? null : Number(added),
|
|
1308
|
-
linesDeleted: deleted === '-' ? null : Number(deleted),
|
|
1309
|
-
})
|
|
1310
|
-
}
|
|
1311
|
-
return out
|
|
1312
|
-
},
|
|
1313
|
-
}
|
|
1314
|
-
}
|
|
1315
|
-
|
|
1316
|
-
/** Options for {@link grep}. */
|
|
1317
|
-
export interface GrepOptions {
|
|
1318
|
-
/** `-E` — extended POSIX regular expressions. */
|
|
1319
|
-
extendedRegexp?: boolean | undefined
|
|
1320
|
-
/** `-n` — prefix each hit with its line number. */
|
|
1321
|
-
lineNumber?: boolean | undefined
|
|
1322
|
-
/** `--no-color` — never emit SGR escapes, whatever the config says. */
|
|
1323
|
-
noColor?: boolean | undefined
|
|
1324
|
-
/** Pathspecs, passed after `--`. */
|
|
1325
|
-
paths?: string[] | undefined
|
|
1326
|
-
}
|
|
1327
|
-
|
|
1328
|
-
/**
|
|
1329
|
-
* Matching lines from the working tree (`git grep`), verbatim.
|
|
1330
|
-
*
|
|
1331
|
-
* `absent: [1]`: `git grep` exits 1 for "no matches", a legitimate answer. A
|
|
1332
|
-
* real failure is 128 (not a repository, an unbalanced regex) or 129 (a usage
|
|
1333
|
-
* error), and those throw.
|
|
1334
|
-
*
|
|
1335
|
-
* The one dull edge: a pathspec that matches no file also exits 1, so a typo'd
|
|
1336
|
-
* path reads as "no matches" rather than as an error. git gives us nothing to
|
|
1337
|
-
* separate the two.
|
|
1338
|
-
*
|
|
1339
|
-
* Lines, not `-z`: the output is `path:line:text`, not a path listing, and `-z`
|
|
1340
|
-
* only changes the separator after the path — a caller still has to split the
|
|
1341
|
-
* record, and would then have to do it two different ways.
|
|
1342
|
-
*/
|
|
1343
|
-
export function grep(pattern: string, opts: GrepOptions = {}): GitVerb<string[]> {
|
|
1344
|
-
const argv = ['grep']
|
|
1345
|
-
if (opts.lineNumber) argv.push('-n')
|
|
1346
|
-
if (opts.extendedRegexp) argv.push('-E')
|
|
1347
|
-
if (opts.noColor) argv.push('--no-color')
|
|
1348
|
-
// `-e` marks the pattern as a pattern, so one that starts with `-` is searched for.
|
|
1349
|
-
argv.push('-e', pattern)
|
|
1350
|
-
if (opts.paths !== undefined && opts.paths.length > 0) argv.push('--', ...opts.paths)
|
|
1351
|
-
return { argv, absent: [1], parse: lines }
|
|
1352
|
-
}
|
|
1353
|
-
|
|
1354
|
-
/**
|
|
1355
|
-
* True iff `a` is an ancestor of `b` (`git merge-base --is-ancestor`).
|
|
1356
|
-
*
|
|
1357
|
-
* A boolean carried entirely by the exit code. `absent: [1]` — measured: `b`
|
|
1358
|
-
* reachable from `a` → 0; a genuine "no", diverged or unrelated alike → 1; a
|
|
1359
|
-
* rev that does not resolve → **128, which throws**. A typo'd rev must never
|
|
1360
|
-
* read as "not an ancestor", because that answer is usually the one that lets
|
|
1361
|
-
* a caller delete something.
|
|
1362
|
-
*/
|
|
1363
|
-
export function isAncestor(a: string, b: string): GitVerb<boolean> {
|
|
1364
|
-
return {
|
|
1365
|
-
argv: [
|
|
1366
|
-
'merge-base',
|
|
1367
|
-
'--is-ancestor',
|
|
1368
|
-
positional('isAncestor', 'a', a),
|
|
1369
|
-
positional('isAncestor', 'b', b),
|
|
1370
|
-
],
|
|
1371
|
-
absent: [1],
|
|
1372
|
-
parse: (r) => r.exitCode === 0,
|
|
1373
|
-
}
|
|
1374
|
-
}
|
|
1375
|
-
|
|
1376
|
-
/** Commits each side of a fork point has that the other does not. */
|
|
1377
|
-
export interface AheadBehind {
|
|
1378
|
-
/** Commits on `tip` that are not on `base`. */
|
|
1379
|
-
ahead: number
|
|
1380
|
-
/** Commits on `base` that are not on `tip`. */
|
|
1381
|
-
behind: number
|
|
1382
|
-
}
|
|
1383
|
-
|
|
1384
|
-
/**
|
|
1385
|
-
* How far `tip` has diverged from `base`
|
|
1386
|
-
* (`git rev-list --left-right --count base...tip`).
|
|
1387
|
-
*
|
|
1388
|
-
* The verb owns the field order: git prints the left count first, and left is
|
|
1389
|
-
* `base` — so the first number is *behind*, not ahead.
|
|
1390
|
-
*
|
|
1391
|
-
* `absent: []` — unrelated histories are still a counted answer (exit 0); a
|
|
1392
|
-
* rev that does not resolve exits 128 and throws.
|
|
1393
|
-
*/
|
|
1394
|
-
export function aheadBehind(base: string, tip: string): GitVerb<AheadBehind> {
|
|
1395
|
-
positional('aheadBehind', 'tip', tip)
|
|
1396
|
-
const argv = [
|
|
1397
|
-
'rev-list',
|
|
1398
|
-
'--left-right',
|
|
1399
|
-
'--count',
|
|
1400
|
-
`${positional('aheadBehind', 'base', base)}...${tip}`,
|
|
1401
|
-
]
|
|
1402
|
-
return {
|
|
1403
|
-
argv,
|
|
1404
|
-
absent: NONE,
|
|
1405
|
-
parse(r, ranArgv) {
|
|
1406
|
-
const m = /^(\d+)\s+(\d+)/.exec(r.stdout)
|
|
1407
|
-
// Exit 0 with output we cannot read is not an answer; reporting it as
|
|
1408
|
-
// 0/0 would be indistinguishable from "in sync", the one state a caller
|
|
1409
|
-
// acts on.
|
|
1410
|
-
if (m === null) throw new CommandFailed(ranArgv, r)
|
|
1411
|
-
return { behind: Number(m[1]), ahead: Number(m[2]) }
|
|
1412
|
-
},
|
|
1413
|
-
}
|
|
1414
|
-
}
|
|
1415
|
-
|
|
1416
|
-
/**
|
|
1417
|
-
* Configured remote names (`git remote`). The clients call it as `remotes()`.
|
|
1418
|
-
*
|
|
1419
|
-
* `absent: []` — a repository with no remotes is exit 0 with empty stdout.
|
|
1420
|
-
* Outside a repository git exits 128 and this throws.
|
|
1421
|
-
*/
|
|
1422
|
-
export function remote(): GitVerb<string[]> {
|
|
1423
|
-
return { argv: ['remote'], absent: NONE, parse: trimmedLines }
|
|
1424
|
-
}
|
|
1425
|
-
|
|
1426
|
-
/** Options for {@link remoteGetUrl} and {@link remoteGetUrls}. */
|
|
1427
|
-
export interface RemoteGetUrlOptions {
|
|
1428
|
-
/**
|
|
1429
|
-
* `--push` — the push URL. git falls back to the fetch URL when the remote
|
|
1430
|
-
* sets no `pushurl`.
|
|
1431
|
-
*/
|
|
1432
|
-
push?: boolean | undefined
|
|
1433
|
-
}
|
|
1434
|
-
|
|
1435
|
-
/**
|
|
1436
|
-
* A remote's fetch URL (`git remote get-url <name>`), or null when no remote
|
|
1437
|
-
* by that name is configured. With `push`, its push URL. When a remote has
|
|
1438
|
-
* several URLs this is the first; {@link remoteGetUrls} gives them all.
|
|
1439
|
-
*
|
|
1440
|
-
* `absent: [2]` — measured: git reports an unknown remote as exit 2, not 1 or
|
|
1441
|
-
* 128. Outside a repository it exits 128 and this throws.
|
|
1442
|
-
*/
|
|
1443
|
-
export function remoteGetUrl(name: string, opts: RemoteGetUrlOptions = {}): GitVerb<string | null> {
|
|
1444
|
-
const argv = ['remote', 'get-url']
|
|
1445
|
-
if (opts.push) argv.push('--push')
|
|
1446
|
-
argv.push(positional('remoteGetUrl', 'name', name))
|
|
1447
|
-
return { argv, absent: [2], parse: trimmedOrNull }
|
|
1448
|
-
}
|
|
1449
|
-
|
|
1450
|
-
/**
|
|
1451
|
-
* Every URL a remote has (`git remote get-url --all <name>`), or `[]` when no
|
|
1452
|
-
* remote by that name is configured (exit 2).
|
|
1453
|
-
*
|
|
1454
|
-
* A remote can carry several URLs (`remote set-url --add`). A caller that
|
|
1455
|
-
* checks a remote before deleting something compares all of them, not the
|
|
1456
|
-
* first.
|
|
1457
|
-
*/
|
|
1458
|
-
export function remoteGetUrls(name: string, opts: RemoteGetUrlOptions = {}): GitVerb<string[]> {
|
|
1459
|
-
const argv = ['remote', 'get-url', '--all']
|
|
1460
|
-
if (opts.push) argv.push('--push')
|
|
1461
|
-
argv.push(positional('remoteGetUrls', 'name', name))
|
|
1462
|
-
return { argv, absent: [2], parse: trimmedLines }
|
|
1463
|
-
}
|
|
1464
|
-
|
|
1465
|
-
/**
|
|
1466
|
-
* The branch a remote's HEAD points at, as a full refname such as
|
|
1467
|
-
* `refs/heads/main` (`git ls-remote --symref <remote> HEAD`).
|
|
1468
|
-
*
|
|
1469
|
-
* It asks the remote over the network. {@link symbolicRef} on
|
|
1470
|
-
* `refs/remotes/<remote>/HEAD` reads the local copy instead, which a clone
|
|
1471
|
-
* may never have set.
|
|
1472
|
-
*
|
|
1473
|
-
* `absent: []`. null means the remote answered but names no default branch:
|
|
1474
|
-
* an empty repository, or a detached HEAD. An unreachable remote exits 128
|
|
1475
|
-
* and throws.
|
|
1476
|
-
*/
|
|
1477
|
-
export function remoteHead(remote: string): GitVerb<string | null> {
|
|
1478
|
-
return {
|
|
1479
|
-
argv: ['ls-remote', '--symref', positional('remoteHead', 'remote', remote), 'HEAD'],
|
|
1480
|
-
absent: NONE,
|
|
1481
|
-
parse(r) {
|
|
1482
|
-
// `ref: refs/heads/main<TAB>HEAD`, then the `<sha><TAB>HEAD` row.
|
|
1483
|
-
for (const line of splitLines(r.stdout)) {
|
|
1484
|
-
const m = /^ref: (\S+)\tHEAD$/.exec(line)
|
|
1485
|
-
if (m !== null) return m[1]!
|
|
1486
|
-
}
|
|
1487
|
-
return null
|
|
1488
|
-
},
|
|
1489
|
-
}
|
|
1490
|
-
}
|
|
1491
|
-
|
|
1492
|
-
// ── mutations ───────────────────────────────────────────────────────────────
|
|
1493
|
-
//
|
|
1494
|
-
// absent: [], so any non-zero exit throws CommandFailed. `configRemoveSection`
|
|
1495
|
-
// is the one exception: it declares 128.
|
|
1496
|
-
|
|
1497
|
-
/** Options for {@link fetch}. */
|
|
1498
|
-
export interface FetchOptions {
|
|
1499
|
-
/** `--prune` — drop remote-tracking refs the remote no longer has. */
|
|
1500
|
-
prune?: boolean | undefined
|
|
1501
|
-
/** `--quiet` — suppress the progress report on stderr. */
|
|
1502
|
-
quiet?: boolean | undefined
|
|
1503
|
-
/**
|
|
1504
|
-
* `--no-write-fetch-head` — do not touch `.git/FETCH_HEAD`.
|
|
1505
|
-
*
|
|
1506
|
-
* The flag a fetch running beside other work wants: FETCH_HEAD is one file
|
|
1507
|
-
* per repository, so two concurrent fetches in the same store race over it
|
|
1508
|
-
* and a caller that only wanted refs updated gets a corrupted one.
|
|
1509
|
-
*/
|
|
1510
|
-
noWriteFetchHead?: boolean | undefined
|
|
1511
|
-
/**
|
|
1512
|
-
* `--depth=<n>` — limit the fetched history to `n` commits from each tip.
|
|
1513
|
-
* Anything but a positive integer throws a `TypeError`.
|
|
1514
|
-
*/
|
|
1515
|
-
depth?: number | undefined
|
|
1516
|
-
/** `--no-tags` — fetch no tags beyond those the refspecs name. */
|
|
1517
|
-
noTags?: boolean | undefined
|
|
1518
|
-
}
|
|
1519
|
-
|
|
1520
|
-
/**
|
|
1521
|
-
* `git fetch <remote> [refspec…]`.
|
|
1522
|
-
*
|
|
1523
|
-
* `absent: []` — nothing about a failed fetch is an answer. A caller that
|
|
1524
|
-
* tolerates an unreachable remote uses `git.try.fetch(…)`.
|
|
1525
|
-
*
|
|
1526
|
-
* `refspec` takes an array, for fetching several refs in one invocation.
|
|
1527
|
-
*/
|
|
1528
|
-
export function fetch(
|
|
1529
|
-
remote: string,
|
|
1530
|
-
refspec?: string | string[] | undefined,
|
|
1531
|
-
opts: FetchOptions = {},
|
|
1532
|
-
): GitVerb<void> {
|
|
1533
|
-
const argv = ['fetch']
|
|
1534
|
-
if (opts.quiet) argv.push('--quiet')
|
|
1535
|
-
if (opts.prune) argv.push('--prune')
|
|
1536
|
-
if (opts.noWriteFetchHead) argv.push('--no-write-fetch-head')
|
|
1537
|
-
if (opts.depth !== undefined) argv.push(depthArg('fetch', opts.depth))
|
|
1538
|
-
if (opts.noTags) argv.push('--no-tags')
|
|
1539
|
-
argv.push(positional('fetch', 'remote', remote))
|
|
1540
|
-
if (refspec !== undefined) {
|
|
1541
|
-
for (const spec of typeof refspec === 'string' ? [refspec] : refspec) {
|
|
1542
|
-
argv.push(positional('fetch', 'refspec', spec))
|
|
1543
|
-
}
|
|
1544
|
-
}
|
|
1545
|
-
return { argv, absent: NONE, parse: nothing }
|
|
1546
|
-
}
|
|
1547
|
-
|
|
1548
|
-
/** Options for {@link add}. */
|
|
1549
|
-
export interface AddOptions {
|
|
1550
|
-
/** `--all` — stage deletions and untracked files too, not just changes. */
|
|
1551
|
-
all?: boolean | undefined
|
|
1552
|
-
/** `--update` — stage changes and deletions to tracked files only. */
|
|
1553
|
-
update?: boolean | undefined
|
|
1554
|
-
/** `--intent-to-add` — record new files as empty so `git diff` lists them. */
|
|
1555
|
-
intentToAdd?: boolean | undefined
|
|
1556
|
-
}
|
|
1557
|
-
|
|
1558
|
-
/** Stage paths. `--` precedes them, so a path starting with `-` is a path, not an option; flags go in `opts`. */
|
|
1559
|
-
export function add(paths: string[], opts: AddOptions = {}): GitVerb<void> {
|
|
1560
|
-
const argv = ['add']
|
|
1561
|
-
if (opts.all) argv.push('--all')
|
|
1562
|
-
if (opts.update) argv.push('--update')
|
|
1563
|
-
if (opts.intentToAdd) argv.push('--intent-to-add')
|
|
1564
|
-
argv.push('--', ...paths)
|
|
1565
|
-
return { argv, absent: NONE, parse: nothing }
|
|
1566
|
-
}
|
|
1567
|
-
|
|
1568
|
-
/** Flags shared by every {@link CommitOptions} message source. */
|
|
1569
|
-
export interface CommitFlags {
|
|
1570
|
-
/** `--allow-empty` — commit even when nothing is staged. */
|
|
1571
|
-
allowEmpty?: boolean | undefined
|
|
1572
|
-
/** `--amend` — replace the previous commit rather than adding one. */
|
|
1573
|
-
amend?: boolean | undefined
|
|
1574
|
-
/** `--no-verify` — skip the commit hooks. */
|
|
1575
|
-
noVerify?: boolean | undefined
|
|
1576
|
-
/** `--signoff` — append a `Signed-off-by` trailer. */
|
|
1577
|
-
signoff?: boolean | undefined
|
|
1578
|
-
}
|
|
1579
|
-
|
|
1580
|
-
/**
|
|
1581
|
-
* Options for {@link commit}. The message comes from exactly one source, and
|
|
1582
|
-
* the types refuse a mix: inline `-m` (`message`, optionally `body`), a file
|
|
1583
|
-
* (`messageFile`, `-F`), or a string fed on stdin (`messageStdin`, `-F -`).
|
|
1584
|
-
*/
|
|
1585
|
-
export type CommitOptions = CommitFlags &
|
|
1586
|
-
(
|
|
1587
|
-
| {
|
|
1588
|
-
/** The subject, as `-m`. */
|
|
1589
|
-
message?: string | undefined
|
|
1590
|
-
/** A second `-m`, rendered as the body after a blank line. */
|
|
1591
|
-
body?: string | undefined
|
|
1592
|
-
messageFile?: undefined
|
|
1593
|
-
messageStdin?: undefined
|
|
1594
|
-
}
|
|
1595
|
-
| {
|
|
1596
|
-
/** `-F <path>` — take the whole message from a file. */
|
|
1597
|
-
messageFile: string
|
|
1598
|
-
message?: undefined
|
|
1599
|
-
body?: undefined
|
|
1600
|
-
messageStdin?: undefined
|
|
1601
|
-
}
|
|
1602
|
-
| {
|
|
1603
|
-
/**
|
|
1604
|
-
* `-F -` — the whole message, fed on stdin through the runner's
|
|
1605
|
-
* `input`, so no temp file is needed. The bytes reach git unchanged
|
|
1606
|
-
* (git's default `whitespace` cleanup still applies, exactly as for a
|
|
1607
|
-
* file): a missing trailing newline is not added here, git adds it.
|
|
1608
|
-
*/
|
|
1609
|
-
messageStdin: string
|
|
1610
|
-
message?: undefined
|
|
1611
|
-
body?: undefined
|
|
1612
|
-
messageFile?: undefined
|
|
1613
|
-
}
|
|
1614
|
-
)
|
|
1615
|
-
|
|
1616
|
-
/**
|
|
1617
|
-
* Commit with an inline message, a message file, or a stdin message (exactly
|
|
1618
|
-
* one source).
|
|
1619
|
-
*
|
|
1620
|
-
* `absent: []`. A failing commit hook is a failure, not an answer — and its
|
|
1621
|
-
* output goes to **stdout**, so a caller that must report it reads
|
|
1622
|
-
* `e.result.stdout`, not stderr.
|
|
1623
|
-
*/
|
|
1624
|
-
export function commit(opts: CommitOptions): GitVerb<void> {
|
|
1625
|
-
const argv = ['commit']
|
|
1626
|
-
if (opts.allowEmpty) argv.push('--allow-empty')
|
|
1627
|
-
if (opts.amend) argv.push('--amend')
|
|
1628
|
-
if (opts.noVerify) argv.push('--no-verify')
|
|
1629
|
-
if (opts.signoff) argv.push('--signoff')
|
|
1630
|
-
if (opts.messageStdin !== undefined) {
|
|
1631
|
-
argv.push('-F', '-')
|
|
1632
|
-
return { argv, input: opts.messageStdin, absent: NONE, parse: nothing }
|
|
1633
|
-
}
|
|
1634
|
-
if (opts.messageFile !== undefined) argv.push('-F', opts.messageFile)
|
|
1635
|
-
else {
|
|
1636
|
-
argv.push('-m', opts.message ?? '')
|
|
1637
|
-
if (opts.body !== undefined) argv.push('-m', opts.body)
|
|
1638
|
-
}
|
|
1639
|
-
return { argv, absent: NONE, parse: nothing }
|
|
1640
|
-
}
|
|
1641
|
-
|
|
1642
|
-
/** Options for {@link configSet}. */
|
|
1643
|
-
export interface ConfigSetOptions {
|
|
1644
|
-
/**
|
|
1645
|
-
* Which file to write. Omitted means git's default: `--local` inside a
|
|
1646
|
-
* repository, something else outside one.
|
|
1647
|
-
*/
|
|
1648
|
-
scope?: ConfigScope | undefined
|
|
1649
|
-
}
|
|
1650
|
-
|
|
1651
|
-
/** `git config <key> <value>` — the write twin of {@link configGet}. */
|
|
1652
|
-
export function configSet(key: string, value: string, opts: ConfigSetOptions = {}): GitVerb<void> {
|
|
1653
|
-
const argv = ['config']
|
|
1654
|
-
if (opts.scope !== undefined) argv.push(`--${opts.scope}`)
|
|
1655
|
-
argv.push(positional('configSet', 'key', key), value)
|
|
1656
|
-
return { argv, absent: NONE, parse: nothing }
|
|
1657
|
-
}
|
|
1658
|
-
|
|
1659
|
-
/**
|
|
1660
|
-
* `git config --remove-section <name>`: true when removed, false when there was
|
|
1661
|
-
* no such section. `absent: [128]` also covers "not a repository", which git
|
|
1662
|
-
* spells the same way, so `false` can also mean git could not ask. It is a
|
|
1663
|
-
* mutation, so it has no `soft` form.
|
|
1664
|
-
*/
|
|
1665
|
-
export function configRemoveSection(name: string): GitVerb<boolean> {
|
|
1666
|
-
return {
|
|
1667
|
-
argv: ['config', '--remove-section', positional('configRemoveSection', 'name', name)],
|
|
1668
|
-
absent: [128],
|
|
1669
|
-
parse: (r) => r.exitCode === 0,
|
|
1670
|
-
}
|
|
1671
|
-
}
|
|
1672
|
-
|
|
1673
|
-
/** Options for {@link init}. */
|
|
1674
|
-
export interface InitOptions {
|
|
1675
|
-
/** `--bare` — a store with no working tree. */
|
|
1676
|
-
bare?: boolean | undefined
|
|
1677
|
-
/** `-b` — the initial branch name, rather than git's configured default. */
|
|
1678
|
-
initialBranch?: string | undefined
|
|
1679
|
-
/** `--quiet` — suppress the "Initialized empty repository" line. */
|
|
1680
|
-
quiet?: boolean | undefined
|
|
1681
|
-
}
|
|
1682
|
-
|
|
1683
|
-
/**
|
|
1684
|
-
* `git init [path]`. `path` defaults to the client's `cwd`.
|
|
1685
|
-
*
|
|
1686
|
-
* Pass `initialBranch`: without it the branch name comes from the developer's
|
|
1687
|
-
* `init.defaultBranch`, so a fixture assuming `main` fails on some machines.
|
|
1688
|
-
*/
|
|
1689
|
-
export function init(path?: string | undefined, opts: InitOptions = {}): GitVerb<void> {
|
|
1690
|
-
const argv = ['init']
|
|
1691
|
-
if (opts.quiet) argv.push('--quiet')
|
|
1692
|
-
if (opts.bare) argv.push('--bare')
|
|
1693
|
-
if (opts.initialBranch !== undefined) argv.push('-b', opts.initialBranch)
|
|
1694
|
-
const target = optionalPositional('init', 'path', path)
|
|
1695
|
-
if (target !== undefined) argv.push(target)
|
|
1696
|
-
return { argv, absent: NONE, parse: nothing }
|
|
1697
|
-
}
|
|
1698
|
-
|
|
1699
|
-
/** Options for {@link clone}. */
|
|
1700
|
-
export interface CloneOptions {
|
|
1701
|
-
/**
|
|
1702
|
-
* `--depth=<n>` — a shallow clone with that much history. Anything but a
|
|
1703
|
-
* positive integer throws a `TypeError`.
|
|
1704
|
-
*/
|
|
1705
|
-
depth?: number | undefined
|
|
1706
|
-
/**
|
|
1707
|
-
* `--branch <ref>` — the branch or tag to land on.
|
|
1708
|
-
*
|
|
1709
|
-
* A commit sha is NOT a `--branch` argument: git refuses one. Clone
|
|
1710
|
-
* without it and `checkout` the sha afterwards.
|
|
1711
|
-
*/
|
|
1712
|
-
branch?: string | undefined
|
|
1713
|
-
/** `--bare` — a store with no working tree. */
|
|
1714
|
-
bare?: boolean | undefined
|
|
1715
|
-
/**
|
|
1716
|
-
* `--mirror` — a bare store that copies every ref of the source, and whose
|
|
1717
|
-
* `fetch` overwrites them. Implies `bare`.
|
|
1718
|
-
*
|
|
1719
|
-
* Its refspec `+refs/*:refs/*` covers every ref, tags included. So with
|
|
1720
|
-
* `mirror`, `noTags` has no effect, and `singleBranch` holds for the clone
|
|
1721
|
-
* only: a later fetch gets every ref. git refuses `mirror` with `branch`
|
|
1722
|
-
* (exit 128).
|
|
1723
|
-
*/
|
|
1724
|
-
mirror?: boolean | undefined
|
|
1725
|
-
/** `--single-branch` — fetch only the branch the clone lands on. */
|
|
1726
|
-
singleBranch?: boolean | undefined
|
|
1727
|
-
/** `--no-tags` — fetch no tags, now or on a later fetch. */
|
|
1728
|
-
noTags?: boolean | undefined
|
|
1729
|
-
/** `--quiet` — suppress the progress lines. */
|
|
1730
|
-
quiet?: boolean | undefined
|
|
1731
|
-
}
|
|
1732
|
-
|
|
1733
|
-
/**
|
|
1734
|
-
* `git clone [--depth=n] [--branch ref] [--bare|--mirror] <url> [dest]`.
|
|
1735
|
-
*
|
|
1736
|
-
* The one verb in this table that does not run inside a repository — it
|
|
1737
|
-
* makes one. A client's `cwd` is where a relative `dest` resolves, and both
|
|
1738
|
-
* clients bind it the same way they bind every other call.
|
|
1739
|
-
*/
|
|
1740
|
-
export function clone(
|
|
1741
|
-
url: string,
|
|
1742
|
-
dest?: string | undefined,
|
|
1743
|
-
opts: CloneOptions = {},
|
|
1744
|
-
): GitVerb<void> {
|
|
1745
|
-
const argv = ['clone']
|
|
1746
|
-
if (opts.quiet) argv.push('--quiet')
|
|
1747
|
-
if (opts.bare) argv.push('--bare')
|
|
1748
|
-
if (opts.mirror) argv.push('--mirror')
|
|
1749
|
-
if (opts.singleBranch) argv.push('--single-branch')
|
|
1750
|
-
if (opts.noTags) argv.push('--no-tags')
|
|
1751
|
-
if (opts.depth !== undefined) argv.push(depthArg('clone', opts.depth))
|
|
1752
|
-
if (opts.branch !== undefined) argv.push('--branch', opts.branch)
|
|
1753
|
-
argv.push(positional('clone', 'url', url))
|
|
1754
|
-
const target = optionalPositional('clone', 'dest', dest)
|
|
1755
|
-
if (target !== undefined) argv.push(target)
|
|
1756
|
-
return { argv, absent: NONE, parse: nothing }
|
|
1757
|
-
}
|
|
1758
|
-
|
|
1759
|
-
/**
|
|
1760
|
-
* A pinned `--force-with-lease`: `ref` must still be at `expect` for the push
|
|
1761
|
-
* to go through. `expect: null` pins "the ref does not exist", which is what a
|
|
1762
|
-
* create-only push wants.
|
|
1763
|
-
*/
|
|
1764
|
-
export interface ForceLease {
|
|
1765
|
-
/** Full remote ref, e.g. `refs/heads/feature`. */
|
|
1766
|
-
readonly ref: string
|
|
1767
|
-
/** The object id the remote ref is expected to hold; `null` for "absent". */
|
|
1768
|
-
readonly expect: string | null
|
|
1769
|
-
}
|
|
1770
|
-
|
|
1771
|
-
/**
|
|
1772
|
-
* The `--force-with-lease=<ref>:<oid>` argument for `lease`. Pure, so display
|
|
1773
|
-
* text (a plan's command line) can share the exact spelling that is executed.
|
|
1774
|
-
*
|
|
1775
|
-
* An empty `ref` or `expect` is refused: the empty-oid spelling means "ref
|
|
1776
|
-
* must be absent", and reaching it from a missing sha by accident would turn
|
|
1777
|
-
* an intended pin into the wrong guard. Absence is only ever `expect: null`.
|
|
1778
|
-
*/
|
|
1779
|
-
export function forceWithLeaseArg(lease: ForceLease): string {
|
|
1780
|
-
if (lease.ref === '') throw new Error('force-with-lease: ref is empty')
|
|
1781
|
-
if (lease.expect === '') {
|
|
1782
|
-
throw new Error(`force-with-lease: empty expected oid for ${lease.ref}; use null for "absent"`)
|
|
1783
|
-
}
|
|
1784
|
-
return `--force-with-lease=${lease.ref}:${lease.expect ?? ''}`
|
|
1785
|
-
}
|
|
1786
|
-
|
|
1787
|
-
/**
|
|
1788
|
-
* Push a refspec.
|
|
1789
|
-
*
|
|
1790
|
-
* `forceWithLease` takes a {@link ForceLease} for the pinned form, or `true`
|
|
1791
|
-
* for the bare `--force-with-lease`. `true` is the unsafe form. It trusts
|
|
1792
|
-
* whatever the local remote-tracking ref says, and a background fetch can
|
|
1793
|
-
* bring that up to date. The lease then vetoes nothing, and a concurrent push
|
|
1794
|
-
* is erased. Pin the lease whenever the expected remote sha is known.
|
|
1795
|
-
*/
|
|
1796
|
-
export function push(
|
|
1797
|
-
remote: string,
|
|
1798
|
-
refspec: string,
|
|
1799
|
-
opts: { forceWithLease?: boolean | ForceLease | undefined } = {},
|
|
1800
|
-
): GitVerb<void> {
|
|
1801
|
-
const argv = ['push']
|
|
1802
|
-
const lease = opts.forceWithLease
|
|
1803
|
-
if (lease === true) argv.push('--force-with-lease')
|
|
1804
|
-
else if (typeof lease === 'object' && lease !== null) argv.push(forceWithLeaseArg(lease))
|
|
1805
|
-
else if (lease !== undefined && lease !== false) {
|
|
1806
|
-
throw new Error(`force-with-lease: unsupported value ${JSON.stringify(lease)}`)
|
|
1807
|
-
}
|
|
1808
|
-
argv.push(positional('push', 'remote', remote), positional('push', 'refspec', refspec))
|
|
1809
|
-
return { argv, absent: NONE, parse: nothing }
|
|
1810
|
-
}
|
|
1811
|
-
|
|
1812
|
-
/** `git reset --hard <rev>`. */
|
|
1813
|
-
export function resetHard(rev: string): GitVerb<void> {
|
|
1814
|
-
return {
|
|
1815
|
-
argv: ['reset', '--hard', positional('resetHard', 'rev', rev)],
|
|
1816
|
-
absent: NONE,
|
|
1817
|
-
parse: nothing,
|
|
1818
|
-
}
|
|
1819
|
-
}
|
|
1820
|
-
|
|
1821
|
-
/** Options for {@link clean}. */
|
|
1822
|
-
export interface CleanOptions {
|
|
1823
|
-
/** `-d` — also delete untracked directories. */
|
|
1824
|
-
directories?: boolean | undefined
|
|
1825
|
-
}
|
|
1826
|
-
|
|
1827
|
-
/**
|
|
1828
|
-
* `git clean -f`: delete untracked files, and untracked directories with
|
|
1829
|
-
* `{directories: true}`. Ignored files are kept.
|
|
1830
|
-
*/
|
|
1831
|
-
export function clean(opts: CleanOptions = {}): GitVerb<void> {
|
|
1832
|
-
return { argv: ['clean', opts.directories ? '-fd' : '-f'], absent: NONE, parse: nothing }
|
|
1833
|
-
}
|
|
1834
|
-
|
|
1835
|
-
/** Delete a local branch (`-d`, or `-D` with `{force: true}`). */
|
|
1836
|
-
export function deleteBranch(
|
|
1837
|
-
name: string,
|
|
1838
|
-
opts: { force?: boolean | undefined } = {},
|
|
1839
|
-
): GitVerb<void> {
|
|
1840
|
-
return {
|
|
1841
|
-
argv: ['branch', opts.force ? '-D' : '-d', positional('deleteBranch', 'name', name)],
|
|
1842
|
-
absent: NONE,
|
|
1843
|
-
parse: nothing,
|
|
1844
|
-
}
|
|
1845
|
-
}
|
|
1846
|
-
|
|
1847
|
-
/**
|
|
1848
|
-
* `git update-ref -d <ref> <expected>`: delete `ref` only while it still
|
|
1849
|
-
* points at `expected`, so a commit pushed after the caller looked is never
|
|
1850
|
-
* lost. Unlike `branch -d`, git does not refuse a branch checked out in a
|
|
1851
|
-
* worktree; the caller must rule that out. It also leaves the branch's
|
|
1852
|
-
* `branch.<name>.*` config section in place.
|
|
1853
|
-
*/
|
|
1854
|
-
export function deleteRef(ref: string, opts: { expected: string }): GitVerb<void> {
|
|
1855
|
-
return {
|
|
1856
|
-
argv: [
|
|
1857
|
-
'update-ref',
|
|
1858
|
-
'-d',
|
|
1859
|
-
positional('deleteRef', 'ref', ref),
|
|
1860
|
-
positional('deleteRef', 'expected', opts.expected),
|
|
1861
|
-
],
|
|
1862
|
-
absent: NONE,
|
|
1863
|
-
parse: nothing,
|
|
1864
|
-
}
|
|
1865
|
-
}
|
|
1866
|
-
|
|
1867
|
-
/** `git worktree add [--detach] [-b branch] <path> [startPoint]`. */
|
|
1868
|
-
export function worktreeAdd(
|
|
1869
|
-
path: string,
|
|
1870
|
-
opts: {
|
|
1871
|
-
branch?: string | undefined
|
|
1872
|
-
startPoint?: string | undefined
|
|
1873
|
-
detach?: boolean | undefined
|
|
1874
|
-
} = {},
|
|
1875
|
-
): GitVerb<void> {
|
|
1876
|
-
const argv = ['worktree', 'add']
|
|
1877
|
-
if (opts.detach) argv.push('--detach')
|
|
1878
|
-
if (opts.branch !== undefined) argv.push('-b', opts.branch)
|
|
1879
|
-
argv.push(positional('worktreeAdd', 'path', path))
|
|
1880
|
-
const start = optionalPositional('worktreeAdd', 'startPoint', opts.startPoint)
|
|
1881
|
-
if (start !== undefined) argv.push(start)
|
|
1882
|
-
return { argv, absent: NONE, parse: nothing }
|
|
1883
|
-
}
|
|
1884
|
-
|
|
1885
|
-
/** `git worktree remove [--force] <path>`. */
|
|
1886
|
-
export function worktreeRemove(
|
|
1887
|
-
path: string,
|
|
1888
|
-
opts: { force?: boolean | undefined } = {},
|
|
1889
|
-
): GitVerb<void> {
|
|
1890
|
-
const argv = ['worktree', 'remove']
|
|
1891
|
-
if (opts.force) argv.push('--force')
|
|
1892
|
-
argv.push(positional('worktreeRemove', 'path', path))
|
|
1893
|
-
return { argv, absent: NONE, parse: nothing }
|
|
1894
|
-
}
|
|
1895
|
-
|
|
1896
|
-
/** Options for {@link worktreeMove}. */
|
|
1897
|
-
export interface WorktreeMoveOptions {
|
|
1898
|
-
/** `--force` — move even when the worktree is dirty or locked. */
|
|
1899
|
-
force?: boolean | undefined
|
|
1900
|
-
}
|
|
1901
|
-
|
|
1902
|
-
/** `git worktree move [--force] <from> <to>`. */
|
|
1903
|
-
export function worktreeMove(
|
|
1904
|
-
from: string,
|
|
1905
|
-
to: string,
|
|
1906
|
-
opts: WorktreeMoveOptions = {},
|
|
1907
|
-
): GitVerb<void> {
|
|
1908
|
-
const argv = ['worktree', 'move']
|
|
1909
|
-
if (opts.force) argv.push('--force')
|
|
1910
|
-
argv.push(positional('worktreeMove', 'from', from), positional('worktreeMove', 'to', to))
|
|
1911
|
-
return { argv, absent: NONE, parse: nothing }
|
|
1912
|
-
}
|
|
1913
|
-
|
|
1914
|
-
/** `git worktree prune`. */
|
|
1915
|
-
export function worktreePrune(): GitVerb<void> {
|
|
1916
|
-
return { argv: ['worktree', 'prune'], absent: NONE, parse: nothing }
|
|
1917
|
-
}
|
|
1918
|
-
|
|
1919
|
-
/** `git remote add <name> <url>`. */
|
|
1920
|
-
export function remoteAdd(name: string, url: string): GitVerb<void> {
|
|
1921
|
-
return {
|
|
1922
|
-
argv: [
|
|
1923
|
-
'remote',
|
|
1924
|
-
'add',
|
|
1925
|
-
positional('remoteAdd', 'name', name),
|
|
1926
|
-
positional('remoteAdd', 'url', url),
|
|
1927
|
-
],
|
|
1928
|
-
absent: NONE,
|
|
1929
|
-
parse: nothing,
|
|
1930
|
-
}
|
|
1931
|
-
}
|
|
1932
|
-
|
|
1933
|
-
// ── integration ─────────────────────────────────────────────────────────────
|
|
1934
|
-
//
|
|
1935
|
-
// `merge` and `rebase` are the verbs where a non-zero exit carries the answer:
|
|
1936
|
-
// a conflict is the outcome a caller asked about, not a failure to report. So
|
|
1937
|
-
// exit 1 is declared absent and the parse turns it into a `conflict` outcome.
|
|
1938
|
-
//
|
|
1939
|
-
// Which is only safe because the parse looks past the exit code. Measured
|
|
1940
|
-
// against git 2.50.1, and the assumptions did not survive:
|
|
1941
|
-
//
|
|
1942
|
-
// git merge, conflict 1 (stdout carries the report)
|
|
1943
|
-
// git merge, unknown ref 1 (stdout empty)
|
|
1944
|
-
// git merge, would overwrite local edits 2
|
|
1945
|
-
// git merge, merge already in progress 128
|
|
1946
|
-
// git merge, unrelated histories 128
|
|
1947
|
-
// git merge, outside a repository 128
|
|
1948
|
-
// git rebase, conflict 1
|
|
1949
|
-
// git rebase --continue, still conflicted 1
|
|
1950
|
-
// git rebase, unknown ref 128
|
|
1951
|
-
// git rebase/merge --abort, none running 128
|
|
1952
|
-
//
|
|
1953
|
-
// An unknown ref exits 1 exactly like a conflict, so the exit code alone
|
|
1954
|
-
// cannot tell them apart. The discriminator is that a conflict always writes
|
|
1955
|
-
// its report to stdout and a refusal writes nothing there — a structural
|
|
1956
|
-
// signal rather than a string match.
|
|
1957
|
-
//
|
|
1958
|
-
// `fastForward`, `alreadyUpToDate` and the conflict list do read git's text.
|
|
1959
|
-
// That text is translatable, so `merge`, `rebase` and `rebaseContinue` run
|
|
1960
|
-
// with `LC_ALL=C`, and a caller's locale does not change an outcome.
|
|
1961
|
-
|
|
1962
|
-
/** How an integration attempt ended. */
|
|
1963
|
-
export type IntegrationOutcome<Extra> =
|
|
1964
|
-
| ({ status: 'clean' } & Extra)
|
|
1965
|
-
/**
|
|
1966
|
-
* Conflicted. `conflicts` is a best-effort read of git's own report. It has
|
|
1967
|
-
* no parseable form for rename/rename or rename/delete, so it can be empty
|
|
1968
|
-
* on a real conflict. Ask
|
|
1969
|
-
* {@link lsFilesUnmerged} or `diffNameOnly({ diffFilter: "U" })` for the
|
|
1970
|
-
* authoritative list.
|
|
1971
|
-
*/
|
|
1972
|
-
| { status: 'conflict'; conflicts: string[] }
|
|
1973
|
-
|
|
1974
|
-
export type MergeOutcome = IntegrationOutcome<{
|
|
1975
|
-
fastForward: boolean
|
|
1976
|
-
alreadyUpToDate: boolean
|
|
1977
|
-
}>
|
|
1978
|
-
|
|
1979
|
-
export type RebaseOutcome = IntegrationOutcome<{ alreadyUpToDate: boolean }>
|
|
1980
|
-
|
|
1981
|
-
/** `CONFLICT (content|add/add|…): Merge conflict in <path>` */
|
|
1982
|
-
const CONFLICT_MERGE_IN = /^CONFLICT \([^)]*\): Merge conflict in (.+)$/
|
|
1983
|
-
/** `CONFLICT (modify/delete): <path> deleted in <x> and modified in <y>…` */
|
|
1984
|
-
const CONFLICT_MODIFY_DELETE = /^CONFLICT \(modify\/delete\): (.+?) deleted in .+? and modified in /
|
|
1985
|
-
|
|
1986
|
-
/** Paths git named in its own conflict report. Best effort — see the type. */
|
|
1987
|
-
function conflictPaths(stdout: string): string[] {
|
|
1988
|
-
const seen = new Set<string>()
|
|
1989
|
-
for (const line of stdout.split('\n')) {
|
|
1990
|
-
const m = CONFLICT_MERGE_IN.exec(line) ?? CONFLICT_MODIFY_DELETE.exec(line)
|
|
1991
|
-
if (m?.[1] !== undefined) seen.add(m[1])
|
|
1992
|
-
}
|
|
1993
|
-
return [...seen]
|
|
1994
|
-
}
|
|
1995
|
-
|
|
1996
|
-
/**
|
|
1997
|
-
* Read an exit-1 integration result: a conflict, or a refusal that must throw.
|
|
1998
|
-
*
|
|
1999
|
-
* Empty stdout means git declined before it started merging — an unknown ref,
|
|
2000
|
-
* a name it cannot resolve. That is not an answer, so it fails like any other
|
|
2001
|
-
* broken invocation.
|
|
2002
|
-
*/
|
|
2003
|
-
function conflictOrThrow(
|
|
2004
|
-
argv: string[],
|
|
2005
|
-
r: CommandResult,
|
|
2006
|
-
): { status: 'conflict'; conflicts: string[] } {
|
|
2007
|
-
if (r.stdout.trim() === '') throw new CommandFailed(argv, r)
|
|
2008
|
-
return { status: 'conflict', conflicts: conflictPaths(r.stdout) }
|
|
2009
|
-
}
|
|
2010
|
-
|
|
2011
|
-
/** Options for {@link merge}. */
|
|
2012
|
-
export interface MergeOptions {
|
|
2013
|
-
/** `--no-ff` — always record a merge commit, even where a fast-forward fits. */
|
|
2014
|
-
noFf?: boolean | undefined
|
|
2015
|
-
/** `--no-commit` — merge the trees but leave the commit to the caller. */
|
|
2016
|
-
noCommit?: boolean | undefined
|
|
2017
|
-
/** `--ff-only` — refuse (exit 128) unless the merge is a fast-forward. */
|
|
2018
|
-
ffOnly?: boolean | undefined
|
|
2019
|
-
/** `-m` — the merge commit's message. */
|
|
2020
|
-
message?: string | undefined
|
|
2021
|
-
}
|
|
2022
|
-
|
|
2023
|
-
/**
|
|
2024
|
-
* Merge `ref` into the current branch (`git merge --no-edit`).
|
|
2025
|
-
*
|
|
2026
|
-
* `--no-edit` is unconditional: an editor prompt in a non-interactive caller
|
|
2027
|
-
* is a hang, not a prompt.
|
|
2028
|
-
*
|
|
2029
|
-
* `absent: [1]` — a conflict is this verb's "asked and answered". See the
|
|
2030
|
-
* section note above for the measured codes and why the parse looks at
|
|
2031
|
-
* stdout rather than trusting the exit code alone.
|
|
2032
|
-
*/
|
|
2033
|
-
export function merge(ref: string, opts: MergeOptions = {}): GitVerb<MergeOutcome> {
|
|
2034
|
-
const argv = ['merge', '--no-edit']
|
|
2035
|
-
if (opts.noFf) argv.push('--no-ff')
|
|
2036
|
-
if (opts.noCommit) argv.push('--no-commit')
|
|
2037
|
-
if (opts.ffOnly) argv.push('--ff-only')
|
|
2038
|
-
if (opts.message !== undefined) argv.push('-m', opts.message)
|
|
2039
|
-
argv.push(positional('merge', 'ref', ref))
|
|
2040
|
-
const verb: GitVerb<MergeOutcome> = {
|
|
2041
|
-
argv,
|
|
2042
|
-
env: C_LOCALE,
|
|
2043
|
-
absent: [1],
|
|
2044
|
-
parse(r, ranArgv) {
|
|
2045
|
-
if (r.exitCode !== 0) return conflictOrThrow(ranArgv, r)
|
|
2046
|
-
return {
|
|
2047
|
-
status: 'clean',
|
|
2048
|
-
fastForward: /^Fast-forward$/m.test(r.stdout),
|
|
2049
|
-
alreadyUpToDate: /^Already up[- ]to[- ]date\.?$/m.test(r.stdout),
|
|
2050
|
-
}
|
|
2051
|
-
},
|
|
2052
|
-
}
|
|
2053
|
-
return verb
|
|
2054
|
-
}
|
|
2055
|
-
|
|
2056
|
-
/**
|
|
2057
|
-
* `git merge --abort`.
|
|
2058
|
-
*
|
|
2059
|
-
* `absent: []` — exit 128 means no merge was in progress, and a caller that
|
|
2060
|
-
* asked to abort one has been told something it did not know.
|
|
2061
|
-
*/
|
|
2062
|
-
export function mergeAbort(): GitVerb<void> {
|
|
2063
|
-
return { argv: ['merge', '--abort'], absent: NONE, parse: nothing }
|
|
2064
|
-
}
|
|
2065
|
-
|
|
2066
|
-
/** Options for {@link rebase}. */
|
|
2067
|
-
export interface RebaseOptions {
|
|
2068
|
-
/** `--autostash` — shelve and restore a dirty tree around the replay. */
|
|
2069
|
-
autostash?: boolean | undefined
|
|
2070
|
-
}
|
|
2071
|
-
|
|
2072
|
-
/**
|
|
2073
|
-
* Replay the current branch onto `onto` (`git rebase`).
|
|
2074
|
-
*
|
|
2075
|
-
* `absent: [1]` for the same reason as {@link merge}. An unknown ref exits
|
|
2076
|
-
* 128 here rather than 1, so this verb is the less ambiguous of the two —
|
|
2077
|
-
* the stdout check costs nothing and keeps the two parses identical.
|
|
2078
|
-
*/
|
|
2079
|
-
export function rebase(onto: string, opts: RebaseOptions = {}): GitVerb<RebaseOutcome> {
|
|
2080
|
-
const argv = ['rebase']
|
|
2081
|
-
if (opts.autostash) argv.push('--autostash')
|
|
2082
|
-
argv.push(positional('rebase', 'onto', onto))
|
|
2083
|
-
const verb: GitVerb<RebaseOutcome> = {
|
|
2084
|
-
argv,
|
|
2085
|
-
env: C_LOCALE,
|
|
2086
|
-
absent: [1],
|
|
2087
|
-
parse(r, ranArgv) {
|
|
2088
|
-
if (r.exitCode !== 0) return conflictOrThrow(ranArgv, r)
|
|
2089
|
-
return {
|
|
2090
|
-
status: 'clean',
|
|
2091
|
-
alreadyUpToDate: /is up to date/m.test(r.stdout),
|
|
2092
|
-
}
|
|
2093
|
-
},
|
|
2094
|
-
}
|
|
2095
|
-
return verb
|
|
2096
|
-
}
|
|
2097
|
-
|
|
2098
|
-
/** `git rebase --abort`. `absent: []` — 128 means no rebase was running. */
|
|
2099
|
-
export function rebaseAbort(): GitVerb<void> {
|
|
2100
|
-
return { argv: ['rebase', '--abort'], absent: NONE, parse: nothing }
|
|
2101
|
-
}
|
|
2102
|
-
|
|
2103
|
-
/**
|
|
2104
|
-
* `git rebase --continue`, with the editor stubbed out.
|
|
2105
|
-
*
|
|
2106
|
-
* `-c core.editor=true` rather than an environment variable: the verb table
|
|
2107
|
-
* describes an invocation, and git's own config override keeps that
|
|
2108
|
-
* description complete.
|
|
2109
|
-
*
|
|
2110
|
-
* `absent: [1]` — the replay can conflict again on the next commit, which is
|
|
2111
|
-
* an answer, not a failure.
|
|
2112
|
-
*/
|
|
2113
|
-
export function rebaseContinue(): GitVerb<RebaseOutcome> {
|
|
2114
|
-
const verb: GitVerb<RebaseOutcome> = {
|
|
2115
|
-
argv: ['-c', 'core.editor=true', 'rebase', '--continue'],
|
|
2116
|
-
env: C_LOCALE,
|
|
2117
|
-
absent: [1],
|
|
2118
|
-
parse(r, ranArgv) {
|
|
2119
|
-
if (r.exitCode !== 0) return conflictOrThrow(ranArgv, r)
|
|
2120
|
-
return { status: 'clean', alreadyUpToDate: false }
|
|
2121
|
-
},
|
|
2122
|
-
}
|
|
2123
|
-
return verb
|
|
2124
|
-
}
|
|
2125
|
-
|
|
2126
|
-
/**
|
|
2127
|
-
* How a merge would end, computed without a working tree.
|
|
2128
|
-
*
|
|
2129
|
-
* `tree` is the merged tree git wrote to the object database — real enough to
|
|
2130
|
-
* hand to `commit-tree`, so a clean prediction is also the whole answer: a
|
|
2131
|
-
* caller that only needs the merge commit never checks anything out. On a
|
|
2132
|
-
* conflict the tree holds the conflict-marked blobs instead.
|
|
2133
|
-
*/
|
|
2134
|
-
export type MergeTreeOutcome =
|
|
2135
|
-
| { status: 'clean'; tree: string }
|
|
2136
|
-
/** Unlike {@link MergeOutcome}, `conflicts` is git's own list — see {@link mergeTree}. */
|
|
2137
|
-
| { status: 'conflict'; tree: string; conflicts: string[] }
|
|
2138
|
-
|
|
2139
|
-
/** Options for {@link mergeTree}. */
|
|
2140
|
-
export interface MergeTreeOptions {
|
|
2141
|
-
/** `--merge-base=<ref>` — fix the base instead of letting git pick it. */
|
|
2142
|
-
mergeBase?: string | undefined
|
|
2143
|
-
}
|
|
2144
|
-
|
|
2145
|
-
/**
|
|
2146
|
-
* `git merge-tree --write-tree`: what merging `theirs` into `ours` would do,
|
|
2147
|
-
* against the object database alone — no index, no checkout, no worktree.
|
|
2148
|
-
*
|
|
2149
|
-
* The cheap half of {@link merge}. Predicting every open PR's merge across a
|
|
2150
|
-
* 10,000-file monorepo costs seconds here; checking each one out to learn the
|
|
2151
|
-
* same thing costs minutes, and most of them turn out to merge cleanly.
|
|
2152
|
-
*
|
|
2153
|
-
* `-z` rather than the plain listing: otherwise git C-quotes any path that
|
|
2154
|
-
* needs it (`"w\303\251ird \"name\".txt"`), and a caller matching those
|
|
2155
|
-
* strings against real paths silently misses the files most worth attention.
|
|
2156
|
-
*
|
|
2157
|
-
* Unlike {@link merge}, the conflict list is authoritative — git names the
|
|
2158
|
-
* paths in a machine-readable section rather than in translatable prose — so
|
|
2159
|
-
* there is no need to follow up with {@link lsFilesUnmerged}.
|
|
2160
|
-
*
|
|
2161
|
-
* `absent: [1]`, with this section's usual discriminator. Measured against
|
|
2162
|
-
* git 2.50.1:
|
|
2163
|
-
*
|
|
2164
|
-
* clean 0 `<tree>`
|
|
2165
|
-
* conflict 1 `<tree>` then the conflicted paths
|
|
2166
|
-
* unmergeable name 1 stdout empty
|
|
2167
|
-
* unrelated histories 128
|
|
2168
|
-
*
|
|
2169
|
-
* A name git cannot merge exits 1 exactly like a conflict, so once again only
|
|
2170
|
-
* stdout separates an answer from a refusal.
|
|
2171
|
-
*/
|
|
2172
|
-
export function mergeTree(
|
|
2173
|
-
ours: string,
|
|
2174
|
-
theirs: string,
|
|
2175
|
-
opts: MergeTreeOptions = {},
|
|
2176
|
-
): GitVerb<MergeTreeOutcome> {
|
|
2177
|
-
const argv = ['merge-tree', '--write-tree', '--name-only', '-z']
|
|
2178
|
-
if (opts.mergeBase !== undefined) argv.push(`--merge-base=${opts.mergeBase}`)
|
|
2179
|
-
argv.push(positional('mergeTree', 'ours', ours), positional('mergeTree', 'theirs', theirs))
|
|
2180
|
-
return {
|
|
2181
|
-
argv,
|
|
2182
|
-
absent: [1],
|
|
2183
|
-
parse(r, ranArgv) {
|
|
2184
|
-
const fields = r.stdout.split('\x00')
|
|
2185
|
-
const tree = fields[0] ?? ''
|
|
2186
|
-
if (tree === '') throw new CommandFailed(ranArgv, r)
|
|
2187
|
-
if (r.exitCode === 0) return { status: 'clean', tree }
|
|
2188
|
-
// `<tree>\0<path>\0…\0\0<info records>` — the paths run to the first
|
|
2189
|
-
// empty field, which is what separates them from git's own commentary.
|
|
2190
|
-
const conflicts: string[] = []
|
|
2191
|
-
for (const field of fields.slice(1)) {
|
|
2192
|
-
if (field === '') break
|
|
2193
|
-
conflicts.push(field)
|
|
2194
|
-
}
|
|
2195
|
-
return { status: 'conflict', tree, conflicts }
|
|
2196
|
-
},
|
|
2197
|
-
}
|
|
2198
|
-
}
|
|
2199
|
-
|
|
2200
|
-
// ── conflict inspection ─────────────────────────────────────────────────────
|
|
2201
|
-
|
|
2202
|
-
/** One `git ls-files -u` row — the same path appears once per present stage. */
|
|
2203
|
-
export interface UnmergedEntry {
|
|
2204
|
-
mode: string
|
|
2205
|
-
sha: string
|
|
2206
|
-
/** 1 = merge base, 2 = ours, 3 = theirs. */
|
|
2207
|
-
stage: 1 | 2 | 3
|
|
2208
|
-
path: string
|
|
2209
|
-
}
|
|
2210
|
-
|
|
2211
|
-
/** `<mode> <sha> <stage>\t<path>` */
|
|
2212
|
-
const UNMERGED_ROW = /^(\d+) ([0-9a-f]+) ([123])\t(.*)$/
|
|
2213
|
-
|
|
2214
|
-
/**
|
|
2215
|
-
* `git ls-files -u`, parsed — the stage detail behind a conflict.
|
|
2216
|
-
*
|
|
2217
|
-
* Which stages are present is what distinguishes the conflict shapes: all of
|
|
2218
|
-
* 1/2/3 is both-modified, 1+3 is we-deleted, 1+2 is they-deleted, and 2+3
|
|
2219
|
-
* with no base is add/add. A resolver that treats every conflict as
|
|
2220
|
-
* both-modified will delete files.
|
|
2221
|
-
*
|
|
2222
|
-
* `absent: []` — a tree with nothing unmerged is exit 0 and empty stdout, so
|
|
2223
|
-
* `[]` means "no conflicts". Outside a repository git exits 128 and this
|
|
2224
|
-
* throws: a resolver that cannot read the index has not "found no conflicts".
|
|
2225
|
-
*
|
|
2226
|
-
* For the paths alone, `diffNameOnly({ diffFilter: "U" })` is cheaper.
|
|
2227
|
-
*/
|
|
2228
|
-
export function lsFilesUnmerged(): GitVerb<UnmergedEntry[]> {
|
|
2229
|
-
return {
|
|
2230
|
-
argv: ['ls-files', '-u', '-z'],
|
|
2231
|
-
absent: NONE,
|
|
2232
|
-
parse(r) {
|
|
2233
|
-
const rows: UnmergedEntry[] = []
|
|
2234
|
-
for (const chunk of r.stdout.split('\x00')) {
|
|
2235
|
-
const m = UNMERGED_ROW.exec(chunk)
|
|
2236
|
-
if (m === null) continue
|
|
2237
|
-
rows.push({
|
|
2238
|
-
mode: m[1]!,
|
|
2239
|
-
sha: m[2]!,
|
|
2240
|
-
stage: Number(m[3]) as 1 | 2 | 3,
|
|
2241
|
-
path: m[4]!,
|
|
2242
|
-
})
|
|
2243
|
-
}
|
|
2244
|
-
return rows
|
|
2245
|
-
},
|
|
2246
|
-
}
|
|
2247
|
-
}
|
|
2248
|
-
|
|
2249
|
-
// ── checkout ────────────────────────────────────────────────────────────────
|
|
2250
|
-
|
|
2251
|
-
/** Which side of a conflict to take wholesale. */
|
|
2252
|
-
export type ConflictSide = 'ours' | 'theirs'
|
|
2253
|
-
|
|
2254
|
-
/**
|
|
2255
|
-
* `git checkout --ours|--theirs -- <paths>` — resolve paths to one side.
|
|
2256
|
-
*
|
|
2257
|
-
* `absent: []` — a checkout that did not happen is not an answer. Both
|
|
2258
|
-
* clients return without running git when `paths` is empty.
|
|
2259
|
-
*
|
|
2260
|
-
* Note the sharp edge git leaves here: on a path that is not conflicted this
|
|
2261
|
-
* exits 0 and does nothing. There is no error to catch, so a caller working
|
|
2262
|
-
* from a stale conflict list silently resolves nothing. Take the path list
|
|
2263
|
-
* from {@link lsFilesUnmerged} in the same breath, not from an earlier one.
|
|
2264
|
-
*/
|
|
2265
|
-
export function checkoutSide(side: ConflictSide, paths: string[]): GitVerb<void> {
|
|
2266
|
-
return {
|
|
2267
|
-
argv: ['checkout', `--${side}`, '--', ...paths],
|
|
2268
|
-
absent: NONE,
|
|
2269
|
-
parse: nothing,
|
|
2270
|
-
}
|
|
2271
|
-
}
|
|
2272
|
-
|
|
2273
|
-
/** Options for {@link checkout}. */
|
|
2274
|
-
export interface CheckoutOptions {
|
|
2275
|
-
/** Create (or with `resetBranch`, repoint) this branch at `ref`. */
|
|
2276
|
-
branch?: string | undefined
|
|
2277
|
-
/**
|
|
2278
|
-
* `-B` rather than `-b`: point an existing branch at `ref` instead of
|
|
2279
|
-
* failing because it exists. What reusing one worktree across many branches
|
|
2280
|
-
* needs.
|
|
2281
|
-
*/
|
|
2282
|
-
resetBranch?: boolean | undefined
|
|
2283
|
-
/** `--force` — discard local modifications rather than refusing. */
|
|
2284
|
-
force?: boolean | undefined
|
|
2285
|
-
}
|
|
2286
|
-
|
|
2287
|
-
/**
|
|
2288
|
-
* `git checkout [-f] [-b|-B <branch>] <ref>`.
|
|
2289
|
-
*
|
|
2290
|
-
* `absent: []` — an unknown ref exits 1 here, and a checkout that did not
|
|
2291
|
-
* happen leaves the caller on a branch it does not expect. That is a failure,
|
|
2292
|
-
* not an absence.
|
|
2293
|
-
*/
|
|
2294
|
-
export function checkout(ref: string, opts: CheckoutOptions = {}): GitVerb<void> {
|
|
2295
|
-
const argv = ['checkout']
|
|
2296
|
-
if (opts.force) argv.push('--force')
|
|
2297
|
-
if (opts.branch !== undefined) argv.push(opts.resetBranch ? '-B' : '-b', opts.branch)
|
|
2298
|
-
argv.push(positional('checkout', 'ref', ref))
|
|
2299
|
-
return { argv, absent: NONE, parse: nothing }
|
|
2300
|
-
}
|