@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
@@ -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
  }
@@ -20,8 +20,10 @@ import {
20
20
  type Pack,
21
21
  packNameOf,
22
22
  } from "@statewalker/vcs-core";
23
- import { readRepositoryFormat } from "@statewalker/vcs-store-files";
23
+ import { readRepositoryFormat, setupGitDirectory } from "@statewalker/vcs-store-files";
24
24
  import { compareGitPaths } from "@statewalker/vcs-utils/encoding";
25
+ import { normalizePath } from "@statewalker/vcs-utils/files";
26
+ import { type GitHostEnvironment, readIndexFileEntries } from "@statewalker/vcs-working-tree";
25
27
  import { quotePath } from "../results/quote-path.js";
26
28
  import { hookHostOf } from "./git-hooks.js";
27
29
  import { hostEnvironmentOf } from "./git-ident.js";
@@ -105,6 +107,8 @@ interface RepoFacts {
105
107
  index?: string;
106
108
  workTree?: string;
107
109
  superproject?: string;
110
+ /** git's current directory after its setup (host path), when the caller gave it */
111
+ setupDirectory?: string;
108
112
  /** git's `repo->prefix`: the current directory below the worktree top, with a `/` */
109
113
  prefix: string;
110
114
  }
@@ -113,8 +117,9 @@ type InfoField = (facts: RepoFacts) => string;
113
117
 
114
118
  const relativeTo = (facts: RepoFacts, path: string | undefined): string => {
115
119
  if (path === undefined) return "";
116
- // git runs from the worktree top (the git directory when bare); the prefix is below it
117
- const base = facts.workTree ?? facts.gitDir ?? "";
120
+ // git runs from where its setup went: the worktree top (the git directory when a bare one
121
+ // is discovered), else where it started; the prefix is below it
122
+ const base = facts.setupDirectory ?? facts.workTree ?? facts.gitDir ?? "";
118
123
  const cwd = facts.prefix ? `${base}/${facts.prefix}` : base;
119
124
  return gitRelativePath(path, cwd);
120
125
  };
@@ -165,11 +170,19 @@ function hostPathOf(files: FilesApi, path: string): string | undefined {
165
170
  * `git repo info [--format=(lines|nul) | -z] [--all | <key>...]` and `git repo info --keys`.
166
171
  *
167
172
  * Paths are host paths: the FilesApi's root directory joined with its paths, resolved through
168
- * the host's `realPath`; without a root directory the path keys are empty. Not followed:
169
- * `$GIT_DIR`/`$GIT_COMMON_DIR` given apart from the working copy (the working copy's own
170
- * directories are reported). `path.superprojectworkingtree.*` is found where the repository's
171
- * git directory is `<super>/.git/modules/<name>` and the superproject's worktree holds the
172
- * repository at its place (git asks the superproject's index).
173
+ * the host's `realPath`; without a root directory the path keys are empty. The git directory
174
+ * and worktree are the working copy's: open it where git's setup puts them
175
+ * (`openRepositoryFromEnvironment` for `$GIT_DIR`/`$GIT_WORK_TREE`) and pass its `prefix` to
176
+ * {@link setCurrentDirectory}, and the setup's current directory (`setup.cwd`, as a host path)
177
+ * to {@link setSetupDirectory}; `$GIT_COMMON_DIR` and `$GIT_INDEX_FILE` are read from the host
178
+ * environment. Relative keys are relative to the setup directory plus the prefix, and a relative
179
+ * `$GIT_INDEX_FILE` is read in the setup directory (the worktree top, else where git started:
180
+ * outside the worktree, or with a bare `$GIT_DIR`). Without a setup directory git is taken to
181
+ * have gone to the worktree top (the git directory when bare), and a relative index is the
182
+ * file the working copy's staging opened.
183
+ * `path.superprojectworkingtree.*` is submodule.c's `get_superproject_working_tree`: the
184
+ * repository of the worktree's parent directory (reached through `hostFilesOf`, else the
185
+ * FilesApi) must hold a gitlink at the worktree's path in its index.
173
186
  */
174
187
  export class RepoInfoCommand extends PlumbingCommand {
175
188
  private format = "lines";
@@ -178,6 +191,7 @@ export class RepoInfoCommand extends PlumbingCommand {
178
191
  private keys: string[] = [];
179
192
  private compatibility: RepoCompatibility = "2.57";
180
193
  private currentDirectory = "";
194
+ private setupDirectory: string | undefined;
181
195
 
182
196
  /** `--format=<format>` (`lines`, `nul`; `table` is refused when printing values) */
183
197
  setFormat(format: string): this {
@@ -228,6 +242,16 @@ export class RepoInfoCommand extends PlumbingCommand {
228
242
  return this;
229
243
  }
230
244
 
245
+ /**
246
+ * The directory git's setup went to, as a host path (`setupGitDirectory`'s `cwd` joined to
247
+ * the FilesApi's root): the worktree top when git started inside it, else where it started.
248
+ */
249
+ setSetupDirectory(hostPath: string | undefined): this {
250
+ this.checkCallable();
251
+ this.setupDirectory = hostPath === undefined ? undefined : hostPath.replace(/(.)\/+$/, "$1");
252
+ return this;
253
+ }
254
+
231
255
  protected async run(): Promise<number> {
232
256
  const format = parseFormat(this.format.replace(/^!/, ""));
233
257
  const fields = infoFields(this.compatibility);
@@ -288,6 +312,7 @@ export class RepoInfoCommand extends PlumbingCommand {
288
312
  objectFormat: this.objectFormat.name,
289
313
  refStorage,
290
314
  prefix: this.currentDirectory ? `${this.currentDirectory}/` : "",
315
+ setupDirectory: await real(this.setupDirectory),
291
316
  };
292
317
  if (!layout) return facts;
293
318
  const files = layout.files;
@@ -306,7 +331,14 @@ export class RepoInfoCommand extends PlumbingCommand {
306
331
  : named
307
332
  ? await real(named.startsWith("/") ? named : `${facts.gitDir}/${named}`)
308
333
  : facts.gitDir;
334
+ // repo_get_index_file: `$GIT_INDEX_FILE` (an absolute one as given; a relative one is the
335
+ // file in the directory git's setup went to: the worktree top, else where it started; the
336
+ // file the working copy opened when the caller did not say), else `<git dir>/index`
309
337
  const indexFile = environment?.indexFile;
338
+ const location =
339
+ indexFile && !indexFile.startsWith("/") && facts.setupDirectory === undefined
340
+ ? this.indexLocation()
341
+ : undefined;
310
342
  facts.index =
311
343
  indexFile === undefined
312
344
  ? facts.gitDir
@@ -314,37 +346,104 @@ export class RepoInfoCommand extends PlumbingCommand {
314
346
  : undefined
315
347
  : indexFile.startsWith("/")
316
348
  ? indexFile
317
- : // relative to the directory git was started in
318
- await real(
319
- `${hostPathOf(files, layout.bare ? layout.gitDir : layout.top) ?? ""}/${facts.prefix}${indexFile}`,
320
- );
349
+ : facts.setupDirectory !== undefined
350
+ ? `${facts.setupDirectory.replace(/\/$/, "")}/${indexFile}`
351
+ : await real(
352
+ location
353
+ ? hostPathOf(location.files, location.path)
354
+ : `${hostPathOf(files, layout.bare ? layout.gitDir : layout.top) ?? ""}/${indexFile}`,
355
+ );
321
356
  if (!layout.bare) {
322
357
  facts.workTree = await real(hostPathOf(files, layout.top));
323
- facts.superproject = await this.superprojectOf(facts.gitDir, facts.workTree);
358
+ facts.superproject = await this.superprojectOf(files, layout.top, facts.workTree);
324
359
  }
325
360
  return facts;
326
361
  }
327
362
 
328
- /** get_superproject_working_tree, for a git directory under `<super>/.git/modules/`. */
363
+ /** The index file of the working copy's staging; undefined without one (bare, memory). */
364
+ private indexLocation(): { files: FilesApi; path: string } | undefined {
365
+ try {
366
+ return this.resolveStaging().indexLocation?.();
367
+ } catch {
368
+ return undefined;
369
+ }
370
+ }
371
+
372
+ /**
373
+ * submodule.c's `get_superproject_working_tree`: the repository found from the directory
374
+ * above the worktree (discovered as git's child `git -C <parent> ls-files` discovers it,
375
+ * the repository variables cleared) must hold a gitlink at the worktree's path in its
376
+ * index; the superproject is the worktree less that path. Whatever the submodule's git
377
+ * directory is (embedded `.git`, `.git/modules/<name>`, a linked worktree's modules).
378
+ */
329
379
  private async superprojectOf(
330
- gitDir: string | undefined,
380
+ files: FilesApi,
381
+ top: string,
331
382
  workTree: string | undefined,
332
383
  ): Promise<string | undefined> {
333
- if (!gitDir || !workTree) return undefined;
334
- const at = gitDir.lastIndexOf("/.git/modules/");
335
- if (at < 0) return undefined;
336
- const superTop = gitDir.slice(0, at);
337
- if (!workTree.startsWith(`${superTop}/`)) return undefined;
338
- // the superproject's worktree must hold this one (git asks its index for the gitlink)
384
+ if (!workTree) return undefined;
339
385
  const environment = hostEnvironmentOf(this.workingCopy);
340
- if (environment?.statFile) {
341
- const s = await environment.statFile(`${superTop}/.git`).catch(() => undefined);
342
- if (!s) return undefined;
386
+ const real = async (path: string) =>
387
+ (await environment?.realPath?.(path).catch(() => undefined)) ?? path;
388
+ const oneUp = await real(parentHostPath(workTree));
389
+ const subpath = gitRelativePath(workTree, oneUp).replace(/\/$/, "");
390
+ if (!subpath || subpath === "./" || subpath.startsWith("../")) return undefined;
391
+ // the parent directory through the host, else inside the repository's own storage
392
+ const host = await environment?.hostFilesOf?.(oneUp).catch(() => undefined);
393
+ const parent = host
394
+ ? { files: host.files, cwd: host.path }
395
+ : top
396
+ ? { files, cwd: normalizePath(top.slice(0, Math.max(0, top.lastIndexOf("/")))) }
397
+ : undefined;
398
+ if (!parent) return undefined;
399
+ // prepare_submodule_repo_env: none of the repository variables reach the child
400
+ const {
401
+ gitDir: _gitDir,
402
+ workTree: _workTree,
403
+ commonDir: _commonDir,
404
+ indexFile: _indexFile,
405
+ objectDirectory: _objectDirectory,
406
+ implicitWorkTree: _implicitWorkTree,
407
+ ...childEnvironment
408
+ } = environment ?? ({} as GitHostEnvironment);
409
+ let setup: Awaited<ReturnType<typeof setupGitDirectory>>;
410
+ try {
411
+ setup = await setupGitDirectory({
412
+ files: parent.files,
413
+ cwd: parent.cwd,
414
+ ...(environment ? { environment: childEnvironment as GitHostEnvironment } : {}),
415
+ });
416
+ } catch {
417
+ return undefined; // not a git repository (ls-files' exit 128)
343
418
  }
344
- return superTop;
419
+ if (setup.workTree === undefined) return undefined; // ls-files needs a worktree
420
+ const format = await readRepositoryFormat(parent.files, setup.commonDir).catch(() => undefined);
421
+ const index = await readIndexFileEntries(parent.files, setup.indexFile, {
422
+ gitDir: setup.gitDir,
423
+ ...(format ? { objectFormat: format.objectFormat } : {}),
424
+ }).catch(() => undefined);
425
+ if (!index) return undefined;
426
+ // `ls-files --stage --full-name -- <subpath>`: the first entry at or below the path
427
+ const fullName = `${setup.prefix ?? ""}${subpath}`;
428
+ const first = index.entries.find(
429
+ (e) => e.path === fullName || e.path.startsWith(`${fullName}/`),
430
+ );
431
+ if (!first || first.mode !== S_IFGITLINK) return undefined;
432
+ if (!workTree.endsWith(`/${fullName}`)) return undefined; // git's BUG()
433
+ const superTop = workTree.slice(0, workTree.length - fullName.length - 1) || "/";
434
+ return real(superTop);
345
435
  }
346
436
  }
347
437
 
438
+ const S_IFGITLINK = 0o160000;
439
+
440
+ /** The host directory holding `path` (`/a/b` → `/a`). */
441
+ function parentHostPath(path: string): string {
442
+ const trimmed = path.replace(/\/+$/, "");
443
+ const at = trimmed.lastIndexOf("/");
444
+ return at <= 0 ? "/" : trimmed.slice(0, at);
445
+ }
446
+
348
447
  /** Counts and sizes `repo structure` prints of each object type. */
349
448
  interface ObjectValues {
350
449
  commits: number;
@@ -13,6 +13,7 @@
13
13
  import { rerereGc } from "@statewalker/vcs-store-files";
14
14
  import { unifiedDiff } from "@statewalker/vcs-utils";
15
15
  import { decodeGitPath, encodeGitPath } from "@statewalker/vcs-utils/encoding";
16
+ import type { RerereEngine } from "@statewalker/vcs-working-tree/transformation";
16
17
 
17
18
  import { GitCommand } from "../git-command.js";
18
19
  import type { PlumbingTextOutput } from "./check-ref-format-command.js";
@@ -23,6 +24,7 @@ import {
23
24
  type RerereHost,
24
25
  rerereClear,
25
26
  rerereDiff,
27
+ rerereEngineOf,
26
28
  rerereForget,
27
29
  rerereGcLocation,
28
30
  rerereRemaining,
@@ -75,6 +77,21 @@ export class RerereCommand extends GitCommand<PlumbingTextOutput> {
75
77
  return this;
76
78
  }
77
79
 
80
+ /**
81
+ * git's rerere for a resolution store (vcs-store-files `GitResolutionStore`): its records
82
+ * written and replayed as `git rerere` does ({@link rerereEngineOf}); undefined without a
83
+ * worktree. Give the store the index this command reads (`workingCopy.checkout.staging`).
84
+ *
85
+ * @example
86
+ * ```typescript
87
+ * const store = createResolutionStore(files, staging, blobs, ".git", "", git.rerere().engine());
88
+ * ```
89
+ */
90
+ engine(): RerereEngine | undefined {
91
+ const host = this.rerereHost();
92
+ return host && rerereEngineOf(host);
93
+ }
94
+
78
95
  async call(): Promise<PlumbingTextOutput> {
79
96
  this.checkCallable();
80
97
  this.setCallable(false);
@@ -24,6 +24,7 @@ import { decodeGitPath, encodeGitPath, parseGitBool } from "@statewalker/vcs-uti
24
24
  import type { FilesApi } from "@statewalker/vcs-utils/files";
25
25
  import { joinPath } from "@statewalker/vcs-utils/files";
26
26
  import type { Staging, WorkingCopy, Worktree } from "@statewalker/vcs-working-tree";
27
+ import type { RerereEngine, RerereReplay } from "@statewalker/vcs-working-tree/transformation";
27
28
 
28
29
  import { conflictMarkerSizeOf } from "../results/diff-check.js";
29
30
  import { worktreeModeTrust } from "./core-config.js";
@@ -412,6 +413,12 @@ class RerereRun {
412
413
  if (!current) return false;
413
414
  const result = await this.tryMerge(id, path, current);
414
415
  if (!result) return false;
416
+ await this.writeReplayed(id, path, result);
417
+ return true;
418
+ }
419
+
420
+ /** The end of `merge`: a replayed resolution written to the worktree. */
421
+ async writeReplayed(id: RerereId, path: string, result: Uint8Array): Promise<void> {
415
422
  // the resolution was used: its mtime tells rerere gc
416
423
  const postimage = this.path(id, "postimage");
417
424
  if (!(await this.files.touch?.(postimage))) {
@@ -423,7 +430,6 @@ class RerereRun {
423
430
  raw: true,
424
431
  ...(entry && !entry.isDirectory ? { mode: entry.mode } : {}),
425
432
  });
426
- return true;
427
433
  }
428
434
 
429
435
  /** `remove_variant`. */
@@ -826,7 +832,7 @@ async function handleCache(
826
832
  path: string,
827
833
  stages: Stages,
828
834
  output?: string,
829
- ): Promise<{ status: number; id?: string }> {
835
+ ): Promise<{ status: number; id?: string; output?: Uint8Array }> {
830
836
  if (stages.some((s) => s.stage === 0)) return { status: -1 };
831
837
  const read = async (stage: number): Promise<Uint8Array> => {
832
838
  const entry = stages.find((s) => s.stage === stage);
@@ -863,7 +869,7 @@ async function handleCache(
863
869
  run.host.objectFormat,
864
870
  );
865
871
  if (output) await run.writeFile(output, parsed.output);
866
- return { status: parsed.status, ...(parsed.id ? { id: parsed.id } : {}) };
872
+ return { status: parsed.status, output: parsed.output, ...(parsed.id ? { id: parsed.id } : {}) };
867
873
  }
868
874
 
869
875
  /** `rerere_forget_one_path`. */
@@ -923,3 +929,138 @@ export async function rerereGcLocation(
923
929
  if (!location) return undefined;
924
930
  return { files: location.files, gitDir: location.path.replace(/\/?rr-cache$/, "") || "." };
925
931
  }
932
+
933
+ /** `check_one_conflict`'s three-staged conflict: no stage 0, ours and theirs regular files. */
934
+ function threeStaged(stages: Stages): boolean {
935
+ if (stages.length === 0 || stages.some((s) => s.stage === 0)) return false;
936
+ const isRegular = (mode: number | undefined) =>
937
+ mode !== undefined && (mode & 0o170000) === 0o100000;
938
+ return (
939
+ isRegular(stages.find((s) => s.stage === 2)?.mode) &&
940
+ isRegular(stages.find((s) => s.stage === 3)?.mode)
941
+ );
942
+ }
943
+
944
+ async function stagesOf(staging: Staging, path: string): Promise<Stages> {
945
+ return (await staging.getEntries(path)).map((e) => ({
946
+ stage: e.stage,
947
+ mode: e.mode,
948
+ objectId: e.objectId,
949
+ }));
950
+ }
951
+
952
+ /**
953
+ * rerere for a resolution store (`ResolutionStore` of vcs-store-files): its records are
954
+ * git's, written by rerere.c's steps only.
955
+ *
956
+ * `record(path)` is what two `git rerere` runs record for a path, one while it was
957
+ * conflicted and one once resolved: the variant `MERGE_RR` names for the path; else the
958
+ * preimage recreated from the stages as `rerere forget` recreates it (`handle_cache`),
959
+ * nothing recorded when a recorded variant replays cleanly onto it (git's first run would
960
+ * have replayed it; its id is returned), else a new variant (`assign_variant`); then the
961
+ * worktree file as the postimage (`copy_file`: an existing one stays) and the path dropped
962
+ * from `MERGE_RR`.
963
+ * `replay(path)` is `do_rerere_one_path`'s replay over the conflicted worktree file.
964
+ * Nothing is written where rerere is off (`setup_rerere`).
965
+ *
966
+ * @example
967
+ * ```typescript
968
+ * const engine = rerereEngineOf(rerereHostOf(workingCopy, staging, worktree, blobs, format));
969
+ * await engine.record("f"); // "<conflict id>"
970
+ * ```
971
+ */
972
+ export function rerereEngineOf(host: RerereHost): RerereEngine {
973
+ return {
974
+ record: (path) => recordOnePath(host, path),
975
+ replay: (path, options) => replayOnePath(host, path, options?.apply === true),
976
+ };
977
+ }
978
+
979
+ async function recordOnePath(host: RerereHost, path: string): Promise<string | undefined> {
980
+ const run = await setupRerere(host);
981
+ if (!run) return undefined;
982
+ // resolved in the worktree: no conflict hunk left (handle_file's 0)
983
+ if ((await run.handleFile(path, false)).status !== 0) return undefined;
984
+ const rr = await run.readRr();
985
+ const waiting = rr.get(path);
986
+ let id: RerereId;
987
+ if (waiting && waiting.variant >= 0) {
988
+ // the id and variant `git rerere` gave the conflict (do_rerere_one_path's first step)
989
+ id = waiting;
990
+ } else {
991
+ const stages = await stagesOf(host.staging, path);
992
+ if (!threeStaged(stages)) return undefined;
993
+ const { status, id: hex, output } = await handleCache(run, path, stages);
994
+ if (status < 1 || !hex || !output) return undefined;
995
+ id = await run.newId(hex);
996
+ // the first run: a recorded resolution that applies cleanly would have been replayed,
997
+ // and nothing recorded (do_rerere_one_path)
998
+ for (let variant = 0; variant < id.dir.status.length; variant++) {
999
+ if (((id.dir.status[variant] ?? 0) & BOTH) !== BOTH) continue;
1000
+ if (await run.tryMerge({ dir: id.dir, variant }, path, output)) return hex;
1001
+ }
1002
+ run.assignVariant(id);
1003
+ await run.mkdir(run.path(id));
1004
+ if (!((id.dir.status[id.variant] ?? 0) & RR_HAS_PREIMAGE)) {
1005
+ await run.writeFile(run.path(id, "preimage"), output);
1006
+ }
1007
+ }
1008
+ fit(id.dir, id.variant);
1009
+ const bits = id.dir.status[id.variant] ?? 0;
1010
+ // copy_file: O_EXCL, an existing postimage stays
1011
+ const postimage = run.path(id, "postimage");
1012
+ if ((await run.files.stats(postimage)) === undefined) {
1013
+ const content = await run.readWorktree(path);
1014
+ if (!content) return undefined;
1015
+ await run.mkdir(run.path(id));
1016
+ await run.writeFile(postimage, content);
1017
+ }
1018
+ id.dir.status[id.variant] = bits | RR_HAS_POSTIMAGE | RR_HAS_PREIMAGE;
1019
+ if (rr.has(path)) {
1020
+ rr.delete(path);
1021
+ await run.writeRr(rr);
1022
+ }
1023
+ return id.dir.hex;
1024
+ }
1025
+
1026
+ async function replayOnePath(
1027
+ host: RerereHost,
1028
+ path: string,
1029
+ apply: boolean,
1030
+ ): Promise<RerereReplay | undefined> {
1031
+ const run = await setupRerere(host);
1032
+ if (!run) return undefined;
1033
+ if (!threeStaged(await stagesOf(host.staging, path))) return undefined;
1034
+ const content = await run.readWorktree(path);
1035
+ if (!content) return undefined;
1036
+ // thisimage: the file normalised (handle_file), kept in memory
1037
+ const parsed = normalizeConflicts(content, await run.markerSize(path), host.objectFormat);
1038
+ if (parsed.status < 1 || !parsed.id) return undefined;
1039
+ const dir = await run.dir(parsed.id);
1040
+ for (let variant = 0; variant < dir.status.length; variant++) {
1041
+ if (((dir.status[variant] ?? 0) & BOTH) !== BOTH) continue;
1042
+ const id = { dir, variant };
1043
+ // git's `merge` writes the normalised file as the variant's thisimage before it tries
1044
+ if (apply) await run.writeFile(run.path(id, "thisimage"), parsed.output);
1045
+ const merged = await run.tryMerge(id, path, parsed.output);
1046
+ if (!merged) continue;
1047
+ const preimage = await run.readFile(run.path(id, "preimage"));
1048
+ const postimage = await run.readFile(run.path(id, "postimage"));
1049
+ if (!preimage || !postimage) continue;
1050
+ if (apply) {
1051
+ await run.writeReplayed(id, path, merged);
1052
+ const rr = await run.readRr();
1053
+ const waiting = rr.get(path);
1054
+ if (waiting !== undefined) {
1055
+ // a different variant applies cleanly: no point keeping the path's own
1056
+ if (waiting && waiting.dir === dir && waiting.variant >= 0 && waiting.variant !== variant) {
1057
+ await run.removeVariant(waiting);
1058
+ }
1059
+ rr.delete(path);
1060
+ await run.writeRr(rr);
1061
+ }
1062
+ }
1063
+ return { signature: dir.hex, variant, preimage, postimage, content: merged };
1064
+ }
1065
+ return undefined;
1066
+ }