@statewalker/vcs-commands 0.4.0 → 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 (99) hide show
  1. package/dist/commands/add-command.d.ts.map +1 -1
  2. package/dist/commands/checkout-command.d.ts +7 -24
  3. package/dist/commands/checkout-command.d.ts.map +1 -1
  4. package/dist/commands/clean-command.d.ts +34 -4
  5. package/dist/commands/clean-command.d.ts.map +1 -1
  6. package/dist/commands/clone-command.d.ts +62 -7
  7. package/dist/commands/clone-command.d.ts.map +1 -1
  8. package/dist/commands/core-config.d.ts +16 -0
  9. package/dist/commands/core-config.d.ts.map +1 -0
  10. package/dist/commands/fetch-command.d.ts +96 -14
  11. package/dist/commands/fetch-command.d.ts.map +1 -1
  12. package/dist/commands/index.d.ts +1 -0
  13. package/dist/commands/index.d.ts.map +1 -1
  14. package/dist/commands/index.js +2 -2
  15. package/dist/commands/init-command.d.ts.map +1 -1
  16. package/dist/commands/remote-command.d.ts +115 -6
  17. package/dist/commands/remote-command.d.ts.map +1 -1
  18. package/dist/commands/reset-command.d.ts.map +1 -1
  19. package/dist/commands/stash-apply-command.d.ts +35 -13
  20. package/dist/commands/stash-apply-command.d.ts.map +1 -1
  21. package/dist/commands/stash-create-command.d.ts +59 -25
  22. package/dist/commands/stash-create-command.d.ts.map +1 -1
  23. package/dist/commands/stash-drop-command.d.ts +8 -2
  24. package/dist/commands/stash-drop-command.d.ts.map +1 -1
  25. package/dist/commands/stash-list-command.d.ts +2 -4
  26. package/dist/commands/stash-list-command.d.ts.map +1 -1
  27. package/dist/commands/stash-working-tree.d.ts +72 -0
  28. package/dist/commands/stash-working-tree.d.ts.map +1 -0
  29. package/dist/commands/status-command.d.ts +29 -22
  30. package/dist/commands/status-command.d.ts.map +1 -1
  31. package/dist/commands/tree-restore.d.ts +52 -5
  32. package/dist/commands/tree-restore.d.ts.map +1 -1
  33. package/dist/commands/worktree-overwrite-checks.d.ts +64 -0
  34. package/dist/commands/worktree-overwrite-checks.d.ts.map +1 -0
  35. package/dist/{commands-BpeXZTC3.js → commands-CsLNyvZ1.js} +2940 -631
  36. package/dist/core-commands/add.command.impl.d.ts.map +1 -1
  37. package/dist/core-commands/index.d.ts +0 -3
  38. package/dist/core-commands/index.d.ts.map +1 -1
  39. package/dist/errors/checkout-errors.d.ts +13 -0
  40. package/dist/errors/checkout-errors.d.ts.map +1 -1
  41. package/dist/errors/index.js +18 -1
  42. package/dist/git-command.d.ts +10 -1
  43. package/dist/git-command.d.ts.map +1 -1
  44. package/dist/git.d.ts +21 -3
  45. package/dist/git.d.ts.map +1 -1
  46. package/dist/index.js +4 -4
  47. package/dist/remote-config/index.d.ts +1 -0
  48. package/dist/remote-config/index.d.ts.map +1 -1
  49. package/dist/remote-config/remote-config-store.d.ts +18 -0
  50. package/dist/remote-config/remote-config-store.d.ts.map +1 -1
  51. package/dist/remote-config/remote-refs.d.ts +37 -0
  52. package/dist/remote-config/remote-refs.d.ts.map +1 -0
  53. package/dist/results/clone-result.d.ts +6 -0
  54. package/dist/results/clone-result.d.ts.map +1 -1
  55. package/dist/results/fetch-result.d.ts +9 -1
  56. package/dist/results/fetch-result.d.ts.map +1 -1
  57. package/dist/results/index.js +2 -2
  58. package/dist/results/status-result.d.ts +91 -20
  59. package/dist/results/status-result.d.ts.map +1 -1
  60. package/dist/{status-result-BapZoQaR.js → status-result-BpyUK1Sg.js} +113 -5
  61. package/dist/transport-command.d.ts +12 -0
  62. package/dist/transport-command.d.ts.map +1 -1
  63. package/package.json +11 -10
  64. package/src/commands/add-command.ts +9 -7
  65. package/src/commands/checkout-command.ts +200 -118
  66. package/src/commands/clean-command.ts +187 -88
  67. package/src/commands/clone-command.ts +244 -40
  68. package/src/commands/core-config.ts +41 -0
  69. package/src/commands/fetch-command.ts +476 -57
  70. package/src/commands/index.ts +1 -0
  71. package/src/commands/init-command.ts +32 -7
  72. package/src/commands/remote-command.ts +429 -19
  73. package/src/commands/reset-command.ts +18 -5
  74. package/src/commands/stash-apply-command.ts +632 -97
  75. package/src/commands/stash-create-command.ts +142 -62
  76. package/src/commands/stash-drop-command.ts +53 -5
  77. package/src/commands/stash-list-command.ts +10 -4
  78. package/src/commands/stash-working-tree.ts +243 -0
  79. package/src/commands/status-command.ts +197 -91
  80. package/src/commands/tree-restore.ts +142 -13
  81. package/src/commands/worktree-overwrite-checks.ts +215 -0
  82. package/src/core-commands/add.command.impl.ts +2 -4
  83. package/src/core-commands/index.ts +0 -8
  84. package/src/errors/checkout-errors.ts +20 -0
  85. package/src/git-command.ts +42 -1
  86. package/src/git.ts +30 -2
  87. package/src/remote-config/index.ts +1 -0
  88. package/src/remote-config/remote-config-store.ts +84 -8
  89. package/src/remote-config/remote-refs.ts +103 -0
  90. package/src/results/clone-result.ts +6 -0
  91. package/src/results/fetch-result.ts +9 -1
  92. package/src/results/status-result.ts +212 -29
  93. package/src/transport-command.ts +18 -0
  94. package/dist/core-commands/checkout.command.d.ts +0 -103
  95. package/dist/core-commands/checkout.command.d.ts.map +0 -1
  96. package/dist/core-commands/checkout.command.impl.d.ts +0 -110
  97. package/dist/core-commands/checkout.command.impl.d.ts.map +0 -1
  98. package/src/core-commands/checkout.command.impl.ts +0 -564
  99. package/src/core-commands/checkout.command.ts +0 -125
@@ -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
+ }
@@ -12,6 +12,7 @@
12
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,
@@ -233,10 +234,7 @@ export class AddCommand implements Add {
233
234
 
234
235
  // Add to staging
235
236
  editor.add(
236
- new UpdateStagingEntry(file.path, stored.id, stored.entry.mode, {
237
- size: stored.entry.size,
238
- mtime: stored.entry.mtime,
239
- }),
237
+ new UpdateStagingEntry(file.path, stored.id, stored.entry.mode, entryStatOf(stored.entry)),
240
238
  );
241
239
  added.push(file.path);
242
240
  }
@@ -3,12 +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";
14
6
  export * from "./store-worktree-file.js";
@@ -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
  *
@@ -251,11 +309,29 @@ export class RemoteConfigStore {
251
309
  return value === undefined || value === null ? undefined : String(value);
252
310
  }
253
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
+
254
320
  /** Sets a config variable, replacing every value it had. */
255
321
  setValue(key: string, value: string): void {
256
322
  this.config.set(key, value);
257
323
  }
258
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
+
259
335
  /** Flush to the backing file, if the config has one. */
260
336
  async save(): Promise<void> {
261
337
  await this.config.save?.();
@@ -0,0 +1,103 @@
1
+ /**
2
+ * Multi-ref writes of the remote commands (`git remote remove`, `git remote rename`,
3
+ * `git fetch --prune`), as one ref batch where the store can apply it.
4
+ *
5
+ * Internal to the package.
6
+ */
7
+
8
+ import { isSymbolicRef, type OwnReflogLine, type Refs } from "@statewalker/vcs-core";
9
+
10
+ /** One ref of a {@link moveRefs}: where it goes and the reflog it takes along. */
11
+ export interface RefMove {
12
+ from: string;
13
+ to: string;
14
+ /** The reflog lines of the new name, oldest first (git carries the old log over) */
15
+ reflog?: OwnReflogLine[];
16
+ }
17
+
18
+ /**
19
+ * Deletes `names` with their reflogs: the refs holding an object id in one atomic batch
20
+ * (logged `message` where the store logs deletes), symbolic refs themselves (not their
21
+ * targets) one by one, as git deletes with REF_NO_DEREF. A store that cannot batch several
22
+ * refs (`unsupported`) deletes them one by one.
23
+ *
24
+ * @throws Error naming the refs when the batch is refused (nothing deleted then)
25
+ */
26
+ export async function deleteRefs(refs: Refs, names: string[], message: string): Promise<void> {
27
+ const direct: string[] = [];
28
+ const symbolic: string[] = [];
29
+ for (const name of names) {
30
+ const ref = await refs.get(name);
31
+ if (!ref) continue;
32
+ (isSymbolicRef(ref) ? symbolic : direct).push(name);
33
+ }
34
+ if (direct.length > 0) {
35
+ const result = await refs.batch(
36
+ direct.map((name) => ({ name, new: null })),
37
+ { message },
38
+ );
39
+ if (!result.ok) {
40
+ if (!result.rejected.every((r) => r.reason === "unsupported")) throw refused(result);
41
+ for (const name of direct) await refs.remove(name);
42
+ }
43
+ }
44
+ for (const name of symbolic) await refs.remove(name);
45
+ }
46
+
47
+ /**
48
+ * Renames refs, as `git remote rename` moves `refs/remotes/<old>/*`: the refs holding an
49
+ * object id are deleted and created under their new names in one atomic batch, each new
50
+ * name with the reflog lines given (the old log, carried over); symbolic refs are then
51
+ * re-created under their new names pointing at `symbolicTarget(old target)`. A store whose
52
+ * batch refuses several refs (`unsupported`: vcs-core's interim `kvStoreRefs`, which keeps
53
+ * no reflogs) moves them one by one: each new name is created only if it does not exist
54
+ * (compare-and-swap) before the old one goes, so no ref is overwritten or lost.
55
+ *
56
+ * @throws Error naming the refs when the batch is refused (a name conflict: nothing moved),
57
+ * or naming the ref whose new name exists in the one-by-one move (the refs before it moved)
58
+ */
59
+ export async function moveRefs(
60
+ refs: Refs,
61
+ moves: RefMove[],
62
+ symbolicTarget: (target: string) => string,
63
+ ): Promise<void> {
64
+ const direct: { move: RefMove; id: string }[] = [];
65
+ const symbolic: { move: RefMove; target: string }[] = [];
66
+ for (const move of moves) {
67
+ const ref = await refs.get(move.from);
68
+ if (!ref) continue;
69
+ if (isSymbolicRef(ref)) symbolic.push({ move, target: ref.target });
70
+ else if (ref.objectId) direct.push({ move, id: ref.objectId });
71
+ }
72
+ if (direct.length > 0) {
73
+ const commands = [
74
+ ...direct.map(({ move, id }) => ({ name: move.from, old: id, new: null })),
75
+ ...direct.map(({ move, id }) => ({
76
+ name: move.to,
77
+ old: null,
78
+ new: id,
79
+ ...(move.reflog ? { reflog: move.reflog } : {}),
80
+ })),
81
+ ];
82
+ const result = await refs.batch(commands);
83
+ if (!result.ok) {
84
+ if (!result.rejected.every((r) => r.reason === "unsupported")) throw refused(result);
85
+ for (const { move, id } of direct) {
86
+ if (!(await refs.compareAndSwap(move.to, undefined, id)).success) {
87
+ throw new Error(`Cannot update refs: ${move.to} exists`);
88
+ }
89
+ await refs.remove(move.from);
90
+ }
91
+ }
92
+ }
93
+ for (const { move, target } of symbolic) {
94
+ if (await refs.has(move.to)) throw new Error(`Cannot update refs: ${move.to} exists`);
95
+ await refs.setSymbolic(move.to, symbolicTarget(target));
96
+ await refs.remove(move.from);
97
+ }
98
+ }
99
+
100
+ function refused(result: { rejected: { name: string; reason: string }[] }): Error {
101
+ const why = result.rejected.map((r) => `${r.name}: ${r.reason}`).join(", ");
102
+ return new Error(`Cannot update refs: ${why}`);
103
+ }
@@ -22,4 +22,10 @@ export interface CloneResult {
22
22
  bare: boolean;
23
23
  /** Head commit after clone */
24
24
  headCommit?: ObjectId;
25
+ /**
26
+ * Files of the checked-out tree whose paths differ only in case (`README`, `readme`),
27
+ * on a worktree that folds case (`core.ignorecase`): only one of each group is in the
28
+ * worktree, as with git's "the following paths have collided" warning.
29
+ */
30
+ collidedPaths?: string[];
25
31
  }