@statewalker/vcs-commands 0.10.0 → 0.12.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.
Files changed (115) hide show
  1. package/dist/commands/am/am-command.d.ts.map +1 -1
  2. package/dist/commands/archive/archive-command.d.ts +81 -7
  3. package/dist/commands/archive/archive-command.d.ts.map +1 -1
  4. package/dist/commands/archive/archive-entry.d.ts +48 -5
  5. package/dist/commands/archive/archive-entry.d.ts.map +1 -1
  6. package/dist/commands/archive/tar-archive.d.ts +5 -2
  7. package/dist/commands/archive/tar-archive.d.ts.map +1 -1
  8. package/dist/commands/archive/zip-archive.d.ts +9 -2
  9. package/dist/commands/archive/zip-archive.d.ts.map +1 -1
  10. package/dist/commands/attributes-source.d.ts +5 -0
  11. package/dist/commands/attributes-source.d.ts.map +1 -1
  12. package/dist/commands/cat-file/cat-file-command.d.ts +9 -0
  13. package/dist/commands/cat-file/cat-file-command.d.ts.map +1 -1
  14. package/dist/commands/checkout-command.d.ts.map +1 -1
  15. package/dist/commands/clone-command.d.ts +9 -0
  16. package/dist/commands/clone-command.d.ts.map +1 -1
  17. package/dist/commands/default-branch.d.ts +12 -0
  18. package/dist/commands/default-branch.d.ts.map +1 -1
  19. package/dist/commands/diff-command.d.ts.map +1 -1
  20. package/dist/commands/format-rev-command.d.ts +6 -4
  21. package/dist/commands/format-rev-command.d.ts.map +1 -1
  22. package/dist/commands/fsmonitor-ipc.d.ts +30 -0
  23. package/dist/commands/fsmonitor-ipc.d.ts.map +1 -0
  24. package/dist/commands/fsmonitor-refresh.d.ts.map +1 -1
  25. package/dist/commands/http-config.d.ts +4 -2
  26. package/dist/commands/http-config.d.ts.map +1 -1
  27. package/dist/commands/index.d.ts +2 -0
  28. package/dist/commands/index.d.ts.map +1 -1
  29. package/dist/commands/index.js +6 -6
  30. package/dist/commands/log-output.d.ts +6 -0
  31. package/dist/commands/log-output.d.ts.map +1 -1
  32. package/dist/commands/ls-files-command.d.ts.map +1 -1
  33. package/dist/commands/ls-tree-command.d.ts.map +1 -1
  34. package/dist/commands/mv-command.d.ts.map +1 -1
  35. package/dist/commands/pathspec.d.ts.map +1 -1
  36. package/dist/commands/plumbing-shared.d.ts +72 -0
  37. package/dist/commands/plumbing-shared.d.ts.map +1 -0
  38. package/dist/commands/repack-command.d.ts +12 -3
  39. package/dist/commands/repack-command.d.ts.map +1 -1
  40. package/dist/commands/replace-command.d.ts.map +1 -1
  41. package/dist/commands/repo-command.d.ts +28 -6
  42. package/dist/commands/repo-command.d.ts.map +1 -1
  43. package/dist/commands/rerere-command.d.ts +12 -0
  44. package/dist/commands/rerere-command.d.ts.map +1 -1
  45. package/dist/commands/rerere.d.ts +22 -0
  46. package/dist/commands/rerere.d.ts.map +1 -1
  47. package/dist/commands/reset-command.d.ts +19 -2
  48. package/dist/commands/reset-command.d.ts.map +1 -1
  49. package/dist/commands/rev-parse-command.d.ts +3 -7
  50. package/dist/commands/rev-parse-command.d.ts.map +1 -1
  51. package/dist/commands/revision-resolver.d.ts +24 -5
  52. package/dist/commands/revision-resolver.d.ts.map +1 -1
  53. package/dist/commands/signing.d.ts +8 -1
  54. package/dist/commands/signing.d.ts.map +1 -1
  55. package/dist/commands/status-command.d.ts +14 -1
  56. package/dist/commands/status-command.d.ts.map +1 -1
  57. package/dist/commands/submodule-add-command.d.ts +12 -0
  58. package/dist/commands/submodule-add-command.d.ts.map +1 -1
  59. package/dist/commands/submodule-update-command.d.ts +14 -0
  60. package/dist/commands/submodule-update-command.d.ts.map +1 -1
  61. package/dist/commands/tag-command.d.ts.map +1 -1
  62. package/dist/commands/update-index-command.d.ts +21 -0
  63. package/dist/commands/update-index-command.d.ts.map +1 -1
  64. package/dist/{commands-Mlo1dxQN.js → commands-C2E51T1z.js} +942 -293
  65. package/dist/{fsck-CrhVMNIH.js → fsck-BjlxStsM.js} +1 -1
  66. package/dist/git-command.d.ts +14 -6
  67. package/dist/git-command.d.ts.map +1 -1
  68. package/dist/index.js +6 -6
  69. package/dist/{maintenance-run-command-Bw21HEkH.js → maintenance-run-command-G_eWdA8O.js} +48 -17
  70. package/dist/remote-config/remote-config-store.d.ts +4 -1
  71. package/dist/remote-config/remote-config-store.d.ts.map +1 -1
  72. package/dist/{remote-transport-Bu4PGSMD.js → remote-transport-CSgTJ1BH.js} +3 -3
  73. package/dist/results/index.js +1 -1
  74. package/dist/{results-ERo9vELd.js → results-Dg1KHG8y.js} +669 -96
  75. package/dist/transport-command.d.ts.map +1 -1
  76. package/package.json +13 -13
  77. package/src/commands/am/am-command.ts +30 -14
  78. package/src/commands/archive/archive-command.ts +395 -59
  79. package/src/commands/archive/archive-entry.ts +88 -5
  80. package/src/commands/archive/tar-archive.ts +40 -9
  81. package/src/commands/archive/zip-archive.ts +72 -21
  82. package/src/commands/attributes-source.ts +13 -1
  83. package/src/commands/cat-file/cat-file-command.ts +64 -52
  84. package/src/commands/checkout-command.ts +22 -1
  85. package/src/commands/clone-command.ts +41 -2
  86. package/src/commands/default-branch.ts +19 -0
  87. package/src/commands/diff-command.ts +19 -1
  88. package/src/commands/format-rev-command.ts +28 -12
  89. package/src/commands/fsmonitor-ipc.ts +121 -0
  90. package/src/commands/fsmonitor-refresh.ts +7 -2
  91. package/src/commands/http-config.ts +14 -2
  92. package/src/commands/index.ts +2 -0
  93. package/src/commands/log-output.ts +11 -0
  94. package/src/commands/ls-files-command.ts +25 -33
  95. package/src/commands/ls-tree-command.ts +30 -22
  96. package/src/commands/mv-command.ts +37 -6
  97. package/src/commands/pathspec.ts +2 -4
  98. package/src/commands/plumbing-shared.ts +197 -0
  99. package/src/commands/repack-command.ts +44 -11
  100. package/src/commands/replace-command.ts +16 -4
  101. package/src/commands/repo-command.ts +124 -25
  102. package/src/commands/rerere-command.ts +17 -0
  103. package/src/commands/rerere.ts +144 -3
  104. package/src/commands/reset-command.ts +75 -3
  105. package/src/commands/rev-parse-command.ts +14 -28
  106. package/src/commands/revision-resolver.ts +85 -34
  107. package/src/commands/signing.ts +54 -7
  108. package/src/commands/status-command.ts +31 -2
  109. package/src/commands/submodule-add-command.ts +18 -1
  110. package/src/commands/submodule-update-command.ts +18 -1
  111. package/src/commands/tag-command.ts +33 -11
  112. package/src/commands/update-index-command.ts +137 -5
  113. package/src/git-command.ts +60 -19
  114. package/src/remote-config/remote-config-store.ts +11 -3
  115. package/src/transport-command.ts +4 -1
@@ -13,23 +13,30 @@
13
13
  */
14
14
 
15
15
  import type { ObjectId, TreeEntry } from "@statewalker/vcs-core";
16
- import { approxidateCareful, parseGitBool, parseGitInt } from "@statewalker/vcs-utils";
17
- import { deflateSync } from "@statewalker/vcs-utils/compression";
16
+ import { createByteQueue } from "@statewalker/vcs-transport";
17
+ import {
18
+ approxidateCareful,
19
+ parseGitBool,
20
+ parseGitInt,
21
+ parseGitUlong,
22
+ } from "@statewalker/vcs-utils";
23
+ import { createDeflater } from "@statewalker/vcs-utils/compression";
18
24
  import { decodeGitPath, encodeGitPath } from "@statewalker/vcs-utils/encoding";
19
25
  import {
20
26
  type AttributesResolver,
21
27
  type AttributeValue,
22
28
  attributesIndexOfTree,
29
+ type CheckoutMetadata,
23
30
  type ContentAttributesContext,
24
31
  type ConversionSettings,
25
32
  convAttrsOf,
26
33
  crlfToWorktree,
27
34
  FilterDriverError,
28
35
  type FilterDriverRegistry,
36
+ FilterDriverRunError,
29
37
  identToWorktree,
30
38
  readConversionSettings,
31
39
  reencode,
32
- smudgeContent,
33
40
  type Worktree,
34
41
  } from "@statewalker/vcs-working-tree";
35
42
  import { GitApiError, InvalidPathError } from "../../errors/index.js";
@@ -39,6 +46,7 @@ import { cUnquote, latin1ToBytes, latin1ToPath, pathToLatin1 } from "../apply/in
39
46
  import { bareAttributesResolver } from "../attributes-source.js";
40
47
  import { createIdAbbreviator } from "../core-config.js";
41
48
  import { createDescriber } from "../git-describe.js";
49
+ import { hostEnvironmentOf } from "../git-ident.js";
42
50
  import { configValue } from "../merge-config.js";
43
51
  import {
44
52
  DO_MATCH_DIRECTORY,
@@ -51,6 +59,7 @@ import { formatCommitPretty } from "../pretty-format.js";
51
59
  import { treePathRefusal, withTreePathRefusal, worktreePathRules } from "../worktree-path-rules.js";
52
60
  import {
53
61
  type ArchiveEntry,
62
+ type ArchiveOutput,
54
63
  type ArchiveWriter,
55
64
  isDirMode,
56
65
  isGitlinkMode,
@@ -70,6 +79,19 @@ export const INTERNAL_GZIP_COMMAND = "git archive gzip";
70
79
  */
71
80
  export type ArchiveFilterRunner = (command: string, input: Uint8Array) => Promise<Uint8Array>;
72
81
 
82
+ /**
83
+ * A tar filter run as a pipe (see {@link ArchiveCommand.setStreamFilterRunner}): the tar
84
+ * archive's chunks in as they are written, the filtered bytes out as the command writes
85
+ * them. Throwing (or a failing iteration) is git's `'<command>' filter reported error`.
86
+ */
87
+ export type ArchiveStreamFilterRunner = (
88
+ command: string,
89
+ input: AsyncIterable<Uint8Array>,
90
+ ) => AsyncIterable<Uint8Array>;
91
+
92
+ /** How many bytes {@link ArchiveCommand.callStream} holds before the writer waits. */
93
+ const STREAM_HIGH_WATER_MARK = 1 << 20;
94
+
73
95
  /** An archive format git knows (`git archive --list`). */
74
96
  interface Archiver {
75
97
  name: string;
@@ -127,6 +149,8 @@ export class ArchiveCommand extends GitCommand<Uint8Array> {
127
149
  private worktreeAttributes = false;
128
150
  private currentDirectory = "";
129
151
  private filterRunner?: ArchiveFilterRunner;
152
+ private streamFilterRunner?: ArchiveStreamFilterRunner;
153
+ private bigFileThreshold?: number;
130
154
  private userUmask = 0o022;
131
155
  private localTzOffset?: (time: number) => number;
132
156
  private filterDrivers?: FilterDriverRegistry;
@@ -167,8 +191,12 @@ export class ArchiveCommand extends GitCommand<Uint8Array> {
167
191
  }
168
192
 
169
193
  /**
170
- * `--add-file=<file>`: a file of the worktree (relative to {@link setCurrentDirectory}),
171
- * added under the current prefix and its base name; `content` gives its bytes instead.
194
+ * `--add-file=<file>`: a file added under the current prefix and its base name, read as
195
+ * git reads it: an absolute path as it stands, a relative one from the worktree's top (and
196
+ * {@link setCurrentDirectory}), through the host environment (`GitHostEnvironment`'s
197
+ * `realPath`/`hostFilesOf`: files outside the repository, symbolic links followed as
198
+ * `stat` follows them), else from the worktree itself; git's `File not found` and `Not a
199
+ * regular file` deaths. `content` gives its bytes instead.
172
200
  */
173
201
  addFile(path: string, content?: Uint8Array, options: { executable?: boolean } = {}): this {
174
202
  this.checkCallable();
@@ -270,6 +298,17 @@ export class ArchiveCommand extends GitCommand<Uint8Array> {
270
298
  return this;
271
299
  }
272
300
 
301
+ /**
302
+ * Runs the tar filters' commands as pipes, the archive streamed through them (git's
303
+ * `write_tar_filter_archive`); preferred over {@link setFilterRunner}, which is handed the
304
+ * whole tar archive.
305
+ */
306
+ setStreamFilterRunner(runner: ArchiveStreamFilterRunner): this {
307
+ this.checkCallable();
308
+ this.streamFilterRunner = runner;
309
+ return this;
310
+ }
311
+
273
312
  /** The umask `tar.umask=user` stands for (default 022). */
274
313
  setUserUmask(umask: number): this {
275
314
  this.checkCallable();
@@ -302,6 +341,8 @@ export class ArchiveCommand extends GitCommand<Uint8Array> {
302
341
 
303
342
  /** `git archive --list`: the formats, as git lists them. */
304
343
  listFormats(): string[] {
344
+ this.checkTarConfig();
345
+ if (this.compatibility === "2.43") this.archiveBigFileThreshold();
305
346
  return this.archivers().map((a) => a.name);
306
347
  }
307
348
 
@@ -346,6 +387,7 @@ export class ArchiveCommand extends GitCommand<Uint8Array> {
346
387
  if (last <= 4 || !name) continue;
347
388
  const type = key.slice(last + 1);
348
389
  if (type === "command") {
390
+ // a key without a value: config_error_nonbool (see checkTarConfig)
349
391
  if (value !== undefined) define(name, value);
350
392
  } else if (type === "remote") {
351
393
  // git_config_bool: a key without a value is true, a bad one dies
@@ -364,33 +406,127 @@ export class ArchiveCommand extends GitCommand<Uint8Array> {
364
406
  return this.uploadArchive ? all.filter((a) => a.remote) : all;
365
407
  }
366
408
 
367
- /** The `tar.*` variables in configuration order. */
368
- private tarConfig(): { key: string; value: string | undefined }[] {
409
+ /** The `tar.*` variables in configuration order, with where each was read. */
410
+ private tarConfig(): { key: string; value: string | undefined; file?: string; line?: number }[] {
369
411
  return RemoteConfigStore.from(this._workingCopy).entriesWithPrefix("tar.") ?? [];
370
412
  }
371
413
 
372
- /** `tar.umask`. */
414
+ /**
415
+ * `init_tar_archiver`'s `git_config(git_tar_config)`, which every `git archive` runs
416
+ * first (`--list` and zip included): the first variable it refuses, in configuration
417
+ * order, dies (a `tar.<format>.command` without a value, a `tar.umask` that is no number).
418
+ */
419
+ private checkTarConfig(): void {
420
+ this.tarUmask();
421
+ }
422
+
423
+ /** `tar.umask`, the tar config's deaths checked on the way. */
373
424
  private tarUmask(): number {
374
425
  let umask = 0o002;
375
- for (const { key, value } of this.tarConfig()) {
426
+ for (const { key, value, file, line } of this.tarConfig()) {
427
+ const last = key.lastIndexOf(".");
428
+ if (last > 4 && key.slice(last + 1) === "command" && value === undefined) {
429
+ const fatal =
430
+ file !== undefined && line !== undefined
431
+ ? `fatal: bad config variable '${key}' in file '${file}' at line ${line}`
432
+ : `fatal: unable to parse '${key}' from command-line config`;
433
+ throw new GitApiError(`error: missing value for '${key}'\n${fatal}`);
434
+ }
376
435
  if (key !== "tar.umask") continue;
377
436
  if (value === "user") umask = this.userUmask;
378
437
  else {
379
- const n = parseGitInt(value);
380
- if (n === undefined)
438
+ // git_config_int: a key without a value reads as ''
439
+ const n = parseGitInt(value ?? "");
440
+ if (n === undefined) {
441
+ const where = file !== undefined ? ` in file ${file}` : "";
381
442
  throw new GitApiError(
382
- `fatal: bad numeric config value '${value}' for 'tar.umask': invalid unit`,
443
+ `fatal: bad numeric config value '${value ?? ""}' for 'tar.umask'${where}: invalid unit`,
383
444
  );
445
+ }
384
446
  umask = n;
385
447
  }
386
448
  }
387
449
  return umask;
388
450
  }
389
451
 
452
+ /**
453
+ * `core.bigFileThreshold` (git's `unsigned long`, default 512 MiB): git 2.43 reads it with
454
+ * the core settings when it starts (every value in order, the first it refuses dying), 2.5x
455
+ * at the first regular file it archives (the last value only).
456
+ *
457
+ * @internal
458
+ */
459
+ archiveBigFileThreshold(): number {
460
+ if (this.bigFileThreshold !== undefined) return this.bigFileThreshold;
461
+ const key = "core.bigfilethreshold";
462
+ const values = RemoteConfigStore.from(this._workingCopy).valuesWithOrigin(key);
463
+ let threshold = DEFAULT_BIG_FILE_THRESHOLD;
464
+ const checked = this.compatibility === "2.43" ? values : values.slice(-1);
465
+ for (const { text, file } of checked) {
466
+ const n = parseGitUlong(text);
467
+ if (typeof n !== "number") {
468
+ const where = file !== undefined ? ` in file ${file}` : "";
469
+ throw new GitApiError(
470
+ `fatal: bad numeric config value '${text ?? ""}' for '${key}'${where}: ${n}`,
471
+ );
472
+ }
473
+ threshold = n;
474
+ }
475
+ this.bigFileThreshold = threshold;
476
+ return threshold;
477
+ }
478
+
390
479
  /** The archive's bytes. */
391
480
  async call(): Promise<Uint8Array> {
392
481
  this.checkCallable();
393
482
  this.setCallable(false);
483
+ const chunks: Uint8Array[] = [];
484
+ await this.produce((chunk) => {
485
+ chunks.push(chunk);
486
+ });
487
+ return join(chunks);
488
+ }
489
+
490
+ /**
491
+ * The archive's bytes as they are written, in chunks of about 64 KiB, the same bytes
492
+ * {@link call} returns: blobs above `core.bigFileThreshold` are streamed from the store
493
+ * and never held whole, and a tar filter (the builtin gzip, or a command through
494
+ * {@link setStreamFilterRunner}) filters as the archive is written. The writer waits while
495
+ * a mebibyte is unread. Nothing runs until the iteration starts; where git dies the
496
+ * iteration throws a {@link GitApiError} (after the bytes git would have written).
497
+ *
498
+ * @example
499
+ * ```typescript
500
+ * for await (const chunk of git.archive().setFormat("zip").setTree("HEAD").callStream()) {
501
+ * await sink.write(chunk);
502
+ * }
503
+ * ```
504
+ */
505
+ callStream(): AsyncIterable<Uint8Array> {
506
+ this.checkCallable();
507
+ this.setCallable(false);
508
+ const queue = createByteQueue({ highWaterMark: STREAM_HIGH_WATER_MARK, coalesce: 0 });
509
+ let started = false;
510
+ const start = () => {
511
+ if (started) return;
512
+ started = true;
513
+ this.produce((chunk) => queue.push(chunk)).then(
514
+ () => queue.end(),
515
+ (error: unknown) => queue.end(error instanceof Error ? error : new Error(String(error))),
516
+ );
517
+ };
518
+ return {
519
+ [Symbol.asyncIterator]() {
520
+ start();
521
+ return queue.stream;
522
+ },
523
+ };
524
+ }
525
+
526
+ /** `write_archive`: the archive written to `output`. */
527
+ private async produce(output: ArchiveOutput): Promise<void> {
528
+ this.checkTarConfig();
529
+ if (this.compatibility === "2.43") this.archiveBigFileThreshold();
394
530
  const extras = await this.readExtraFiles();
395
531
  let format = this.format;
396
532
  if (format === undefined && this.outputName !== undefined) {
@@ -411,11 +547,16 @@ export class ArchiveCommand extends GitCommand<Uint8Array> {
411
547
  );
412
548
  }
413
549
  }
414
- return this.inOneOperation(async () => {
550
+ await this.inOneOperation(async () => {
415
551
  const target = await this.resolveTreeish(this.tree as string);
552
+ const filter =
553
+ archiver.command === undefined
554
+ ? undefined
555
+ : this.openFilter(archiver.command, level, output);
416
556
  const settings = {
417
557
  time: target.time,
418
558
  compressionLevel: level,
559
+ output: filter?.input ?? output,
419
560
  ...(target.commitId ? { commitId: target.commitId } : {}),
420
561
  };
421
562
  const writer: ArchiveWriter =
@@ -443,46 +584,115 @@ export class ArchiveCommand extends GitCommand<Uint8Array> {
443
584
  ? new GitApiError(refusal.message, { exitCode: 255 })
444
585
  : refusal,
445
586
  );
446
- const archive = writer.finish();
447
- if (archiver.command === undefined) return archive;
448
- return this.filter(archiver.command, archive, level);
587
+ await writer.finish();
588
+ await filter?.finish();
449
589
  });
450
590
  }
451
591
 
452
- private async filter(command: string, archive: Uint8Array, level: number): Promise<Uint8Array> {
592
+ /**
593
+ * `write_tar_filter_archive`: the tar archive's bytes through the filter (the builtin
594
+ * gzip, else the command, started before anything is written).
595
+ */
596
+ private openFilter(
597
+ command: string,
598
+ level: number,
599
+ output: ArchiveOutput,
600
+ ): { input: ArchiveOutput; finish(): Promise<void> } {
453
601
  if (command === INTERNAL_GZIP_COMMAND) {
454
602
  // zlib refuses the levels the tar filters' option parsing lets through
455
603
  if (level > 9) {
456
604
  throw new GitApiError("fatal: deflateInit2: stream consistency error (no message)");
457
605
  }
458
- return deflateSync([archive], { format: "gzip", level });
606
+ const deflater = createDeflater({ format: "gzip", level });
607
+ const send = async (chunks: Uint8Array[]) => {
608
+ for (const chunk of chunks) await output(chunk);
609
+ };
610
+ return {
611
+ input: (chunk) => send(deflater.push(chunk)),
612
+ finish: () => send(deflater.finish()),
613
+ };
459
614
  }
460
615
  const cmd = level >= 0 ? `${command} -${level}` : command;
461
616
  // an empty command: start_command finds nothing to run
462
617
  if (!cmd) throw new GitApiError("fatal: unable to start '' filter: No such file or directory");
463
- if (!this.filterRunner) throw new GitApiError(`fatal: unable to start '${cmd}' filter`);
464
- try {
465
- return await this.filterRunner(cmd, archive);
466
- } catch {
467
- throw new GitApiError(`fatal: '${cmd}' filter reported error`);
618
+ const failed = () => new GitApiError(`fatal: '${cmd}' filter reported error`);
619
+ const streamRunner = this.streamFilterRunner;
620
+ if (streamRunner) {
621
+ const queue = createByteQueue({ highWaterMark: STREAM_HIGH_WATER_MARK, coalesce: 0 });
622
+ let failure: GitApiError | undefined;
623
+ const pump = (async () => {
624
+ try {
625
+ for await (const chunk of streamRunner(cmd, queue.stream)) await output(chunk);
626
+ } catch {
627
+ failure = failed();
628
+ queue.end(failure);
629
+ }
630
+ })();
631
+ return {
632
+ input: async (chunk) => {
633
+ if (failure) throw failure;
634
+ try {
635
+ await queue.push(chunk);
636
+ } catch (error) {
637
+ throw failure ?? error;
638
+ }
639
+ },
640
+ finish: async () => {
641
+ queue.end();
642
+ await pump;
643
+ if (failure) throw failure;
644
+ },
645
+ };
468
646
  }
647
+ const runner = this.filterRunner;
648
+ if (!runner) throw new GitApiError(`fatal: unable to start '${cmd}' filter`);
649
+ const chunks: Uint8Array[] = [];
650
+ return {
651
+ input: (chunk) => {
652
+ chunks.push(chunk);
653
+ },
654
+ finish: async () => {
655
+ let filtered: Uint8Array;
656
+ try {
657
+ filtered = await runner(cmd, join(chunks));
658
+ } catch {
659
+ throw failed();
660
+ }
661
+ await output(filtered);
662
+ },
663
+ };
469
664
  }
470
665
 
471
- /** `--add-file`'s files read (git stats them while parsing its options). */
666
+ /**
667
+ * `--add-file`'s files checked as git stats them while parsing its options (their content
668
+ * is read when they are written).
669
+ */
472
670
  private async readExtraFiles(): Promise<ResolvedExtra[]> {
473
671
  const out: ResolvedExtra[] = [];
474
672
  for (const extra of this.extraFiles) {
475
- const path = `${this.currentDirectory}${extra.path}`;
673
+ // prefix_filename: an absolute path stays, a relative one is taken from the prefix
674
+ const path =
675
+ !extra.virtual && extra.path.startsWith("/")
676
+ ? extra.path
677
+ : `${this.currentDirectory}${extra.path}`;
476
678
  if (extra.content) {
679
+ const content = extra.content;
477
680
  out.push({
478
681
  path,
479
682
  base: extra.base,
480
- content: extra.content,
683
+ read: async () => content,
481
684
  mode: extra.executable ? 0o100755 : 0o100644,
482
685
  virtual: extra.virtual,
483
686
  });
484
687
  continue;
485
688
  }
689
+ const host = await this.hostExtraFile(path);
690
+ if (host === "missing") throw new GitApiError(`fatal: File not found: ${path}`);
691
+ if (host === "not-regular") throw new GitApiError(`fatal: Not a regular file: ${path}`);
692
+ if (host) {
693
+ out.push({ path, base: extra.base, read: host.read, mode: host.mode, virtual: false });
694
+ continue;
695
+ }
486
696
  const worktree = this.worktreeAccess;
487
697
  // prefix_filename: `..` resolved against the current directory, the worktree's top kept
488
698
  const resolved = normalizeWorktreePath(path);
@@ -494,12 +704,16 @@ export class ArchiveCommand extends GitCommand<Uint8Array> {
494
704
  if (entry.isDirectory || (entry.mode & 0o170000) !== 0o100000) {
495
705
  throw new GitApiError(`fatal: Not a regular file: ${path}`);
496
706
  }
497
- const chunks: Uint8Array[] = [];
498
- for await (const c of (worktree as Worktree).readContent(resolved as string)) chunks.push(c);
499
707
  out.push({
500
708
  path,
501
709
  base: extra.base,
502
- content: join(chunks),
710
+ read: async () => {
711
+ const chunks: Uint8Array[] = [];
712
+ for await (const c of (worktree as Worktree).readContent(resolved as string)) {
713
+ chunks.push(c);
714
+ }
715
+ return join(chunks);
716
+ },
503
717
  mode: entry.mode & 0o100 ? 0o100755 : 0o100644,
504
718
  virtual: false,
505
719
  });
@@ -507,6 +721,55 @@ export class ArchiveCommand extends GitCommand<Uint8Array> {
507
721
  return out;
508
722
  }
509
723
 
724
+ /**
725
+ * `--add-file`'s `stat` through the host environment: the path from the worktree's top
726
+ * (a bare repository's git directory), links followed (`realPath`), the file read through
727
+ * `hostFilesOf`; undefined when the host gives no access to its files (the worktree is
728
+ * read instead).
729
+ */
730
+ private async hostExtraFile(
731
+ path: string,
732
+ ): Promise<
733
+ { read: () => Promise<Uint8Array>; mode: number } | "missing" | "not-regular" | undefined
734
+ > {
735
+ const environment = hostEnvironmentOf(this._workingCopy);
736
+ if (!environment?.hostFilesOf) return undefined;
737
+ let top: string | undefined;
738
+ if (!path.startsWith("/")) {
739
+ top =
740
+ this.archiveWorktree?.hostPath ??
741
+ (this._workingCopy.config as { hostGitDir?: string } | undefined)?.hostGitDir;
742
+ if (top === undefined) return undefined;
743
+ }
744
+ const hostPath = top === undefined ? path : `${top.replace(/\/+$/, "")}/${path}`;
745
+ const real = environment.realPath
746
+ ? await environment.realPath(hostPath).catch(() => undefined)
747
+ : hostPath;
748
+ if (real === undefined) return "missing";
749
+ const location = await environment.hostFilesOf(real).catch(() => undefined);
750
+ if (!location) return undefined;
751
+ // stat(2): the link's target (statFile follows links; the real path has none left)
752
+ const stats =
753
+ (environment.statFile
754
+ ? await environment.statFile(real).catch(() => undefined)
755
+ : undefined) ?? (await location.files.stats(location.path).catch(() => undefined));
756
+ if (!stats) return "missing";
757
+ if (stats.kind !== "file") return "not-regular";
758
+ const { files, path: inFiles } = location;
759
+ return {
760
+ mode: ((stats as { mode?: number }).mode ?? 0o644) & 0o100 ? 0o100755 : 0o100644,
761
+ read: async () => {
762
+ const chunks: Uint8Array[] = [];
763
+ try {
764
+ for await (const c of files.read(inFiles)) chunks.push(c);
765
+ } catch {
766
+ throw new GitApiError(`error: cannot read '${path}'`, { exitCode: 255 });
767
+ }
768
+ return join(chunks);
769
+ },
770
+ };
771
+ }
772
+
510
773
  /** `parse_treeish_arg`: the tree, the commit (if any) and the archive's time. */
511
774
  private async resolveTreeish(name: string): Promise<ArchiveTarget> {
512
775
  const resolver = this.revisionResolver();
@@ -519,6 +782,13 @@ export class ArchiveCommand extends GitCommand<Uint8Array> {
519
782
  }
520
783
  const id = await resolver.resolve(name).catch(() => undefined);
521
784
  if (id === undefined) throw new GitApiError(`fatal: not a valid object name: ${name}`);
785
+ // the ref the tree-ish names (the process filters' `ref=`)
786
+ const colon = name.indexOf(":");
787
+ const refName =
788
+ this.uploadArchive && !this.uploadArchive.allowUnreachable && colon >= 0
789
+ ? name.slice(0, colon)
790
+ : name;
791
+ const ref = (await resolver.dwimRef(refName).catch(() => []))[0]?.ref;
522
792
  const peeled = await resolver.peelTags(id);
523
793
  let commitId: ObjectId | undefined;
524
794
  let time: number;
@@ -544,7 +814,7 @@ export class ArchiveCommand extends GitCommand<Uint8Array> {
544
814
  }
545
815
  if (refusal) throw refusal;
546
816
  }
547
- return { tree, time, ...(commitId ? { commitId } : {}) };
817
+ return { tree, time, ...(commitId ? { commitId } : {}), ...(ref ? { ref } : {}) };
548
818
  }
549
819
 
550
820
  // ---- what the run reads through the command ----
@@ -571,6 +841,21 @@ export class ArchiveCommand extends GitCommand<Uint8Array> {
571
841
  return this.treeEntries(id);
572
842
  }
573
843
 
844
+ /** @internal The size of a blob (`oid_object_info`), undefined when it cannot be read. */
845
+ archiveBlobSize(id: ObjectId): Promise<number | undefined> {
846
+ return this.blobs.size(id).catch(() => undefined);
847
+ }
848
+
849
+ /** @internal A blob's bytes as the store reads them (`open_istream`). */
850
+ async archiveBlobStream(id: ObjectId): Promise<AsyncIterable<Uint8Array> | undefined> {
851
+ return (await this.blobs.load(id).catch(() => undefined)) ?? undefined;
852
+ }
853
+
854
+ /** @internal */
855
+ archiveCompatibility(): "2.43" | "2.56" {
856
+ return this.compatibility;
857
+ }
858
+
574
859
  /** @internal */
575
860
  async archiveBlob(id: ObjectId): Promise<Uint8Array | undefined> {
576
861
  const content = await this.blobs.load(id).catch(() => undefined);
@@ -609,7 +894,11 @@ export class ArchiveCommand extends GitCommand<Uint8Array> {
609
894
  return configValue(this._workingCopy, key);
610
895
  }
611
896
 
612
- /** @internal The attributes git reads without a worktree (bare, or `GIT_ATTR_INDEX`). */
897
+ /**
898
+ * @internal The attributes git reads without a worktree (bare, or `GIT_ATTR_INDEX`). git
899
+ * 2.43 reads a bare repository's in-tree files from HEAD when no attribute source is set
900
+ * (2.5x reads none): `--worktree-attributes` in a bare repository sees them there.
901
+ */
613
902
  archiveBareAttributes(indexTree: ObjectId | undefined): AttributesResolver {
614
903
  return bareAttributesResolver({
615
904
  workingCopy: this._workingCopy,
@@ -617,6 +906,9 @@ export class ArchiveCommand extends GitCommand<Uint8Array> {
617
906
  blobs: this.blobs,
618
907
  revisions: () => this.revisionResolver(),
619
908
  ...(indexTree ? { indexTree } : {}),
909
+ ...(this.compatibility === "2.43" && !("worktree" in this._workingCopy)
910
+ ? { defaultSource: "HEAD" }
911
+ : {}),
620
912
  });
621
913
  }
622
914
 
@@ -657,7 +949,8 @@ export class ArchiveCommand extends GitCommand<Uint8Array> {
657
949
  interface ResolvedExtra {
658
950
  path: string;
659
951
  base: string;
660
- content: Uint8Array;
952
+ /** The content, read when the file is written (`strbuf_read_file`) */
953
+ read(): Promise<Uint8Array>;
661
954
  mode: number;
662
955
  virtual: boolean;
663
956
  }
@@ -666,6 +959,8 @@ interface ArchiveTarget {
666
959
  tree: ObjectId;
667
960
  commitId?: ObjectId;
668
961
  time: number;
962
+ /** The ref the tree-ish was named through (`dwim_ref`), for the checkout metadata */
963
+ ref?: string;
669
964
  }
670
965
 
671
966
  /** A queued directory (archive.c's `struct directory`). */
@@ -685,6 +980,7 @@ function matchExtension(filename: string, ext: string): boolean {
685
980
 
686
981
  function join(chunks: Uint8Array[]): Uint8Array {
687
982
  if (chunks.length === 1) return chunks[0] as Uint8Array;
983
+ if (chunks.length === 0) return new Uint8Array(0);
688
984
  let size = 0;
689
985
  for (const c of chunks) size += c.length;
690
986
  const out = new Uint8Array(size);
@@ -744,7 +1040,6 @@ class ArchiveRun {
744
1040
  private readonly attrCache = new Map<string, ReadonlyMap<string, AttributeValue>>();
745
1041
  private bareResolver?: AttributesResolver;
746
1042
  private filterContext?: ContentAttributesContext;
747
- private bigFileThreshold = DEFAULT_BIG_FILE_THRESHOLD;
748
1043
  private describeBudget = 1;
749
1044
  private conversionSettings?: ConversionSettings;
750
1045
  private readonly base: Uint8Array;
@@ -767,8 +1062,6 @@ class ArchiveRun {
767
1062
 
768
1063
  /** `parse_pathspec_arg` and the attribute sources. */
769
1064
  async prepare(): Promise<void> {
770
- const threshold = parseGitInt(this.cmd.archiveConfig("core.bigFileThreshold"));
771
- if (threshold !== undefined && threshold > 0) this.bigFileThreshold = threshold;
772
1065
  const worktree = this.worktree;
773
1066
  if (!this.settings.worktreeAttributes) {
774
1067
  if (worktree?.contentFilter) {
@@ -893,8 +1186,8 @@ class ArchiveRun {
893
1186
  if (this.settings.verbose) this.settings.messages.push(decodeGitPath(path));
894
1187
  }
895
1188
 
896
- private emit(entry: ArchiveEntry): void {
897
- const error = this.writer.entry(entry);
1189
+ private async emit(entry: ArchiveEntry): Promise<void> {
1190
+ const error = await this.writer.entry(entry);
898
1191
  if (error) throw new GitApiError(`error: ${error}`, { exitCode: 255 });
899
1192
  }
900
1193
 
@@ -906,7 +1199,7 @@ class ArchiveRun {
906
1199
  while (len > 1 && base[len - 2] === "/") len--;
907
1200
  const path = this.base.subarray(0, encodeGitPath(base.slice(0, len)).length);
908
1201
  this.report(path);
909
- this.emit({ path, mode: 0o40777, id: this.target.tree, content: new Uint8Array(0) });
1202
+ await this.emit({ path, mode: 0o40777, id: this.target.tree, content: new Uint8Array(0) });
910
1203
  }
911
1204
  await this.walk(this.target.tree, "", []);
912
1205
  const hexLength = this.target.commitId?.length ?? this.target.tree.length;
@@ -916,7 +1209,7 @@ class ArchiveRun {
916
1209
  const id = (i + 1).toString(16).padStart(16, "0").padEnd(hexLength, "0");
917
1210
  const text = extra.virtual ? extra.path : `${extra.base}${baseName(extra.path)}`;
918
1211
  const path = encodeGitPath(text);
919
- const entry: ArchiveEntry = { path, mode: extra.mode, id, content: extra.content };
1212
+ const entry: ArchiveEntry = { path, mode: extra.mode, id, content: new Uint8Array(0) };
920
1213
  // zip asks the diff driver of the path less the prefix's length (archive-zip.c)
921
1214
  binaries.push(this.binaryOf(decodeGitPath(path.subarray(this.base.length))));
922
1215
  entries.push(entry);
@@ -925,7 +1218,8 @@ class ArchiveRun {
925
1218
  const entry = entries[i] as ArchiveEntry;
926
1219
  const binary = await binaries[i];
927
1220
  if (binary !== undefined) entry.binary = binary;
928
- this.emit(entry);
1221
+ entry.content = await (this.extras[i] as ResolvedExtra).read();
1222
+ await this.emit(entry);
929
1223
  }
930
1224
  }
931
1225
 
@@ -975,23 +1269,49 @@ class ArchiveRun {
975
1269
  const convertPath = rel;
976
1270
  this.report(archivePath);
977
1271
  if (isDir) {
978
- this.emit({ path: archivePath, mode, id, content: new Uint8Array(0) });
1272
+ await this.emit({ path: archivePath, mode, id, content: new Uint8Array(0) });
979
1273
  return;
980
1274
  }
981
- let content = await this.cmd.archiveBlob(id);
982
- if (!content) throw new GitApiError(`error: cannot read '${id}'`, { exitCode: 255 });
983
- const streamed = isRegMode(mode) && !convert && content.length > this.bigFileThreshold;
984
- if (isRegMode(mode) && !streamed) {
985
- content = await this.smudge(convertPath, id, content, mode);
986
- if (convert && this.target.commitId) content = await this.substitute(content);
1275
+ // write_archive_entry: a regular blob above core.bigFileThreshold is streamed unconverted
1276
+ let size: number | undefined;
1277
+ if (isRegMode(mode) && !convert) {
1278
+ const threshold = this.cmd.archiveBigFileThreshold();
1279
+ size = await this.cmd.archiveBlobSize(id);
1280
+ if (size !== undefined && size <= threshold) size = undefined;
1281
+ }
1282
+ let entry: ArchiveEntry;
1283
+ if (size !== undefined) {
1284
+ const stream = await this.cmd.archiveBlobStream(id);
1285
+ if (!stream) throw new GitApiError(`error: cannot stream blob ${id}`, { exitCode: 255 });
1286
+ entry = {
1287
+ path: archivePath,
1288
+ mode,
1289
+ id,
1290
+ content: new Uint8Array(0),
1291
+ streamed: true,
1292
+ stream,
1293
+ size,
1294
+ };
1295
+ } else {
1296
+ let content = await this.cmd.archiveBlob(id);
1297
+ if (!content) throw new GitApiError(`error: cannot read '${id}'`, { exitCode: 255 });
1298
+ if (isRegMode(mode)) {
1299
+ content = await this.smudge(convertPath, id, content, mode);
1300
+ if (convert && this.target.commitId) content = await this.substitute(content);
1301
+ }
1302
+ entry = { path: archivePath, mode, id, content };
987
1303
  }
988
- const entry: ArchiveEntry = { path: archivePath, mode, id, content };
989
- if (streamed) entry.streamed = true;
990
1304
  if (this.writer instanceof ZipArchiveWriter && (isRegMode(mode) || isLinkMode(mode))) {
991
1305
  const binary = await this.binaryOf(convertPath);
992
1306
  if (binary !== undefined) entry.binary = binary;
993
1307
  }
994
- this.emit(entry);
1308
+ await this.emit(entry);
1309
+ }
1310
+
1311
+ /** archive.c's `init_checkout_metadata`: the ref, the commit (else the tree), the blob. */
1312
+ private metadata(blob: ObjectId): CheckoutMetadata {
1313
+ const treeish = this.target.commitId ?? this.target.tree;
1314
+ return { ...(this.target.ref ? { ref: this.target.ref } : {}), treeish, blob };
995
1315
  }
996
1316
 
997
1317
  /** zip's `entry_is_binary`: the diff driver's `binary`, undefined to look at the content. */
@@ -1038,9 +1358,25 @@ class ArchiveRun {
1038
1358
  }
1039
1359
  }
1040
1360
  const smudge = ca.driver?.host?.smudge;
1361
+ const command = ca.driver?.smudge;
1041
1362
  let filtered: Uint8Array | undefined;
1042
- if (smudge) {
1043
- filtered = await smudge.call(ca.driver?.host, out, { path }).catch(() => undefined);
1363
+ // an empty command turns the direction off (git's `-c filter.<driver>.smudge=`)
1364
+ if (smudge && command !== "") {
1365
+ try {
1366
+ filtered = await smudge.call(ca.driver?.host, out, {
1367
+ path,
1368
+ ...(command !== undefined ? { command } : {}),
1369
+ metadata: this.metadata(id),
1370
+ });
1371
+ } catch (error) {
1372
+ // apply_single_file_filter: the command's own lines, then its failure
1373
+ if (command !== undefined && !ca.driver?.required) {
1374
+ const own = error instanceof FilterDriverRunError ? error.lines : [];
1375
+ for (const line of [...own, `external filter '${command}' failed`]) {
1376
+ this.settings.messages.push(`error: ${line}`);
1377
+ }
1378
+ }
1379
+ }
1044
1380
  }
1045
1381
  if (filtered === undefined && ca.driver?.required) {
1046
1382
  throw new GitApiError(`fatal: ${path}: smudge filter ${ca.driver.name} failed`);
@@ -1048,20 +1384,20 @@ class ArchiveRun {
1048
1384
  return filtered ?? out;
1049
1385
  }
1050
1386
  const filter = this.worktree?.contentFilter;
1051
- if (!filter) return content;
1052
- let out: Awaited<ReturnType<typeof smudgeContent>>;
1387
+ if (!filter || !isRegMode(mode)) return content;
1053
1388
  try {
1054
- out = await smudgeContent(filter, path, content, mode, this.filterContext);
1389
+ const conversion = await filter.checkout(path, this.filterContext);
1390
+ if (!conversion) return content;
1391
+ return await conversion.apply(content, {
1392
+ onWarning: (message) => this.settings.messages.push(message),
1393
+ metadata: this.metadata(id),
1394
+ });
1055
1395
  } catch (error) {
1056
1396
  if (error instanceof FilterDriverError || isEncodingAttributeError(error)) {
1057
1397
  throw new GitApiError(`fatal: ${(error as Error).message}`);
1058
1398
  }
1059
1399
  throw error;
1060
1400
  }
1061
- if (out instanceof Uint8Array) return out;
1062
- const chunks: Uint8Array[] = [];
1063
- for await (const c of out as AsyncIterable<Uint8Array>) chunks.push(c);
1064
- return join(chunks);
1065
1401
  }
1066
1402
 
1067
1403
  /** `format_subst`: each `$Format:<fmt>$` expanded for the commit. */