@statewalker/vcs-commands 0.10.0 → 0.11.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 (72) hide show
  1. package/dist/commands/am/am-command.d.ts.map +1 -1
  2. package/dist/commands/cat-file/cat-file-command.d.ts +9 -0
  3. package/dist/commands/cat-file/cat-file-command.d.ts.map +1 -1
  4. package/dist/commands/checkout-command.d.ts.map +1 -1
  5. package/dist/commands/clone-command.d.ts +9 -0
  6. package/dist/commands/clone-command.d.ts.map +1 -1
  7. package/dist/commands/default-branch.d.ts +12 -0
  8. package/dist/commands/default-branch.d.ts.map +1 -1
  9. package/dist/commands/diff-command.d.ts.map +1 -1
  10. package/dist/commands/format-rev-command.d.ts +6 -4
  11. package/dist/commands/format-rev-command.d.ts.map +1 -1
  12. package/dist/commands/fsmonitor-ipc.d.ts +30 -0
  13. package/dist/commands/fsmonitor-ipc.d.ts.map +1 -0
  14. package/dist/commands/fsmonitor-refresh.d.ts.map +1 -1
  15. package/dist/commands/index.d.ts +1 -0
  16. package/dist/commands/index.d.ts.map +1 -1
  17. package/dist/commands/index.js +6 -6
  18. package/dist/commands/log-output.d.ts +6 -0
  19. package/dist/commands/log-output.d.ts.map +1 -1
  20. package/dist/commands/ls-tree-command.d.ts.map +1 -1
  21. package/dist/commands/repo-command.d.ts +28 -6
  22. package/dist/commands/repo-command.d.ts.map +1 -1
  23. package/dist/commands/reset-command.d.ts +19 -2
  24. package/dist/commands/reset-command.d.ts.map +1 -1
  25. package/dist/commands/rev-parse-command.d.ts +3 -7
  26. package/dist/commands/rev-parse-command.d.ts.map +1 -1
  27. package/dist/commands/revision-resolver.d.ts +15 -1
  28. package/dist/commands/revision-resolver.d.ts.map +1 -1
  29. package/dist/commands/signing.d.ts +8 -1
  30. package/dist/commands/signing.d.ts.map +1 -1
  31. package/dist/commands/status-command.d.ts +14 -1
  32. package/dist/commands/status-command.d.ts.map +1 -1
  33. package/dist/commands/submodule-add-command.d.ts +12 -0
  34. package/dist/commands/submodule-add-command.d.ts.map +1 -1
  35. package/dist/commands/submodule-update-command.d.ts +14 -0
  36. package/dist/commands/submodule-update-command.d.ts.map +1 -1
  37. package/dist/commands/tag-command.d.ts.map +1 -1
  38. package/dist/commands/update-index-command.d.ts +21 -0
  39. package/dist/commands/update-index-command.d.ts.map +1 -1
  40. package/dist/{commands-Mlo1dxQN.js → commands-bQQ9OmCh.js} +354 -77
  41. package/dist/{fsck-CrhVMNIH.js → fsck-BHT9bUS-.js} +1 -1
  42. package/dist/git-command.d.ts +8 -2
  43. package/dist/git-command.d.ts.map +1 -1
  44. package/dist/index.js +6 -6
  45. package/dist/{maintenance-run-command-Bw21HEkH.js → maintenance-run-command-Cx2PlGV9.js} +9 -4
  46. package/dist/{remote-transport-Bu4PGSMD.js → remote-transport-BrQZfyHu.js} +3 -3
  47. package/dist/results/index.js +1 -1
  48. package/dist/{results-ERo9vELd.js → results-CNHQnU5Y.js} +327 -54
  49. package/package.json +12 -12
  50. package/src/commands/am/am-command.ts +30 -14
  51. package/src/commands/cat-file/cat-file-command.ts +46 -8
  52. package/src/commands/checkout-command.ts +22 -1
  53. package/src/commands/clone-command.ts +41 -2
  54. package/src/commands/default-branch.ts +19 -0
  55. package/src/commands/diff-command.ts +19 -1
  56. package/src/commands/format-rev-command.ts +28 -12
  57. package/src/commands/fsmonitor-ipc.ts +121 -0
  58. package/src/commands/fsmonitor-refresh.ts +7 -2
  59. package/src/commands/index.ts +1 -0
  60. package/src/commands/log-output.ts +11 -0
  61. package/src/commands/ls-tree-command.ts +25 -1
  62. package/src/commands/repo-command.ts +124 -25
  63. package/src/commands/reset-command.ts +75 -3
  64. package/src/commands/rev-parse-command.ts +14 -28
  65. package/src/commands/revision-resolver.ts +53 -11
  66. package/src/commands/signing.ts +54 -7
  67. package/src/commands/status-command.ts +31 -2
  68. package/src/commands/submodule-add-command.ts +18 -1
  69. package/src/commands/submodule-update-command.ts +18 -1
  70. package/src/commands/tag-command.ts +33 -11
  71. package/src/commands/update-index-command.ts +137 -5
  72. package/src/git-command.ts +48 -4
@@ -103,6 +103,7 @@ export async function refreshFsmonitor(
103
103
  if (done && done.owner === options.owner) return done.run;
104
104
  }
105
105
  const nanotime = options.nanotime ?? (() => BigInt(Date.now()) * 1_000_000n);
106
+ const added = !state;
106
107
  if (!state) {
107
108
  // add_fsmonitor: a V1-like token for now, every entry dirty, the index changed
108
109
  state = new FsmonitorState(String(nanotime()));
@@ -112,7 +113,7 @@ export async function refreshFsmonitor(
112
113
  const run: FsmonitorRun = { state, untrackedPaths: [], warnings: [] };
113
114
  runs.set(state, { owner: options.owner, run });
114
115
  state.hasRun = true;
115
- await refresh(run, mode, options, nanotime);
116
+ await refresh(run, mode, options, nanotime, added);
116
117
  // the untracked cache in memory loses the reported directories (refresh_fsmonitor's
117
118
  // untracked_cache_invalidate_trimmed_path), carried by whatever writes the index next:
118
119
  // the new token must never be written beside directories the monitor reported
@@ -154,6 +155,7 @@ async function refresh(
154
155
  mode: Exclude<FsmonitorMode, { kind: "disabled" }>,
155
156
  options: RefreshFsmonitorOptions,
156
157
  nanotime: () => bigint,
158
+ added: boolean,
157
159
  ): Promise<void> {
158
160
  const { state } = run;
159
161
  let result: Uint8Array | undefined;
@@ -161,7 +163,8 @@ async function refresh(
161
163
  let bol = 0;
162
164
  let trivial = false;
163
165
  if (mode.kind === "ipc") {
164
- result = await ask(options, { mode: "ipc", token: state.token });
166
+ // add_fsmonitor leaves no token: the daemon is asked since "builtin:fake"
167
+ result = await ask(options, { mode: "ipc", token: added ? "builtin:fake" : state.token });
165
168
  if (result) {
166
169
  token = cString(result, 0);
167
170
  bol = token.length + 1;
@@ -287,6 +290,8 @@ function onPath(
287
290
  run.state.markInvalid(e);
288
291
  count++;
289
292
  }
293
+ // a sparse index's directory entry in the cone (held apart from the expanded entries)
294
+ if (run.state.markSparseDirectoriesInvalid(prefix)) count++;
290
295
  };
291
296
  if (name.endsWith("/")) {
292
297
  cone(name);
@@ -43,6 +43,7 @@ export * from "./fmt-merge-msg-command.js";
43
43
  export * from "./format-patch-command.js";
44
44
  export * from "./format-rev-command.js";
45
45
  export * from "./fsck/index.js";
46
+ export * from "./fsmonitor-ipc.js";
46
47
  export * from "./gc-command.js";
47
48
  export * from "./git-describe.js";
48
49
  export * from "./git-hooks.js";
@@ -216,6 +216,12 @@ export interface LogOutputOptions {
216
216
  * `mergetag`'s, after the commit's header
217
217
  */
218
218
  showSignature?: boolean;
219
+ /**
220
+ * pretty.c's `pretty_print_commit` alone, as `git format-rev` prints a commit: no
221
+ * `commit <id>` (or mail `From <id>`) header line, no separator between commits, no notes,
222
+ * and tabs not expanded (format-rev's pretty context is zeroed: `expand_tabs_in_log` 0)
223
+ */
224
+ prettyOnly?: boolean;
219
225
  }
220
226
 
221
227
  /** What `git format-patch` adds to the `email` format (log-tree.c, pretty.c). */
@@ -913,6 +919,7 @@ export class LogPrinter {
913
919
  this.verboseHeader = !options.diffTree || prettyGiven;
914
920
  const pretty = options.oneline ? "oneline" : (options.pretty ?? host.config("format.pretty"));
915
921
  this.format = parseCommitFormat(pretty, host);
922
+ if (options.prettyOnly) this.format = { ...this.format, expandTabs: 0 };
916
923
  const dateSpec = options.date ?? host.config("log.date");
917
924
  this.dateMode = dateSpec
918
925
  ? parseDateMode(dateSpec)
@@ -1406,6 +1413,10 @@ export class LogPrinter {
1406
1413
  log.pending = false;
1407
1414
  const { fmt } = this.format;
1408
1415
  if (this.options.noCommitId) return;
1416
+ if (this.options.prettyOnly) {
1417
+ this.out.text(await this.prettyPrint(entry, ""));
1418
+ return;
1419
+ }
1409
1420
  if (!this.verboseHeader) {
1410
1421
  // show_log without verbose_header: the id (and parents), the line termination
1411
1422
  if (this.graph) this.out.text(this.graph.showCommit());
@@ -263,7 +263,9 @@ export class LsTreeCommand extends PlumbingCommand {
263
263
  const resolver = this.revisionResolver();
264
264
  let id: string | undefined;
265
265
  try {
266
- id = await resolver.resolve(this.treeish);
266
+ // GET_OID_HASH_ANY: a tree named by an id of the compatibility format is listed with
267
+ // that format's ids
268
+ id = await resolver.resolve(this.treeish, { hashAny: true });
267
269
  } catch (e) {
268
270
  if (!(e instanceof RefNotFoundError)) throw e;
269
271
  }
@@ -370,6 +372,18 @@ export class LsTreeCommand extends PlumbingCommand {
370
372
 
371
373
  /** parse_tree_indirect: a commit's tree, a tag's object peeled, a tree itself. */
372
374
  private async peelToTree(id: string): Promise<string | undefined> {
375
+ const compat = this.compatObjects;
376
+ if (compat && id.length !== this.objectFormat.hexLength) {
377
+ // git parses an object named by a compatibility id with the storage format's parsers:
378
+ // a tree reads (its entries decoded at the id's width), a commit's `tree` line is too
379
+ // short for them (`bogus commit object`), a blob is hashed with the storage format's
380
+ // hash (`hash mismatch`), a tag fails quietly
381
+ const type = (await compat.readAsCompat(id).catch(() => undefined))?.type;
382
+ if (type === "tree") return id;
383
+ if (type === "commit") this.warn(`error: bogus commit object ${id}`);
384
+ if (type === "blob") this.warn(`error: hash mismatch ${id}`);
385
+ return undefined;
386
+ }
373
387
  const peeled = await this.revisionResolver().peelTags(id);
374
388
  if (peeled.type === "tree") return peeled.id;
375
389
  if (peeled.type === "commit") {
@@ -435,6 +449,12 @@ export class LsTreeCommand extends PlumbingCommand {
435
449
 
436
450
  private async abbreviated(id: string): Promise<string> {
437
451
  if (this.abbrev === 0) return id;
452
+ if (id.length !== this.objectFormat.hexLength) {
453
+ // an id of the compatibility format: the minimum asked (default 7), not measured
454
+ // against the repository's ids
455
+ const min = this.abbrev < 0 ? 7 : Math.max(4, this.abbrev);
456
+ return id.slice(0, Math.min(min, id.length));
457
+ }
438
458
  const hex = this.objectFormat.hexLength;
439
459
  const min =
440
460
  this.abbrev < 0 ? undefined : this.abbrev < 4 ? 4 : this.abbrev > hex ? hex : this.abbrev;
@@ -444,6 +464,10 @@ export class LsTreeCommand extends PlumbingCommand {
444
464
 
445
465
  /** The blob's size, undefined when it cannot be read. */
446
466
  private async blobSize(id: string): Promise<number | undefined> {
467
+ const compat = this.compatObjects;
468
+ if (compat && id.length !== this.objectFormat.hexLength) {
469
+ return (await compat.readAsCompat(id).catch(() => undefined))?.content.length;
470
+ }
447
471
  const objects = this._workingCopy.history?.objects;
448
472
  try {
449
473
  if (objects) {
@@ -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;
@@ -438,9 +438,14 @@ export class ResetCommand extends GitCommand<Ref> {
438
438
  // --hard: unpack-trees' one-way merge checks the entries whose flags cheat (assume-unchanged,
439
439
  // skip-worktree) before anything changes; a file kept outside the worktree stays so
440
440
  let flagged: FlaggedEntries | undefined;
441
+ let fsmKept: Map<string, StagingEntry> | undefined;
441
442
  if (this.mode === ResetMode.HARD) {
442
443
  const commit = await this.commits.load(targetId);
443
444
  if (commit) {
445
+ // oneway_merge: what the file system monitor holds unchanged is not even lstat'ed
446
+ if (this.worktreeAccess) {
447
+ fsmKept = await fsmonitorKeptEntries(this.trees, this.staging, commit.tree);
448
+ }
444
449
  flagged = await checkFlaggedEntries(
445
450
  {
446
451
  trees: this.trees,
@@ -508,7 +513,7 @@ export class ResetCommand extends GitCommand<Ref> {
508
513
  this.staging,
509
514
  this.mode === ResetMode.HARD ? { workdir: true } : { skipWorktree: true },
510
515
  );
511
- await this.resetStaging(targetId);
516
+ await this.resetStaging(targetId, fsmKept);
512
517
  }
513
518
  // a mixed reset refreshes the index and lists what is left unstaged
514
519
  if (this.mode === ResetMode.MIXED && (await this.refreshAfterReset())) {
@@ -523,6 +528,7 @@ export class ResetCommand extends GitCommand<Ref> {
523
528
  flagged?.keptOut,
524
529
  sparse,
525
530
  submodules && { unpack: submodules, oldIndex },
531
+ fsmKept && new Set(fsmKept.keys()),
526
532
  );
527
533
  // check_updates: the entries written carry the stat of their new files
528
534
  if (this.worktreeAccess && written.size > 0) {
@@ -820,6 +826,7 @@ export class ResetCommand extends GitCommand<Ref> {
820
826
  keptOut?: ReadonlySet<string>,
821
827
  sparse?: SparseUnpack,
822
828
  submodules?: HardResetSubmodules,
829
+ unchanged?: ReadonlySet<string>,
823
830
  ): Promise<Set<string>> {
824
831
  const worktree = this.worktreeAccess;
825
832
  if (!worktree) {
@@ -838,19 +845,25 @@ export class ResetCommand extends GitCommand<Ref> {
838
845
  keptOut,
839
846
  sparse,
840
847
  submodules,
848
+ unchanged,
841
849
  );
842
850
  }
843
851
 
844
852
  /**
845
853
  * Reset staging area to match a tree.
846
854
  */
847
- private async resetStaging(commitId: ObjectId): Promise<void> {
855
+ private async resetStaging(
856
+ commitId: ObjectId,
857
+ kept?: ReadonlyMap<string, StagingEntry>,
858
+ ): Promise<void> {
848
859
  const commit = await this.commits.load(commitId);
849
860
  if (commit) {
850
861
  if (this.mode !== ResetMode.MIXED) {
851
862
  // oneway_merge: an unchanged entry keeps its flags, a changed one its skip-worktree
852
863
  // bit (the stat data goes: every file is written again)
853
864
  await this.staging.readTree(this.trees, commit.tree, { keepMatching: "flags" });
865
+ // an entry the file system monitor holds unchanged stays whole (oneway_merge)
866
+ if (kept) await restoreKeptEntries(this.staging, kept);
854
867
  await this.primeCacheTree(commit.tree);
855
868
  await this.staging.write();
856
869
  return;
@@ -934,6 +947,8 @@ export async function restoreWorktreeHard(
934
947
  keptOut?: ReadonlySet<string>,
935
948
  sparse?: SparseUnpack,
936
949
  submodules?: HardResetSubmodules,
950
+ /** Entries oneway_merge leaves alone (fsmonitor-valid and unchanged: `fsmonitorKeptEntries`) */
951
+ unchanged?: ReadonlySet<string>,
937
952
  ): Promise<Set<string>> {
938
953
  const { trees, blobs, workingCopy, worktree } = deps;
939
954
  const subs = submodules?.unpack;
@@ -952,11 +967,15 @@ export async function restoreWorktreeHard(
952
967
  // a skip-worktree entry the tree keeps is not checked out (oneway_merge skips it); in a
953
968
  // sparse checkout, nothing outside its patterns is (apply_sparse_checkout), and an entry
954
969
  // coming back into them is written
955
- const skip = sparse
970
+ const outside = sparse
956
971
  ? (path: string) => !sparse.writes(path)
957
972
  : keptOut && keptOut.size > 0
958
973
  ? (path: string) => keptOut.has(path)
959
974
  : undefined;
975
+ const skip =
976
+ unchanged && unchanged.size > 0
977
+ ? (path: string) => unchanged.has(path) || !!outside?.(path)
978
+ : outside;
960
979
  const plan = skip
961
980
  ? {
962
981
  ...fullPlan,
@@ -1050,6 +1069,59 @@ export async function recordWrittenStat(
1050
1069
  if (edits > 0) await editor.finish();
1051
1070
  }
1052
1071
 
1072
+ /**
1073
+ * unpack-trees' `oneway_merge` under a reset (`reset --hard`, `checkout -f`): a stage-0 entry
1074
+ * the target keeps unchanged and the file system monitor holds valid (`CE_FSMONITOR_VALID`)
1075
+ * is neither lstat'ed nor written, and stays in the index as it is, bit and stat included.
1076
+ * Only an entry the monitor was asked about in this command, and reported nothing for, is
1077
+ * held valid (`FsmonitorState.isValid`: exactly as marked); gitlinks and skip-worktree
1078
+ * entries never are here. The entries by path, empty when the monitor is off.
1079
+ */
1080
+ export async function fsmonitorKeptEntries(
1081
+ trees: CommandTrees,
1082
+ staging: Staging,
1083
+ treeId: ObjectId,
1084
+ ): Promise<Map<string, StagingEntry>> {
1085
+ const kept = new Map<string, StagingEntry>();
1086
+ const state = staging.getFsmonitor?.();
1087
+ if (!state?.hasRun) return kept;
1088
+ let target: Awaited<ReturnType<typeof flatTree>> | undefined;
1089
+ for await (const entry of staging.entries()) {
1090
+ if (entry.stage !== 0 || entry.mode === FileMode.GITLINK) continue;
1091
+ if (entry.skipWorktree || entry.intentToAdd || !state.isValid(entry)) continue;
1092
+ target ??= await flatTree(trees, treeId);
1093
+ const t = target.get(entry.path);
1094
+ if (t && t.mode === entry.mode && t.objectId === entry.objectId) kept.set(entry.path, entry);
1095
+ }
1096
+ return kept;
1097
+ }
1098
+
1099
+ /**
1100
+ * After a one-way reset read the target into the index: the entries `oneway_merge` kept
1101
+ * (`fsmonitorKeptEntries`) put back exactly as they were (`add_entry` of the old entry), so
1102
+ * their stat and fsmonitor bit survive. Not written here.
1103
+ */
1104
+ export async function restoreKeptEntries(
1105
+ staging: Staging,
1106
+ kept: ReadonlyMap<string, StagingEntry>,
1107
+ ): Promise<void> {
1108
+ if (kept.size === 0) return;
1109
+ const editor = staging.createEditor();
1110
+ for (const old of kept.values()) {
1111
+ editor.add({
1112
+ path: old.path,
1113
+ apply: (existing) =>
1114
+ existing &&
1115
+ existing.stage === 0 &&
1116
+ existing.mode === old.mode &&
1117
+ existing.objectId === old.objectId
1118
+ ? old
1119
+ : existing,
1120
+ });
1121
+ }
1122
+ await editor.finish();
1123
+ }
1124
+
1053
1125
  /** What {@link checkFlaggedEntries} found. */
1054
1126
  export interface FlaggedEntries {
1055
1127
  /** The first path whose flagged entry the tree changes or deletes over a changed file. */
@@ -194,16 +194,14 @@ export class RevParseCommand extends GitCommand<RevParseResult> {
194
194
  if (await this.tryParentShorthands(resolver, arg, lines)) continue;
195
195
  const reversed = arg.startsWith("^");
196
196
  let id: ObjectId | undefined;
197
- if (output !== undefined) {
198
- const translated = await this.translatedRevision(reversed ? arg.slice(1) : arg, output);
199
- if (translated !== undefined) {
200
- lines.push(reversed ? `^${translated}` : translated);
201
- continue;
202
- }
203
- }
204
197
  try {
205
- id = await resolver.resolve(reversed ? arg.slice(1) : arg);
206
- if (id !== undefined && output === "compat") id = await this.outputCompat(id);
198
+ // under --output-object-format git adds GET_OID_HASH_ANY: ids of the compatibility
199
+ // format, full or abbreviated, name objects too
200
+ id = await resolver.resolve(
201
+ reversed ? arg.slice(1) : arg,
202
+ output !== undefined ? { hashAny: true } : {},
203
+ );
204
+ if (id !== undefined && output !== undefined) id = await this.outputId(id, output);
207
205
  } catch (error) {
208
206
  if (error instanceof RevisionError && resolver.warnings.length > 0) {
209
207
  throw new RevisionError(arg, [...resolver.warnings, error.message].join("\n"));
@@ -237,27 +235,15 @@ export class RevParseCommand extends GitCommand<RevParseResult> {
237
235
  }
238
236
 
239
237
  /**
240
- * A full id of the compatibility format under `--output-object-format` (git's
241
- * `GET_OID_HASH_ANY`): printed as given in that format, else as the storage id the map
242
- * gives (as given when it has none, as git's ignored `repo_oid_to_algop` failure leaves it).
243
- * Undefined for anything else.
238
+ * `repo_oid_to_algop`: `id` (of either format) printed in the format asked, through the map;
239
+ * as it is when the map has no translation (git ignores that failure).
244
240
  */
245
- private async translatedRevision(
246
- name: string,
247
- output: "storage" | "compat",
248
- ): Promise<string | undefined> {
241
+ private async outputId(id: ObjectId, output: "storage" | "compat"): Promise<ObjectId> {
249
242
  const compat = this.compatObjects;
250
- if (!compat || name.length !== compat.compat.hexLength || !/^[0-9a-fA-F]+$/.test(name)) {
251
- return undefined;
252
- }
253
- const id = name.toLowerCase();
254
- if (output === "compat") return id;
255
- return (await compat.toStorage(id)) ?? id;
256
- }
257
-
258
- /** `id` in the compatibility format, as the map gives it (else as it is, as git) */
259
- private async outputCompat(id: ObjectId): Promise<ObjectId> {
260
- return (await this.compatObjects?.toCompat(id)) ?? id;
243
+ if (!compat) return id;
244
+ const isStorage = id.length === this.objectFormat.hexLength;
245
+ if (output === "storage") return isStorage ? id : ((await compat.toStorage(id)) ?? id);
246
+ return isStorage ? ((await compat.toCompat(id)) ?? id) : id;
261
247
  }
262
248
 
263
249
  /**