@osdlc/typed-git 0.14.0 → 0.16.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 CHANGED
@@ -1,5 +1,26 @@
1
1
  # @osdlc/typed-git
2
2
 
3
+ ## 0.16.0
4
+
5
+ ### Minor Changes
6
+
7
+ - cde222c: Byte-exact output. `rawBytes(argv, opts)` and `rawBytesChecked(argv, opts)` on `Git` and `AsyncGit` return stdout as a `Buffer`, the bytes git wrote, for output that is hashed or replayed: a blob, `status -z` with names that are not UTF-8, `diff --binary` of a file in another encoding. `rawBytesChecked` fails as `rawChecked` does. They run on a new `bytesRunner` option on `Git` and `cliBackend`, which defaults to command-seam's bytes runner when no `runner` is given. A client given a `runner` and no `bytesRunner` throws `UnsupportedRequest` from both, so an injected runner is never bypassed. All three are experimental, as command-seam's bytes runners are. `input` is still a string.
8
+
9
+ `statusEntries({ ignored: true })` adds `--ignored` and reports each ignored file as a `{ x: '!', y: '!' }` entry. `diffText(rev, { binary: true })` adds `--binary`, so a binary file's change is a patch `git apply` replays. `StatusEntriesOptions` is exported, and so are `spawnRunnerBytes`, `spawnRunnerBytesAsync`, `BytesCommandRunner` and `AsyncBytesCommandRunner` from command-seam.
10
+
11
+ The experimental backend seam gets a `rawBytes` request kind, and the `statusEntries` and `diffText` requests take the optional `ignored` and `binary` fields. A backend that ignores them answers without ignored files and without binary patches.
12
+
13
+ ## 0.15.0
14
+
15
+ ### Minor Changes
16
+
17
+ - 912296d: Add `hashObject`, `mktree` and `updateRef` to `Git`, `AsyncGit` and the backend seam, so a commit can be written and a ref pointed at it without the index or a checkout.
18
+
19
+ - `hashObject(content, { write })` runs `git hash-object [-w] --stdin` and returns the blob sha. `content` goes on stdin as UTF-8, with no `.gitattributes` filters. Binary content is not supported.
20
+ - `mktree(entries)` runs `git mktree -z` and returns the tree sha. Each entry is `{ mode, type?, sha, path }`, and a non-recursive `lsTree` row fits. A mode git does not write, a type that does not match the mode, a sha that is not full, a name that is empty, `.`, `..`, has `/` or NUL, or appears twice, a name git reads as `.git` (any letter case, also after a backslash, and the NTFS and HFS+ spellings such as `git~1`, `.git.` and `.git` with a zero-width character inside), and a `.gitmodules` (or `gitmod~1`) that is not a file throw a `TypeError` before git runs. git does not check a submodule (`160000`) entry's sha.
21
+ - `updateRef(ref, sha, { oldSha, reason })` runs `git update-ref [-m <reason>] <ref> <sha> <oldSha>`: it moves `ref` only while it holds `oldSha`, or with `oldSha: null` only while it does not exist. `oldSha` is required and must be a full sha. `ref` must be `HEAD` or start with `refs/`. A lost race throws.
22
+ - A new example, `examples/orphan-commit.ts`, keeps data on an orphan branch with all four plumbing verbs.
23
+
3
24
  ## 0.14.0
4
25
 
5
26
  ### Minor Changes
package/README.md CHANGED
@@ -443,6 +443,39 @@ need to call `lsFilesUnmerged()` after it. And it takes
443
443
  both sides as arguments rather than merging into the current branch, so
444
444
  nothing depends on where `HEAD` happens to be.
445
445
 
446
+ ## Writing a commit without a checkout
447
+
448
+ `hashObject`, `mktree`, `commitTree` and `updateRef` write a commit straight
449
+ into the object store and point a ref at it. The index, the working tree and
450
+ `HEAD` stay as they are, so a tool can keep data on a side branch while
451
+ someone works in the checkout:
452
+
453
+ ```ts
454
+ const parent = git.resolveRef("refs/heads/data"); // null: no branch yet
455
+ const blob = git.hashObject(json, { write: true });
456
+ const tree = git.mktree([{ mode: "100644", sha: blob, path: "state.json" }]);
457
+ const commit = git.commitTree(tree, { parents: parent ? [parent] : [], message: "Save" });
458
+ git.updateRef("refs/heads/data", commit, { oldSha: parent });
459
+ ```
460
+
461
+ `oldSha` is required. git moves the ref only while it still holds `oldSha`,
462
+ or, for `null`, only while it does not exist, so two writers cannot both
463
+ win. The one that loses gets a thrown failure (exit 128, `is at … but
464
+ expected …` or `reference already exists` in `detail`) and can re-read the
465
+ ref and try again. `mktree` takes one directory level: a subdirectory is an
466
+ entry with mode `040000` and the sha of a tree written before it.
467
+
468
+ Before git runs, `mktree` throws a `TypeError` for a name that git's fsck
469
+ reports, so a tool that builds names from data keys cannot write a tree a
470
+ host's push check rejects. That covers `.git` and the spellings NTFS and
471
+ HFS+ read as `.git`, such as `git~1`, `.git.` and `.git` with a zero-width
472
+ character inside, and a `.gitmodules` (or `gitmod~1`) that is not a file.
473
+ Each sha must name an object already in the store, except a submodule
474
+ (`160000`) commit: it lives in another repository, and git does not check
475
+ it. The
476
+ [orphan-commit example](https://github.com/osdlc/osdlc/tree/main/packages/ts/typed-git/examples/orphan-commit.ts)
477
+ runs the whole sequence.
478
+
446
479
  ## Pushing: a rejected ref is a value
447
480
 
448
481
  `push` runs `git push --porcelain` and returns one result per ref, so a
@@ -674,7 +707,7 @@ exit throws the classified failure.
674
707
  | `symbolicRef(ref)` | `symbolic-ref <ref>` | `128` → `null` |
675
708
  | `currentBranch()` | `branch --show-current` | none — `null` when detached |
676
709
  | `statusPorcelain({ paths })` | `status --porcelain` | none |
677
- | `statusEntries()` | `status --porcelain -z --untracked-files=all` | none — `{ x, y, path }` rows; a rename is one row, with the source dropped |
710
+ | `statusEntries({ ignored })` | `status --porcelain -z --untracked-files=all [--ignored]` | none — `{ x, y, path }` rows; a rename is one row, with the source dropped; `ignored` adds each ignored file as a `!` row |
678
711
  | `isDirty({ paths })` | `statusPorcelain().length > 0` | none |
679
712
  | `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 |
680
713
  | `branches(pattern)` | `branch --list --format=%(refname:lstrip=2)` | none |
@@ -698,7 +731,7 @@ exit throws the classified failure.
698
731
  | `diffNameStatus({ cached, range, noRenames, paths })` | `diff --name-status -z` | none |
699
732
  | `diffStat({ rangeArgs, paths })` | `diff --stat` | none — raw stdout |
700
733
  | `diffCheck({ paths })` | `diff --check` | `1`, `2` → `{ ok: false, output }` |
701
- | `diffText(rev?, { staged, paths })` | `diff [--cached] [rev]` | none — empty string only when nothing differs; a bad rev or a non-repository throws |
734
+ | `diffText(rev?, { staged, binary, paths })` | `diff [--cached] [--binary] [rev]` | none — empty string only when nothing differs; a bad rev or a non-repository throws; `binary` writes a binary file's change as a patch `git apply` replays |
702
735
  | `diffAddedFile(relPath)` | `diff --no-index -- /dev/null <path>` | none — exit 1 with output is success; exit 1 with no output, or exit 2, throws |
703
736
  | `log(opts)` | `log` | none — raw stdout, unsplit |
704
737
  | `logLines(opts)` | `log`, split and filtered | none |
@@ -710,6 +743,8 @@ exit throws the classified failure.
710
743
  | `aheadBehind(base, tip)` | `rev-list --left-right --count <base>...<tip>` | none |
711
744
  | `cherry(upstream, head)` | `cherry <upstream> [<head>]` | none — `{ sha, equivalent }` per commit; empty output is `[]`, an unreadable line throws |
712
745
  | `commitTree(tree, { parents, message })` | `commit-tree <tree> [-p <parent>]... -m <message>` | none — writes an object and no ref; needs a git identity |
746
+ | `hashObject(content, { write })` | `hash-object [-w] --stdin` | none — the blob sha; `write` stores the blob; `content` goes on stdin as UTF-8, unfiltered |
747
+ | `mktree(entries)` | `mktree -z` | none — writes a tree object and no ref; each entry is `{ mode, type?, sha, path }`, one name per entry; a duplicate name, a mode git does not write, a name git reads as `.git` (including `git~1`, `.git.` and the HFS+ spellings), or a `.gitmodules` that is not a file, each of which `git fsck --strict` reports, throws a `TypeError` |
713
748
  | `remotes()` | `remote` | none — names, not remotes |
714
749
  | `remote()` | `remote` | none — deprecated alias of `remotes()` |
715
750
  | `remoteGetUrl(name, { push })` | `remote get-url [--push] <name>` | `2` → `null` (unknown remote) — the first URL |
@@ -742,6 +777,7 @@ Integration, declares exit 1 absent and returns the rejected refs.
742
777
  | `clean({ directories })` | `clean -f`, or `-fd` — ignored files are kept |
743
778
  | `deleteBranch(name, { force })` | `branch -d` / `-D` |
744
779
  | `deleteRef(ref, { expected })` | `update-ref -d <ref> <expected>` — refuses when `ref` has moved |
780
+ | `updateRef(ref, sha, { oldSha, reason })` | `update-ref [-m <reason>] <ref> <sha> <oldSha>` — refuses when `ref` is not at `oldSha`; `oldSha: null` refuses when `ref` exists. `ref` is `HEAD` or a full `refs/…` name, and `oldSha` a full sha; anything else throws a `TypeError` |
745
781
  | `worktreeAdd(path, { branch, resetBranch, startPoint, detach })` | `worktree add` — `branch` is `-b`; `resetBranch` picks `-B` (create, or reset an existing branch), as for `checkout` |
746
782
  | `worktreeRemove(path, { force })` | `worktree remove` |
747
783
  | `worktreeMove(from, to, { force })` | `worktree move` |
@@ -775,13 +811,54 @@ other non-zero exit throws.
775
811
  | --- | --- |
776
812
  | `raw(argv, opts)` | Run anything. Returns `CommandResult`; you read `exitCode`. |
777
813
  | `rawChecked(argv, opts)` | Same, but throws the classified failure on a non-zero exit or on output cut short at a cap or a timeout. |
814
+ | `rawBytes(argv, opts)` | `raw` with stdout as a `Buffer`: the bytes git wrote, never decoded. Experimental. |
815
+ | `rawBytesChecked(argv, opts)` | `rawChecked` with stdout as a `Buffer`. Experimental. |
778
816
  | `at(cwd)` | The same client rooted elsewhere, reusing the runner or backend. |
779
817
  | `try.*` | The whole surface again, returning `Result<T, GitFailure>` (from `@osdlc/result`) instead of throwing. |
780
818
  | `soft.*` | Every verb with an absence value, returning it instead of throwing. |
781
819
 
782
- Use `raw` for a one-off command, such as `update-ref`, `tag -a` or a patch
783
- from `diff --unified`. A git command gets its own verb only when it has a
784
- parser worth sharing or an absence worth declaring.
820
+ Use `raw` for a one-off command, such as `tag -a`, `update-ref --stdin` for
821
+ several refs in one transaction, or a patch from `diff --unified`. A git
822
+ command gets its own verb only when it has a parser worth sharing or an
823
+ absence worth declaring.
824
+
825
+ ### Byte-exact output
826
+
827
+ Every verb, `raw` and `rawChecked` decode stdout as UTF-8. Bytes that are not
828
+ valid UTF-8 become U+FFFD, so a blob, a file name or a patch line in another
829
+ encoding changes on the way. `rawBytes` and `rawBytesChecked` return stdout
830
+ as the bytes git wrote. Stderr stays text, and a failure reads as it does for
831
+ `rawChecked`.
832
+
833
+ ```ts
834
+ const blob = git.rawBytesChecked(["cat-file", "blob", "HEAD:logo.png"]).stdout;
835
+ createHash("sha256").update(blob).digest("hex"); // the hash of the blob itself
836
+
837
+ git.rawBytesChecked(["status", "--porcelain", "-z", "--ignored"]).stdout; // names as stored
838
+ git.rawBytesChecked(["diff", "--cached", "--binary"]).stdout; // a patch, byte for byte
839
+ ```
840
+
841
+ They run on a second runner, `bytesRunner` (a `BytesCommandRunner` on `Git`,
842
+ an `AsyncBytesCommandRunner` on `cliBackend`). Without a `runner` it defaults
843
+ to command-seam's bytes runner, with the same absolute-`PATH` rule. A client
844
+ given a `runner` and no `bytesRunner` throws `UnsupportedRequest` from both,
845
+ so a fake or a supervised runner is never bypassed by a default spawn:
846
+
847
+ ```ts
848
+ new Git(cwd, { runner: fake, bytesRunner: fakeBytes });
849
+ new AsyncGit(cwd, { backend: cliBackend({ runner, bytesRunner }) });
850
+ ```
851
+
852
+ They are experimental because command-seam's bytes runners are. `input` is
853
+ still a string, so bytes cannot be piped in yet (see [Limits](#limits)).
854
+
855
+ Two verb options cover the common byte-sensitive cases without dropping to
856
+ `rawBytes`. `statusEntries({ ignored: true })` adds each ignored file as a
857
+ `{ x: "!", y: "!" }` row. `diffText(rev, { binary: true })` writes a binary
858
+ file's change as a `GIT binary patch`, which is ASCII, so the string holds it
859
+ intact and `rawChecked(["apply"], { input: patch })` replays it. A text file
860
+ whose lines are not UTF-8 still loses bytes in `diffText`. Read that patch
861
+ with `rawBytesChecked`.
785
862
 
786
863
  ## Driving the CLI, or something else
787
864
 
@@ -806,7 +883,7 @@ await new AsyncGit(cwd, { backend }).worktrees(); // UnsupportedReques
806
883
  ```
807
884
 
808
885
  Because a request is data, it can also be logged, queued, or replayed. The
809
- exception is `raw`, which is argv by definition.
886
+ exceptions are `raw` and `rawBytes`, which are argv by definition.
810
887
 
811
888
  ## Injecting the subprocess seam
812
889
 
@@ -855,13 +932,15 @@ A fake without the pin must answer `["--version"]` (once per runner) with
855
932
 
856
933
  `runner: undefined` is the same as omitting it, so a caller holding an optional
857
934
  runner passes it straight through, without a conditional spread. `cliBackend`
858
- accepts it too.
935
+ accepts it too. The same holds for `bytesRunner`, the runner behind
936
+ `rawBytes` (see [Byte-exact output](#byte-exact-output)). A fake `runner`
937
+ needs a fake `bytesRunner` beside it before `rawBytes` can run.
859
938
 
860
939
  The runner and result types, `CommandFailed`, `spawnRunner`, `spawnRunnerAsync`,
861
- `runChecked`, `runCheckedAsync` and `asAsync` are re-exported from command-seam,
862
- so wiring a runner or catching a `CommandFailed` needs one import rather than
863
- two. Import other runners, such as `spawnRunnerBytes` and `streamRunner`, from
864
- `@osdlc/command-seam`.
940
+ `spawnRunnerBytes`, `spawnRunnerBytesAsync`, `runChecked`, `runCheckedAsync`
941
+ and `asAsync` are re-exported from command-seam, so wiring a runner or catching
942
+ a `CommandFailed` needs one import rather than two. Import other runners, such
943
+ as `streamRunner`, from `@osdlc/command-seam`.
865
944
 
866
945
  ## Also: git references
867
946
 
@@ -1019,10 +1098,13 @@ de-duplicate.
1019
1098
  the classified failure. `AsyncGit` has no such cap. The `maxOutputBytes` call
1020
1099
  option sets the cap for one call on either client. Output cut short at a
1021
1100
  cap or a timeout is a failure, never an answer.
1022
- - stdout is text. There is no verb or call option that returns raw bytes,
1023
- such as a binary blob. Use command-seam's `spawnRunnerBytes` for that.
1024
- `raw` and `rawChecked` take `input` as a string, so binary stdin, such as
1025
- `hash-object --stdin` on a binary file, needs that runner too.
1101
+ - Verbs return text. Only `rawBytes` and `rawBytesChecked` return stdout as
1102
+ bytes. `input` is a string on every call, `rawBytes` and `hashObject` too,
1103
+ because command-seam takes stdin as a string. For binary stdin, such as
1104
+ `hash-object --stdin` on a binary file or `apply` of a patch read with
1105
+ `rawBytes`, write the bytes to a file and pass its path
1106
+ (`hash-object <file>`, `apply <file>`). See
1107
+ [D-04](docs/planning/decisions/D-04-byte-output.md).
1026
1108
  - Output is captured, never streamed. For live progress from `clone` or
1027
1109
  `fetch`, run git through command-seam's `streamRunner`.
1028
1110
  - `Git` cannot cancel a call. `AsyncGit` takes a `signal`.
package/dist/async.d.ts CHANGED
@@ -17,7 +17,7 @@ import { type GitBackend, type GitCallOptions } from './backend.ts';
17
17
  import type { GitVersion } from './git-version.ts';
18
18
  import { type Soft, type TriedAsync } from './outcome.ts';
19
19
  import { type RemoteCoordinate } from './remote-url.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 IndexSubmodule, 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 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
+ import { type AddOptions, type AheadBehind, type CherryEntry, type CommitTreeOptions, type CommitOptions, type HashObjectOptions, type MktreeEntry, type UpdateRefOptions, type CheckoutOptions, type ConfigGetOptions, type CloneOptions, type ConflictSide, type MergeOptions, type MergeOutcome, type MergeTreeOptions, type MergeTreeOutcome, type RebaseOptions, type RebaseOutcome, type RemoteGetUrlOptions, type IndexSubmodule, 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 PushReport, type RemoteRef, type CleanOptions, type DiffCheckOptions, type DiffCheckResult, type StatusEntriesOptions, type StatusEntry, type StatusPorcelainOptions, type TreeEntry, type Worktree, type WorktreeAddOptions, type WorktreeMoveOptions, type GcOptions, type PushOptions, type RemoteSetBranchesOptions, type RemoteSetHeadOptions } from './verbs.ts';
21
21
  /** A typed, awaitable git client bound to one working directory. */
22
22
  export declare class AsyncGit {
23
23
  readonly cwd: string;
@@ -44,9 +44,9 @@ export declare class AsyncGit {
44
44
  * Every method again, resolving to a `Result<T, GitFailure>` instead of
45
45
  * rejecting. A declared absence is `ok: true`; see `./outcome.ts`.
46
46
  *
47
- * The type leaves out `raw`, `rawChecked` and `at`, but at runtime the proxy
48
- * wraps them too: `git.try.raw(argv)` resolves to `{ ok: true, value }`.
49
- * Call those three on the client itself.
47
+ * The type leaves out the `raw*` methods
48
+ * and `at`, but at runtime the proxy wraps them too: `git.try.raw(argv)`
49
+ * resolves to `{ ok: true, value }`. Call those on the client itself.
50
50
  */
51
51
  get try(): TriedAsync<AsyncGit>;
52
52
  /**
@@ -56,7 +56,7 @@ export declare class AsyncGit {
56
56
  * `null` both for a missing ref and for a broken repo. Use `try` when the
57
57
  * failure itself matters.
58
58
  *
59
- * As with `try`, the proxy also wraps `raw`, `rawChecked` and `at` at
59
+ * As with `try`, the proxy also wraps the `raw*` methods and `at` at
60
60
  * runtime, though the type leaves them out.
61
61
  */
62
62
  get soft(): Soft<AsyncGit>;
@@ -75,6 +75,25 @@ export declare class AsyncGit {
75
75
  rawChecked(argv: string[], opts?: GitCallOptions & {
76
76
  input?: string | undefined;
77
77
  }): Promise<CommandResult>;
78
+ /**
79
+ * {@link AsyncGit.raw} with stdout as the bytes git wrote, never decoded.
80
+ * Rejects with `UnsupportedRequest` when the backend has no bytes
81
+ * runner (see `cliBackend`), as a non-CLI backend does. See {@link Git.rawBytes}.
82
+ *
83
+ * @experimental command-seam's bytes runners are experimental.
84
+ */
85
+ rawBytes(argv: string[], opts?: GitCallOptions & {
86
+ input?: string | undefined;
87
+ }): Promise<CommandResult<Buffer>>;
88
+ /**
89
+ * {@link AsyncGit.rawBytes} that rejects with the classified failure, as
90
+ * {@link AsyncGit.rawChecked} does. See {@link Git.rawBytesChecked}.
91
+ *
92
+ * @experimental command-seam's bytes runners are experimental.
93
+ */
94
+ rawBytesChecked(argv: string[], opts?: GitCallOptions & {
95
+ input?: string | undefined;
96
+ }): Promise<CommandResult<Buffer>>;
78
97
  /**
79
98
  * The git the backend runs, from `git --version`; see {@link Git.version}.
80
99
  * `cliBackend` probes once per runner and caches it, or returns its
@@ -127,8 +146,8 @@ export declare class AsyncGit {
127
146
  * outside a repository. `paths` narrows the report to those pathspecs.
128
147
  */
129
148
  statusPorcelain(opts?: GitCallOptions & StatusPorcelainOptions): Promise<string[]>;
130
- /** Every changed or untracked file, from `status --porcelain -z`. */
131
- statusEntries(opts?: GitCallOptions): Promise<StatusEntry[]>;
149
+ /** Every changed or untracked file, and ignored ones with `ignored`. See {@link Git.statusEntries}. */
150
+ statusEntries(opts?: GitCallOptions & StatusEntriesOptions): Promise<StatusEntry[]>;
132
151
  /** True iff anything is staged. See {@link Git.hasStagedChanges}. */
133
152
  hasStagedChanges(opts?: GitCallOptions): Promise<boolean>;
134
153
  /** True iff the working tree has any staged/unstaged/untracked change. */
@@ -233,6 +252,10 @@ export declare class AsyncGit {
233
252
  cherry(upstream: string, head?: string, opts?: GitCallOptions): Promise<CherryEntry[]>;
234
253
  /** Write a commit for `tree` and return its sha; no ref moves. Needs a git identity. */
235
254
  commitTree(tree: string, commitOpts: CommitTreeOptions, opts?: GitCallOptions): Promise<string>;
255
+ /** The blob sha of `content`; `{ write: true }` also writes the blob. See {@link Git.hashObject}. */
256
+ hashObject(content: string, opts?: GitCallOptions & HashObjectOptions): Promise<string>;
257
+ /** Write a tree of `entries` and return its sha; no ref moves. See {@link Git.mktree}. */
258
+ mktree(entries: readonly MktreeEntry[], opts?: GitCallOptions): Promise<string>;
236
259
  /** Configured remote names (`git remote`); `[]` when there are none. */
237
260
  remotes(opts?: GitCallOptions): Promise<string[]>;
238
261
  /**
@@ -295,6 +318,11 @@ export declare class AsyncGit {
295
318
  deleteRef(ref: string, opts: GitCallOptions & {
296
319
  expected: string;
297
320
  }): Promise<void>;
321
+ /**
322
+ * Point `ref` at `sha` only while it holds `oldSha` (`null`: only while it
323
+ * does not exist). See {@link Git.updateRef}.
324
+ */
325
+ updateRef(ref: string, sha: string, opts: GitCallOptions & UpdateRefOptions): Promise<void>;
298
326
  /** `git worktree add [--detach] [-b|-B branch] <path> [startPoint]`. See {@link Git.worktreeAdd}. */
299
327
  worktreeAdd(path: string, opts?: GitCallOptions & WorktreeAddOptions): Promise<void>;
300
328
  /** `git worktree remove [--force] <path>`. */
package/dist/async.js CHANGED
@@ -59,9 +59,9 @@ export class AsyncGit {
59
59
  * Every method again, resolving to a `Result<T, GitFailure>` instead of
60
60
  * rejecting. A declared absence is `ok: true`; see `./outcome.ts`.
61
61
  *
62
- * The type leaves out `raw`, `rawChecked` and `at`, but at runtime the proxy
63
- * wraps them too: `git.try.raw(argv)` resolves to `{ ok: true, value }`.
64
- * Call those three on the client itself.
62
+ * The type leaves out the `raw*` methods
63
+ * and `at`, but at runtime the proxy wraps them too: `git.try.raw(argv)`
64
+ * resolves to `{ ok: true, value }`. Call those on the client itself.
65
65
  */
66
66
  get try() {
67
67
  return (this.tried ??= triedAsync(this));
@@ -73,7 +73,7 @@ export class AsyncGit {
73
73
  * `null` both for a missing ref and for a broken repo. Use `try` when the
74
74
  * failure itself matters.
75
75
  *
76
- * As with `try`, the proxy also wraps `raw`, `rawChecked` and `at` at
76
+ * As with `try`, the proxy also wraps the `raw*` methods and `at` at
77
77
  * runtime, though the type leaves them out.
78
78
  */
79
79
  get soft() {
@@ -96,6 +96,25 @@ export class AsyncGit {
96
96
  rawChecked(argv, opts = {}) {
97
97
  return this.backend.execute(this.cwd, { kind: 'raw', argv, checked: true, input: opts.input }, opts);
98
98
  }
99
+ /**
100
+ * {@link AsyncGit.raw} with stdout as the bytes git wrote, never decoded.
101
+ * Rejects with `UnsupportedRequest` when the backend has no bytes
102
+ * runner (see `cliBackend`), as a non-CLI backend does. See {@link Git.rawBytes}.
103
+ *
104
+ * @experimental command-seam's bytes runners are experimental.
105
+ */
106
+ rawBytes(argv, opts = {}) {
107
+ return this.backend.execute(this.cwd, { kind: 'rawBytes', argv, input: opts.input }, opts);
108
+ }
109
+ /**
110
+ * {@link AsyncGit.rawBytes} that rejects with the classified failure, as
111
+ * {@link AsyncGit.rawChecked} does. See {@link Git.rawBytesChecked}.
112
+ *
113
+ * @experimental command-seam's bytes runners are experimental.
114
+ */
115
+ rawBytesChecked(argv, opts = {}) {
116
+ return this.backend.execute(this.cwd, { kind: 'rawBytes', argv, checked: true, input: opts.input }, opts);
117
+ }
99
118
  // ── queries ───────────────────────────────────────────────────────────────
100
119
  /**
101
120
  * The git the backend runs, from `git --version`; see {@link Git.version}.
@@ -190,9 +209,10 @@ export class AsyncGit {
190
209
  const [call, req] = splitCallOptions(opts);
191
210
  return this.backend.execute(this.cwd, { kind: 'statusPorcelain', ...req }, call);
192
211
  }
193
- /** Every changed or untracked file, from `status --porcelain -z`. */
212
+ /** Every changed or untracked file, and ignored ones with `ignored`. See {@link Git.statusEntries}. */
194
213
  statusEntries(opts = {}) {
195
- return this.backend.execute(this.cwd, { kind: 'statusEntries' }, opts);
214
+ const [call, req] = splitCallOptions(opts);
215
+ return this.backend.execute(this.cwd, { kind: 'statusEntries', ...req }, call);
196
216
  }
197
217
  /** True iff anything is staged. See {@link Git.hasStagedChanges}. */
198
218
  hasStagedChanges(opts = {}) {
@@ -289,7 +309,7 @@ export class AsyncGit {
289
309
  */
290
310
  diffText(rev, opts = {}) {
291
311
  const [call, req] = splitCallOptions(opts);
292
- return this.backend.execute(this.cwd, { kind: 'diffText', rev, staged: req.staged, paths: req.paths }, call);
312
+ return this.backend.execute(this.cwd, { kind: 'diffText', rev, staged: req.staged, binary: req.binary, paths: req.paths }, call);
293
313
  }
294
314
  /**
295
315
  * One untracked file rendered as an all-added diff. A path git cannot read
@@ -388,6 +408,15 @@ export class AsyncGit {
388
408
  commitTree(tree, commitOpts, opts = {}) {
389
409
  return this.backend.execute(this.cwd, { kind: 'commitTree', tree, ...commitOpts }, opts);
390
410
  }
411
+ /** The blob sha of `content`; `{ write: true }` also writes the blob. See {@link Git.hashObject}. */
412
+ hashObject(content, opts = {}) {
413
+ const [call, req] = splitCallOptions(opts);
414
+ return this.backend.execute(this.cwd, { kind: 'hashObject', content, ...req }, call);
415
+ }
416
+ /** Write a tree of `entries` and return its sha; no ref moves. See {@link Git.mktree}. */
417
+ mktree(entries, opts = {}) {
418
+ return this.backend.execute(this.cwd, { kind: 'mktree', entries }, opts);
419
+ }
391
420
  /** Configured remote names (`git remote`); `[]` when there are none. */
392
421
  remotes(opts = {}) {
393
422
  return this.backend.execute(this.cwd, { kind: 'remote' }, opts);
@@ -494,6 +523,14 @@ export class AsyncGit {
494
523
  deleteRef(ref, opts) {
495
524
  return this.backend.execute(this.cwd, { kind: 'deleteRef', ref, expected: opts.expected }, opts);
496
525
  }
526
+ /**
527
+ * Point `ref` at `sha` only while it holds `oldSha` (`null`: only while it
528
+ * does not exist). See {@link Git.updateRef}.
529
+ */
530
+ updateRef(ref, sha, opts) {
531
+ const [call, req] = splitCallOptions(opts);
532
+ return this.backend.execute(this.cwd, { kind: 'updateRef', ref, sha, ...req }, call);
533
+ }
497
534
  /** `git worktree add [--detach] [-b|-B branch] <path> [startPoint]`. See {@link Git.worktreeAdd}. */
498
535
  worktreeAdd(path, opts = {}) {
499
536
  const [call, req] = splitCallOptions(opts);
package/dist/backend.d.ts CHANGED
@@ -9,17 +9,17 @@
9
9
  * the same client work with either.
10
10
  *
11
11
  * It also means a request can be logged, queued, or replayed as data. The
12
- * exception is `raw`, which is argv by definition. A non-CLI backend rejects
13
- * it with {@link UnsupportedRequest}.
12
+ * exceptions are `raw` and `rawBytes`, which are argv by definition. A non-CLI
13
+ * backend rejects them with {@link UnsupportedRequest}.
14
14
  *
15
15
  * The interface is experimental: `GitBackend`, `GitRequest`, `GitResults` and
16
16
  * `partialBackend`. Each new verb adds a request kind, which breaks a backend
17
17
  * written as an exhaustive switch. Such a change can land in a minor release.
18
18
  * `cliBackend` and `AsyncGit` are stable.
19
19
  */
20
- import { type AsyncCommandRunner, type CommandResult } from '@osdlc/command-seam';
20
+ import { type AsyncBytesCommandRunner, type AsyncCommandRunner, type CommandResult } from '@osdlc/command-seam';
21
21
  import { type GitVersion } from './git-version.ts';
22
- import { type AddOptions, type AheadBehind, type CherryEntry, type CommitTreeOptions, type CheckoutOptions, type CloneOptions, type CommitOptions, type ConfigGetOptions, type ConfigSetOptions, type ConflictSide, type DiffEntry, type DiffNameOnlyOptions, type DiffStatOptions, type DiffNameStatusOptions, type DiffTextOptions, type DiffTreeOptions, type FetchOptions, type ForEachRefOptions, type GcOptions, type GrepOptions, type InitOptions, type LogOptions, type IgnoreMatch, type LsFilesOptions, type LsRemoteOptions, type LsTreeOptions, type MergeOptions, type MergeOutcome, type MergeTreeOptions, type MergeTreeOutcome, type NumstatEntry, type PushOptions, type PushReport, type RemoteSetBranchesOptions, type RemoteSetHeadOptions, type WorktreeAddOptions, type RebaseOptions, type RebaseOutcome, type RemoteGetUrlOptions, type RemoteRef, type CleanOptions, type DiffCheckOptions, type DiffCheckResult, type StatusEntry, type StatusPorcelainOptions, type TreeEntry, type IndexSubmodule, type TaggedFile, type UnmergedEntry, type Worktree, type WorktreeMoveOptions } from './verbs.ts';
22
+ import { type AddOptions, type AheadBehind, type CherryEntry, type CommitTreeOptions, type HashObjectOptions, type MktreeEntry, type UpdateRefOptions, type CheckoutOptions, type CloneOptions, type CommitOptions, type ConfigGetOptions, type ConfigSetOptions, type ConflictSide, type DiffEntry, type DiffNameOnlyOptions, type DiffStatOptions, type DiffNameStatusOptions, type DiffTextOptions, type DiffTreeOptions, type FetchOptions, type ForEachRefOptions, type GcOptions, type GrepOptions, type InitOptions, type LogOptions, type IgnoreMatch, type LsFilesOptions, type LsRemoteOptions, type LsTreeOptions, type MergeOptions, type MergeOutcome, type MergeTreeOptions, type MergeTreeOutcome, type NumstatEntry, type PushOptions, type PushReport, type RemoteSetBranchesOptions, type RemoteSetHeadOptions, type WorktreeAddOptions, type RebaseOptions, type RebaseOutcome, type RemoteGetUrlOptions, type RemoteRef, type CleanOptions, type DiffCheckOptions, type DiffCheckResult, type StatusEntriesOptions, type StatusEntry, type StatusPorcelainOptions, type TreeEntry, type IndexSubmodule, type TaggedFile, type UnmergedEntry, type Worktree, type WorktreeMoveOptions } from './verbs.ts';
23
23
  /** Per-call concerns that are not part of the operation itself. */
24
24
  export interface GitCallOptions {
25
25
  /**
@@ -88,9 +88,9 @@ export type GitRequest = {
88
88
  kind: 'currentBranch';
89
89
  } | ({
90
90
  kind: 'statusPorcelain';
91
- } & StatusPorcelainOptions) | {
91
+ } & StatusPorcelainOptions) | ({
92
92
  kind: 'statusEntries';
93
- } | {
93
+ } & StatusEntriesOptions) | {
94
94
  kind: 'branches';
95
95
  pattern?: string | undefined;
96
96
  } | {
@@ -140,6 +140,12 @@ export type GitRequest = {
140
140
  kind: 'commitTree';
141
141
  tree: string;
142
142
  } & CommitTreeOptions) | ({
143
+ kind: 'hashObject';
144
+ content: string;
145
+ } & HashObjectOptions) | {
146
+ kind: 'mktree';
147
+ entries: readonly MktreeEntry[];
148
+ } | ({
143
149
  kind: 'lsFiles';
144
150
  } & LsFilesOptions) | {
145
151
  kind: 'lsFilesTagged';
@@ -219,6 +225,10 @@ export type GitRequest = {
219
225
  ref: string;
220
226
  expected: string;
221
227
  } | ({
228
+ kind: 'updateRef';
229
+ ref: string;
230
+ sha: string;
231
+ } & UpdateRefOptions) | ({
222
232
  kind: 'worktreeAdd';
223
233
  path: string;
224
234
  } & WorktreeAddOptions) | {
@@ -288,6 +298,11 @@ export type GitRequest = {
288
298
  argv: string[];
289
299
  input?: string | undefined;
290
300
  checked?: boolean | undefined;
301
+ } | {
302
+ kind: 'rawBytes';
303
+ argv: string[];
304
+ input?: string | undefined;
305
+ checked?: boolean | undefined;
291
306
  };
292
307
  /**
293
308
  * The result type each request kind resolves to.
@@ -323,6 +338,8 @@ export interface GitResults {
323
338
  aheadBehind: AheadBehind;
324
339
  cherry: CherryEntry[];
325
340
  commitTree: string;
341
+ hashObject: string;
342
+ mktree: string;
326
343
  lsFiles: string[];
327
344
  lsFilesTagged: TaggedFile[];
328
345
  submodules: IndexSubmodule[];
@@ -351,6 +368,7 @@ export interface GitResults {
351
368
  clean: void;
352
369
  deleteBranch: void;
353
370
  deleteRef: void;
371
+ updateRef: void;
354
372
  worktreeAdd: void;
355
373
  worktreeRemove: void;
356
374
  worktreeMove: void;
@@ -374,6 +392,7 @@ export interface GitResults {
374
392
  remoteSetBranches: void;
375
393
  gc: void;
376
394
  raw: CommandResult;
395
+ rawBytes: CommandResult<Buffer>;
377
396
  }
378
397
  /** Every request kind, as a union of string literals. */
379
398
  export type GitRequestKind = GitRequest['kind'];
@@ -398,20 +417,27 @@ export type GitRequestKind = GitRequest['kind'];
398
417
  export interface GitBackend {
399
418
  execute<R extends GitRequest>(cwd: string, request: R, opts?: GitCallOptions): Promise<GitResults[R['kind']]>;
400
419
  }
401
- /** Thrown by a backend asked for an operation it cannot perform. */
402
- export declare class UnsupportedRequest extends Error {
403
- readonly kind: string;
404
- constructor(kind: string, backend: string);
405
- }
406
420
  /**
407
421
  * The default backend: every request becomes a `git` subprocess, run through
408
422
  * an {@link AsyncCommandRunner} so the caller decides how spawning happens
409
423
  * (and tests inject a fake). The default runner spawns the `git` found on an
410
424
  * absolute `PATH` entry, so a `git` file in the checkout cannot run in its
411
425
  * place.
426
+ *
427
+ * `rawBytes` runs on a second runner, `bytesRunner`, which keeps stdout as
428
+ * bytes. Without `runner` it defaults to `spawnRunnerBytesAsync` with the same
429
+ * `PATH` rule. A backend given a `runner` and no `bytesRunner` rejects
430
+ * `rawBytes` with {@link UnsupportedRequest}, so a fake or a supervised runner
431
+ * is never bypassed by a default spawn.
412
432
  */
413
433
  export declare function cliBackend(opts?: {
414
434
  runner?: AsyncCommandRunner | undefined;
435
+ /**
436
+ * The runner for `rawBytes`. See the function doc for its default.
437
+ *
438
+ * @experimental command-seam's bytes runners are experimental.
439
+ */
440
+ bytesRunner?: AsyncBytesCommandRunner | undefined;
415
441
  /**
416
442
  * The repository to work on, added to every call as `--git-dir` /
417
443
  * `--work-tree`. They are set on the backend, not on `GitRequest`, because
package/dist/backend.js CHANGED
@@ -9,28 +9,20 @@
9
9
  * the same client work with either.
10
10
  *
11
11
  * It also means a request can be logged, queued, or replayed as data. The
12
- * exception is `raw`, which is argv by definition. A non-CLI backend rejects
13
- * it with {@link UnsupportedRequest}.
12
+ * exceptions are `raw` and `rawBytes`, which are argv by definition. A non-CLI
13
+ * backend rejects them with {@link UnsupportedRequest}.
14
14
  *
15
15
  * The interface is experimental: `GitBackend`, `GitRequest`, `GitResults` and
16
16
  * `partialBackend`. Each new verb adds a request kind, which breaks a backend
17
17
  * written as an exhaustive switch. Such a change can land in a minor release.
18
18
  * `cliBackend` and `AsyncGit` are stable.
19
19
  */
20
- import { spawnRunnerAsync, } from '@osdlc/command-seam';
20
+ import { spawnRunnerAsync, spawnRunnerBytesAsync, } from '@osdlc/command-seam';
21
+ import { UnsupportedRequest } from "./failure.js";
21
22
  import { versionedVerb } from "./features.js";
22
23
  import { pinnedGitVersion, probeGitVersionAsync, versionVerb, } from "./git-version.js";
23
24
  import * as v from "./verbs.js";
24
- import { gate, mergeEnv, repoPrefix, } from "./verbs.js";
25
- /** Thrown by a backend asked for an operation it cannot perform. */
26
- export class UnsupportedRequest extends Error {
27
- kind;
28
- constructor(kind, backend) {
29
- super(`${backend} cannot perform '${kind}'`);
30
- this.name = 'UnsupportedRequest';
31
- this.kind = kind;
32
- }
33
- }
25
+ import { bytesRunnerFor, gate, gateBytes, mergeEnv, repoPrefix, } from "./verbs.js";
34
26
  /** Translate a request into the CLI verb that performs it. */
35
27
  function toVerb(request) {
36
28
  switch (request.kind) {
@@ -59,7 +51,7 @@ function toVerb(request) {
59
51
  case 'statusPorcelain':
60
52
  return v.statusPorcelain(request);
61
53
  case 'statusEntries':
62
- return v.statusEntries();
54
+ return v.statusEntries(request);
63
55
  case 'branches':
64
56
  return v.branches(request.pattern);
65
57
  case 'worktrees':
@@ -86,6 +78,10 @@ function toVerb(request) {
86
78
  return v.cherry(request.upstream, request.head);
87
79
  case 'commitTree':
88
80
  return v.commitTree(request.tree, request);
81
+ case 'hashObject':
82
+ return v.hashObject(request.content, request);
83
+ case 'mktree':
84
+ return v.mktree(request.entries);
89
85
  case 'checkIgnore':
90
86
  return v.checkIgnore(request.relPaths);
91
87
  case 'checkIgnoreVerbose':
@@ -146,6 +142,8 @@ function toVerb(request) {
146
142
  return v.deleteBranch(request.name, { force: request.force });
147
143
  case 'deleteRef':
148
144
  return v.deleteRef(request.ref, { expected: request.expected });
145
+ case 'updateRef':
146
+ return v.updateRef(request.ref, request.sha, request);
149
147
  case 'worktreeAdd':
150
148
  return v.worktreeAdd(request.path, request);
151
149
  case 'worktreeRemove':
@@ -210,9 +208,16 @@ function toVerb(request) {
210
208
  * (and tests inject a fake). The default runner spawns the `git` found on an
211
209
  * absolute `PATH` entry, so a `git` file in the checkout cannot run in its
212
210
  * place.
211
+ *
212
+ * `rawBytes` runs on a second runner, `bytesRunner`, which keeps stdout as
213
+ * bytes. Without `runner` it defaults to `spawnRunnerBytesAsync` with the same
214
+ * `PATH` rule. A backend given a `runner` and no `bytesRunner` rejects
215
+ * `rawBytes` with {@link UnsupportedRequest}, so a fake or a supervised runner
216
+ * is never bypassed by a default spawn.
213
217
  */
214
218
  export function cliBackend(opts = {}) {
215
219
  const runner = opts.runner ?? spawnRunnerAsync('git', { absolutePathOnly: true });
220
+ const bytesRunner = bytesRunnerFor(opts, () => spawnRunnerBytesAsync('git', { absolutePathOnly: true }));
216
221
  const pinned = pinnedGitVersion(opts.gitVersion);
217
222
  // A failed probe names `report`: the gated verb's argv, so a missing git
218
223
  // reads `git worktree: …` rather than `git --version: …`.
@@ -227,7 +232,6 @@ export function cliBackend(opts = {}) {
227
232
  const prefix = repoPrefix(opts.gitDir, opts.workTree);
228
233
  return {
229
234
  async execute(cwd, request, callOpts = {}) {
230
- const gated = toVerb(request);
231
235
  const runOpts = { cwd };
232
236
  if (callOpts.timeoutMs !== undefined)
233
237
  runOpts.timeoutMs = callOpts.timeoutMs;
@@ -245,6 +249,17 @@ export function cliBackend(opts = {}) {
245
249
  if (req.kind === 'version') {
246
250
  return (await versionOf(runOpts, ['--version']));
247
251
  }
252
+ if (req.kind === 'rawBytes') {
253
+ if (bytesRunner === undefined) {
254
+ throw new UnsupportedRequest(req.kind, 'cliBackend with a runner and no bytesRunner');
255
+ }
256
+ if (req.input !== undefined)
257
+ runOpts.input = req.input;
258
+ const argv = prefix.length === 0 ? req.argv : [...prefix, ...req.argv];
259
+ const result = await bytesRunner.run(argv, runOpts);
260
+ return (req.checked === true ? gateBytes(result, argv) : result);
261
+ }
262
+ const gated = toVerb(req);
248
263
  // A verb that needs a git feature runs in the form this git supports,
249
264
  // or rejects as `unsupported-git`. Others never probe.
250
265
  const verb = gated.needs === undefined
@@ -257,9 +272,9 @@ export function cliBackend(opts = {}) {
257
272
  runOpts.env = { ...runOpts.env, ...verb.env };
258
273
  const argv = prefix.length === 0 ? verb.argv : [...prefix, ...verb.argv];
259
274
  const result = await runner.run(argv, runOpts);
260
- // Unchecked `raw` is the only request that skips `gate`: it returns the
261
- // result at any exit code. Everything else goes through the same `gate`
262
- // the sync client uses.
275
+ // Unchecked `raw`, and unchecked `rawBytes` above, are the only requests
276
+ // that skip `gate`: they return the result at any exit code. Everything
277
+ // else goes through the same `gate` the sync client uses.
263
278
  const checked = req.kind !== 'raw' || req.checked === true;
264
279
  // The prefixed argv is what ran, so it is what a `CommandFailed` reports.
265
280
  const value = checked ? gate(verb, result, argv) : verb.parse(result, argv);