@osdlc/typed-git 0.8.2 → 0.11.1

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 CHANGED
@@ -1,5 +1,67 @@
1
1
  # @osdlc/typed-git
2
2
 
3
+ ## 0.11.1
4
+
5
+ ### Patch Changes
6
+
7
+ - 7fe7f51: `parseRemoteRepo` reads `ssh.github.com` (GitHub's SSH over port 443) and `www.github.com` as `github.com`, so a remote on either names the same repository as one on `github.com`.
8
+
9
+ ## 0.11.0
10
+
11
+ ### Minor Changes
12
+
13
+ - 82d9841: Add `cherry(upstream, head?)` and `commitTree(tree, { parents, message })` to `Git` and `AsyncGit`.
14
+
15
+ - `cherry` runs `git cherry` and returns `{ sha, equivalent }` per commit on `head` that `upstream` lacks. Output it cannot read throws instead of being skipped. `soft.cherry` falls back to `[]`.
16
+ - `commitTree` runs `git commit-tree` and returns the new commit's sha. It writes an object and no ref, and needs a git identity. A reply that is not a sha throws.
17
+ - Both refuse a leading-dash revision before spawning, like the other revision-taking verbs.
18
+ - ebe0e0d: typed-git knows which git it runs, and which features need a newer one. The supported floor is git 2.34 (Ubuntu 22.04 LTS). One table, `GIT_FEATURES`, lists the features newer than that: `merge-tree --write-tree` (git 2.38), `merge-tree --merge-base` (2.40) and `worktree list -z` (2.36). The README's new "Git versions" section is checked against it.
19
+
20
+ - A verb that uses one of these features runs `git --version` first and caches it per runner and per effective `PATH`. Other verbs never run it. The probe runs in the OS temp directory, and a failed probe names the verb that asked (`git worktree: …`) and is not cached. Concurrent `AsyncGit` callers share one probe, which runs with no caller's signal and a fixed 15 s limit; each caller waits under its own `timeoutMs` and `signal`. The first gated call can take up to the probe's time plus its own `timeoutMs`. `git.version()` and `await asyncGit.version()` return the parsed version, `{ major, minor, patch, text }`, for plain, Apple (`2.39.3 (Apple Git-146)`), Windows (`2.45.1.windows.1`) and rc builds.
21
+ - **Breaking:** new `GitFailureKind` `unsupported-git`. On a git older than the feature, `mergeTree` fails with it before git runs ("merge-tree --write-tree needs git 2.38 or later; found 2.34.1."), where it failed as a generic `exit` with git's usage error. On a git older than 2.34, `worktrees()` and `mergeTree()` now fail as `unsupported-git` with the feature `typed-git`. `worktrees()` worked there before; a caller that used `git.soft.worktrees()` now gets `[]` on such a git, so do not read that `[]` as "no worktrees" where it matters. The failure carries `unsupported: { feature, needs, have }`. An exhaustive `switch` over `GitFailureKind` needs the new case. `git.try` returns it and `git.soft` falls back on it, like any other failure.
22
+ - **Breaking:** `GitFailure.cause` is now optional (`CommandFailed | undefined`), as in `@osdlc/typed-gh`. It is absent only for `unsupported-git`, where git did not run. Read `error.cause?.result`.
23
+ - `worktrees()` runs `worktree list --porcelain -z` on git 2.36 or later (#381). A path holding a newline parses, and `lockReason` is the reason as written, where it came back C-quoted. Older git runs the newline form as before.
24
+ - **Breaking for fake runners:** a `CommandRunner` behind `worktrees()` or `mergeTree()` is now also asked for `["--version"]`. To migrate, pin the version with the new `gitVersion` option: `new Git(cwd, { runner, gitVersion: '2.55.0' })` or `cliBackend({ runner, gitVersion: '2.55.0' })`. Gated verbs then use it and never run `git --version`, `version()` returns it, and `at()` keeps it. It takes `'2.55.0'` or a whole `git version …` line, and throws a `RangeError` at construction for anything else. A fake without the pin must answer `--version` with `git version <x.y.z>`; output that is not a version line fails as `exit`.
25
+ - `cliBackend` does the version check. A backend other than the CLI gets every request unchecked, and answers the new `version` request kind itself (`partialBackend` rejects it with `UnsupportedRequest` when it is not implemented).
26
+ - New exports: `GIT_FEATURES`, `GIT_FLOOR`, `gitSupports`, `parseGitVersion`, `compareGitVersions`, and the types `GitVersion`, `GitFeature`, `GitFeatureSpec`, `GitRelease` and `UnsupportedGit`.
27
+
28
+ ## 0.10.0
29
+
30
+ ### Minor Changes
31
+
32
+ - da5e6a3: New: `parseRemoteRepo(url)` reads a git remote into `{ host, owner, repo }` (type `RemoteRepo`), or null when it names no project. It reads a known host through `parseGitUrl` first (so shorthand reads as GitHub and a GitLab nested group stays whole in `owner`), then any other host through `parseRemoteUrl`, so a GitHub Enterprise or self-hosted Forgejo remote answers too. `host` is lower-cased and has no port. It is on the root entry, not `./client`.
33
+ The result gate, the `try` proxy, the start of `classifyGitFailure` and the leading-dash guard now use `@osdlc/command-seam`'s `runFailed`, `tryMethods`, `methodFacade`, `classifyFailed` and `notAnOption`. Nothing a caller sees changes: the same failures, the same `TypeError` and message for a positional that starts with `-`.
34
+
35
+ ### Patch Changes
36
+
37
+ - Updated dependencies [da5e6a3]
38
+ - @osdlc/command-seam@0.14.0
39
+
40
+ ## 0.9.0
41
+
42
+ ### Minor Changes
43
+
44
+ - b835ae4: Behaviour change: `mainCheckout()` now answers null for a bare store with no main checkout, instead of the store's parent folder. When the common dir is not `<checkout>/.git` (a submodule, a `--separate-git-dir` clone), it reads `core.worktree`, this checkout when the cwd is the main worktree, or the first non-bare `worktree list` entry.
45
+ `branches()` lists `refs/heads/` names, so a branch that shares its name with a tag is no longer reported as `heads/<name>`. `statusEntries()` skips the source field of a rename or copy in the worktree column too, so the entry after it is no longer misread. `parseRepoRef` reads a GitLab page in a nested group (`…/group/sub/repo/-/…`) as the whole project path, and still reads a GitHub page whose path holds a `-` segment. `parseRemoteUrl` answers null for a `file://` URL and strips `.git` from `repo.git/`. `scanForCheckouts` on a folder that is itself a checkout answers that folder alone.
46
+ - fdef74f: New verbs and verb options, on both `Git` and `AsyncGit`, for operations that needed `raw` before:
47
+
48
+ - `worktreeAdd(path, { branch, resetBranch: true })` is `worktree add -B`: create the branch, or reset an existing one. This is the same shape as `checkout`'s `resetBranch`. `resetBranch` without `branch` throws a `TypeError`.
49
+ - `commit({ ..., paths })` appends `-- <paths…>`, with every message source, so only those paths are committed. An empty `paths` throws a `TypeError`, because git would commit everything staged.
50
+ - `push(remote, refspec, { delete: true })` is `push --delete`, and combines with `forceWithLease`.
51
+ - `hasStagedChanges()` is `diff --cached --quiet`: `true` for exit 1, `false` for exit 0, and a throw for anything else. On an unborn HEAD the index is compared against the empty tree. `git.soft.hasStagedChanges()` falls back to `false`.
52
+ - `showAtRevChecked(rev, path)` runs the same `show` as `showAtRev`, but a missing path throws the classified failure instead of returning `null`.
53
+ - `remoteSetHead(remote, { branch } | { auto: true } | { delete: true })` and `remoteSetBranches(remote, branches, { add })`. An empty `branches` throws a `TypeError`.
54
+ - `gc({ auto, aggressive, prune, quiet })`, where `prune` is a date string or `false` for `--no-prune`.
55
+
56
+ The new option types `WorktreeAddOptions`, `PushOptions`, `RemoteSetHeadOptions`, `RemoteSetBranchesOptions` and `GcOptions` are exported. `GitRequest` and `GitResults` gain the `hasStagedChanges`, `showAtRevChecked`, `remoteSetHead`, `remoteSetBranches` and `gc` kinds.
57
+
58
+ Fixed: `worktreeAdd` and `checkout` now refuse a `branch` that starts with `-`, as every other positional value already was. `worktree add` passes the name to a child `git branch`, so `worktreeAdd(path, { branch: '-M', resetBranch: true, startPoint: 'x' })` used to rename the current branch to `x` before failing.
59
+
60
+ ### Patch Changes
61
+
62
+ - Updated dependencies [b835ae4]
63
+ - @osdlc/command-seam@0.13.0
64
+
3
65
  ## 0.8.2
4
66
 
5
67
  ### Patch Changes
package/README.md CHANGED
@@ -29,16 +29,72 @@ Node.js, on macOS, Linux and Windows. CI runs the tests and the built package
29
29
  on Linux and macOS, on Node 22 and 24. Windows is supported but not tested in
30
30
  CI yet.
31
31
 
32
- The minimum git version is the oldest one CI tests. CI uses the git that the
33
- GitHub-hosted runners ship. On 2026-10-20 that was git 2.55.0 on
34
- `ubuntu-latest` (Ubuntu 24.04) and git 2.56.0 on `macos-latest` (macOS 26), as
35
- the checkout step logs it. So the tested minimum is git 2.55.0. Older git may
36
- work, but no test shows it. The behaviour tables below were measured against
37
- git 2.50.1. A verb that needs a newer git than you have fails with git's own
38
- error and throws the classified failure. `mergeTree` needs git 2.38 or later.
32
+ It needs git 2.34 or later, the git of Ubuntu 22.04 LTS. See [Git versions](#git-versions).
39
33
 
40
34
  The tests run on Vitest under Node. Bun is not a tested runtime for consumers.
41
35
 
36
+ ## Git versions
37
+
38
+ The supported floor is git 2.34, the git of Ubuntu 22.04 LTS. CI tests the
39
+ git that the GitHub-hosted runners ship. On 2026-10-20 that was git 2.55.0 on
40
+ `ubuntu-latest` (Ubuntu 24.04) and git 2.56.0 on `macos-latest` (macOS 26), as
41
+ the checkout step logs it. The behaviour tables below were measured against
42
+ git 2.50.1.
43
+
44
+ Every flag typed-git passes unconditionally is in git 2.34. A few features are
45
+ newer, and one table (`GIT_FEATURES`, in `src/features.ts`) lists them:
46
+
47
+ | Feature | Needs git | Used by | On an older git |
48
+ | --- | --- | --- | --- |
49
+ | `merge-tree --write-tree` | 2.38 | `mergeTree` | throws `unsupported-git` |
50
+ | `merge-tree --merge-base` | 2.40 | `mergeTree({ mergeBase })` | throws `unsupported-git` |
51
+ | `worktree list -z` | 2.36 | `worktrees` | newline-split `worktree list --porcelain`: a path with a newline breaks it, and a lock reason comes back C-quoted |
52
+
53
+ A verb that uses one of these runs `git --version` first, once per runner,
54
+ and caches the answer. A client that never calls such a verb never runs it.
55
+ `git.version()` (and `await asyncGit.version()`) returns the same parsed
56
+ version: `{ major, minor, patch, text }`, where `text` keeps a vendor suffix
57
+ such as `2.39.3 (Apple Git-146)` or `2.45.1.windows.1`.
58
+
59
+ The answer is cached per runner and per effective `PATH` (the call's `env`
60
+ over the client's over the process's; `PATHEXT` too on Windows), because the
61
+ default runner runs whichever `git` that `PATH` finds. The probe runs in the
62
+ OS temp directory, so a missing cwd cannot fail it; the verb itself still
63
+ runs in its own cwd. A failed probe is not cached, and its failure names the
64
+ verb that asked (`git worktree: …`), not `--version`.
65
+
66
+ `AsyncGit` callers that probe at the same time share one probe. It runs with
67
+ no caller's `signal` and a fixed 15 s limit. Each caller waits under its own
68
+ `timeoutMs` and `signal`, so one that gives up rejects alone. The sync client
69
+ probes under the call's `timeoutMs` (15 s at most). Either way the first gated
70
+ call can take up to the probe's time plus its own `timeoutMs`.
71
+
72
+ The `gitVersion` option pins the version instead: `new Git(cwd, { runner,
73
+ gitVersion: "2.55.0" })`, or `cliBackend({ runner, gitVersion: "2.55.0" })`.
74
+ It takes a version string, either `"2.55.0"` or a whole
75
+ `"git version 2.39.3 (Apple Git-146)"` line. Gated verbs then use it and
76
+ never run `git --version`, `version()` returns it, and `at()` keeps it. An
77
+ unparsable value throws a `RangeError` when the client or backend is built.
78
+ It is the way to put a fake runner behind a gated verb, and to test either
79
+ side of a feature.
80
+
81
+ On a git older than a feature, a verb with a fallback runs it, and one
82
+ without fails as `unsupported-git` before git runs:
83
+
84
+ ```ts
85
+ const r = git.try.mergeTree("main", "topic");
86
+ if (!r.ok && r.error.kind === "unsupported-git") {
87
+ // r.error.message: "merge-tree --write-tree needs git 2.38 or later; found 2.34.1."
88
+ // r.error.unsupported: { feature, needs, have }
89
+ }
90
+ ```
91
+
92
+ Below 2.34 every one of these verbs fails that way, with the feature
93
+ `typed-git`, and no fallback is tried. Verbs that need no newer feature run
94
+ on any git without a version check. A backend other than `cliBackend` has no
95
+ git version, so `AsyncGit` checks nothing for it; it answers or rejects each
96
+ request itself.
97
+
42
98
  ## Stability
43
99
 
44
100
  The package is on the 0.x line. A breaking change ships only in a new minor
@@ -141,7 +197,8 @@ use(r.value);
141
197
  The error is a `GitFailure`: a `Failure` from `@osdlc/result` with a `kind` to
142
198
  branch on, a one-line `message` and a `hint` for a person (`describe(error)`
143
199
  joins them), git's own output in `detail`, the `argv` and `exitCode`, and the
144
- `CommandFailed` it was read from in `cause`.
200
+ `CommandFailed` it was read from in `cause`. An `unsupported-git` failure has
201
+ no `cause`, because git did not run; it carries `unsupported` instead.
145
202
 
146
203
  The methods that throw (`git.push()` and the rest) throw the same failure,
147
204
  wrapped in a `FailureError` (`error.failure`). So a CLI that reports a thrown
@@ -161,6 +218,7 @@ line for a failure from `git.try.*`.
161
218
  | `not-authenticated` | `Authentication failed`, `Permission denied (publickey)`, `could not read Username`, `unable to access` with HTTP 401 or 403 | `The remote refused the credentials.` / `Check that you are signed in to the host, or that your SSH key is added.` |
162
219
  | `not-found` | `unable to access` with HTTP 404 | `The remote repository was not found, or you cannot see it.` / `Check the remote URL, and that your account can see the repository.` |
163
220
  | `tls` | `unable to access` with `SSL certificate problem` | `The remote's TLS certificate could not be verified.` / `Check the system clock and CA certificates, or the remote's certificate.` |
221
+ | `unsupported-git` | the local git is older than the verb needs (see [Git versions](#git-versions)); git did not run, so there is no `cause` | `merge-tree --write-tree needs git 2.38 or later; found 2.34.1.` / `Upgrade git to 2.38 or later from https://git-scm.com.` |
164
222
  | `not-executable`, `bad-cwd`, `timeout`, `output-cap`, `signal`, `aborted`, `spawn` | as in `@osdlc/command-seam` | command-seam's message, no hint |
165
223
  | `exit` | any other non-zero exit | git's first stderr line |
166
224
 
@@ -205,6 +263,11 @@ there: `git.try.logSubject("HEAD")` outside a repository is `{ ok: true,
205
263
  value: null }`, not a failure. The contract reduces these cases. It does not
206
264
  remove them.
207
265
 
266
+ When a missing file is an error rather than an answer, use
267
+ `showAtRevChecked(rev, path)`. It runs the same `show` and declares no
268
+ absence, so a missing path throws the classified failure instead of reading as
269
+ `null`.
270
+
208
271
  Where the difference matters, probe with `hasHistory()` first:
209
272
 
210
273
  ```ts
@@ -505,7 +568,7 @@ trailing argument that is not a string.
505
568
 
506
569
  A ref, remote, URL, path, ref pattern or config key argument that starts with
507
570
  `-` could be read by git as an option, for example `--upload-pack=...` or
508
- `--output=<file>`. Forty-two verbs refuse it: they throw a `TypeError`
571
+ `--output=<file>`. Every verb that takes such an argument refuses it: they throw a `TypeError`
509
572
  before git runs. In `log` this covers `rev`, `range` and each `notRefs` entry.
510
573
  In `diffNameOnly` and `diffStat` it covers each `rangeArgs` token. The message is
511
574
  `typed-git: <verb>: <param> must not start with "-" (got "...")`. `try` and
@@ -531,22 +594,25 @@ exit throws the classified failure.
531
594
  | Method | git | Absence → value |
532
595
  | --- | --- | --- |
533
596
  | `showAtRev(rev, path)` | `show <rev>:<path>` | `128` → `null` |
597
+ | `showAtRevChecked(rev, path)` | `show <rev>:<path>` | none — a missing path throws; no `soft` form |
534
598
  | `revParse(...args)` | `rev-parse <args>` | `1` → `null` — needs `--verify --quiet` |
535
599
  | `resolveRef(ref)` | `rev-parse --verify --quiet <ref>` | `1` → `null` |
536
600
  | `hasHistory()` | `resolveRef("HEAD") !== null` | — |
537
601
  | `headRef()` | `rev-parse --abbrev-ref HEAD` | none — literal `"HEAD"` when detached |
602
+ | `version()` | `--version`, once per runner | none — `{ major, minor, patch, text }`; see [Git versions](#git-versions) |
538
603
  | `topLevel()` | `rev-parse --show-toplevel` | `128` → `null` (not a repository) |
539
604
  | `gitCommonDir()` | `rev-parse --path-format=absolute --git-common-dir` | `128` → `null` |
540
605
  | `gitDir()` | `rev-parse --absolute-git-dir` | `128` → `null` — this worktree's own dir, `<common>/worktrees/<name>` in a linked worktree |
541
- | `mainCheckout()` | the parent of `gitCommonDir()` | `null` outside a repository |
606
+ | `mainCheckout()` | the parent of `gitCommonDir()` when that is `<checkout>/.git`, else `core.worktree` or the main worktree | `null` outside a repository, or for a bare store |
542
607
  | `symbolicRef(ref)` | `symbolic-ref <ref>` | `128` → `null` |
543
608
  | `currentBranch()` | `branch --show-current` | none — `null` when detached |
544
609
  | `statusPorcelain({ paths })` | `status --porcelain` | none |
545
610
  | `statusEntries()` | `status --porcelain -z --untracked-files=all` | none — `{ x, y, path }` rows; a rename is one row, with the source dropped |
546
611
  | `isDirty({ paths })` | `statusPorcelain().length > 0` | none |
547
- | `branches(pattern)` | `branch --list --format=%(refname:short)` | none |
612
+ | `hasStagedChanges()` | `diff --cached --quiet` | `1` → `true`, `0` → `false` — on an unborn HEAD the index is compared against the empty tree; outside a repository (`129`) it throws |
613
+ | `branches(pattern)` | `branch --list --format=%(refname:lstrip=2)` | none |
548
614
  | `branchExists(name)` | `branches(name).includes(name)` | none |
549
- | `worktrees()` | `worktree list --porcelain` | none — rows carry `locked` and `lockReason` |
615
+ | `worktrees()` | `worktree list --porcelain -z` (git 2.36; the newline form before) | none — rows carry `locked` and `lockReason` |
550
616
  | `mergeBase(a, b)` | `merge-base <a> <b>` | `1` → `null` (unrelated histories) |
551
617
  | `logSubject(ref)` | `log -1 --format=%s <ref>` | `128` → `null` |
552
618
  | `configGet(key, { scope })` | `config [--local\|--global\|--system] --get <key>` | `1` → `null` (unset) |
@@ -574,6 +640,8 @@ exit throws the classified failure.
574
640
  | `grep(pattern, { extendedRegexp, lineNumber, noColor, paths })` | `grep` | `1` → `[]` (no match) |
575
641
  | `isAncestor(a, b)` | `merge-base --is-ancestor` | `1` → `false` |
576
642
  | `aheadBehind(base, tip)` | `rev-list --left-right --count <base>...<tip>` | none |
643
+ | `cherry(upstream, head)` | `cherry <upstream> [<head>]` | none — `{ sha, equivalent }` per commit; empty output is `[]`, an unreadable line throws |
644
+ | `commitTree(tree, { parents, message })` | `commit-tree <tree> [-p <parent>]... -m <message>` | none — writes an object and no ref; needs a git identity |
577
645
  | `remotes()` | `remote` | none — names, not remotes |
578
646
  | `remote()` | `remote` | none — deprecated alias of `remotes()` |
579
647
  | `remoteGetUrl(name, { push })` | `remote get-url [--push] <name>` | `2` → `null` (unknown remote) — the first URL |
@@ -597,8 +665,8 @@ Integration, declares exit 1 absent and returns the rejected refs.
597
665
  | --- | --- |
598
666
  | `fetch(remote, refspec, { prune, quiet, noWriteFetchHead, depth, noTags })` | `fetch` |
599
667
  | `add(paths, { all, update, intentToAdd })` | `add` (paths go after `--`) |
600
- | `commit({ message, body } \| { messageFile } \| { messageStdin }, { allowEmpty, amend, noVerify, signoff })` | `commit` — one message source, enforced by the types; `messageStdin` is `-F -` with the string on stdin, no temp file |
601
- | `push(remote, refspec, { forceWithLease })` | `push` — `forceWithLease` takes `true` or a pinned `{ ref, expect }` (`expect: null` = ref must be absent); `forceWithLeaseArg(lease)` is the pure formatter. `true` is the bare form: it overwrites whatever is on the remote, so prefer the pinned form. To learn why a push was rejected, use `pushPorcelain` |
668
+ | `commit({ message, body } \| { messageFile } \| { messageStdin }, plus { allowEmpty, amend, noVerify, signoff, paths } in the same object)` | `commit` — one argument, e.g. `commit({ message, allowEmpty: true })`; one message source, enforced by the types; `messageStdin` is `-F -` with the string on stdin, no temp file. `paths` appends `-- <paths…>`: only those paths are committed, from the working tree, and anything else staged stays staged. An empty `paths` throws a `TypeError`, because git would commit everything staged |
669
+ | `push(remote, refspec, { forceWithLease, delete })` | `push` — `forceWithLease` takes `true` or a pinned `{ ref, expect }` (`expect: null` = ref must be absent); `forceWithLeaseArg(lease)` is the pure formatter. `true` is the bare form: it overwrites whatever is on the remote, so prefer the pinned form. `delete` is `--delete`, and a pinned lease deletes only while the remote ref holds `expect`. To learn why a push was rejected, use `pushPorcelain` |
602
670
  | `configSet(key, value, { scope })` | `config` |
603
671
  | `configRemoveSection(name)` | `config --remove-section` — `false` when there is no such section |
604
672
  | `init(path, { bare, initialBranch, quiet })` | `init` |
@@ -607,12 +675,15 @@ Integration, declares exit 1 absent and returns the rejected refs.
607
675
  | `clean({ directories })` | `clean -f`, or `-fd` — ignored files are kept |
608
676
  | `deleteBranch(name, { force })` | `branch -d` / `-D` |
609
677
  | `deleteRef(ref, { expected })` | `update-ref -d <ref> <expected>` — refuses when `ref` has moved |
610
- | `worktreeAdd(path, { branch, startPoint, detach })` | `worktree add` |
678
+ | `worktreeAdd(path, { branch, resetBranch, startPoint, detach })` | `worktree add` — `branch` is `-b`; `resetBranch` picks `-B` (create, or reset an existing branch), as for `checkout` |
611
679
  | `worktreeRemove(path, { force })` | `worktree remove` |
612
680
  | `worktreeMove(from, to, { force })` | `worktree move` |
613
681
  | `worktreeUnlock(path)` | `worktree unlock` |
614
682
  | `worktreePrune()` | `worktree prune` |
615
683
  | `remoteAdd(name, url)` | `remote add` |
684
+ | `remoteSetHead(remote, { branch } \| { auto: true } \| { delete: true })` | `remote set-head <remote> <branch>\|--auto\|--delete` — exactly one, enforced by the types and at run time |
685
+ | `remoteSetBranches(remote, branches, { add })` | `remote set-branches [--add]` — an empty `branches` throws a `TypeError`, because git would clear every fetch refspec |
686
+ | `gc({ auto, aggressive, prune, quiet })` | `gc` — `prune` is a date such as `'now'` for `--prune=<date>`, or `false` for `--no-prune` |
616
687
  | `checkout(ref, { branch, resetBranch, force })` | `checkout` — `resetBranch` picks `-B` |
617
688
  | `checkoutSide(side, paths)` | `checkout --ours\|--theirs --` |
618
689
  | `mergeAbort()` / `rebaseAbort()` | `merge --abort` / `rebase --abort` |
@@ -703,12 +774,27 @@ The default runner finds `git` on absolute `PATH` entries only, so a file named
703
774
  `git` in the checkout cannot run in its place. A real runner you build yourself
704
775
  should do the same: `spawnRunner("git", { absolutePathOnly: true })`.
705
776
 
777
+ A fake runner behind a version-gated verb (`worktrees`, `mergeTree`; see
778
+ [Git versions](#git-versions)) would also be asked for `git --version`. Pin
779
+ the version so it is not:
780
+
781
+ ```ts
782
+ const git = new Git("/nowhere", { runner: recording, gitVersion: "2.55.0" });
783
+ git.worktrees(); // runs `worktree list --porcelain -z`, and no `--version`
784
+ ```
785
+
786
+ A fake without the pin must answer `["--version"]` (once per runner) with
787
+ `git version <x.y.z>`, or the gated verb fails as `exit`.
788
+
706
789
  `runner: undefined` is the same as omitting it, so a caller holding an optional
707
790
  runner passes it straight through, without a conditional spread. `cliBackend`
708
791
  accepts it too.
709
792
 
710
- command-seam's exports are re-exported here, so wiring a runner or catching a
711
- `CommandFailed` needs one import rather than two.
793
+ The runner and result types, `CommandFailed`, `spawnRunner`, `spawnRunnerAsync`,
794
+ `runChecked`, `runCheckedAsync` and `asAsync` are re-exported from command-seam,
795
+ so wiring a runner or catching a `CommandFailed` needs one import rather than
796
+ two. Import other runners, such as `spawnRunnerBytes` and `streamRunner`, from
797
+ `@osdlc/command-seam`.
712
798
 
713
799
  ## Also: git references
714
800
 
@@ -732,6 +818,25 @@ is what `remoteOwnerRepo` uses, and it stays on `@osdlc/typed-git/client`.
732
818
  Use it for a remote read from a checkout (any host); use `parseGitUrl` /
733
819
  `parseRepoRef` for a URL a person pasted.
734
820
 
821
+ `parseRemoteRepo` reads a remote into `{ host, owner, repo }`, for a known
822
+ host and any other alike. It tries `parseGitUrl` first, so shorthand reads as
823
+ GitHub and a GitLab nested group stays whole in `owner`, then falls back to
824
+ `parseRemoteUrl`, so a GitHub Enterprise or self-hosted Forgejo remote
825
+ answers too. `host` is lower-cased and carries no port, and GitHub's other
826
+ names for itself (`ssh.github.com`, its SSH over port 443, and
827
+ `www.github.com`) read as `github.com`. Decide which forge a
828
+ remote is on from `host`, not from the URL text.
829
+
830
+ ```ts
831
+ parseRemoteRepo("git@github.com:acme/widgets.git");
832
+ // { host: "github.com", owner: "acme", repo: "widgets" }
833
+ parseRemoteRepo("https://forge.example.com:3000/team/app.git");
834
+ // { host: "forge.example.com", owner: "team", repo: "app" }
835
+ parseRemoteRepo("ssh://git@ssh.github.com:443/acme/widgets.git");
836
+ // { host: "github.com", owner: "acme", repo: "widgets" }
837
+ parseRemoteRepo("/srv/git/repo.git"); // null — a local path names no project
838
+ ```
839
+
735
840
  `parseRepoRef` answers the question a clone command asks. Given anything a
736
841
  person might paste (a clone URL, the page of a pull request or a file, a bare
737
842
  `owner/repo`), which repository is it, and what does `git clone` take? It returns
@@ -751,7 +856,7 @@ parseRepoRef("./a/local/path"); // null — the input names no repository
751
856
  ## Subpath exports
752
857
 
753
858
  `@osdlc/typed-git/client` is everything above except the URL parsers
754
- (`parseGitUrl`, `gitSshUrl`, `parseRepoRef` and their types) and the checkout
859
+ (`parseGitUrl`, `gitSshUrl`, `parseRemoteRepo`, `parseRepoRef` and their types) and the checkout
755
860
  walks (`checkoutRoot`, `discoverCheckouts`, `scanForCheckouts`, their types,
756
861
  `DEFAULT_MAX_DEPTH` and `DEFAULT_WARN_AFTER`). It has no `hosted-git-info` on
757
862
  your module graph. That package stays in `dependencies` either way, so this
package/dist/async.d.ts CHANGED
@@ -14,9 +14,10 @@
14
14
  */
15
15
  import type { CommandResult } from '@osdlc/command-seam';
16
16
  import { type GitBackend, type GitCallOptions } from './backend.ts';
17
+ import type { GitVersion } from './git-version.ts';
17
18
  import { type Soft, type TriedAsync } from './outcome.ts';
18
19
  import { type RemoteCoordinate } from './remote-url.ts';
19
- import { type AddOptions, type AheadBehind, type CommitOptions, type CheckoutOptions, type ConfigGetOptions, type CloneOptions, type ConflictSide, type MergeOptions, type MergeOutcome, type MergeTreeOptions, type MergeTreeOutcome, type RebaseOptions, type RebaseOutcome, type RemoteGetUrlOptions, type TaggedFile, type UnmergedEntry, type ConfigSetOptions, type DiffEntry, type DiffNameOnlyOptions, type DiffStatOptions, type DiffNameStatusOptions, type DiffTextOptions, type DiffTreeOptions, type FetchOptions, type ForEachRefOptions, type ForceLease, type GrepOptions, type InitOptions, type LogOptions, type IgnoreMatch, type LsFilesOptions, type LsRemoteOptions, type LsTreeOptions, type NumstatEntry, type PushPorcelainOptions, type PushReport, type RemoteRef, type CleanOptions, type DiffCheckOptions, type DiffCheckResult, type StatusEntry, type StatusPorcelainOptions, type TreeEntry, type Worktree, type WorktreeMoveOptions } from './verbs.ts';
20
+ import { type AddOptions, type AheadBehind, type CherryEntry, type CommitTreeOptions, type CommitOptions, type CheckoutOptions, type ConfigGetOptions, type CloneOptions, type ConflictSide, type MergeOptions, type MergeOutcome, type MergeTreeOptions, type MergeTreeOutcome, type RebaseOptions, type RebaseOutcome, type RemoteGetUrlOptions, type TaggedFile, type UnmergedEntry, type ConfigSetOptions, type DiffEntry, type DiffNameOnlyOptions, type DiffStatOptions, type DiffNameStatusOptions, type DiffTextOptions, type DiffTreeOptions, type FetchOptions, type ForEachRefOptions, type GrepOptions, type InitOptions, type LogOptions, type IgnoreMatch, type LsFilesOptions, type LsRemoteOptions, type LsTreeOptions, type NumstatEntry, type PushPorcelainOptions, type PushReport, type RemoteRef, type CleanOptions, type DiffCheckOptions, type DiffCheckResult, type StatusEntry, type StatusPorcelainOptions, type TreeEntry, type Worktree, type WorktreeAddOptions, type WorktreeMoveOptions, type GcOptions, type PushOptions, type RemoteSetBranchesOptions, type RemoteSetHeadOptions } from './verbs.ts';
20
21
  /** A typed, awaitable git client bound to one working directory. */
21
22
  export declare class AsyncGit {
22
23
  readonly cwd: string;
@@ -74,8 +75,18 @@ export declare class AsyncGit {
74
75
  rawChecked(argv: string[], opts?: GitCallOptions & {
75
76
  input?: string | undefined;
76
77
  }): Promise<CommandResult>;
78
+ /**
79
+ * The git the backend runs, from `git --version`; see {@link Git.version}.
80
+ * `cliBackend` probes once per runner and caches it, or returns its
81
+ * `gitVersion` option without running anything. A non-CLI backend has
82
+ * no git version unless it answers the `version` request itself;
83
+ * `partialBackend` rejects it with `UnsupportedRequest` otherwise.
84
+ */
85
+ version(opts?: GitCallOptions): Promise<GitVersion>;
77
86
  /** A file's content at a rev, null if absent. */
78
87
  showAtRev(rev: string, relPath: string, opts?: GitCallOptions): Promise<string | null>;
88
+ /** A file's content at a rev, rejecting when the path is missing. See {@link Git.showAtRevChecked}. */
89
+ showAtRevChecked(rev: string, relPath: string, opts?: GitCallOptions): Promise<string>;
79
90
  /**
80
91
  * See {@link Git.revParse}. Call options go last, as an object. For a ref,
81
92
  * prefer {@link AsyncGit.resolveRef}.
@@ -118,6 +129,8 @@ export declare class AsyncGit {
118
129
  statusPorcelain(opts?: GitCallOptions & StatusPorcelainOptions): Promise<string[]>;
119
130
  /** Every changed or untracked file, from `status --porcelain -z`. */
120
131
  statusEntries(opts?: GitCallOptions): Promise<StatusEntry[]>;
132
+ /** True iff anything is staged. See {@link Git.hasStagedChanges}. */
133
+ hasStagedChanges(opts?: GitCallOptions): Promise<boolean>;
121
134
  /** True iff the working tree has any staged/unstaged/untracked change. */
122
135
  isDirty(opts?: GitCallOptions & StatusPorcelainOptions): Promise<boolean>;
123
136
  /** Local branch shortnames matching `pattern` (all when omitted). */
@@ -211,6 +224,13 @@ export declare class AsyncGit {
211
224
  isAncestor(a: string, b: string, opts?: GitCallOptions): Promise<boolean>;
212
225
  /** How far `tip` has diverged from `base`. See {@link AheadBehind}. */
213
226
  aheadBehind(base: string, tip: string, opts?: GitCallOptions): Promise<AheadBehind>;
227
+ /**
228
+ * Commits on `head` (default `HEAD`) that `upstream` lacks, each marked by
229
+ * whether `upstream` has the same patch. See {@link CherryEntry}.
230
+ */
231
+ cherry(upstream: string, head?: string, opts?: GitCallOptions): Promise<CherryEntry[]>;
232
+ /** Write a commit for `tree` and return its sha; no ref moves. Needs a git identity. */
233
+ commitTree(tree: string, commitOpts: CommitTreeOptions, opts?: GitCallOptions): Promise<string>;
214
234
  /** Configured remote names (`git remote`); `[]` when there are none. */
215
235
  remotes(opts?: GitCallOptions): Promise<string[]>;
216
236
  /**
@@ -252,12 +272,10 @@ export declare class AsyncGit {
252
272
  clone(url: string, dest?: string | undefined, opts?: GitCallOptions & CloneOptions): Promise<void>;
253
273
  /**
254
274
  * Push a refspec. A {@link ForceLease} pins `--force-with-lease`.
255
- * `{forceWithLease: true}` adds the bare flag, which is the unsafe form. See
256
- * {@link Git.push}.
275
+ * `{forceWithLease: true}` adds the bare flag, which is the unsafe form.
276
+ * `{delete: true}` deletes `refspec` on the remote. See {@link Git.push}.
257
277
  */
258
- push(remote: string, refspec: string, opts?: GitCallOptions & {
259
- forceWithLease?: boolean | ForceLease | undefined;
260
- }): Promise<void>;
278
+ push(remote: string, refspec: string, opts?: GitCallOptions & PushOptions): Promise<void>;
261
279
  /**
262
280
  * `git push --porcelain`, read into one result per ref. A rejected ref comes
263
281
  * back with a typed `rejection` rather than a rejection of the promise. See
@@ -281,12 +299,8 @@ export declare class AsyncGit {
281
299
  deleteRef(ref: string, opts: GitCallOptions & {
282
300
  expected: string;
283
301
  }): Promise<void>;
284
- /** `git worktree add [--detach] [-b branch] <path> [startPoint]`. */
285
- worktreeAdd(path: string, opts?: GitCallOptions & {
286
- branch?: string | undefined;
287
- startPoint?: string | undefined;
288
- detach?: boolean | undefined;
289
- }): Promise<void>;
302
+ /** `git worktree add [--detach] [-b|-B branch] <path> [startPoint]`. See {@link Git.worktreeAdd}. */
303
+ worktreeAdd(path: string, opts?: GitCallOptions & WorktreeAddOptions): Promise<void>;
290
304
  /** `git worktree remove [--force] <path>`. */
291
305
  worktreeRemove(path: string, opts?: GitCallOptions & {
292
306
  force?: boolean | undefined;
@@ -299,6 +313,12 @@ export declare class AsyncGit {
299
313
  worktreePrune(opts?: GitCallOptions): Promise<void>;
300
314
  /** `git remote add <name> <url>`. */
301
315
  remoteAdd(name: string, url: string, opts?: GitCallOptions): Promise<void>;
316
+ /** `git remote set-head <remote> <branch> | --auto | --delete`. See {@link Git.remoteSetHead}. */
317
+ remoteSetHead(remote: string, opts: GitCallOptions & RemoteSetHeadOptions): Promise<void>;
318
+ /** `git remote set-branches [--add] <remote> <branch…>`; an empty list rejects. */
319
+ remoteSetBranches(remote: string, branches: string[], opts?: GitCallOptions & RemoteSetBranchesOptions): Promise<void>;
320
+ /** `git gc [--auto] [--aggressive] [--prune=<date> | --no-prune] [--quiet]`. */
321
+ gc(opts?: GitCallOptions & GcOptions): Promise<void>;
302
322
  /**
303
323
  * Merge `ref` into the current branch. A conflict is a value, not a
304
324
  * rejection: the outcome is `clean` or `conflict`. Git refusing to merge at
package/dist/async.js CHANGED
@@ -12,7 +12,7 @@
12
12
  * `new AsyncGit(cwd, { backend: cliBackend({ gitDir }) })`, where the sync
13
13
  * client takes `gitDir` on its own constructor.
14
14
  */
15
- import { dirname } from 'node:path';
15
+ import { basename, dirname, resolve } from 'node:path';
16
16
  import { cliBackend } from "./backend.js";
17
17
  import { softAsync, triedAsync } from "./outcome.js";
18
18
  import { parseRemoteUrl } from "./remote-url.js";
@@ -97,10 +97,24 @@ export class AsyncGit {
97
97
  return this.backend.execute(this.cwd, { kind: 'raw', argv, checked: true, input: opts.input }, opts);
98
98
  }
99
99
  // ── queries ───────────────────────────────────────────────────────────────
100
+ /**
101
+ * The git the backend runs, from `git --version`; see {@link Git.version}.
102
+ * `cliBackend` probes once per runner and caches it, or returns its
103
+ * `gitVersion` option without running anything. A non-CLI backend has
104
+ * no git version unless it answers the `version` request itself;
105
+ * `partialBackend` rejects it with `UnsupportedRequest` otherwise.
106
+ */
107
+ version(opts = {}) {
108
+ return this.backend.execute(this.cwd, { kind: 'version' }, opts);
109
+ }
100
110
  /** A file's content at a rev, null if absent. */
101
111
  showAtRev(rev, relPath, opts = {}) {
102
112
  return this.backend.execute(this.cwd, { kind: 'showAtRev', rev, relPath }, opts);
103
113
  }
114
+ /** A file's content at a rev, rejecting when the path is missing. See {@link Git.showAtRevChecked}. */
115
+ showAtRevChecked(rev, relPath, opts = {}) {
116
+ return this.backend.execute(this.cwd, { kind: 'showAtRevChecked', rev, relPath }, opts);
117
+ }
104
118
  /**
105
119
  * See {@link Git.revParse}. Call options go last, as an object. For a ref,
106
120
  * prefer {@link AsyncGit.resolveRef}.
@@ -152,7 +166,17 @@ export class AsyncGit {
152
166
  */
153
167
  async mainCheckout(opts = {}) {
154
168
  const common = await this.gitCommonDir(opts);
155
- return common === null ? null : dirname(common);
169
+ if (common === null)
170
+ return null;
171
+ if (basename(common) === '.git')
172
+ return dirname(common);
173
+ const configured = await this.configGet('core.worktree', opts);
174
+ if (configured !== null)
175
+ return resolve(common, configured);
176
+ if ((await this.gitDir(opts)) === common)
177
+ return this.topLevel(opts);
178
+ const main = (await this.worktrees(opts))[0];
179
+ return main === undefined || main.bare ? null : main.path;
156
180
  }
157
181
  /** Current branch shortname, or null when detached. Rejects outside a repo. */
158
182
  currentBranch(opts = {}) {
@@ -170,6 +194,10 @@ export class AsyncGit {
170
194
  statusEntries(opts = {}) {
171
195
  return this.backend.execute(this.cwd, { kind: 'statusEntries' }, opts);
172
196
  }
197
+ /** True iff anything is staged. See {@link Git.hasStagedChanges}. */
198
+ hasStagedChanges(opts = {}) {
199
+ return this.backend.execute(this.cwd, { kind: 'hasStagedChanges' }, opts);
200
+ }
173
201
  /** True iff the working tree has any staged/unstaged/untracked change. */
174
202
  async isDirty(opts = {}) {
175
203
  return (await this.statusPorcelain(opts)).length > 0;
@@ -345,6 +373,17 @@ export class AsyncGit {
345
373
  aheadBehind(base, tip, opts = {}) {
346
374
  return this.backend.execute(this.cwd, { kind: 'aheadBehind', base, tip }, opts);
347
375
  }
376
+ /**
377
+ * Commits on `head` (default `HEAD`) that `upstream` lacks, each marked by
378
+ * whether `upstream` has the same patch. See {@link CherryEntry}.
379
+ */
380
+ cherry(upstream, head, opts = {}) {
381
+ return this.backend.execute(this.cwd, { kind: 'cherry', upstream, head }, opts);
382
+ }
383
+ /** Write a commit for `tree` and return its sha; no ref moves. Needs a git identity. */
384
+ commitTree(tree, commitOpts, opts = {}) {
385
+ return this.backend.execute(this.cwd, { kind: 'commitTree', tree, ...commitOpts }, opts);
386
+ }
348
387
  /** Configured remote names (`git remote`); `[]` when there are none. */
349
388
  remotes(opts = {}) {
350
389
  return this.backend.execute(this.cwd, { kind: 'remote' }, opts);
@@ -420,11 +459,11 @@ export class AsyncGit {
420
459
  }
421
460
  /**
422
461
  * Push a refspec. A {@link ForceLease} pins `--force-with-lease`.
423
- * `{forceWithLease: true}` adds the bare flag, which is the unsafe form. See
424
- * {@link Git.push}.
462
+ * `{forceWithLease: true}` adds the bare flag, which is the unsafe form.
463
+ * `{delete: true}` deletes `refspec` on the remote. See {@link Git.push}.
425
464
  */
426
465
  push(remote, refspec, opts = {}) {
427
- return this.backend.execute(this.cwd, { kind: 'push', remote, refspec, forceWithLease: opts.forceWithLease }, opts);
466
+ return this.backend.execute(this.cwd, { kind: 'push', remote, refspec, forceWithLease: opts.forceWithLease, delete: opts.delete }, opts);
428
467
  }
429
468
  /**
430
469
  * `git push --porcelain`, read into one result per ref. A rejected ref comes
@@ -459,15 +498,10 @@ export class AsyncGit {
459
498
  deleteRef(ref, opts) {
460
499
  return this.backend.execute(this.cwd, { kind: 'deleteRef', ref, expected: opts.expected }, opts);
461
500
  }
462
- /** `git worktree add [--detach] [-b branch] <path> [startPoint]`. */
501
+ /** `git worktree add [--detach] [-b|-B branch] <path> [startPoint]`. See {@link Git.worktreeAdd}. */
463
502
  worktreeAdd(path, opts = {}) {
464
- return this.backend.execute(this.cwd, {
465
- kind: 'worktreeAdd',
466
- path,
467
- branch: opts.branch,
468
- startPoint: opts.startPoint,
469
- detach: opts.detach,
470
- }, opts);
503
+ const [call, req] = splitCallOptions(opts);
504
+ return this.backend.execute(this.cwd, { kind: 'worktreeAdd', path, ...req }, call);
471
505
  }
472
506
  /** `git worktree remove [--force] <path>`. */
473
507
  worktreeRemove(path, opts = {}) {
@@ -490,6 +524,21 @@ export class AsyncGit {
490
524
  remoteAdd(name, url, opts = {}) {
491
525
  return this.backend.execute(this.cwd, { kind: 'remoteAdd', name, url }, opts);
492
526
  }
527
+ /** `git remote set-head <remote> <branch> | --auto | --delete`. See {@link Git.remoteSetHead}. */
528
+ remoteSetHead(remote, opts) {
529
+ const [call, req] = splitCallOptions(opts);
530
+ return this.backend.execute(this.cwd, { kind: 'remoteSetHead', remote, ...req }, call);
531
+ }
532
+ /** `git remote set-branches [--add] <remote> <branch…>`; an empty list rejects. */
533
+ remoteSetBranches(remote, branches, opts = {}) {
534
+ const [call, req] = splitCallOptions(opts);
535
+ return this.backend.execute(this.cwd, { kind: 'remoteSetBranches', remote, branches, ...req }, call);
536
+ }
537
+ /** `git gc [--auto] [--aggressive] [--prune=<date> | --no-prune] [--quiet]`. */
538
+ gc(opts = {}) {
539
+ const [call, req] = splitCallOptions(opts);
540
+ return this.backend.execute(this.cwd, { kind: 'gc', ...req }, call);
541
+ }
493
542
  // ── integration ───────────────────────────────────────────────────────────
494
543
  /**
495
544
  * Merge `ref` into the current branch. A conflict is a value, not a