@statewalker/vcs-commands 0.11.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 (65) hide show
  1. package/dist/commands/archive/archive-command.d.ts +81 -7
  2. package/dist/commands/archive/archive-command.d.ts.map +1 -1
  3. package/dist/commands/archive/archive-entry.d.ts +48 -5
  4. package/dist/commands/archive/archive-entry.d.ts.map +1 -1
  5. package/dist/commands/archive/tar-archive.d.ts +5 -2
  6. package/dist/commands/archive/tar-archive.d.ts.map +1 -1
  7. package/dist/commands/archive/zip-archive.d.ts +9 -2
  8. package/dist/commands/archive/zip-archive.d.ts.map +1 -1
  9. package/dist/commands/attributes-source.d.ts +5 -0
  10. package/dist/commands/attributes-source.d.ts.map +1 -1
  11. package/dist/commands/cat-file/cat-file-command.d.ts.map +1 -1
  12. package/dist/commands/http-config.d.ts +4 -2
  13. package/dist/commands/http-config.d.ts.map +1 -1
  14. package/dist/commands/index.d.ts +1 -0
  15. package/dist/commands/index.d.ts.map +1 -1
  16. package/dist/commands/index.js +6 -6
  17. package/dist/commands/ls-files-command.d.ts.map +1 -1
  18. package/dist/commands/ls-tree-command.d.ts.map +1 -1
  19. package/dist/commands/mv-command.d.ts.map +1 -1
  20. package/dist/commands/pathspec.d.ts.map +1 -1
  21. package/dist/commands/plumbing-shared.d.ts +72 -0
  22. package/dist/commands/plumbing-shared.d.ts.map +1 -0
  23. package/dist/commands/repack-command.d.ts +12 -3
  24. package/dist/commands/repack-command.d.ts.map +1 -1
  25. package/dist/commands/replace-command.d.ts.map +1 -1
  26. package/dist/commands/rerere-command.d.ts +12 -0
  27. package/dist/commands/rerere-command.d.ts.map +1 -1
  28. package/dist/commands/rerere.d.ts +22 -0
  29. package/dist/commands/rerere.d.ts.map +1 -1
  30. package/dist/commands/revision-resolver.d.ts +9 -4
  31. package/dist/commands/revision-resolver.d.ts.map +1 -1
  32. package/dist/{commands-bQQ9OmCh.js → commands-C2E51T1z.js} +595 -223
  33. package/dist/{fsck-BHT9bUS-.js → fsck-BjlxStsM.js} +1 -1
  34. package/dist/git-command.d.ts +6 -4
  35. package/dist/git-command.d.ts.map +1 -1
  36. package/dist/index.js +6 -6
  37. package/dist/{maintenance-run-command-Cx2PlGV9.js → maintenance-run-command-G_eWdA8O.js} +42 -16
  38. package/dist/remote-config/remote-config-store.d.ts +4 -1
  39. package/dist/remote-config/remote-config-store.d.ts.map +1 -1
  40. package/dist/{remote-transport-BrQZfyHu.js → remote-transport-CSgTJ1BH.js} +3 -3
  41. package/dist/results/index.js +1 -1
  42. package/dist/{results-CNHQnU5Y.js → results-Dg1KHG8y.js} +351 -51
  43. package/dist/transport-command.d.ts.map +1 -1
  44. package/package.json +12 -12
  45. package/src/commands/archive/archive-command.ts +395 -59
  46. package/src/commands/archive/archive-entry.ts +88 -5
  47. package/src/commands/archive/tar-archive.ts +40 -9
  48. package/src/commands/archive/zip-archive.ts +72 -21
  49. package/src/commands/attributes-source.ts +13 -1
  50. package/src/commands/cat-file/cat-file-command.ts +18 -44
  51. package/src/commands/http-config.ts +14 -2
  52. package/src/commands/index.ts +1 -0
  53. package/src/commands/ls-files-command.ts +25 -33
  54. package/src/commands/ls-tree-command.ts +5 -21
  55. package/src/commands/mv-command.ts +37 -6
  56. package/src/commands/pathspec.ts +2 -4
  57. package/src/commands/plumbing-shared.ts +197 -0
  58. package/src/commands/repack-command.ts +44 -11
  59. package/src/commands/replace-command.ts +16 -4
  60. package/src/commands/rerere-command.ts +17 -0
  61. package/src/commands/rerere.ts +144 -3
  62. package/src/commands/revision-resolver.ts +32 -23
  63. package/src/git-command.ts +17 -20
  64. package/src/remote-config/remote-config-store.ts +11 -3
  65. package/src/transport-command.ts +4 -1
@@ -56,6 +56,12 @@ import {
56
56
  untrackedScanPathspec,
57
57
  } from "./pathspec.js";
58
58
  import { PlumbingCommand, PlumbingError } from "./plumbing-command.js";
59
+ import {
60
+ CorruptTreeError,
61
+ objectTypeOfMode,
62
+ readAllBytes,
63
+ SHORT_MAGIC,
64
+ } from "./plumbing-shared.js";
59
65
 
60
66
  /** One entry of the index as ls-files walks it (`struct cache_entry`). */
61
67
  interface ListedEntry {
@@ -680,18 +686,29 @@ export class LsFilesCommand extends PlumbingCommand {
680
686
  let id: string;
681
687
  try {
682
688
  id = await this.resolveRevision(name);
683
- } catch {
689
+ } catch (e) {
690
+ // get_oid dies on a corrupt tree on the way (`<rev>:<path>`)
691
+ if (e instanceof CorruptTreeError) throw e;
684
692
  throw new PlumbingError(`fatal: tree-ish ${name} not found.`);
685
693
  }
686
694
  let tree: string;
687
695
  try {
688
696
  tree = await this.resolveRevision(`${id}^{tree}`);
689
- } catch {
697
+ } catch (e) {
698
+ if (e instanceof CorruptTreeError) throw e;
690
699
  throw new PlumbingError(`fatal: bad tree-ish ${name}`);
691
700
  }
692
701
  for (const e of list) if (e.stage !== 0) e.stage = 3;
702
+ // read_tree_at: the trees as git's readers walk them (names unchecked, a corrupt entry
703
+ // git's death); a tree that cannot be read ends the walk (`error: Could not read`) and
704
+ // overlay_tree_on_index dies
693
705
  const add = async (treeId: string, base: string) => {
694
- for (const entry of await this.treeEntries(treeId)) {
706
+ const entries = await this.listedTreeEntries(treeId);
707
+ if (!entries) {
708
+ this.warn(`error: Could not read ${treeId}`);
709
+ throw new PlumbingError(`fatal: unable to read tree entries ${name}`);
710
+ }
711
+ for (const entry of entries) {
695
712
  const path = base + entry.name;
696
713
  const nameBytes = pathspecName(path);
697
714
  if ((entry.mode & S_IFMT) === 0o040000) {
@@ -789,7 +806,7 @@ export class LsFilesCommand extends PlumbingCommand {
789
806
  if (path.startsWith(".git/") && worktree.readGitDirFile) {
790
807
  return worktree.readGitDirFile(path.slice(5)).catch(() => undefined);
791
808
  }
792
- return readAll(worktree.readContent(path)).catch(() => undefined);
809
+ return readAllBytes(worktree.readContent(path)).catch(() => undefined);
793
810
  }
794
811
  return undefined;
795
812
  };
@@ -830,7 +847,7 @@ export class LsFilesCommand extends PlumbingCommand {
830
847
  if (worktree) {
831
848
  const entry = await worktree.getEntry(path).catch(() => undefined);
832
849
  if (entry && !entry.isDirectory && entry.mode !== FileMode.SYMLINK) {
833
- const bytes = await readAll(worktree.readContent(path)).catch(() => undefined);
850
+ const bytes = await readAllBytes(worktree.readContent(path)).catch(() => undefined);
834
851
  if (bytes) return decodeGitPatternFile(bytes);
835
852
  }
836
853
  if (entry) return undefined;
@@ -839,7 +856,7 @@ export class LsFilesCommand extends PlumbingCommand {
839
856
  const id = skipWorktree.get(path);
840
857
  if (!id) return undefined;
841
858
  const content = await this.blobs.load(id).catch(() => undefined);
842
- return content ? decodeGitPatternFile(await readAll(content)) : undefined;
859
+ return content ? decodeGitPatternFile(await readAllBytes(content)) : undefined;
843
860
  };
844
861
  return new ExcludeRules(
845
862
  this.excludes.length > 0 ? createCommandLineExcludes(this.excludes) : undefined,
@@ -881,7 +898,7 @@ export class LsFilesCommand extends PlumbingCommand {
881
898
  }
882
899
  if (!found) return eolStatsAscii(undefined);
883
900
  const content = await this.blobs.load(found.objectId).catch(() => undefined);
884
- return eolStatsAscii(content ? await readAll(content) : undefined);
901
+ return eolStatsAscii(content ? await readAllBytes(content) : undefined);
885
902
  }
886
903
 
887
904
  /** show_ce_fmt: one entry through `--format`. */
@@ -1055,13 +1072,6 @@ function lowerTag(tag: string): string {
1055
1072
  return `v${c} `;
1056
1073
  }
1057
1074
 
1058
- /** object_type of an index mode. */
1059
- function objectTypeOfMode(mode: number): string {
1060
- if ((mode & S_IFMT) === 0o040000) return "tree";
1061
- if (mode === FileMode.GITLINK) return "commit";
1062
- return "blob";
1063
- }
1064
-
1065
1075
  /**
1066
1076
  * show_killed_files' test of one walked path: a leading directory of it is an index file, or
1067
1077
  * (for the last component) the index has entries below it.
@@ -1117,28 +1127,10 @@ async function worktreeEolInfo(worktree: Worktree, path: string): Promise<string
1117
1127
  entry.mode === FileMode.GITLINK
1118
1128
  )
1119
1129
  return "";
1120
- const bytes = await readAll(worktree.readContent(path)).catch(() => undefined);
1130
+ const bytes = await readAllBytes(worktree.readContent(path)).catch(() => undefined);
1121
1131
  return bytes ? eolStatsAscii(bytes) : "";
1122
1132
  }
1123
1133
 
1124
- async function readAll(content: AsyncIterable<Uint8Array>): Promise<Uint8Array> {
1125
- const chunks: Uint8Array[] = [];
1126
- let size = 0;
1127
- for await (const c of content) {
1128
- chunks.push(c);
1129
- size += c.length;
1130
- }
1131
- const out = new Uint8Array(size);
1132
- let at = 0;
1133
- for (const c of chunks) {
1134
- out.set(c, at);
1135
- at += c.length;
1136
- }
1137
- return out;
1138
- }
1139
-
1140
- const SHORT_MAGIC = new Set([..."!\"#%&',-;<=>@_`~^/"]);
1141
-
1142
1134
  /**
1143
1135
  * A pathspec element read against the current directory, as parse_pathspec's
1144
1136
  * `prefix_path_gently` reads it (`:(top)` and `:/` from the top; an absolute path against the
@@ -28,6 +28,7 @@ import {
28
28
  treePathspec,
29
29
  } from "./pathspec.js";
30
30
  import { PlumbingCommand, PlumbingError } from "./plumbing-command.js";
31
+ import { concatBytes, objectTypeOfMode, SHORT_MAGIC } from "./plumbing-shared.js";
31
32
 
32
33
  /** ls-tree's `cmdmode`: the output options that exclude one another. */
33
34
  export type LsTreeMode = "long" | "name-only" | "name-status" | "object-only";
@@ -52,9 +53,6 @@ const MAGIC = [
52
53
  { name: "attr", mnemonic: "" },
53
54
  ] as const;
54
55
 
55
- /** ctype.c's GIT_PATHSPEC_MAGIC characters (and `/`, `^`) */
56
- const SHORT_MAGIC = new Set([..."!\"#%&',-;<=>@_`~^/"]);
57
-
58
56
  const FLUSH_AT = 64 * 1024;
59
57
 
60
58
  /**
@@ -502,17 +500,17 @@ export class LsTreeCommand extends PlumbingCommand {
502
500
  const modeText = mode.toString(8).padStart(6, "0");
503
501
  switch (ctx.fn) {
504
502
  case "default":
505
- return concat(
503
+ return concatBytes([
506
504
  latin1Bytes(`${modeText} ${type} ${await this.abbreviated(id)}\t`),
507
505
  this.fastPath(ctx, path),
508
- );
506
+ ]);
509
507
  case "long": {
510
508
  let size = "-";
511
509
  if (type === "blob") size = String((await this.blobSize(id)) ?? "BAD");
512
- return concat(
510
+ return concatBytes([
513
511
  latin1Bytes(`${modeText} ${type} ${await this.abbreviated(id)} ${size.padStart(7)}\t`),
514
512
  this.fastPath(ctx, path),
515
- );
513
+ ]);
516
514
  }
517
515
  case "name-only":
518
516
  return this.fastPath(ctx, path);
@@ -629,20 +627,6 @@ interface WalkContext {
629
627
  nulTerminated: boolean;
630
628
  }
631
629
 
632
- function objectTypeOfMode(mode: number): "tree" | "commit" | "blob" {
633
- const kind = mode & 0o170000;
634
- if (kind === 0o040000) return "tree";
635
- if (kind === 0o160000) return "commit";
636
- return "blob";
637
- }
638
-
639
- function concat(a: Uint8Array, b: Uint8Array): Uint8Array {
640
- const out = new Uint8Array(a.length + b.length);
641
- out.set(a);
642
- out.set(b, a.length);
643
- return out;
644
- }
645
-
646
630
  /** A byte string as git prints it in an error message (bytes as they are). */
647
631
  function decodeLatin1Path(s: string): string {
648
632
  return new TextDecoder().decode(latin1Bytes(s));
@@ -7,9 +7,11 @@ import { FileMode, type ObjectId } from "@statewalker/vcs-core";
7
7
  import { compareGitPaths } from "@statewalker/vcs-utils/encoding";
8
8
  import {
9
9
  attributesIndexOf,
10
+ basicStatMatches,
10
11
  compareWithWorktree,
11
12
  entryStatOf,
12
13
  type IndexEntry,
14
+ isCleanByStat,
13
15
  type Worktree,
14
16
  type WorktreeModeTrust,
15
17
  } from "@statewalker/vcs-working-tree";
@@ -517,6 +519,10 @@ export class MvCommand extends GitCommand<MvResult> {
517
519
  });
518
520
  const current = new Map<string, IndexEntry>();
519
521
  for (const e of cache) if (e.stage === 0) current.set(e.path, e);
522
+ // the monitor as the index read asked it (core.fsmonitor): rename_index_entry_at's
523
+ // refresh_cache_entry marks the entries it finds up to date CE_FSMONITOR_VALID
524
+ const fsm = await this.fsmonitorRefresh(this.staging);
525
+ const validMoves: string[] = [];
520
526
  const dirtyPaths: string[] = [];
521
527
  let gitmodulesModified = false;
522
528
  let changed = false;
@@ -558,21 +564,37 @@ export class MvCommand extends GitCommand<MvResult> {
558
564
  const at = await lstat(src);
559
565
  if (at) sparseAndDirty = await entryModified(worktree, entry, trust, indexTime);
560
566
  }
561
- // rename_index_entry_at: flags kept; refresh_cache_entry takes the new file's stat
562
- // only while the content still matches (a gitlink's never: ie_match_stat compares its
563
- // type and HEAD alone, so its stat data stays as it was)
567
+ // rename_index_entry_at: flags kept (CE_FSMONITOR_VALID too); refresh_cache_entry
568
+ // returns a skip-worktree, assume-valid or fsmonitor-valid entry as it is, keeps one whose
569
+ // stat still matches (marked fsmonitor-valid), and takes the new file's stat only while
570
+ // the content still matches (fill_stat_cache_info: only a regular file then marked
571
+ // valid). A gitlink's stat is never taken (ie_match_stat compares its type and HEAD
572
+ // alone) nor marked; an intent-to-add entry always differs.
564
573
  let moved: IndexEntry = { ...entry, path: dst };
574
+ let valid = !!fsm && fsm.state.isValid(entry);
565
575
  if (
566
576
  !entry.skipWorktree &&
567
577
  !entry.assumeValid &&
578
+ !valid &&
568
579
  !entry.intentToAdd &&
569
580
  entry.mode !== FileMode.GITLINK
570
581
  ) {
571
582
  const file = await lstat(dst);
572
- if (file && !(await entryModified(worktree, moved, trust, indexTime, true))) {
573
- moved = { ...moved, ...entryStatOf(file) };
583
+ if (file && isCleanByStat(moved, file, trust, indexTime)) valid = true;
584
+ else if (file && !(await entryModified(worktree, moved, trust, indexTime, true))) {
585
+ // a racily clean entry: ie_match_stat compared the content, the stat stays
586
+ if (basicStatMatches(moved, file, trust)) valid = true;
587
+ else {
588
+ moved = { ...moved, ...entryStatOf(file) };
589
+ // S_ISREG of the file: a symbolic link's entry checked out as a file
590
+ // (core.symlinks=false) is one
591
+ valid = !file.isDirectory && file.mode !== FileMode.SYMLINK;
592
+ }
574
593
  }
575
594
  }
595
+ // add_index_entry replaces a tracked destination (-f): replace_index_entry's
596
+ // mark_fsmonitor_invalid
597
+ if (current.has(dst)) valid = false;
576
598
  let checkout = false;
577
599
  if (this.sparse && sparseConfig.enabled && sparseConfig.cone) {
578
600
  if (mode & SPARSE && inSparse(dst)) {
@@ -603,6 +625,7 @@ export class MvCommand extends GitCommand<MvResult> {
603
625
  const { skipWorktree: _drop, ...rest } = moved;
604
626
  moved = rest;
605
627
  }
628
+ if (fsm && valid) validMoves.push(dst);
606
629
  current.delete(src);
607
630
  current.set(dst, moved);
608
631
  adder.remove(src);
@@ -643,7 +666,12 @@ export class MvCommand extends GitCommand<MvResult> {
643
666
  }
644
667
  }
645
668
  if (changed || gitmodulesModified) {
646
- await this.writeMoves(adder, worktree, gitmodulesModified);
669
+ await this.writeMoves(adder, worktree, gitmodulesModified, async () => {
670
+ for (const path of validMoves) {
671
+ const entry = await this.staging.getEntry(path);
672
+ if (entry && entry.stage === 0) fsm?.state.markValid(entry);
673
+ }
674
+ });
647
675
  }
648
676
  return result;
649
677
  }
@@ -662,12 +690,15 @@ export class MvCommand extends GitCommand<MvResult> {
662
690
  adder: IndexAdder,
663
691
  worktree: Worktree,
664
692
  gitmodulesModified: boolean,
693
+ /** marks the moved entries fsmonitor-valid once they are in the index */
694
+ markValid: () => Promise<void>,
665
695
  ): Promise<void> {
666
696
  if (gitmodulesModified) {
667
697
  const entry = await worktree.getEntry(".gitmodules");
668
698
  if (entry && !entry.isDirectory) await adder.add(worktree, ".gitmodules", entry);
669
699
  }
670
700
  await adder.finish();
701
+ await markValid();
671
702
  await this.staging.write();
672
703
  }
673
704
 
@@ -11,6 +11,7 @@ import {
11
11
  unquoteGitPath,
12
12
  } from "@statewalker/vcs-utils/encoding";
13
13
  import { wildmatch, wildmatchBytes } from "@statewalker/vcs-working-tree";
14
+ import { SHORT_MAGIC } from "./plumbing-shared.js";
14
15
 
15
16
  export const MATCHED_RECURSIVELY = 1;
16
17
  export const MATCHED_RECURSIVELY_LEADING_PATHSPEC = 2;
@@ -206,9 +207,6 @@ function unescapeAttrValue(value: string): string {
206
207
  return out;
207
208
  }
208
209
 
209
- /** git's characters that may introduce short pathspec magic (`GIT_PATHSPEC_MAGIC`). */
210
- const SHORT_MAGIC_CHARS = new Set([..."!\"#%&',-;<=>@_`~^/"]);
211
-
212
210
  /**
213
211
  * The pathspec elements as git's `parse_pathspec` reads them from the top of the worktree:
214
212
  * short magic (`:/` top, `:!` and `:^` exclude) and long magic (`:(top,literal,glob,icase,
@@ -298,7 +296,7 @@ export function parsePathspecItem(elem: string, options: PathspecParseOptions =
298
296
  if (ch === "!" || ch === "^") exclude = true;
299
297
  else if (ch === "/") {
300
298
  // top: the paths are from the top already
301
- } else if (!SHORT_MAGIC_CHARS.has(ch)) break;
299
+ } else if (!SHORT_MAGIC.has(ch)) break;
302
300
  else throw new Error(`Unimplemented pathspec magic '${ch}' in '${elem}'`);
303
301
  }
304
302
  if (elem[pos] === ":") pos++;
@@ -0,0 +1,197 @@
1
+ /**
2
+ * Helpers the listing plumbing commands share (`ls-files`, `ls-tree`, `cat-file`, pathspec
3
+ * parsing), and tree-walk.c's `tree_desc` over a tree's stored bytes: git's readers walk a
4
+ * tree entry by entry and die on the first one that cannot be decoded, after showing what
5
+ * came before it.
6
+ */
7
+
8
+ import { canonTreeMode, type ObjectId, type TreeEntry } from "@statewalker/vcs-core";
9
+ import { bytesToHex } from "@statewalker/vcs-utils";
10
+ import { decodeGitPath } from "@statewalker/vcs-utils/encoding";
11
+
12
+ import { GitApiError } from "../errors/index.js";
13
+
14
+ /** ctype.c's GIT_PATHSPEC_MAGIC characters (and `/`, `^`): those that may start short magic */
15
+ export const SHORT_MAGIC = new Set([..."!\"#%&',-;<=>@_`~^/"]);
16
+
17
+ /** object_type of a tree or index mode. */
18
+ export function objectTypeOfMode(mode: number): "tree" | "commit" | "blob" {
19
+ const kind = mode & 0o170000;
20
+ if (kind === 0o040000) return "tree";
21
+ if (kind === 0o160000) return "commit";
22
+ return "blob";
23
+ }
24
+
25
+ /** The chunks joined (the chunk itself when there is one). */
26
+ export function concatBytes(chunks: readonly Uint8Array[]): Uint8Array {
27
+ if (chunks.length === 1) return chunks[0] as Uint8Array;
28
+ let size = 0;
29
+ for (const c of chunks) size += c.length;
30
+ const out = new Uint8Array(size);
31
+ let at = 0;
32
+ for (const c of chunks) {
33
+ out.set(c, at);
34
+ at += c.length;
35
+ }
36
+ return out;
37
+ }
38
+
39
+ /** Everything a byte stream yields, joined. */
40
+ export async function readAllBytes(content: AsyncIterable<Uint8Array>): Promise<Uint8Array> {
41
+ const chunks: Uint8Array[] = [];
42
+ for await (const c of content) chunks.push(c);
43
+ return chunks.length === 0 ? new Uint8Array(0) : concatBytes(chunks);
44
+ }
45
+
46
+ /**
47
+ * git's death on a tree it cannot decode (tree-walk.c's `decode_tree_entry` and
48
+ * `update_tree_entry`): `fatal: too-short tree object`, `fatal: malformed mode in tree entry`,
49
+ * `fatal: empty filename in tree entry`, `fatal: too-short tree file`; exit 128.
50
+ */
51
+ export class CorruptTreeError extends GitApiError {
52
+ constructor(
53
+ /** git's message, without `fatal: ` */
54
+ readonly reason: string,
55
+ /** the tree that could not be decoded */
56
+ readonly treeId?: ObjectId,
57
+ ) {
58
+ super(`fatal: ${reason}`, { exitCode: 128 });
59
+ this.name = "CorruptTreeError";
60
+ }
61
+ }
62
+
63
+ const SPACE = 0x20;
64
+
65
+ /** An entry of a tree's stored bytes: its canonical mode, name at `[nameStart, nameEnd)`. */
66
+ interface TreeDescEntry {
67
+ mode: number;
68
+ nameStart: number;
69
+ nameEnd: number;
70
+ }
71
+
72
+ /**
73
+ * tree-walk.c's `tree_desc` over a tree's stored bytes, as git's readers (`read_tree_at`,
74
+ * `ls-tree`, `cat-file -p`) walk it: each entry is yielded only once the one after it was
75
+ * decoded (`tree_entry` advances before its caller looks at the entry it got), so a walk over
76
+ * a tree whose third entry is corrupt sees the first and dies with {@link CorruptTreeError}
77
+ * asking for the second. Names are not checked (git's readers list `..`), modes are
78
+ * canonical (`canon_mode`).
79
+ *
80
+ * @example
81
+ * ```typescript
82
+ * for (const entry of walkTreeDesc(raw, 20)) console.log(entry.name);
83
+ * ```
84
+ *
85
+ * @param raw the tree's stored content
86
+ * @param rawLength the id width of the repository's hash (20 or 32)
87
+ * @param treeId the tree, carried by the error
88
+ * @throws CorruptTreeError where git dies
89
+ */
90
+ export function* walkTreeDesc(
91
+ raw: Uint8Array,
92
+ rawLength: number,
93
+ treeId?: ObjectId,
94
+ ): Generator<TreeEntry> {
95
+ for (const e of treeDesc(raw, rawLength, treeId)) {
96
+ yield {
97
+ mode: e.mode,
98
+ name: decodeGitPath(raw.subarray(e.nameStart, e.nameEnd)),
99
+ id: bytesToHex(raw.subarray(e.nameEnd + 1, e.nameEnd + 1 + rawLength)),
100
+ };
101
+ }
102
+ }
103
+
104
+ /**
105
+ * tree-walk.c's `find_tree_entry`: the entry a path (bytes, not empty) names in a tree's
106
+ * stored bytes, each entry compared with the whole path as git compares it (an entry that
107
+ * matches a leading part followed by `/` is entered, one sorting after the path ends the
108
+ * walk), each looked at once the next one decoded (a corrupt entry right after the one
109
+ * found is still git's death). `rest` is the path left to look up in the subtree `id`
110
+ * (`get_tree_entry`'s recursion); none when the entry itself was found (`d/` names `d`).
111
+ *
112
+ * @example
113
+ * ```typescript
114
+ * findTreeDescEntry(raw, 20, encodeGitPath("src/main.ts")); // { id, mode, rest: "main.ts" }
115
+ * ```
116
+ *
117
+ * @throws CorruptTreeError where git dies
118
+ */
119
+ export function findTreeDescEntry(
120
+ raw: Uint8Array,
121
+ rawLength: number,
122
+ name: Uint8Array,
123
+ treeId?: ObjectId,
124
+ ): { id: ObjectId; mode: number; rest?: Uint8Array } | undefined {
125
+ const namelen = name.length;
126
+ for (const e of treeDesc(raw, rawLength, treeId)) {
127
+ const entrylen = e.nameEnd - e.nameStart;
128
+ if (entrylen > namelen) continue;
129
+ let cmp = 0;
130
+ for (let i = 0; i < entrylen && cmp === 0; i++) {
131
+ cmp = (name[i] as number) - (raw[e.nameStart + i] as number);
132
+ }
133
+ if (cmp > 0) continue;
134
+ if (cmp < 0) break;
135
+ const id = () => bytesToHex(raw.subarray(e.nameEnd + 1, e.nameEnd + 1 + rawLength));
136
+ if (entrylen === namelen) return { id: id(), mode: e.mode };
137
+ if (name[entrylen] !== 0x2f) continue;
138
+ if ((e.mode & 0o170000) !== 0o040000) break;
139
+ if (entrylen + 1 === namelen) return { id: id(), mode: e.mode };
140
+ return { id: id(), mode: e.mode, rest: name.subarray(entrylen + 1) };
141
+ }
142
+ return undefined;
143
+ }
144
+
145
+ /** The walk of {@link walkTreeDesc}, entries by position. */
146
+ function* treeDesc(
147
+ raw: Uint8Array,
148
+ rawLength: number,
149
+ treeId: ObjectId | undefined,
150
+ ): Generator<TreeDescEntry> {
151
+ const end = raw.length;
152
+ let at = 0;
153
+ if (at >= end) return;
154
+ // init_tree_desc decodes the first entry
155
+ let current = decodeTreeEntry(raw, at, end, rawLength, treeId);
156
+ for (;;) {
157
+ // update_tree_entry: past the entry held, then the next one decoded
158
+ const len = current.nameEnd + 1 - at + rawLength;
159
+ if (end - at < len) throw new CorruptTreeError("too-short tree file", treeId);
160
+ at += len;
161
+ const held = current;
162
+ if (at >= end) {
163
+ yield held;
164
+ return;
165
+ }
166
+ current = decodeTreeEntry(raw, at, end, rawLength, treeId);
167
+ yield held;
168
+ }
169
+ }
170
+
171
+ /** decode_tree_entry: the entry at `at`. */
172
+ function decodeTreeEntry(
173
+ raw: Uint8Array,
174
+ at: number,
175
+ end: number,
176
+ rawLength: number,
177
+ treeId: ObjectId | undefined,
178
+ ): TreeDescEntry {
179
+ const size = end - at;
180
+ if (size < rawLength + 3 || raw[end - (rawLength + 1)] !== 0) {
181
+ throw new CorruptTreeError("too-short tree object", treeId);
182
+ }
183
+ // get_mode: octal digits up to a space; none, or another character, is malformed
184
+ let i = at;
185
+ let mode = 0;
186
+ if (raw[i] === SPACE) throw new CorruptTreeError("malformed mode in tree entry", treeId);
187
+ for (;;) {
188
+ const c = raw[i++] as number;
189
+ if (c === SPACE) break;
190
+ if (c < 0x30 || c > 0x37) throw new CorruptTreeError("malformed mode in tree entry", treeId);
191
+ mode = mode * 8 + (c - 0x30);
192
+ }
193
+ // the name ends at a NUL, which the check above puts at least an id before the end
194
+ const nameEnd = raw.indexOf(0, i);
195
+ if (nameEnd === i) throw new CorruptTreeError("empty filename in tree entry", treeId);
196
+ return { mode: canonTreeMode(mode), nameStart: i, nameEnd };
197
+ }
@@ -6,10 +6,13 @@ import {
6
6
  repack as storeRepack,
7
7
  } from "@statewalker/vcs-store-files";
8
8
  import { parseGitBool } from "@statewalker/vcs-utils/encoding";
9
+ import { AttributesMemo, attributesSourceSetting } from "@statewalker/vcs-working-tree";
9
10
  import { GitApiError } from "../errors/index.js";
10
11
  import { GitCommand } from "../git-command.js";
11
12
  import { RemoteConfigStore } from "../remote-config/index.js";
13
+ import { bareAttributesResolver } from "./attributes-source.js";
12
14
  import { hostEnvironmentOf } from "./git-ident.js";
15
+ import { configValue } from "./merge-config.js";
13
16
 
14
17
  /** What `git repack` did. */
15
18
  export interface RepackCommandResult {
@@ -89,7 +92,7 @@ export class RepackCommand extends GitCommand<RepackCommandResult> {
89
92
  return this;
90
93
  }
91
94
 
92
- /** `--cruft`: unreachable objects into a cruft pack (needs `-d` here). */
95
+ /** `--cruft`: unreachable objects into a cruft pack (without `-d` the old packs stay). */
93
96
  setCruft(cruft: boolean): this {
94
97
  this.checkCallable();
95
98
  this._cruft = cruft;
@@ -169,7 +172,11 @@ export class RepackCommand extends GitCommand<RepackCommandResult> {
169
172
  return this;
170
173
  }
171
174
 
172
- /** `--filter=<spec>` (with `-a`): filtered-out objects go into a pack of their own. */
175
+ /**
176
+ * `--filter=<spec>`: the new pack leaves out what the filter omits, and the objects of the
177
+ * existing packs the new ones lack go into a pack of their own (git's `write_filtered_pack`,
178
+ * with or without `-a`).
179
+ */
173
180
  setFilter(spec: string): this {
174
181
  this.checkCallable();
175
182
  this._filter = spec;
@@ -242,8 +249,13 @@ export class RepackCommand extends GitCommand<RepackCommandResult> {
242
249
  return value === undefined ? fallback : (parseGitBool(value) ?? fallback);
243
250
  }
244
251
 
245
- /** The `delta` attribute's check (git's `no_try_delta`), when the repository has a worktree. */
246
- private noDeltaCheck(): ((path: string) => Promise<boolean>) | undefined {
252
+ /**
253
+ * The `delta` attribute's check (git's `no_try_delta`): through the worktree's attributes, or
254
+ * in a bare repository builtin, system, global and `info/attributes` plus an attribute source
255
+ * (`$GIT_ATTR_SOURCE`, `attr.tree`); 2.43 reads HEAD's tree as the source when none is set
256
+ * (attr.c's `compute_default_attr_source` for a bare repository).
257
+ */
258
+ private async noDeltaCheck(): Promise<((path: string) => Promise<boolean>) | undefined> {
247
259
  const worktree = "worktree" in this.workingCopy ? this.worktreeAccess : undefined;
248
260
  const filter = worktree?.contentFilter as
249
261
  | {
@@ -255,8 +267,30 @@ export class RepackCommand extends GitCommand<RepackCommandResult> {
255
267
  }
256
268
  | undefined;
257
269
  const attributes = filter?.attributes?.bind(filter);
258
- if (!attributes) return undefined;
259
- return async (path) => (await attributes(path, ["delta"], "checkin")).get("delta") === false;
270
+ if (attributes)
271
+ return async (path) => (await attributes(path, ["delta"], "checkin")).get("delta") === false;
272
+ if (worktree) return undefined;
273
+ const { history } = this.workingCopy;
274
+ let sourceTree: string | undefined;
275
+ if (
276
+ this.hooks.compatibility === "2.43" &&
277
+ !attributesSourceSetting(
278
+ hostEnvironmentOf(this.workingCopy)?.attrSource,
279
+ configValue(this.workingCopy, "attr.tree"),
280
+ )
281
+ )
282
+ sourceTree = await this.revisionResolver()
283
+ .resolve("HEAD^{tree}")
284
+ .catch(() => undefined);
285
+ const resolver = bareAttributesResolver({
286
+ workingCopy: this.workingCopy,
287
+ trees: history.trees,
288
+ blobs: history.blobs,
289
+ revisions: () => this.revisionResolver(),
290
+ ...(sourceTree !== undefined ? { sourceTree } : {}),
291
+ });
292
+ const memo = new AttributesMemo();
293
+ return async (path) => (await resolver.get(path, ["delta"], { memo })).get("delta") === false;
260
294
  }
261
295
 
262
296
  /**
@@ -295,10 +329,6 @@ export class RepackCommand extends GitCommand<RepackCommandResult> {
295
329
  const geometric = this._geometric ? this._geometric : undefined;
296
330
  if (geometric !== undefined && all)
297
331
  throw new GitApiError("fatal: options '--geometric' and '-A/-a' cannot be used together");
298
- if (this._filter !== undefined && !all)
299
- throw new GitApiError("repack --filter without -a is not supported");
300
- if (this._cruft && !this._delete)
301
- throw new GitApiError("repack --cruft without -d is not supported");
302
332
 
303
333
  const repository = await this.filesRepository();
304
334
  if (!repository) throw new GitApiError("repack needs a files repository");
@@ -312,7 +342,8 @@ export class RepackCommand extends GitCommand<RepackCommandResult> {
312
342
  ...(this._depth !== undefined ? { depth: this._depth } : {}),
313
343
  }
314
344
  : undefined;
315
- const noDelta = this.noDeltaCheck();
345
+ const noDelta = await this.noDeltaCheck();
346
+ const geometricWarnings: string[] = [];
316
347
  const unpackExpireMs = (() => {
317
348
  if (this._unpackUnreachable === undefined) return Number.POSITIVE_INFINITY;
318
349
  const cutoff = parseExpiryDate(this._unpackUnreachable, nowSeconds, "--unpack-unreachable");
@@ -366,6 +397,7 @@ export class RepackCommand extends GitCommand<RepackCommandResult> {
366
397
  this._updateServerInfo ?? this.configBool("repack.updateServerInfo", true),
367
398
  deltaIslands: this._deltaIslands ?? this.configBool("repack.useDeltaIslands", false),
368
399
  ...(noDelta ? { noDelta } : {}),
400
+ onWarning: (line) => geometricWarnings.push(line),
369
401
  });
370
402
  const result = noDelta && worktree?.batch ? await worktree.batch(run) : await run();
371
403
  const output: string[] = [];
@@ -375,6 +407,7 @@ export class RepackCommand extends GitCommand<RepackCommandResult> {
375
407
  output,
376
408
  warnings: [
377
409
  ...this.alternatesErrors(),
410
+ ...geometricWarnings,
378
411
  ...(result?.warnings ?? []),
379
412
  ...(result?.errors ?? []).filter((l) => !this.alternatesErrors().includes(l)),
380
413
  ],
@@ -30,6 +30,7 @@ import { FsckMessageTypes } from "./fsck/fsck-msg-ids.js";
30
30
  import { fsckCommit, fsckTag, fsckTree } from "./fsck/fsck-object-checks.js";
31
31
  import { hostEnvironmentOf } from "./git-ident.js";
32
32
  import { PlumbingCommand, PlumbingError } from "./plumbing-command.js";
33
+ import { CorruptTreeError } from "./plumbing-shared.js";
33
34
 
34
35
  /** git replace's command modes (OPT_CMDMODE); unset: list without arguments, else replace. */
35
36
  export type ReplaceMode = "list" | "delete" | "edit" | "graft" | "convert-graft-file" | "replace";
@@ -249,7 +250,11 @@ export class ReplaceCommand extends PlumbingCommand {
249
250
  private async getOid(name: string): Promise<ObjectId | undefined> {
250
251
  return this.revisionResolver()
251
252
  .resolve(name)
252
- .catch(() => undefined);
253
+ .catch((e) => {
254
+ // get_oid dies on a corrupt tree on the way (`<rev>:<path>`)
255
+ if (e instanceof CorruptTreeError) throw e;
256
+ return undefined;
257
+ });
253
258
  }
254
259
 
255
260
  /** odb_read_object_info: the object's type, undefined when it is missing. */
@@ -428,9 +433,16 @@ export class ReplaceCommand extends PlumbingCommand {
428
433
  const entries = await this.listedTreeEntries(id);
429
434
  if (!entries) this.fail("cat-file reported failure");
430
435
  let out = "";
431
- for (const entry of entries) {
432
- const mode = entry.mode.toString(8).padStart(6, "0");
433
- out += `${mode} ${modeType(entry.mode)} ${entry.id}\t${quotePath(entry.name, quoteFully)}\n`;
436
+ try {
437
+ for (const entry of entries) {
438
+ const mode = entry.mode.toString(8).padStart(6, "0");
439
+ out += `${mode} ${modeType(entry.mode)} ${entry.id}\t${quotePath(entry.name, quoteFully)}\n`;
440
+ }
441
+ } catch (e) {
442
+ // the child cat-file's death on a corrupt tree, then export_object's failure
443
+ if (!(e instanceof CorruptTreeError)) throw e;
444
+ this.warn(e.message);
445
+ this.fail("cat-file reported failure");
434
446
  }
435
447
  return encodeGitPath(out);
436
448
  }