@statewalker/vcs-commands 0.3.2 → 0.5.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 (133) hide show
  1. package/README.md +19 -0
  2. package/dist/commands/add-command.d.ts +0 -6
  3. package/dist/commands/add-command.d.ts.map +1 -1
  4. package/dist/commands/blame-command.d.ts +14 -0
  5. package/dist/commands/blame-command.d.ts.map +1 -1
  6. package/dist/commands/branch-command.d.ts.map +1 -1
  7. package/dist/commands/checkout-command.d.ts +7 -24
  8. package/dist/commands/checkout-command.d.ts.map +1 -1
  9. package/dist/commands/clean-command.d.ts +34 -4
  10. package/dist/commands/clean-command.d.ts.map +1 -1
  11. package/dist/commands/clone-command.d.ts +61 -21
  12. package/dist/commands/clone-command.d.ts.map +1 -1
  13. package/dist/commands/core-config.d.ts +16 -0
  14. package/dist/commands/core-config.d.ts.map +1 -0
  15. package/dist/commands/fetch-command.d.ts +104 -37
  16. package/dist/commands/fetch-command.d.ts.map +1 -1
  17. package/dist/commands/index.d.ts +1 -0
  18. package/dist/commands/index.d.ts.map +1 -1
  19. package/dist/commands/index.js +2 -2
  20. package/dist/commands/init-command.d.ts.map +1 -1
  21. package/dist/commands/merge-command.d.ts +15 -2
  22. package/dist/commands/merge-command.d.ts.map +1 -1
  23. package/dist/commands/push-command.d.ts +58 -25
  24. package/dist/commands/push-command.d.ts.map +1 -1
  25. package/dist/commands/remote-command.d.ts +115 -6
  26. package/dist/commands/remote-command.d.ts.map +1 -1
  27. package/dist/commands/reset-command.d.ts.map +1 -1
  28. package/dist/commands/stash-apply-command.d.ts +35 -13
  29. package/dist/commands/stash-apply-command.d.ts.map +1 -1
  30. package/dist/commands/stash-create-command.d.ts +59 -25
  31. package/dist/commands/stash-create-command.d.ts.map +1 -1
  32. package/dist/commands/stash-drop-command.d.ts +8 -2
  33. package/dist/commands/stash-drop-command.d.ts.map +1 -1
  34. package/dist/commands/stash-list-command.d.ts +2 -4
  35. package/dist/commands/stash-list-command.d.ts.map +1 -1
  36. package/dist/commands/stash-working-tree.d.ts +72 -0
  37. package/dist/commands/stash-working-tree.d.ts.map +1 -0
  38. package/dist/commands/status-command.d.ts +29 -22
  39. package/dist/commands/status-command.d.ts.map +1 -1
  40. package/dist/commands/tag-command.d.ts.map +1 -1
  41. package/dist/commands/tree-restore.d.ts +52 -5
  42. package/dist/commands/tree-restore.d.ts.map +1 -1
  43. package/dist/commands/worktree-overwrite-checks.d.ts +64 -0
  44. package/dist/commands/worktree-overwrite-checks.d.ts.map +1 -0
  45. package/dist/{commands-COO4tJhv.js → commands-CsLNyvZ1.js} +3370 -1057
  46. package/dist/core-commands/add.command.impl.d.ts +0 -4
  47. package/dist/core-commands/add.command.impl.d.ts.map +1 -1
  48. package/dist/core-commands/index.d.ts +1 -3
  49. package/dist/core-commands/index.d.ts.map +1 -1
  50. package/dist/core-commands/store-worktree-file.d.ts +6 -0
  51. package/dist/core-commands/store-worktree-file.d.ts.map +1 -0
  52. package/dist/errors/checkout-errors.d.ts +13 -0
  53. package/dist/errors/checkout-errors.d.ts.map +1 -1
  54. package/dist/errors/index.js +18 -1
  55. package/dist/git-command.d.ts +10 -1
  56. package/dist/git-command.d.ts.map +1 -1
  57. package/dist/git.d.ts +21 -3
  58. package/dist/git.d.ts.map +1 -1
  59. package/dist/index.js +4 -4
  60. package/dist/remote-config/index.d.ts +1 -0
  61. package/dist/remote-config/index.d.ts.map +1 -1
  62. package/dist/remote-config/remote-config-store.d.ts +22 -0
  63. package/dist/remote-config/remote-config-store.d.ts.map +1 -1
  64. package/dist/remote-config/remote-refs.d.ts +37 -0
  65. package/dist/remote-config/remote-refs.d.ts.map +1 -0
  66. package/dist/results/clone-result.d.ts +6 -0
  67. package/dist/results/clone-result.d.ts.map +1 -1
  68. package/dist/results/diff-formatter.d.ts +14 -7
  69. package/dist/results/diff-formatter.d.ts.map +1 -1
  70. package/dist/results/fetch-result.d.ts +16 -1
  71. package/dist/results/fetch-result.d.ts.map +1 -1
  72. package/dist/results/index.js +28 -23
  73. package/dist/results/push-result.d.ts +9 -2
  74. package/dist/results/push-result.d.ts.map +1 -1
  75. package/dist/results/status-result.d.ts +91 -20
  76. package/dist/results/status-result.d.ts.map +1 -1
  77. package/dist/{status-result-BwAyxq6R.js → status-result-BpyUK1Sg.js} +115 -5
  78. package/dist/transport-command.d.ts +12 -0
  79. package/dist/transport-command.d.ts.map +1 -1
  80. package/package.json +14 -12
  81. package/src/commands/add-command.ts +23 -30
  82. package/src/commands/blame-command.ts +41 -0
  83. package/src/commands/branch-command.ts +2 -53
  84. package/src/commands/checkout-command.ts +205 -127
  85. package/src/commands/clean-command.ts +187 -81
  86. package/src/commands/clone-command.ts +334 -137
  87. package/src/commands/core-config.ts +41 -0
  88. package/src/commands/fetch-command.ts +536 -211
  89. package/src/commands/gc-command.ts +1 -1
  90. package/src/commands/index.ts +1 -0
  91. package/src/commands/init-command.ts +108 -11
  92. package/src/commands/merge-command.ts +60 -27
  93. package/src/commands/pack-refs-command.ts +2 -2
  94. package/src/commands/push-command.ts +242 -308
  95. package/src/commands/reflog-command.ts +2 -2
  96. package/src/commands/remote-command.ts +429 -19
  97. package/src/commands/reset-command.ts +18 -5
  98. package/src/commands/stash-apply-command.ts +632 -97
  99. package/src/commands/stash-create-command.ts +142 -62
  100. package/src/commands/stash-drop-command.ts +53 -5
  101. package/src/commands/stash-list-command.ts +10 -4
  102. package/src/commands/stash-working-tree.ts +243 -0
  103. package/src/commands/status-command.ts +197 -91
  104. package/src/commands/tag-command.ts +2 -53
  105. package/src/commands/tree-restore.ts +143 -18
  106. package/src/commands/worktree-overwrite-checks.ts +215 -0
  107. package/src/core-commands/add.command.impl.ts +15 -20
  108. package/src/core-commands/index.ts +1 -8
  109. package/src/core-commands/store-worktree-file.ts +5 -0
  110. package/src/errors/checkout-errors.ts +20 -0
  111. package/src/git-command.ts +42 -1
  112. package/src/git.ts +30 -2
  113. package/src/remote-config/index.ts +1 -0
  114. package/src/remote-config/remote-config-store.ts +95 -8
  115. package/src/remote-config/remote-refs.ts +103 -0
  116. package/src/results/clone-result.ts +6 -0
  117. package/src/results/diff-formatter.ts +31 -38
  118. package/src/results/fetch-result.ts +16 -1
  119. package/src/results/push-result.ts +9 -2
  120. package/src/results/status-result.ts +212 -29
  121. package/src/transport-command.ts +18 -0
  122. package/dist/core-commands/checkout.command.d.ts +0 -103
  123. package/dist/core-commands/checkout.command.d.ts.map +0 -1
  124. package/dist/core-commands/checkout.command.impl.d.ts +0 -114
  125. package/dist/core-commands/checkout.command.impl.d.ts.map +0 -1
  126. package/dist/pack-import/index.d.ts +0 -8
  127. package/dist/pack-import/index.d.ts.map +0 -1
  128. package/dist/pack-import/pack-import.d.ts +0 -11
  129. package/dist/pack-import/pack-import.d.ts.map +0 -1
  130. package/src/core-commands/checkout.command.impl.ts +0 -586
  131. package/src/core-commands/checkout.command.ts +0 -125
  132. package/src/pack-import/index.ts +0 -8
  133. package/src/pack-import/pack-import.ts +0 -24
@@ -0,0 +1,215 @@
1
+ /**
2
+ * What a checkout or a stash apply must not overwrite, as git's unpack-trees checks it
3
+ * before writing anything: local changes (`verify_uptodate`), untracked files on a path or
4
+ * a leading component (`verify_absent`, `check_leading_path`), and untracked files in a
5
+ * directory a file replaces (`verify_clean_subdirectory`).
6
+ */
7
+
8
+ import { FileMode, type ObjectId } from "@statewalker/vcs-core";
9
+ import type { Worktree, WorktreeModeTrust } from "@statewalker/vcs-working-tree";
10
+
11
+ /** An index or tree entry, with the index's stat where it has one. */
12
+ export interface CheckedEntry {
13
+ objectId: ObjectId;
14
+ mode: number;
15
+ size?: number;
16
+ mtime?: number;
17
+ ctime?: number;
18
+ }
19
+
20
+ /**
21
+ * Whether the worktree file at `path` no longer holds the index entry (git's
22
+ * `verify_uptodate`): changed content, type, or executable bit where the worktree shows it.
23
+ * A missing file is no local change.
24
+ */
25
+ export async function worktreeDiffers(
26
+ worktree: Worktree,
27
+ path: string,
28
+ entry: CheckedEntry,
29
+ trust?: WorktreeModeTrust,
30
+ ): Promise<boolean> {
31
+ const current = await worktree.getEntry(path);
32
+ if (!current) return false;
33
+ if (current.isDirectory) return entry.mode !== FileMode.GITLINK;
34
+ if (entry.mode === FileMode.GITLINK) return false;
35
+ if (
36
+ trust?.executable &&
37
+ entry.mode !== FileMode.SYMLINK &&
38
+ current.mode !== FileMode.SYMLINK &&
39
+ (current.mode === FileMode.EXECUTABLE_FILE) !== (entry.mode === FileMode.EXECUTABLE_FILE)
40
+ ) {
41
+ return true;
42
+ }
43
+ // the stat the index recorded still matches: unchanged, as git's ie_match_stat
44
+ if (
45
+ entry.mtime &&
46
+ current.size === entry.size &&
47
+ current.mtime === entry.mtime &&
48
+ (entry.ctime === undefined || current.ctime === undefined || entry.ctime === current.ctime)
49
+ ) {
50
+ return false;
51
+ }
52
+ if ((current.mode === FileMode.SYMLINK) !== (entry.mode === FileMode.SYMLINK)) {
53
+ // a link written as a file (core.symlinks=false) is still the link
54
+ if (worktree.capabilities?.symlinks !== false) return true;
55
+ }
56
+ return (await worktree.computeHash(path)) !== entry.objectId;
57
+ }
58
+
59
+ /** What stands where an operation writes: untracked files, and directories with some. */
60
+ export interface InTheWay {
61
+ /** Untracked files or links on a written path, or on a leading component of one */
62
+ untracked: string[];
63
+ /**
64
+ * Directories a written file replaces that hold untracked files, or tracked files the
65
+ * operation does not remove (never replaced behind the index's back)
66
+ */
67
+ lostDirs: string[];
68
+ }
69
+
70
+ /**
71
+ * Finds what stands where `writes` (paths not in the index) are written, `removes` being
72
+ * the tracked paths the operation deletes first. Ignored files are expendable, as in git.
73
+ * With `ignoreCase`, a file that is one of `removes` in another case is no obstacle (a
74
+ * case-only rename on a case-folding worktree).
75
+ */
76
+ export async function findInTheWay(
77
+ worktree: Worktree,
78
+ options: {
79
+ writes: string[];
80
+ removes: Set<string>;
81
+ index: Map<string, unknown>;
82
+ ignoreCase?: boolean;
83
+ },
84
+ ): Promise<InTheWay> {
85
+ const { writes, removes, index } = options;
86
+ const untracked = new Set<string>();
87
+ const lostDirs: string[] = [];
88
+ const removingFolded = new Set([...removes].map((p) => p.toLowerCase()));
89
+ const tracked = (p: string) => index.has(p) && !removes.has(p);
90
+ // directories holding tracked files that stay: a file written there would replace them
91
+ const trackedDirs = new Set<string>();
92
+ for (const p of index.keys()) {
93
+ if (removes.has(p)) continue;
94
+ for (let k = p.indexOf("/"); k > 0; k = p.indexOf("/", k + 1)) trackedDirs.add(p.slice(0, k));
95
+ }
96
+ for (const path of writes) {
97
+ if (trackedDirs.has(path)) {
98
+ lostDirs.push(path);
99
+ continue;
100
+ }
101
+ if (index.has(path)) continue;
102
+ const parts = path.split("/");
103
+ let blocked = false;
104
+ for (let k = 1; k < parts.length && !blocked; k++) {
105
+ const prefix = parts.slice(0, k).join("/");
106
+ const entry = await worktree.getEntry(prefix);
107
+ if (!entry || entry.isDirectory || removes.has(prefix)) continue;
108
+ if (!(await worktree.isIgnored(prefix))) untracked.add(prefix);
109
+ blocked = true;
110
+ }
111
+ if (blocked) continue;
112
+ const entry = await worktree.getEntry(path);
113
+ if (!entry) continue;
114
+ if (entry.isDirectory) {
115
+ for await (const inside of worktree.walk({ pathPrefix: path })) {
116
+ if (!tracked(inside.path) && !removes.has(inside.path)) {
117
+ lostDirs.push(path);
118
+ break;
119
+ }
120
+ }
121
+ continue;
122
+ }
123
+ if (options.ignoreCase && removingFolded.has(path.toLowerCase())) continue;
124
+ if (!(await worktree.isIgnored(path))) untracked.add(path);
125
+ }
126
+ return { untracked: [...untracked], lostDirs };
127
+ }
128
+
129
+ /**
130
+ * Removes the directory at `dir` if it holds nothing at all, as git's `rmdir`: never a
131
+ * directory with a file, link, subdirectory, nested repository (`.git`) or FIFO in it, and
132
+ * never recursively. Returns whether it was removed.
133
+ */
134
+ export async function removeDirectoryIfEmpty(worktree: Worktree, dir: string): Promise<boolean> {
135
+ if (worktree.removeEmptyDirectory) return worktree.removeEmptyDirectory(dir);
136
+ // a worktree without the operation: the walk shows directories (nested repositories too)
137
+ const entry = await worktree.getEntry(dir);
138
+ if (!entry?.isDirectory) return false;
139
+ const inside = worktree.walk({ pathPrefix: dir, includeIgnored: true, includeDirectories: true });
140
+ for await (const _ of inside) return false;
141
+ if (await worktree.exists(`${dir}/.git`)) return false;
142
+ // never recursive: a worktree that cannot remove a directory that way keeps it
143
+ return worktree.remove(dir);
144
+ }
145
+
146
+ /**
147
+ * Removes the directories a removal left empty, bottom-up to the worktree root, as git's
148
+ * `schedule_dir_for_removal`: each only if it is truly empty, stopping at the first that is
149
+ * not (a nested repository, an ignored or untracked file, a FIFO keeps its directory).
150
+ */
151
+ export async function pruneEmptyParents(worktree: Worktree, path: string): Promise<void> {
152
+ const parts = path.split("/");
153
+ for (let k = parts.length - 1; k > 0; k--) {
154
+ if (!(await removeDirectoryIfEmpty(worktree, parts.slice(0, k).join("/")))) return;
155
+ }
156
+ }
157
+
158
+ /** git's refusal messages (unpack-trees), for `checkout` or `merge` (stash apply). */
159
+ export function overwriteMessage(
160
+ action: "checkout" | "merge",
161
+ found: {
162
+ local?: string[];
163
+ lostDirs?: string[];
164
+ untracked?: string[];
165
+ untrackedRemoved?: string[];
166
+ },
167
+ ): string | undefined {
168
+ const list = (paths: string[]) => paths.map((p) => `\t${p}`);
169
+ const advice =
170
+ action === "checkout"
171
+ ? "Please commit your changes or stash them before you switch branches."
172
+ : "Please commit your changes or stash them before you merge.";
173
+ const move =
174
+ action === "checkout"
175
+ ? "Please move or remove them before you switch branches."
176
+ : "Please move or remove them before you merge.";
177
+ const parts: string[] = [];
178
+ if (found.local?.length) {
179
+ parts.push(
180
+ [
181
+ `error: Your local changes to the following files would be overwritten by ${action}:`,
182
+ ...list(found.local),
183
+ advice,
184
+ ].join("\n"),
185
+ );
186
+ }
187
+ if (found.lostDirs?.length) {
188
+ parts.push(
189
+ [
190
+ "error: Updating the following directories would lose untracked files in them:",
191
+ ...list(found.lostDirs),
192
+ "",
193
+ ].join("\n"),
194
+ );
195
+ }
196
+ if (found.untracked?.length) {
197
+ parts.push(
198
+ [
199
+ `error: The following untracked working tree files would be overwritten by ${action}:`,
200
+ ...list(found.untracked),
201
+ move,
202
+ ].join("\n"),
203
+ );
204
+ }
205
+ if (found.untrackedRemoved?.length) {
206
+ parts.push(
207
+ [
208
+ `error: The following untracked working tree files would be removed by ${action}:`,
209
+ ...list(found.untrackedRemoved),
210
+ move,
211
+ ].join("\n"),
212
+ );
213
+ }
214
+ return parts.length > 0 ? [...parts, "Aborting"].join("\n") : undefined;
215
+ }
@@ -9,14 +9,16 @@
9
9
  * Reference: jgit/org.eclipse.jgit/src/org/eclipse/jgit/api/AddCommand.java
10
10
  */
11
11
 
12
- import { type Blobs, FileMode } from "@statewalker/vcs-core";
12
+ import { type Blobs, EMPTY_BLOB_ID, FileMode } from "@statewalker/vcs-core";
13
13
  import {
14
14
  DeleteStagingEntry,
15
+ entryStatOf,
15
16
  type Staging,
16
17
  UpdateStagingEntry,
17
18
  type Worktree,
18
19
  } from "@statewalker/vcs-working-tree";
19
20
  import type { Add, AddOptions, AddResult } from "./add.command.js";
21
+ import { storeWorktreeFile } from "./store-worktree-file.js";
20
22
 
21
23
  /**
22
24
  * Options for creating an AddCommand.
@@ -205,10 +207,15 @@ export class AddCommand implements Add {
205
207
  const worktreeEntry = await this.worktree.getEntry(file.path);
206
208
  const mode = worktreeEntry?.mode ?? FileMode.REGULAR_FILE;
207
209
  editor.add(
208
- new UpdateStagingEntry(file.path, "", mode, {
209
- size: 0,
210
- mtime: Date.now(),
211
- }),
210
+ // the empty blob's id, flagged intent-to-add, as git records it (never an empty
211
+ // or all-zero id, which a worktree hash could be compared against)
212
+ new UpdateStagingEntry(
213
+ file.path,
214
+ EMPTY_BLOB_ID,
215
+ mode,
216
+ { size: 0, mtime: Date.now() },
217
+ { intentToAdd: true },
218
+ ),
212
219
  );
213
220
  added.push(file.path);
214
221
  continue;
@@ -222,14 +229,12 @@ export class AddCommand implements Add {
222
229
  }
223
230
 
224
231
  // Hash and store content
225
- const objectId = await this.storeFileContent(file.path);
232
+ // the stat that matched the stored content (a fresh one after a retry)
233
+ const stored = await storeWorktreeFile(this.blobs, this.worktree, file.path, worktreeEntry);
226
234
 
227
235
  // Add to staging
228
236
  editor.add(
229
- new UpdateStagingEntry(file.path, objectId, worktreeEntry.mode, {
230
- size: worktreeEntry.size,
231
- mtime: worktreeEntry.mtime,
232
- }),
237
+ new UpdateStagingEntry(file.path, stored.id, stored.entry.mode, entryStatOf(stored.entry)),
233
238
  );
234
239
  added.push(file.path);
235
240
  }
@@ -251,16 +256,6 @@ export class AddCommand implements Add {
251
256
  async addAll(options: AddOptions = {}): Promise<AddResult> {
252
257
  return this.add(["**/*"], { ...options, all: true });
253
258
  }
254
-
255
- /**
256
- * Store file content as blob and return object ID.
257
- */
258
- private async storeFileContent(path: string): Promise<string> {
259
- // Read content from working tree
260
- const content = this.worktree.readContent(path);
261
- // Store using BlobStore which handles Git header automatically
262
- return await this.blobs.store(content);
263
- }
264
259
  }
265
260
 
266
261
  /**
@@ -3,11 +3,4 @@
3
3
  // Core command implementations
4
4
  export * from "./add.command.impl.js";
5
5
  export type { Add, AddOptions } from "./add.command.js";
6
- export * from "./checkout.command.impl.js";
7
- export type {
8
- Checkout,
9
- CheckoutConflict,
10
- CheckoutConflictReason,
11
- CheckoutOptions,
12
- } from "./checkout.command.js";
13
- export { CheckoutConflictReason as CheckoutConflictReasonValues } from "./checkout.command.js";
6
+ export * from "./store-worktree-file.js";
@@ -0,0 +1,5 @@
1
+ /**
2
+ * `storeWorktreeFile` lives in `@statewalker/vcs-working-tree`, so the stash and
3
+ * the add commands share it; re-exported here for existing imports.
4
+ */
5
+ export { storeWorktreeFile } from "@statewalker/vcs-working-tree";
@@ -1,3 +1,4 @@
1
+ import type { CloneResult } from "../results/index.js";
1
2
  import { GitApiError } from "./git-api-error.js";
2
3
 
3
4
  /**
@@ -40,3 +41,22 @@ export class NotADirectoryError extends GitApiError {
40
41
  this.path = path;
41
42
  }
42
43
  }
44
+
45
+ /**
46
+ * Thrown when a clone fetched its objects and wrote its refs and configuration, but could
47
+ * not check out the commit HEAD names (git: "Clone succeeded, but checkout failed").
48
+ *
49
+ * The repository is usable: `result` is what the clone returns, and the cause says
50
+ * why the checkout failed. As with git, fixing the cause and checking out again (or a
51
+ * `reset --hard`) completes the clone.
52
+ */
53
+ export class CloneCheckoutError extends GitApiError {
54
+ readonly result: CloneResult;
55
+
56
+ constructor(result: CloneResult, cause: unknown) {
57
+ const reason = cause instanceof Error ? cause.message : String(cause);
58
+ super(`Clone succeeded, but checkout failed: ${reason}`, { cause });
59
+ this.name = "CloneCheckoutError";
60
+ this.result = result;
61
+ }
62
+ }
@@ -13,7 +13,14 @@ import type {
13
13
  Trees,
14
14
  } from "@statewalker/vcs-core";
15
15
  import { isSymbolicRef } from "@statewalker/vcs-core";
16
- import type { Staging, WorkingCopy, Worktree } from "@statewalker/vcs-working-tree";
16
+ import {
17
+ basicStatMatches,
18
+ compareWithWorktree,
19
+ type Staging,
20
+ type WorkingCopy,
21
+ type Worktree,
22
+ } from "@statewalker/vcs-working-tree";
23
+ import { worktreeModeTrust } from "./commands/core-config.js";
17
24
 
18
25
  import { NoHeadError, RefNotFoundError } from "./errors/index.js";
19
26
 
@@ -152,6 +159,7 @@ function wrapCommits(commits: Commits): CommandCommits {
152
159
  export abstract class GitCommand<T> {
153
160
  protected readonly _workingCopy: WorkingCopy;
154
161
  private callable = true;
162
+ private racyCheckInstalled = false;
155
163
 
156
164
  constructor(workingCopy: WorkingCopy) {
157
165
  this._workingCopy = workingCopy;
@@ -217,6 +225,39 @@ export abstract class GitCommand<T> {
217
225
  * Supports both new architecture (checkout.staging) and legacy/init (staging directly).
218
226
  */
219
227
  protected get staging(): Staging {
228
+ const staging = this.resolveStaging();
229
+ if (!this.racyCheckInstalled) {
230
+ this.racyCheckInstalled = true;
231
+ this.installRacyCheck(staging);
232
+ }
233
+ return staging;
234
+ }
235
+
236
+ /**
237
+ * Gives the staging git's racy-git smudging for its writes: an entry whose mtime second is
238
+ * not older than the index file and whose content changed behind a matching stat is
239
+ * written with size 0 (`ce_smudge_racily_clean_entry`), so a later same-size edit in that
240
+ * second is never taken as clean.
241
+ */
242
+ private installRacyCheck(staging: Staging): void {
243
+ const worktree = this._workingCopy.worktree;
244
+ if (!worktree || typeof staging.setRacyCheck !== "function") return;
245
+ const trust = worktreeModeTrust(this._workingCopy, worktree);
246
+ staging.setRacyCheck(async (entry, indexTime) => {
247
+ try {
248
+ // git returns early when the basic stat already differs: changed, nothing to smudge
249
+ const current = await worktree.getEntry(entry.path);
250
+ if (!current || current.isDirectory || !basicStatMatches(entry, current, trust)) {
251
+ return false;
252
+ }
253
+ return (await compareWithWorktree(worktree, entry, { trust, indexTime })).smudge === true;
254
+ } catch {
255
+ return false;
256
+ }
257
+ });
258
+ }
259
+
260
+ private resolveStaging(): Staging {
220
261
  // Try new architecture first (checkout.staging)
221
262
  if (this._workingCopy.checkout?.staging) {
222
263
  return this._workingCopy.checkout.staging as unknown as Staging;
package/src/git.ts CHANGED
@@ -30,6 +30,8 @@ import {
30
30
  RemoteAddCommand,
31
31
  RemoteListCommand,
32
32
  RemoteRemoveCommand,
33
+ RemoteRenameCommand,
34
+ RemoteSetHeadCommand,
33
35
  RemoteSetUrlCommand,
34
36
  RenameBranchCommand,
35
37
  ResetCommand,
@@ -537,7 +539,7 @@ export class Git implements Disposable {
537
539
  // ============ Status Operations ============
538
540
 
539
541
  /**
540
- * Create a StatusCommand for showing staging area status.
542
+ * Create a StatusCommand for showing the index and worktree status.
541
543
  *
542
544
  * @example
543
545
  * ```typescript
@@ -709,6 +711,32 @@ export class Git implements Disposable {
709
711
  return new RemoteSetUrlCommand(this._workingCopy);
710
712
  }
711
713
 
714
+ /**
715
+ * Create a RemoteSetHeadCommand for setting or deleting `refs/remotes/<name>/HEAD`.
716
+ *
717
+ * @example
718
+ * ```typescript
719
+ * await git.remoteSetHead().setRemoteName("origin").setBranch("develop").call();
720
+ * ```
721
+ */
722
+ remoteSetHead(): RemoteSetHeadCommand {
723
+ this.checkClosed();
724
+ return new RemoteSetHeadCommand(this._workingCopy);
725
+ }
726
+
727
+ /**
728
+ * Create a RemoteRenameCommand for renaming a remote (`git remote rename`).
729
+ *
730
+ * @example
731
+ * ```typescript
732
+ * await git.remoteRename().setOldName("origin").setNewName("upstream").call();
733
+ * ```
734
+ */
735
+ remoteRename(): RemoteRenameCommand {
736
+ this.checkClosed();
737
+ return new RemoteRenameCommand(this._workingCopy);
738
+ }
739
+
712
740
  // ============ Rebase Operations ============
713
741
 
714
742
  /**
@@ -739,8 +767,8 @@ export class Git implements Disposable {
739
767
  *
740
768
  * @example
741
769
  * ```typescript
770
+ * // the working copy's index and worktree are stashed, then reset to HEAD
742
771
  * const stashCommit = await git.stashCreate()
743
- * .setWorkingTreeProvider(provider)
744
772
  * .setMessage("WIP: feature work")
745
773
  * .call();
746
774
  * ```
@@ -10,3 +10,4 @@ export {
10
10
  type RemoteConfig,
11
11
  RemoteConfigStore,
12
12
  } from "./remote-config-store.js";
13
+ export { deleteRefs, moveRefs, type RefMove } from "./remote-refs.js";
@@ -53,6 +53,11 @@ interface GitConfigLike {
53
53
  unset(key: string): void;
54
54
  unsetSection(section: string): void;
55
55
  subsections(section: string): string[];
56
+ /**
57
+ * Optional: renames a section in place (git's `git_config_rename_section`), keeping its
58
+ * position and lines; without it the section's keys are copied and the old one removed.
59
+ */
60
+ renameSection?(oldSection: string, newSection: string): void;
56
61
  /** Optional: a config with no backing file has nothing to save. */
57
62
  save?(): Promise<void>;
58
63
  }
@@ -75,17 +80,17 @@ function isGitConfigLike(
75
80
  }
76
81
 
77
82
  /**
78
- * Split `remote.<subsection>.<name>` into its subsection.
83
+ * Split `<section>.<subsection>.<name>` into its subsection.
79
84
  *
80
85
  * Follows git's key grammar (and `GitWorkingCopyConfig`'s): the first part is
81
86
  * the section, the last is the variable name and everything in between is the
82
87
  * subsection, which keeps its case and may itself contain dots.
83
88
  *
84
- * @returns undefined when the key is not a `remote` subsection key
89
+ * @returns undefined when the key is not a subsection key of `section`
85
90
  */
86
- function remoteSubsectionOf(key: string): string | undefined {
91
+ function subsectionOf(key: string, section: string): string | undefined {
87
92
  const parts = key.split(".");
88
- if (parts.length < 3 || parts[0].toLowerCase() !== "remote") return undefined;
93
+ if (parts.length < 3 || parts[0].toLowerCase() !== section.toLowerCase()) return undefined;
89
94
  return parts.slice(1, -1).join(".");
90
95
  }
91
96
 
@@ -128,19 +133,30 @@ class PlainObjectConfig implements GitConfigLike {
128
133
 
129
134
  unsetSection(section: string): void {
130
135
  const parts = section.split(".");
131
- if (parts.length < 2 || parts[0].toLowerCase() !== "remote") return;
136
+ if (parts.length < 2) return;
132
137
  const subsection = parts.slice(1).join(".");
133
138
  for (const key of Object.keys(this.bag)) {
134
- if (remoteSubsectionOf(key) === subsection) delete this.bag[key];
139
+ if (subsectionOf(key, parts[0]) === subsection) delete this.bag[key];
140
+ }
141
+ }
142
+
143
+ renameSection(oldSection: string, newSection: string): void {
144
+ const [section, ...oldParts] = oldSection.split(".");
145
+ const oldSub = oldParts.join(".");
146
+ const newSub = newSection.split(".").slice(1).join(".");
147
+ for (const key of Object.keys(this.bag)) {
148
+ if (subsectionOf(key, section) !== oldSub) continue;
149
+ const name = key.slice(key.lastIndexOf(".") + 1);
150
+ this.bag[`${section}.${newSub}.${name}`] = this.bag[key];
151
+ delete this.bag[key];
135
152
  }
136
153
  }
137
154
 
138
155
  subsections(section: string): string[] {
139
- if (section.toLowerCase() !== "remote") return [];
140
156
  const found = new Set<string>();
141
157
  for (const key of Object.keys(this.bag)) {
142
158
  if (this.getAll(key).length === 0) continue;
143
- const subsection = remoteSubsectionOf(key);
159
+ const subsection = subsectionOf(key, section);
144
160
  if (subsection !== undefined) found.add(subsection);
145
161
  }
146
162
  return [...found];
@@ -195,6 +211,14 @@ export class RemoteConfigStore {
195
211
  };
196
212
  }
197
213
 
214
+ /**
215
+ * The `remote.<name>.fetch` lines as configured, without the default {@link read} fills
216
+ * in: a remote without any fetches only its HEAD, as `git fetch <name>` does.
217
+ */
218
+ configuredFetchRefspecs(name: string): string[] {
219
+ return this.strings(name, "fetch");
220
+ }
221
+
198
222
  /** Write every field of a remote, replacing whatever was there. */
199
223
  write(remote: RemoteConfig): void {
200
224
  this.setAll(remote.name, "url", remote.urls);
@@ -208,6 +232,40 @@ export class RemoteConfigStore {
208
232
  this.config.unsetSection(`remote.${name}`);
209
233
  }
210
234
 
235
+ /**
236
+ * Rename the `[remote "<oldName>"]` section to `[remote "<newName>"]`, in place where the
237
+ * config can (git's rename_section), else by copying every `remote.<oldName>.*` variable.
238
+ */
239
+ rename(oldName: string, newName: string): void {
240
+ if (this.config.renameSection) {
241
+ this.config.renameSection(`remote.${oldName}`, `remote.${newName}`);
242
+ return;
243
+ }
244
+ // every remote.<old>.* variable: a git-config object mirrors its keys as own
245
+ // properties (the WorkingCopyConfig index signature), so they can be listed
246
+ const variables = new Set<string>();
247
+ for (const key of Object.keys(this.config)) {
248
+ if (subsectionOf(key, "remote") === oldName) {
249
+ variables.add(key.slice(key.lastIndexOf(".") + 1));
250
+ }
251
+ }
252
+ for (const variable of variables) {
253
+ const values = this.strings(oldName, variable);
254
+ if (values.length > 0) this.setAll(newName, variable, values);
255
+ }
256
+ this.config.unsetSection(`remote.${oldName}`);
257
+ }
258
+
259
+ /** Subsection names of a section (`branch`: the branch names with configuration). */
260
+ subsections(section: string): string[] {
261
+ return this.config.subsections(section);
262
+ }
263
+
264
+ /** Remove every value of a config variable. */
265
+ unset(key: string): void {
266
+ this.config.unset(key);
267
+ }
268
+
211
269
  /**
212
270
  * Point a remote at a URL.
213
271
  *
@@ -245,6 +303,35 @@ export class RemoteConfigStore {
245
303
  return this.strings(name, "url")[0];
246
304
  }
247
305
 
306
+ /** A config variable (`push.default`, `branch.main.merge`), the last value when repeated. */
307
+ value(key: string): string | undefined {
308
+ const value = this.config.get(key);
309
+ return value === undefined || value === null ? undefined : String(value);
310
+ }
311
+
312
+ /** Every value of a config variable (`branch.main.merge` may repeat). */
313
+ values(key: string): string[] {
314
+ return this.config
315
+ .getAll(key)
316
+ .filter((value) => value !== undefined && value !== null)
317
+ .map((value) => String(value));
318
+ }
319
+
320
+ /** Sets a config variable, replacing every value it had. */
321
+ setValue(key: string, value: string): void {
322
+ this.config.set(key, value);
323
+ }
324
+
325
+ /** Sets every value of a config variable, in order (none: unset). */
326
+ setValues(key: string, values: string[]): void {
327
+ if (values.length === 0) {
328
+ this.config.unset(key);
329
+ return;
330
+ }
331
+ this.config.set(key, values[0]);
332
+ for (const value of values.slice(1)) this.config.add(key, value);
333
+ }
334
+
248
335
  /** Flush to the backing file, if the config has one. */
249
336
  async save(): Promise<void> {
250
337
  await this.config.save?.();