@osdlc/typed-git 0.17.0 → 0.19.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,25 @@
1
1
  # @osdlc/typed-git
2
2
 
3
+ ## 0.19.0
4
+
5
+ ### Minor Changes
6
+
7
+ - c8470d6: `catFileBatch(names, { maxBytes, chunkBytes })` and `catFileBatchChunks` (on `Git` and `AsyncGit`) read many objects byte for byte through `git cat-file --batch`: one `--batch-check` for the sizes, then `--batch` for the blobs within `maxBytes`, in groups of about `chunkBytes`. Each name maps to `text`, `binary`, `too-large`, `not-blob` or `missing`.
8
+ - 0ce8abc: `fetchMany(remotes, { prune, quiet, noWriteFetchHead, noTags, jobs })`: `git fetch --multiple`, every remote in one call, up to `jobs` at once. Git fetches each remote it can and exits non-zero naming any that failed.
9
+ - 9c0f5ae: `forEachRef` takes `contains`, which passes `--contains=<commit>` so only refs whose history holds that commit are listed.
10
+
11
+ ### Patch Changes
12
+
13
+ - Updated dependencies [6d37030]
14
+ - @osdlc/command-seam@0.15.1
15
+
16
+ ## 0.18.0
17
+
18
+ ### Minor Changes
19
+
20
+ - b0ff1b3: `readTree(rev)` and `writeTree()` on `Git` and `AsyncGit` (and the verbs) run `git read-tree <rev>` and `git write-tree`. With `env: { GIT_INDEX_FILE }` on the call, they seed and read a temporary index, so a commit can be built from a working tree without touching the repository's own index.
21
+ - cb56f16: `submoduleUpdate()` on `Git` and `AsyncGit` (and the `submoduleUpdate` verb) runs `git submodule update --init --recursive --checkout` with the `file` and `ext` transports refused (a pull request's `.gitmodules` is not trusted): it checks out every submodule, nested ones included, at the commit the checked-out tree pins, and clones those not yet initialised.
22
+
3
23
  ## 0.17.0
4
24
 
5
25
  ### Minor Changes
package/README.md CHANGED
@@ -756,6 +756,7 @@ exit throws the classified failure.
756
756
  | `lsFiles({ cached, others, excludeStandard, directory, paths })` | `ls-files -z` | none |
757
757
  | `lsFilesTagged()` | `ls-files -v -z` | none — `{ tag, path }` rows; `S` is skip-worktree, lowercase is assume-unchanged |
758
758
  | `submodules()` | `ls-files --stage -z` | none — `{ path, commit }` per gitlink in the index; whether one is checked out is on disk (its `.git`) |
759
+ | `submoduleUpdate()` | `-c protocol.file.allow=never -c protocol.ext.allow=never submodule update --init --recursive --checkout` | none; refuses `file`/`ext` URLs — checks out each submodule, nested ones too, at the commit the tree pins; clones those not yet initialised, so a `.gitmodules` URL is fetched |
759
760
  | `forEachRef(pattern, { format, sort, count })` | `for-each-ref` | none — lines verbatim |
760
761
  | `refs(pattern)` | `forEachRef` + `parseRefRows` | none |
761
762
  | `diffNameOnly({ cached, diffFilter, rangeArgs, paths })` | `diff --name-only -z` | none |
@@ -776,6 +777,8 @@ exit throws the classified failure.
776
777
  | `commitTree(tree, { parents, message })` | `commit-tree <tree> [-p <parent>]... -m <message>` | none — writes an object and no ref; needs a git identity |
777
778
  | `hashObject(content, { write })` | `hash-object [-w] --stdin` | none — the blob sha; `write` stores the blob; `content` goes on stdin as UTF-8, unfiltered |
778
779
  | `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` |
780
+ | `readTree(rev)` | `read-tree <rev>` | none — loads the tree into the index and leaves the working tree alone; pass `env: { GIT_INDEX_FILE }` on the call to use a temporary index |
781
+ | `writeTree()` | `write-tree` | none — the tree sha of the index; writes objects and no ref; a conflicted index throws |
779
782
  | `remotes()` | `remote` | none — names, not remotes |
780
783
  | `remote()` | `remote` | none — deprecated alias of `remotes()` |
781
784
  | `remoteGetUrl(name, { push })` | `remote get-url [--push] <name>` | `2` → `null` (unknown remote) — the first URL |
@@ -798,6 +801,7 @@ Integration, declares exit 1 absent and returns the rejected refs.
798
801
  | Method | git |
799
802
  | --- | --- |
800
803
  | `fetch(remote, refspec, { prune, quiet, noWriteFetchHead, depth, noTags })` | `fetch` |
804
+ | `fetchMany(remotes, { prune, quiet, noWriteFetchHead, noTags, jobs })` | `fetch --multiple [--jobs=<n>]` — every remote in one call, `jobs` at once; an empty list or a `jobs` that is not a positive integer throws a `TypeError` |
801
805
  | `add(paths, { all, update, intentToAdd })` | `add` (paths go after `--`) |
802
806
  | `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 |
803
807
  | `configSet(key, value, { scope })` | `config` |
@@ -805,7 +809,7 @@ Integration, declares exit 1 absent and returns the rejected refs.
805
809
  | `init(path, { bare, initialBranch, quiet })` | `init` |
806
810
  | `clone(url, dest, { depth, branch, bare, mirror, singleBranch, noTags, quiet })` | `clone` — a relative `dest` resolves in the client's working directory; `branch` takes a branch or a tag, not a sha; with `mirror`, `noTags` has no effect and `singleBranch` holds for the clone only |
807
811
  | `resetHard(rev)` | `reset --hard` |
808
- | `clean({ directories })` | `clean -f`, or `-fd` — ignored files are kept |
812
+ | `clean({ directories, nested })` | `clean -f`, `-fd`, `-ffd` with `nested` (also nested repositories) — ignored files are kept |
809
813
  | `deleteBranch(name, { force })` | `branch -d` / `-D` |
810
814
  | `deleteRef(ref, { expected })` | `update-ref -d <ref> <expected>` — refuses when `ref` has moved |
811
815
  | `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` |
@@ -891,6 +895,34 @@ intact and `rawChecked(["apply"], { input: patch })` replays it. A text file
891
895
  whose lines are not UTF-8 still loses bytes in `diffText`. Read that patch
892
896
  with `rawBytesChecked`.
893
897
 
898
+ ### Many objects at once
899
+
900
+ `catFileBatch(names, { maxBytes, chunkBytes })` reads many objects, byte for
901
+ byte, in a few processes rather than one `git show` each. `names` are anything
902
+ `git cat-file` reads, such as `rev:path` or a sha. It runs
903
+ `cat-file --batch-check` for the sizes, then `cat-file --batch` for the blobs
904
+ within `maxBytes`, in groups of about `chunkBytes` (64 MiB). It returns a map
905
+ from each name to one of:
906
+
907
+ | `kind` | Fields | Meaning |
908
+ | --- | --- | --- |
909
+ | `text`, `binary` | `sha`, `size`, `bytes` | a blob; `binary` has a NUL in its first 8000 bytes |
910
+ | `too-large` | `sha`, `size` | a blob over `maxBytes`; not read |
911
+ | `not-blob` | `type`, `sha`, `size` | a tree, commit or tag, such as `rev:dir`; not read |
912
+ | `missing` | | no such object, or a short sha that names more than one |
913
+
914
+ ```ts
915
+ const got = git.catFileBatch(changed.map((p) => `HEAD:${p}`), { maxBytes: 1 << 20 });
916
+ for (const [name, e] of got) if (e.kind === "text") scan(name, e.bytes.toString("utf8"));
917
+ ```
918
+
919
+ `catFileBatchChunks` yields the map one group at a time, so a caller can use
920
+ the bytes and drop them before the next read; `AsyncGit` has both, with
921
+ `for await` on the chunks. A name that is empty or holds a newline, a NUL or a trailing CR
922
+ throws `TypeError` (the protocol is one name per line). The entry `bytes` are
923
+ views of the group's buffer. Both run on the `bytesRunner`, so they are
924
+ experimental and throw `UnsupportedRequest` where `rawBytes` does.
925
+
894
926
  ## Driving the CLI, or something else
895
927
 
896
928
  `AsyncGit` calls a `GitBackend`, which takes a `GitRequest` (a plain,
package/dist/async.d.ts CHANGED
@@ -13,11 +13,12 @@
13
13
  * client takes `gitDir` on its own constructor.
14
14
  */
15
15
  import type { CommandResult } from '@osdlc/command-seam';
16
+ import { type CatFileBatchOptions, type CatFileEntry } from './cat-file.ts';
16
17
  import { type GitBackend, type GitCallOptions } from './backend.ts';
17
18
  import type { GitVersion } from './git-version.ts';
18
19
  import { type Soft, type TriedAsync } from './outcome.ts';
19
20
  import { type RemoteCoordinate } from './remote-url.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
+ 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 FetchManyOptions, 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
22
  /** A typed, awaitable git client bound to one working directory. */
22
23
  export declare class AsyncGit {
23
24
  readonly cwd: string;
@@ -94,6 +95,21 @@ export declare class AsyncGit {
94
95
  rawBytesChecked(argv: string[], opts?: GitCallOptions & {
95
96
  input?: string | undefined;
96
97
  }): Promise<CommandResult<Buffer>>;
98
+ /**
99
+ * Many objects at once, byte-exact. Rejects with the classified failure if
100
+ * git fails, and with `UnsupportedRequest` when the backend has no bytes
101
+ * runner. See {@link Git.catFileBatch}.
102
+ *
103
+ * @experimental command-seam's bytes runners are experimental.
104
+ */
105
+ catFileBatch(names: readonly string[], opts?: GitCallOptions & CatFileBatchOptions): Promise<Map<string, CatFileEntry>>;
106
+ /**
107
+ * {@link AsyncGit.catFileBatch} one group of blobs at a time. See
108
+ * {@link Git.catFileBatchChunks}.
109
+ *
110
+ * @experimental command-seam's bytes runners are experimental.
111
+ */
112
+ catFileBatchChunks(names: readonly string[], opts?: GitCallOptions & CatFileBatchOptions): AsyncGenerator<Map<string, CatFileEntry>, void, undefined>;
97
113
  /**
98
114
  * The git the backend runs, from `git --version`; see {@link Git.version}.
99
115
  * `cliBackend` probes once per runner and caches it, or returns its
@@ -256,6 +272,10 @@ export declare class AsyncGit {
256
272
  hashObject(content: string, opts?: GitCallOptions & HashObjectOptions): Promise<string>;
257
273
  /** Write a tree of `entries` and return its sha; no ref moves. See {@link Git.mktree}. */
258
274
  mktree(entries: readonly MktreeEntry[], opts?: GitCallOptions): Promise<string>;
275
+ /** Load `rev`'s tree into the index; pass `env: { GIT_INDEX_FILE }` to use a temporary one. See {@link Git.readTree}. */
276
+ readTree(rev: string, opts?: GitCallOptions): Promise<void>;
277
+ /** Write the index as a tree and return its sha; no ref moves. See {@link Git.writeTree}. */
278
+ writeTree(opts?: GitCallOptions): Promise<string>;
259
279
  /** Configured remote names (`git remote`); `[]` when there are none. */
260
280
  remotes(opts?: GitCallOptions): Promise<string[]>;
261
281
  /**
@@ -281,6 +301,8 @@ export declare class AsyncGit {
281
301
  remoteOwnerRepo(remote?: string, opts?: GitCallOptions): Promise<RemoteCoordinate | null>;
282
302
  /** `git fetch <remote> [refspec…]`. See {@link FetchOptions} for the flags. */
283
303
  fetch(remote: string, refspec?: string | string[] | undefined, opts?: GitCallOptions & FetchOptions): Promise<void>;
304
+ /** `git fetch --multiple <remote>…`. See {@link FetchManyOptions}. */
305
+ fetchMany(remotes: readonly string[], opts?: GitCallOptions & FetchManyOptions): Promise<void>;
284
306
  /** Stage paths; `all` / `update` are `git add -A` / `-u`. */
285
307
  add(paths: string[], opts?: GitCallOptions & AddOptions): Promise<void>;
286
308
  /**
@@ -335,6 +357,8 @@ export declare class AsyncGit {
335
357
  worktreeUnlock(path: string, opts?: GitCallOptions): Promise<void>;
336
358
  /** `git worktree prune`. */
337
359
  worktreePrune(opts?: GitCallOptions): Promise<void>;
360
+ /** `git submodule update --init --recursive --checkout`, refusing `file` and `ext` URLs. See `submoduleUpdate` in verbs.ts. */
361
+ submoduleUpdate(opts?: GitCallOptions): Promise<void>;
338
362
  /** `git remote add <name> <url>`. */
339
363
  remoteAdd(name: string, url: string, opts?: GitCallOptions): Promise<void>;
340
364
  /** `git remote set-head <remote> <branch> | --auto | --delete`. See {@link Git.remoteSetHead}. */
package/dist/async.js CHANGED
@@ -13,6 +13,7 @@
13
13
  * client takes `gitDir` on its own constructor.
14
14
  */
15
15
  import { basename, dirname, resolve } from 'node:path';
16
+ import { inOrder, planCatFileBatch, } from "./cat-file.js";
16
17
  import { cliBackend } from "./backend.js";
17
18
  import { softAsync, triedAsync } from "./outcome.js";
18
19
  import { parseRemoteUrl } from "./remote-url.js";
@@ -115,6 +116,44 @@ export class AsyncGit {
115
116
  rawBytesChecked(argv, opts = {}) {
116
117
  return this.backend.execute(this.cwd, { kind: 'rawBytes', argv, checked: true, input: opts.input }, opts);
117
118
  }
119
+ /**
120
+ * Many objects at once, byte-exact. Rejects with the classified failure if
121
+ * git fails, and with `UnsupportedRequest` when the backend has no bytes
122
+ * runner. See {@link Git.catFileBatch}.
123
+ *
124
+ * @experimental command-seam's bytes runners are experimental.
125
+ */
126
+ async catFileBatch(names, opts = {}) {
127
+ const all = new Map();
128
+ for await (const chunk of this.catFileBatchChunks(names, opts)) {
129
+ for (const [name, entry] of chunk)
130
+ all.set(name, entry);
131
+ }
132
+ return inOrder(names, all);
133
+ }
134
+ /**
135
+ * {@link AsyncGit.catFileBatch} one group of blobs at a time. See
136
+ * {@link Git.catFileBatchChunks}.
137
+ *
138
+ * @experimental command-seam's bytes runners are experimental.
139
+ */
140
+ async *catFileBatchChunks(names, opts = {}) {
141
+ const { maxBytes, chunkBytes, ...call } = opts;
142
+ const plan = planCatFileBatch(names, { maxBytes, chunkBytes });
143
+ let step = plan.next();
144
+ while (step.done !== true) {
145
+ if (step.value.type === 'chunk') {
146
+ yield step.value.entries;
147
+ step = plan.next();
148
+ }
149
+ else {
150
+ const { argv, input, maxOutputBytes } = step.value;
151
+ const run = { ...call, maxOutputBytes: call.maxOutputBytes ?? maxOutputBytes };
152
+ const result = await this.rawBytesChecked(argv, { ...run, input });
153
+ step = plan.next(result.stdout);
154
+ }
155
+ }
156
+ }
118
157
  // ── queries ───────────────────────────────────────────────────────────────
119
158
  /**
120
159
  * The git the backend runs, from `git --version`; see {@link Git.version}.
@@ -417,6 +456,14 @@ export class AsyncGit {
417
456
  mktree(entries, opts = {}) {
418
457
  return this.backend.execute(this.cwd, { kind: 'mktree', entries }, opts);
419
458
  }
459
+ /** Load `rev`'s tree into the index; pass `env: { GIT_INDEX_FILE }` to use a temporary one. See {@link Git.readTree}. */
460
+ readTree(rev, opts = {}) {
461
+ return this.backend.execute(this.cwd, { kind: 'readTree', rev }, opts);
462
+ }
463
+ /** Write the index as a tree and return its sha; no ref moves. See {@link Git.writeTree}. */
464
+ writeTree(opts = {}) {
465
+ return this.backend.execute(this.cwd, { kind: 'writeTree' }, opts);
466
+ }
420
467
  /** Configured remote names (`git remote`); `[]` when there are none. */
421
468
  remotes(opts = {}) {
422
469
  return this.backend.execute(this.cwd, { kind: 'remote' }, opts);
@@ -461,6 +508,11 @@ export class AsyncGit {
461
508
  const [call, req] = splitCallOptions(opts);
462
509
  return this.backend.execute(this.cwd, { kind: 'fetch', remote, refspec, ...req }, call);
463
510
  }
511
+ /** `git fetch --multiple <remote>…`. See {@link FetchManyOptions}. */
512
+ fetchMany(remotes, opts = {}) {
513
+ const [call, req] = splitCallOptions(opts);
514
+ return this.backend.execute(this.cwd, { kind: 'fetchMany', remotes, ...req }, call);
515
+ }
464
516
  /** Stage paths; `all` / `update` are `git add -A` / `-u`. */
465
517
  add(paths, opts = {}) {
466
518
  const [call, req] = splitCallOptions(opts);
@@ -553,6 +605,10 @@ export class AsyncGit {
553
605
  worktreePrune(opts = {}) {
554
606
  return this.backend.execute(this.cwd, { kind: 'worktreePrune' }, opts);
555
607
  }
608
+ /** `git submodule update --init --recursive --checkout`, refusing `file` and `ext` URLs. See `submoduleUpdate` in verbs.ts. */
609
+ submoduleUpdate(opts = {}) {
610
+ return this.backend.execute(this.cwd, { kind: 'submoduleUpdate' }, opts);
611
+ }
556
612
  /** `git remote add <name> <url>`. */
557
613
  remoteAdd(name, url, opts = {}) {
558
614
  return this.backend.execute(this.cwd, { kind: 'remoteAdd', name, url }, opts);
package/dist/backend.d.ts CHANGED
@@ -19,7 +19,7 @@
19
19
  */
20
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 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';
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 FetchManyOptions, 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
  /**
@@ -145,6 +145,11 @@ export type GitRequest = {
145
145
  } & HashObjectOptions) | {
146
146
  kind: 'mktree';
147
147
  entries: readonly MktreeEntry[];
148
+ } | {
149
+ kind: 'readTree';
150
+ rev: string;
151
+ } | {
152
+ kind: 'writeTree';
148
153
  } | ({
149
154
  kind: 'lsFiles';
150
155
  } & LsFilesOptions) | {
@@ -189,6 +194,9 @@ export type GitRequest = {
189
194
  remote: string;
190
195
  refspec?: string | string[] | undefined;
191
196
  } & FetchOptions) | ({
197
+ kind: 'fetchMany';
198
+ remotes: readonly string[];
199
+ } & FetchManyOptions) | ({
192
200
  kind: 'add';
193
201
  paths: string[];
194
202
  } & AddOptions) | ({
@@ -244,6 +252,8 @@ export type GitRequest = {
244
252
  path: string;
245
253
  } | {
246
254
  kind: 'worktreePrune';
255
+ } | {
256
+ kind: 'submoduleUpdate';
247
257
  } | ({
248
258
  kind: 'merge';
249
259
  ref: string;
@@ -340,6 +350,8 @@ export interface GitResults {
340
350
  commitTree: string;
341
351
  hashObject: string;
342
352
  mktree: string;
353
+ readTree: void;
354
+ writeTree: string;
343
355
  lsFiles: string[];
344
356
  lsFilesTagged: TaggedFile[];
345
357
  submodules: IndexSubmodule[];
@@ -357,6 +369,7 @@ export interface GitResults {
357
369
  diffText: string;
358
370
  diffAddedFile: string;
359
371
  fetch: void;
372
+ fetchMany: void;
360
373
  add: void;
361
374
  commit: void;
362
375
  configSet: void;
@@ -374,6 +387,7 @@ export interface GitResults {
374
387
  worktreeMove: void;
375
388
  worktreeUnlock: void;
376
389
  worktreePrune: void;
390
+ submoduleUpdate: void;
377
391
  merge: MergeOutcome;
378
392
  mergeAbort: void;
379
393
  rebase: RebaseOutcome;
package/dist/backend.js CHANGED
@@ -82,6 +82,10 @@ function toVerb(request) {
82
82
  return v.hashObject(request.content, request);
83
83
  case 'mktree':
84
84
  return v.mktree(request.entries);
85
+ case 'readTree':
86
+ return v.readTree(request.rev);
87
+ case 'writeTree':
88
+ return v.writeTree();
85
89
  case 'checkIgnore':
86
90
  return v.checkIgnore(request.relPaths);
87
91
  case 'checkIgnoreVerbose':
@@ -120,6 +124,8 @@ function toVerb(request) {
120
124
  return v.diffAddedFile(request.relPath);
121
125
  case 'fetch':
122
126
  return v.fetch(request.remote, request.refspec, request);
127
+ case 'fetchMany':
128
+ return v.fetchMany(request.remotes, request);
123
129
  case 'add':
124
130
  return v.add(request.paths, request);
125
131
  case 'commit':
@@ -154,6 +160,8 @@ function toVerb(request) {
154
160
  return v.worktreeUnlock(request.path);
155
161
  case 'worktreePrune':
156
162
  return v.worktreePrune();
163
+ case 'submoduleUpdate':
164
+ return v.submoduleUpdate();
157
165
  case 'merge':
158
166
  return v.merge(request.ref, request);
159
167
  case 'mergeAbort':
@@ -0,0 +1,78 @@
1
+ /**
2
+ * `git cat-file --batch` reads: many objects, byte-exact, in a few processes.
3
+ *
4
+ * The planner here is a generator that asks its driver to run git and gets
5
+ * the stdout bytes back, so the sync client (`Git.catFileBatch`) and the async
6
+ * one (`AsyncGit.catFileBatch`) share every line of the batching and parsing.
7
+ * Each driver supplies the bytes runner behind `rawBytesChecked`.
8
+ */
9
+ /** What one name resolved to. `bytes` are git's, never decoded. */
10
+ export type CatFileEntry =
11
+ /** A blob with no NUL in its first 8000 bytes (git's own text test). */
12
+ {
13
+ kind: 'text';
14
+ sha: string;
15
+ size: number;
16
+ bytes: Buffer;
17
+ }
18
+ /** A blob with a NUL in its first 8000 bytes. */
19
+ | {
20
+ kind: 'binary';
21
+ sha: string;
22
+ size: number;
23
+ bytes: Buffer;
24
+ }
25
+ /** A blob larger than `maxBytes`; its content was not read. */
26
+ | {
27
+ kind: 'too-large';
28
+ sha: string;
29
+ size: number;
30
+ }
31
+ /** A tree, commit or tag, such as `rev:dir`. Its content was not read. */
32
+ | {
33
+ kind: 'not-blob';
34
+ type: string;
35
+ sha: string;
36
+ size: number;
37
+ }
38
+ /** No such object, or a short sha that names more than one. */
39
+ | {
40
+ kind: 'missing';
41
+ };
42
+ /** Options for `catFileBatch` and `catFileBatchChunks`. */
43
+ export interface CatFileBatchOptions {
44
+ /**
45
+ * A blob larger than this many bytes comes back as `too-large`, and its
46
+ * content is not read. Default `Infinity`.
47
+ */
48
+ maxBytes?: number | undefined;
49
+ /**
50
+ * The most blob bytes one git process is asked for; the default is 64 MiB.
51
+ * A blob larger than this still gets a process of its own, so set
52
+ * `maxBytes` to bound it. Memory held at once is about this value.
53
+ */
54
+ chunkBytes?: number | undefined;
55
+ }
56
+ /** One git run the planner needs. `input` is the object names, one per line. */
57
+ export interface CatFileRun {
58
+ readonly type: 'run';
59
+ readonly argv: string[];
60
+ readonly input: string;
61
+ /** An output cap sized to the answer; `undefined` leaves the runner's default. */
62
+ readonly maxOutputBytes: number | undefined;
63
+ }
64
+ /** A group of finished entries the caller can use now. */
65
+ export interface CatFileChunk {
66
+ readonly type: 'chunk';
67
+ readonly entries: Map<string, CatFileEntry>;
68
+ }
69
+ /** `entries` in the order of `names`, a repeated name once. */
70
+ export declare function inOrder(names: readonly string[], entries: Map<string, CatFileEntry>): Map<string, CatFileEntry>;
71
+ /**
72
+ * Plan the reads of `names`: `--batch-check` for their sizes, then `--batch`
73
+ * for the blobs within `maxBytes`, grouped so a process is asked for about
74
+ * `chunkBytes`. Yields a {@link CatFileRun} for the driver to run, which sends
75
+ * back the stdout bytes, and a {@link CatFileChunk} for each group of finished
76
+ * entries. The first chunk also holds every entry that needed no content read.
77
+ */
78
+ export declare function planCatFileBatch(names: readonly string[], opts?: CatFileBatchOptions): Generator<CatFileRun | CatFileChunk, void, Buffer>;
@@ -0,0 +1,155 @@
1
+ /**
2
+ * `git cat-file --batch` reads: many objects, byte-exact, in a few processes.
3
+ *
4
+ * The planner here is a generator that asks its driver to run git and gets
5
+ * the stdout bytes back, so the sync client (`Git.catFileBatch`) and the async
6
+ * one (`AsyncGit.catFileBatch`) share every line of the batching and parsing.
7
+ * Each driver supplies the bytes runner behind `rawBytesChecked`.
8
+ */
9
+ const DEFAULT_CHUNK_BYTES = 64 * 1024 * 1024;
10
+ /** Names per `--batch-check` run: bounds one process's input and output. */
11
+ const CHECK_NAMES = 10_000;
12
+ /** More than a `<sha> <type> <size>\n` header and the `\n` after the content take. */
13
+ const OBJECT_OVERHEAD = 160;
14
+ /** Git's binary test: a NUL in the first 8000 bytes. */
15
+ const BINARY_WINDOW = 8000;
16
+ // git reads names a line at a time and drops a CR before the LF, so `foo\r`
17
+ // would be read as `foo` and its entry filed under the wrong name.
18
+ function checkNames(names) {
19
+ const unique = new Set();
20
+ for (const name of names) {
21
+ if (typeof name !== 'string' || name === '' || /[\n\0]|\r$/.test(name)) {
22
+ throw new TypeError(`typed-git: catFileBatch: a name must be a non-empty string with no newline, NUL or trailing CR (got ${JSON.stringify(name)})`);
23
+ }
24
+ unique.add(name);
25
+ }
26
+ return [...unique];
27
+ }
28
+ function limit(option, value, fallback, zeroOk) {
29
+ const n = value ?? fallback;
30
+ if (typeof n !== 'number' || Number.isNaN(n) || n < 0 || (!zeroOk && n === 0)) {
31
+ throw new TypeError(`typed-git: catFileBatch: ${option} must be a ${zeroOk ? 'non-negative' : 'positive'} number (got ${JSON.stringify(n)})`);
32
+ }
33
+ return n;
34
+ }
35
+ /** Parses the `--batch-check` answer for `names`: sets `missing` names in `out` and returns the others, in order. */
36
+ function parseCheck(stdout, names, out) {
37
+ const lines = stdout.toString('utf8').split('\n');
38
+ lines.pop(); // the empty string after the trailing newline
39
+ if (lines.length !== names.length) {
40
+ throw new Error(`typed-git: catFileBatch: git answered ${lines.length} lines for ${names.length} names`);
41
+ }
42
+ const found = [];
43
+ lines.forEach((line, i) => {
44
+ const name = names[i];
45
+ if (line.endsWith(' missing') || line.endsWith(' ambiguous')) {
46
+ out.set(name, { kind: 'missing' });
47
+ return;
48
+ }
49
+ const m = /^([0-9a-f]+) (\S+) (\d+)$/.exec(line);
50
+ if (m === null) {
51
+ throw new Error(`typed-git: catFileBatch: cannot read git's answer for ${name}: ${line}`);
52
+ }
53
+ found.push({ name, sha: m[1], type: m[2], size: Number(m[3]) });
54
+ });
55
+ return found;
56
+ }
57
+ /** Reads `blobs`' headers and content, in order, from one `--batch` stdout. */
58
+ function parseContent(stdout, blobs) {
59
+ const out = new Map();
60
+ let at = 0;
61
+ for (const b of blobs) {
62
+ const eol = stdout.indexOf(0x0a, at);
63
+ if (eol < 0)
64
+ throw new Error(`typed-git: catFileBatch: git's output for ${b.name} is cut short`);
65
+ const header = stdout.toString('utf8', at, eol);
66
+ if (header !== `${b.sha} blob ${b.size}`) {
67
+ throw new Error(`typed-git: catFileBatch: unexpected header for ${b.name} (expected "${b.sha} blob ${b.size}", got "${header}")`);
68
+ }
69
+ const start = eol + 1;
70
+ const end = start + b.size;
71
+ if (end >= stdout.length) {
72
+ throw new Error(`typed-git: catFileBatch: git's output for ${b.name} is cut short`);
73
+ }
74
+ const bytes = stdout.subarray(start, end);
75
+ const binary = bytes.subarray(0, BINARY_WINDOW).includes(0);
76
+ out.set(b.name, { kind: binary ? 'binary' : 'text', sha: b.sha, size: b.size, bytes });
77
+ at = end + 1;
78
+ }
79
+ return out;
80
+ }
81
+ /** `entries` in the order of `names`, a repeated name once. */
82
+ export function inOrder(names, entries) {
83
+ const out = new Map();
84
+ for (const name of names)
85
+ out.set(name, entries.get(name));
86
+ return out;
87
+ }
88
+ /**
89
+ * Plan the reads of `names`: `--batch-check` for their sizes, then `--batch`
90
+ * for the blobs within `maxBytes`, grouped so a process is asked for about
91
+ * `chunkBytes`. Yields a {@link CatFileRun} for the driver to run, which sends
92
+ * back the stdout bytes, and a {@link CatFileChunk} for each group of finished
93
+ * entries. The first chunk also holds every entry that needed no content read.
94
+ */
95
+ export function* planCatFileBatch(names, opts = {}) {
96
+ const unique = checkNames(names);
97
+ const maxBytes = limit('maxBytes', opts.maxBytes, Infinity, true);
98
+ const chunkBytes = limit('chunkBytes', opts.chunkBytes, DEFAULT_CHUNK_BYTES, false);
99
+ const settled = new Map();
100
+ const wanted = [];
101
+ for (let i = 0; i < unique.length; i += CHECK_NAMES) {
102
+ const part = unique.slice(i, i + CHECK_NAMES);
103
+ const stdout = yield {
104
+ type: 'run',
105
+ argv: ['cat-file', '--batch-check'],
106
+ input: part.join('\n') + '\n',
107
+ maxOutputBytes: undefined,
108
+ };
109
+ for (const f of parseCheck(stdout, part, settled)) {
110
+ if (f.type !== 'blob') {
111
+ settled.set(f.name, { kind: 'not-blob', type: f.type, sha: f.sha, size: f.size });
112
+ }
113
+ else if (f.size > maxBytes) {
114
+ settled.set(f.name, { kind: 'too-large', sha: f.sha, size: f.size });
115
+ }
116
+ else {
117
+ wanted.push(f);
118
+ }
119
+ }
120
+ }
121
+ let group = [];
122
+ let groupBytes = 0;
123
+ const groups = [];
124
+ for (const f of wanted) {
125
+ if (group.length > 0 && groupBytes + f.size > chunkBytes) {
126
+ groups.push(group);
127
+ group = [];
128
+ groupBytes = 0;
129
+ }
130
+ group.push(f);
131
+ groupBytes += f.size;
132
+ }
133
+ if (group.length > 0)
134
+ groups.push(group);
135
+ if (groups.length === 0) {
136
+ yield { type: 'chunk', entries: settled };
137
+ return;
138
+ }
139
+ let first = true;
140
+ for (const g of groups) {
141
+ const stdout = yield {
142
+ type: 'run',
143
+ argv: ['cat-file', '--batch'],
144
+ // By sha, so a ref that moves after the size check cannot change the object.
145
+ input: g.map((f) => f.sha).join('\n') + '\n',
146
+ maxOutputBytes: g.reduce((sum, f) => sum + f.size + OBJECT_OVERHEAD, 0),
147
+ };
148
+ const entries = parseContent(stdout, g);
149
+ if (first)
150
+ for (const [name, entry] of settled)
151
+ entries.set(name, entry);
152
+ first = false;
153
+ yield { type: 'chunk', entries };
154
+ }
155
+ }
package/dist/client.d.ts CHANGED
@@ -22,5 +22,6 @@ export { classifyGitFailure, describeGitFailure, UnsupportedRequest, type GitFai
22
22
  export { type Soft, type TriedAsync, type TriedSync } from './outcome.ts';
23
23
  export { GIT_FEATURES, GIT_FLOOR, gitSupports, type GitFeature, type GitFeatureSpec, type GitRelease, type UnsupportedGit, } from './features.ts';
24
24
  export { compareGitVersions, parseGitVersion, type GitVersion } from './git-version.ts';
25
- export { forceWithLeaseArg, parseRefRows, PUSH_REJECTIONS, REF_FORMAT, type AddOptions, type AheadBehind, type CherryEntry, type CommitTreeOptions, type CheckoutOptions, type CleanOptions, type CloneOptions, type CommitFlags, type CommitOptions, type ConfigGetOptions, type ConfigScope, type ConfigSetOptions, type ConflictSide, type DiffCheckOptions, type DiffCheckResult, type DiffEntry, type DiffNameOnlyOptions, type DiffNameStatusOptions, type DiffStatOptions, type DiffTextOptions, type DiffTreeOptions, type FetchOptions, type ForEachRefOptions, type ForceLease, type GcOptions, type GrepOptions, type HashObjectOptions, type InitOptions, type IntegrationOutcome, type LogOptions, type IgnoreMatch, type LsFilesOptions, type LsRemoteOptions, type LsTreeOptions, type MergeOptions, type MergeOutcome, type MergeTreeOptions, type MergeTreeOutcome, type MktreeEntry, type NumstatEntry, type PushFlag, type PushOptions, type PushRefResult, type PushRejection, type PushRejectionInfo, type PushReport, type RebaseOptions, type RebaseOutcome, type RemoteGetUrlOptions, type RemoteRef, type RemoteSetBranchesOptions, type RemoteSetHeadOptions, type StatusEntriesOptions, type StatusEntry, type StatusPorcelainOptions, type IndexSubmodule, type TaggedFile, type TreeEntry, type UnmergedEntry, type UpdateRefOptions, type Worktree, type WorktreeAddOptions, type WorktreeMoveOptions, } from './verbs.ts';
25
+ export { forceWithLeaseArg, parseRefRows, PUSH_REJECTIONS, REF_FORMAT, type AddOptions, type AheadBehind, type CherryEntry, type CommitTreeOptions, type CheckoutOptions, type CleanOptions, type CloneOptions, type CommitFlags, type CommitOptions, type ConfigGetOptions, type ConfigScope, type ConfigSetOptions, type ConflictSide, type DiffCheckOptions, type DiffCheckResult, type DiffEntry, type DiffNameOnlyOptions, type DiffNameStatusOptions, type DiffStatOptions, type DiffTextOptions, type DiffTreeOptions, type FetchManyOptions, type FetchOptions, type ForEachRefOptions, type ForceLease, type GcOptions, type GrepOptions, type HashObjectOptions, type InitOptions, type IntegrationOutcome, type LogOptions, type IgnoreMatch, type LsFilesOptions, type LsRemoteOptions, type LsTreeOptions, type MergeOptions, type MergeOutcome, type MergeTreeOptions, type MergeTreeOutcome, type MktreeEntry, type NumstatEntry, type PushFlag, type PushOptions, type PushRefResult, type PushRejection, type PushRejectionInfo, type PushReport, type RebaseOptions, type RebaseOutcome, type RemoteGetUrlOptions, type RemoteRef, type RemoteSetBranchesOptions, type RemoteSetHeadOptions, type StatusEntriesOptions, type StatusEntry, type StatusPorcelainOptions, type IndexSubmodule, type TaggedFile, type TreeEntry, type UnmergedEntry, type UpdateRefOptions, type Worktree, type WorktreeAddOptions, type WorktreeMoveOptions, } from './verbs.ts';
26
26
  export { asAsync, CommandFailed, runChecked, runCheckedAsync, spawnRunner, spawnRunnerAsync, spawnRunnerBytes, spawnRunnerBytesAsync, type AsyncBytesCommandRunner, type AsyncCommandRunner, type AsyncCommandRunOptions, type BytesCommandRunner, type CommandResult, type CommandRunner, type CommandRunOptions, } from '@osdlc/command-seam';
27
+ export type { CatFileBatchOptions, CatFileEntry } from './cat-file.ts';
package/dist/outcome.d.ts CHANGED
@@ -20,14 +20,15 @@
20
20
  import type { Result } from '@osdlc/result';
21
21
  import { type GitFailure } from './failure.ts';
22
22
  /**
23
- * The methods `try` mirrors: everything except the `raw*` methods, `at`,
24
- * and `try` itself. The unchecked `raw*` methods already return a
23
+ * The methods `try` mirrors: everything except the `raw*` methods, the
24
+ * `catFileBatchChunks` generator (git runs as it is iterated, after any
25
+ * `try` could catch), `at`, and `try` itself. The unchecked `raw*` methods already return a
25
26
  * `CommandResult` and never throw for a failed git; the checked ones exist
26
27
  * to throw. `at(cwd)` returns a new client that has its own `.try`. The
27
28
  * types leave them out, but the runtime proxy wraps every function property,
28
29
  * these included.
29
30
  */
30
- type Triable<C> = Omit<C, 'raw' | 'rawChecked' | 'rawBytes' | 'rawBytesChecked' | 'at' | 'try' | 'soft' | 'cwd'>;
31
+ type Triable<C> = Omit<C, 'raw' | 'rawChecked' | 'rawBytes' | 'rawBytesChecked' | 'catFileBatchChunks' | 'at' | 'try' | 'soft' | 'cwd'>;
31
32
  /** Every synchronous client method, returning a `Result<T, GitFailure>`. */
32
33
  export type TriedSync<C> = {
33
34
  [K in keyof Triable<C>]: Triable<C>[K] extends (...a: infer A) => infer R ? (...a: A) => Result<R, GitFailure> : never;
package/dist/sync.d.ts CHANGED
@@ -16,10 +16,11 @@
16
16
  * service's compare-and-swap ref operations. That is not general git.
17
17
  */
18
18
  import { type BytesCommandRunner, type CommandResult, type CommandRunner } from '@osdlc/command-seam';
19
+ import { type CatFileBatchOptions, type CatFileEntry } from './cat-file.ts';
19
20
  import { type GitVersion } from './git-version.ts';
20
21
  import { type Soft, type TriedSync } from './outcome.ts';
21
22
  import { type RemoteCoordinate } from './remote-url.ts';
22
- 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';
23
+ 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 FetchManyOptions, 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';
23
24
  /**
24
25
  * Per-call concerns that are not part of the operation itself.
25
26
  *
@@ -166,6 +167,26 @@ export declare class Git {
166
167
  rawBytesChecked(argv: string[], opts?: GitSyncCallOptions & {
167
168
  input?: string | undefined;
168
169
  }): CommandResult<Buffer>;
170
+ /**
171
+ * Many objects at once, byte-exact: `names` are anything `git cat-file`
172
+ * reads, such as `rev:path` or a sha. Runs `cat-file --batch-check` for the
173
+ * sizes, then `cat-file --batch` for the blobs within `maxBytes`, a few
174
+ * processes in all, on the `bytesRunner`. The map is keyed by the names
175
+ * given. Throws the classified failure if git fails, `UnsupportedRequest`
176
+ * when the client has no bytes runner, and `TypeError` for a name that is
177
+ * empty or holds a newline, a NUL or a trailing CR. See {@link CatFileEntry}.
178
+ *
179
+ * @experimental command-seam's bytes runners are experimental.
180
+ */
181
+ catFileBatch(names: readonly string[], opts?: GitSyncCallOptions & CatFileBatchOptions): Map<string, CatFileEntry>;
182
+ /**
183
+ * {@link Git.catFileBatch} one group of blobs at a time (about `chunkBytes`
184
+ * each), so a caller can use the bytes and drop them before the next read.
185
+ * The first map also holds every entry that needed no content read.
186
+ *
187
+ * @experimental command-seam's bytes runners are experimental.
188
+ */
189
+ catFileBatchChunks(names: readonly string[], opts?: GitSyncCallOptions & CatFileBatchOptions): Generator<Map<string, CatFileEntry>, void, undefined>;
169
190
  private bytes;
170
191
  /** The verb's argv, after this client's `--git-dir` / `--work-tree` flags. */
171
192
  private argv;
@@ -390,6 +411,10 @@ export declare class Git {
390
411
  hashObject(content: string, opts?: GitSyncCallOptions & HashObjectOptions): string;
391
412
  /** Write a tree of `entries` and return its sha; no ref moves. See `mktree` in `verbs.ts`. */
392
413
  mktree(entries: readonly MktreeEntry[], opts?: GitSyncCallOptions): string;
414
+ /** Load `rev`'s tree into the index; pass `env: { GIT_INDEX_FILE }` to use a temporary one. See `readTree` in `verbs.ts`. */
415
+ readTree(rev: string, opts?: GitSyncCallOptions): void;
416
+ /** Write the index as a tree and return its sha; no ref moves. See `writeTree` in `verbs.ts`. */
417
+ writeTree(opts?: GitSyncCallOptions): string;
393
418
  /** Configured remote names (`git remote`); `[]` when there are none. */
394
419
  remotes(opts?: GitSyncCallOptions): string[];
395
420
  /**
@@ -421,6 +446,8 @@ export declare class Git {
421
446
  remoteOwnerRepo(remote?: string, opts?: GitSyncCallOptions): RemoteCoordinate | null;
422
447
  /** `git fetch <remote> [refspec…]`. See {@link FetchOptions} for the flags. */
423
448
  fetch(remote: string, refspec?: string | string[] | undefined, opts?: GitSyncCallOptions & FetchOptions): void;
449
+ /** `git fetch --multiple <remote>…`. See {@link FetchManyOptions}. */
450
+ fetchMany(remotes: readonly string[], opts?: GitSyncCallOptions & FetchManyOptions): void;
424
451
  /** Stage paths; `all` / `update` are `git add -A` / `-u`. */
425
452
  add(paths: string[], opts?: GitSyncCallOptions & AddOptions): void;
426
453
  /**
@@ -488,6 +515,8 @@ export declare class Git {
488
515
  worktreeUnlock(path: string, opts?: GitSyncCallOptions): void;
489
516
  /** `git worktree prune`. */
490
517
  worktreePrune(opts?: GitSyncCallOptions): void;
518
+ /** `git submodule update --init --recursive --checkout`, refusing `file` and `ext` URLs. See `submoduleUpdate` in verbs.ts. */
519
+ submoduleUpdate(opts?: GitSyncCallOptions): void;
491
520
  /** `git remote add <name> <url>`. */
492
521
  remoteAdd(name: string, url: string, opts?: GitSyncCallOptions): void;
493
522
  /**
package/dist/sync.js CHANGED
@@ -17,6 +17,7 @@
17
17
  */
18
18
  import { basename, dirname, resolve } from 'node:path';
19
19
  import { spawnRunner, spawnRunnerBytes, } from '@osdlc/command-seam';
20
+ import { inOrder, planCatFileBatch, } from "./cat-file.js";
20
21
  import { UnsupportedRequest } from "./failure.js";
21
22
  import { versionedVerb } from "./features.js";
22
23
  import { pinnedGitVersion, probeGitVersion } from "./git-version.js";
@@ -170,6 +171,48 @@ export class Git {
170
171
  const ran = this.argv(argv);
171
172
  return gateBytes(this.bytes().run(ran, this.runOpts(opts)), ran);
172
173
  }
174
+ /**
175
+ * Many objects at once, byte-exact: `names` are anything `git cat-file`
176
+ * reads, such as `rev:path` or a sha. Runs `cat-file --batch-check` for the
177
+ * sizes, then `cat-file --batch` for the blobs within `maxBytes`, a few
178
+ * processes in all, on the `bytesRunner`. The map is keyed by the names
179
+ * given. Throws the classified failure if git fails, `UnsupportedRequest`
180
+ * when the client has no bytes runner, and `TypeError` for a name that is
181
+ * empty or holds a newline, a NUL or a trailing CR. See {@link CatFileEntry}.
182
+ *
183
+ * @experimental command-seam's bytes runners are experimental.
184
+ */
185
+ catFileBatch(names, opts = {}) {
186
+ const all = new Map();
187
+ for (const chunk of this.catFileBatchChunks(names, opts)) {
188
+ for (const [name, entry] of chunk)
189
+ all.set(name, entry);
190
+ }
191
+ return inOrder(names, all);
192
+ }
193
+ /**
194
+ * {@link Git.catFileBatch} one group of blobs at a time (about `chunkBytes`
195
+ * each), so a caller can use the bytes and drop them before the next read.
196
+ * The first map also holds every entry that needed no content read.
197
+ *
198
+ * @experimental command-seam's bytes runners are experimental.
199
+ */
200
+ *catFileBatchChunks(names, opts = {}) {
201
+ const { maxBytes, chunkBytes, ...call } = opts;
202
+ const plan = planCatFileBatch(names, { maxBytes, chunkBytes });
203
+ let step = plan.next();
204
+ while (step.done !== true) {
205
+ if (step.value.type === 'chunk') {
206
+ yield step.value.entries;
207
+ step = plan.next();
208
+ }
209
+ else {
210
+ const { argv, input, maxOutputBytes } = step.value;
211
+ const run = { ...call, input, maxOutputBytes: call.maxOutputBytes ?? maxOutputBytes };
212
+ step = plan.next(this.rawBytesChecked(argv, run).stdout);
213
+ }
214
+ }
215
+ }
173
216
  bytes() {
174
217
  if (this.bytesRunner === undefined) {
175
218
  throw new UnsupportedRequest('rawBytes', 'Git with a runner and no bytesRunner');
@@ -565,6 +608,14 @@ export class Git {
565
608
  mktree(entries, opts = {}) {
566
609
  return this.exec(v.mktree(entries), opts);
567
610
  }
611
+ /** Load `rev`'s tree into the index; pass `env: { GIT_INDEX_FILE }` to use a temporary one. See `readTree` in `verbs.ts`. */
612
+ readTree(rev, opts = {}) {
613
+ this.exec(v.readTree(rev), opts);
614
+ }
615
+ /** Write the index as a tree and return its sha; no ref moves. See `writeTree` in `verbs.ts`. */
616
+ writeTree(opts = {}) {
617
+ return this.exec(v.writeTree(), opts);
618
+ }
568
619
  /** Configured remote names (`git remote`); `[]` when there are none. */
569
620
  remotes(opts = {}) {
570
621
  return this.exec(v.remote(), opts);
@@ -612,6 +663,10 @@ export class Git {
612
663
  fetch(remote, refspec, opts = {}) {
613
664
  this.exec(v.fetch(remote, refspec, opts), opts);
614
665
  }
666
+ /** `git fetch --multiple <remote>…`. See {@link FetchManyOptions}. */
667
+ fetchMany(remotes, opts = {}) {
668
+ this.exec(v.fetchMany(remotes, opts), opts);
669
+ }
615
670
  /** Stage paths; `all` / `update` are `git add -A` / `-u`. */
616
671
  add(paths, opts = {}) {
617
672
  this.exec(v.add(paths, opts), opts);
@@ -707,6 +762,10 @@ export class Git {
707
762
  worktreePrune(opts = {}) {
708
763
  this.exec(v.worktreePrune(), opts);
709
764
  }
765
+ /** `git submodule update --init --recursive --checkout`, refusing `file` and `ext` URLs. See `submoduleUpdate` in verbs.ts. */
766
+ submoduleUpdate(opts = {}) {
767
+ this.exec(v.submoduleUpdate(), opts);
768
+ }
710
769
  /** `git remote add <name> <url>`. */
711
770
  remoteAdd(name, url, opts = {}) {
712
771
  this.exec(v.remoteAdd(name, url), opts);
package/dist/verbs.d.ts CHANGED
@@ -526,6 +526,8 @@ export interface ForEachRefOptions {
526
526
  sort?: string | undefined;
527
527
  /** `--count=` cap on the rows returned. */
528
528
  count?: number | undefined;
529
+ /** `--contains=` commit: only refs whose history includes it. */
530
+ contains?: string | undefined;
529
531
  }
530
532
  /** The `forEachRef` format {@link refs} parses: sha, TAB, full refname. */
531
533
  export declare const REF_FORMAT = "%(objectname)%09%(refname)";
@@ -918,6 +920,21 @@ export interface CommitTreeOptions {
918
920
  * this throws. `absent: []`, and a reply that is not a sha throws.
919
921
  */
920
922
  export declare function commitTree(tree: string, opts: CommitTreeOptions): GitVerb<string>;
923
+ /**
924
+ * Load `rev`'s tree into the index (`git read-tree <rev>`), replacing it.
925
+ *
926
+ * It leaves the working tree alone. Run it with `env: { GIT_INDEX_FILE }` on
927
+ * the call to seed a temporary index, so the repository's own index is not
928
+ * touched. `absent: []`.
929
+ */
930
+ export declare function readTree(rev: string): GitVerb<void>;
931
+ /**
932
+ * Write the index as a tree object and print its sha (`git write-tree`).
933
+ *
934
+ * It writes objects and no ref. A conflicted index makes git exit 128 and
935
+ * this throws; a reply that is not a sha throws. `absent: []`.
936
+ */
937
+ export declare function writeTree(): GitVerb<string>;
921
938
  /** Options for {@link hashObject}. */
922
939
  export interface HashObjectOptions {
923
940
  /**
@@ -1068,6 +1085,22 @@ export interface FetchOptions {
1068
1085
  * `refspec` takes an array, for fetching several refs in one invocation.
1069
1086
  */
1070
1087
  export declare function fetch(remote: string, refspec?: string | string[] | undefined, opts?: FetchOptions): GitVerb<void>;
1088
+ /** Options for {@link fetchMany}. */
1089
+ export interface FetchManyOptions extends Omit<FetchOptions, 'depth'> {
1090
+ /**
1091
+ * `--jobs=<n>` — fetch up to `n` remotes at once. Default: git's own
1092
+ * (`fetch.parallel`, 1 unless set). Anything but a positive integer throws a
1093
+ * `TypeError`.
1094
+ */
1095
+ jobs?: number | undefined;
1096
+ }
1097
+ /**
1098
+ * `git fetch --multiple <remote>…`: every remote in one invocation, in
1099
+ * parallel with `jobs`. Git fetches each remote it can and exits non-zero
1100
+ * when any failed, naming it on stderr; the classified failure carries that
1101
+ * text. Throws a `TypeError` for an empty list.
1102
+ */
1103
+ export declare function fetchMany(remotes: readonly string[], opts?: FetchManyOptions): GitVerb<void>;
1071
1104
  /** Options for {@link add}. */
1072
1105
  export interface AddOptions {
1073
1106
  /** `--all` — stage deletions and untracked files too, not just changes. */
@@ -1367,10 +1400,13 @@ export declare function resetHard(rev: string): GitVerb<void>;
1367
1400
  export interface CleanOptions {
1368
1401
  /** `-d` — also delete untracked directories. */
1369
1402
  directories?: boolean | undefined;
1403
+ /** A second `-f`, so a nested repository (a populated submodule) is deleted too. */
1404
+ nested?: boolean | undefined;
1370
1405
  }
1371
1406
  /**
1372
1407
  * `git clean -f`: delete untracked files, and untracked directories with
1373
- * `{directories: true}`. Ignored files are kept.
1408
+ * `{directories: true}`; `{nested: true}` also deletes untracked nested repositories.
1409
+ * Ignored files are kept.
1374
1410
  */
1375
1411
  export declare function clean(opts?: CleanOptions): GitVerb<void>;
1376
1412
  /** Delete a local branch (`-d`, or `-D` with `{force: true}`). */
@@ -1450,6 +1486,17 @@ export declare function worktreeMove(from: string, to: string, opts?: WorktreeMo
1450
1486
  export declare function worktreeUnlock(path: string): GitVerb<void>;
1451
1487
  /** `git worktree prune`. */
1452
1488
  export declare function worktreePrune(): GitVerb<void>;
1489
+ /**
1490
+ * `git submodule update --init --recursive --checkout`, with the `file` and `ext` transports
1491
+ * refused: check out every submodule, nested ones included, at the commit the checked-out tree pins, cloning those not yet initialised. A repository
1492
+ * with no submodules is exit 0 and no work.
1493
+ *
1494
+ * The URLs come from the tree's own `.gitmodules`, which a pull request's author controls, so
1495
+ * the `file` and `ext` transports are refused (a local path or a command as a "URL"). A
1496
+ * `GIT_ALLOW_PROTOCOL` in the environment still takes precedence over these. `--checkout` ignores a
1497
+ * `submodule.<name>.update` the tree's `.gitmodules` sets (`none`, `rebase`, `merge`, `!command`).
1498
+ */
1499
+ export declare function submoduleUpdate(): GitVerb<void>;
1453
1500
  /** `git remote add <name> <url>`. */
1454
1501
  export declare function remoteAdd(name: string, url: string): GitVerb<void>;
1455
1502
  /**
package/dist/verbs.js CHANGED
@@ -813,6 +813,8 @@ export function forEachRef(pattern, opts = {}) {
813
813
  argv.push(`--sort=${opts.sort}`);
814
814
  if (opts.count !== undefined)
815
815
  argv.push(`--count=${opts.count}`);
816
+ if (opts.contains !== undefined)
817
+ argv.push(`--contains=${opts.contains}`);
816
818
  for (const p of typeof pattern === 'string' ? [pattern] : pattern) {
817
819
  argv.push(positional('forEachRef', 'pattern', p));
818
820
  }
@@ -1256,6 +1258,25 @@ export function commitTree(tree, opts) {
1256
1258
  argv.push('-m', opts.message);
1257
1259
  return { argv, absent: NONE, parse: shaReply };
1258
1260
  }
1261
+ /**
1262
+ * Load `rev`'s tree into the index (`git read-tree <rev>`), replacing it.
1263
+ *
1264
+ * It leaves the working tree alone. Run it with `env: { GIT_INDEX_FILE }` on
1265
+ * the call to seed a temporary index, so the repository's own index is not
1266
+ * touched. `absent: []`.
1267
+ */
1268
+ export function readTree(rev) {
1269
+ return { argv: ['read-tree', positional('readTree', 'rev', rev)], absent: NONE, parse: nothing };
1270
+ }
1271
+ /**
1272
+ * Write the index as a tree object and print its sha (`git write-tree`).
1273
+ *
1274
+ * It writes objects and no ref. A conflicted index makes git exit 128 and
1275
+ * this throws; a reply that is not a sha throws. `absent: []`.
1276
+ */
1277
+ export function writeTree() {
1278
+ return { argv: ['write-tree'], absent: NONE, parse: shaReply };
1279
+ }
1259
1280
  /** A full object id in either hash format: 40 hex digits (SHA-1) or 64 (SHA-256). */
1260
1281
  const FULL_SHA = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/;
1261
1282
  /** The one sha a plumbing verb prints. Anything else throws rather than reading as an id. */
@@ -1541,6 +1562,34 @@ export function fetch(remote, refspec, opts = {}) {
1541
1562
  }
1542
1563
  return { argv, absent: NONE, parse: nothing };
1543
1564
  }
1565
+ /**
1566
+ * `git fetch --multiple <remote>…`: every remote in one invocation, in
1567
+ * parallel with `jobs`. Git fetches each remote it can and exits non-zero
1568
+ * when any failed, naming it on stderr; the classified failure carries that
1569
+ * text. Throws a `TypeError` for an empty list.
1570
+ */
1571
+ export function fetchMany(remotes, opts = {}) {
1572
+ if (remotes.length === 0)
1573
+ throw new TypeError('typed-git: fetchMany: no remote given');
1574
+ const argv = ['fetch', '--multiple'];
1575
+ if (opts.quiet)
1576
+ argv.push('--quiet');
1577
+ if (opts.prune)
1578
+ argv.push('--prune');
1579
+ if (opts.noWriteFetchHead)
1580
+ argv.push('--no-write-fetch-head');
1581
+ if (opts.noTags)
1582
+ argv.push('--no-tags');
1583
+ if (opts.jobs !== undefined) {
1584
+ if (!Number.isSafeInteger(opts.jobs) || opts.jobs < 1) {
1585
+ throw new TypeError(`typed-git: fetchMany: jobs must be a positive integer (got ${JSON.stringify(opts.jobs)})`);
1586
+ }
1587
+ argv.push(`--jobs=${opts.jobs}`);
1588
+ }
1589
+ for (const remote of remotes)
1590
+ argv.push(positional('fetchMany', 'remote', remote));
1591
+ return { argv, absent: NONE, parse: nothing };
1592
+ }
1544
1593
  /** Stage paths. `--` precedes them, so a path starting with `-` is a path, not an option; flags go in `opts`. */
1545
1594
  export function add(paths, opts = {}) {
1546
1595
  const argv = ['add'];
@@ -1901,10 +1950,12 @@ export function resetHard(rev) {
1901
1950
  }
1902
1951
  /**
1903
1952
  * `git clean -f`: delete untracked files, and untracked directories with
1904
- * `{directories: true}`. Ignored files are kept.
1953
+ * `{directories: true}`; `{nested: true}` also deletes untracked nested repositories.
1954
+ * Ignored files are kept.
1905
1955
  */
1906
1956
  export function clean(opts = {}) {
1907
- return { argv: ['clean', opts.directories ? '-fd' : '-f'], absent: NONE, parse: nothing };
1957
+ const flags = `${opts.nested ? '-ff' : '-f'}${opts.directories ? 'd' : ''}`;
1958
+ return { argv: ['clean', flags], absent: NONE, parse: nothing };
1908
1959
  }
1909
1960
  /** Delete a local branch (`-d`, or `-D` with `{force: true}`). */
1910
1961
  export function deleteBranch(name, opts = {}) {
@@ -2022,6 +2073,33 @@ export function worktreeUnlock(path) {
2022
2073
  export function worktreePrune() {
2023
2074
  return { argv: ['worktree', 'prune'], absent: NONE, parse: nothing };
2024
2075
  }
2076
+ /**
2077
+ * `git submodule update --init --recursive --checkout`, with the `file` and `ext` transports
2078
+ * refused: check out every submodule, nested ones included, at the commit the checked-out tree pins, cloning those not yet initialised. A repository
2079
+ * with no submodules is exit 0 and no work.
2080
+ *
2081
+ * The URLs come from the tree's own `.gitmodules`, which a pull request's author controls, so
2082
+ * the `file` and `ext` transports are refused (a local path or a command as a "URL"). A
2083
+ * `GIT_ALLOW_PROTOCOL` in the environment still takes precedence over these. `--checkout` ignores a
2084
+ * `submodule.<name>.update` the tree's `.gitmodules` sets (`none`, `rebase`, `merge`, `!command`).
2085
+ */
2086
+ export function submoduleUpdate() {
2087
+ return {
2088
+ argv: [
2089
+ '-c',
2090
+ 'protocol.file.allow=never',
2091
+ '-c',
2092
+ 'protocol.ext.allow=never',
2093
+ 'submodule',
2094
+ 'update',
2095
+ '--init',
2096
+ '--recursive',
2097
+ '--checkout',
2098
+ ],
2099
+ absent: NONE,
2100
+ parse: nothing,
2101
+ };
2102
+ }
2025
2103
  /** `git remote add <name> <url>`. */
2026
2104
  export function remoteAdd(name, url) {
2027
2105
  return {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@osdlc/typed-git",
3
- "version": "0.17.0",
3
+ "version": "0.19.0",
4
4
  "description": "A typed git client for TypeScript, sync and awaitable. Each verb declares what absence means for it; every other failure throws. git.try.* inspects, raw() bypasses — over an injectable backend that drives the git CLI or any other implementation.",
5
5
  "license": "MIT OR Apache-2.0",
6
6
  "author": "sksizer",
@@ -52,7 +52,7 @@
52
52
  ],
53
53
  "dependencies": {
54
54
  "hosted-git-info": "^10.1.1",
55
- "@osdlc/command-seam": "^0.15.0",
55
+ "@osdlc/command-seam": "^0.15.1",
56
56
  "@osdlc/result": "^0.1.0"
57
57
  },
58
58
  "devDependencies": {