@statewalker/vcs-commands 0.3.1 → 0.4.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 (77) hide show
  1. package/README.md +193 -460
  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.map +1 -1
  8. package/dist/commands/clean-command.d.ts.map +1 -1
  9. package/dist/commands/clone-command.d.ts +0 -15
  10. package/dist/commands/clone-command.d.ts.map +1 -1
  11. package/dist/commands/fetch-command.d.ts +16 -31
  12. package/dist/commands/fetch-command.d.ts.map +1 -1
  13. package/dist/commands/index.js +2 -2
  14. package/dist/commands/init-command.d.ts.map +1 -1
  15. package/dist/commands/merge-command.d.ts +15 -2
  16. package/dist/commands/merge-command.d.ts.map +1 -1
  17. package/dist/commands/push-command.d.ts +58 -25
  18. package/dist/commands/push-command.d.ts.map +1 -1
  19. package/dist/commands/stash-create-command.d.ts +1 -1
  20. package/dist/commands/stash-drop-command.d.ts +1 -1
  21. package/dist/commands/stash-list-command.d.ts +1 -1
  22. package/dist/commands/tag-command.d.ts.map +1 -1
  23. package/dist/commands/tree-restore.d.ts.map +1 -1
  24. package/dist/{commands-COO4tJhv.js → commands-BpeXZTC3.js} +473 -469
  25. package/dist/core-commands/add.command.impl.d.ts +0 -4
  26. package/dist/core-commands/add.command.impl.d.ts.map +1 -1
  27. package/dist/core-commands/checkout.command.impl.d.ts +2 -6
  28. package/dist/core-commands/checkout.command.impl.d.ts.map +1 -1
  29. package/dist/core-commands/index.d.ts +1 -0
  30. package/dist/core-commands/index.d.ts.map +1 -1
  31. package/dist/core-commands/store-worktree-file.d.ts +6 -0
  32. package/dist/core-commands/store-worktree-file.d.ts.map +1 -0
  33. package/dist/index.js +3 -3
  34. package/dist/remote-config/remote-config-store.d.ts +4 -0
  35. package/dist/remote-config/remote-config-store.d.ts.map +1 -1
  36. package/dist/results/diff-formatter.d.ts +14 -7
  37. package/dist/results/diff-formatter.d.ts.map +1 -1
  38. package/dist/results/fetch-result.d.ts +7 -0
  39. package/dist/results/fetch-result.d.ts.map +1 -1
  40. package/dist/results/index.js +27 -22
  41. package/dist/results/push-result.d.ts +9 -2
  42. package/dist/results/push-result.d.ts.map +1 -1
  43. package/dist/{status-result-BwAyxq6R.js → status-result-BapZoQaR.js} +2 -0
  44. package/package.json +19 -14
  45. package/src/commands/add-command.ts +16 -25
  46. package/src/commands/blame-command.ts +41 -0
  47. package/src/commands/branch-command.ts +2 -53
  48. package/src/commands/checkout-command.ts +7 -11
  49. package/src/commands/clean-command.ts +7 -0
  50. package/src/commands/clone-command.ts +102 -109
  51. package/src/commands/fetch-command.ts +103 -197
  52. package/src/commands/gc-command.ts +1 -1
  53. package/src/commands/init-command.ts +83 -11
  54. package/src/commands/merge-command.ts +60 -27
  55. package/src/commands/pack-refs-command.ts +2 -2
  56. package/src/commands/push-command.ts +242 -308
  57. package/src/commands/reflog-command.ts +2 -2
  58. package/src/commands/stash-apply-command.ts +1 -1
  59. package/src/commands/stash-create-command.ts +1 -1
  60. package/src/commands/stash-drop-command.ts +1 -1
  61. package/src/commands/stash-list-command.ts +1 -1
  62. package/src/commands/tag-command.ts +2 -53
  63. package/src/commands/tree-restore.ts +2 -6
  64. package/src/core-commands/add.command.impl.ts +16 -19
  65. package/src/core-commands/checkout.command.impl.ts +18 -40
  66. package/src/core-commands/index.ts +1 -0
  67. package/src/core-commands/store-worktree-file.ts +5 -0
  68. package/src/remote-config/remote-config-store.ts +11 -0
  69. package/src/results/diff-formatter.ts +31 -38
  70. package/src/results/fetch-result.ts +7 -0
  71. package/src/results/push-result.ts +9 -2
  72. package/dist/pack-import/index.d.ts +0 -8
  73. package/dist/pack-import/index.d.ts.map +0 -1
  74. package/dist/pack-import/pack-import.d.ts +0 -11
  75. package/dist/pack-import/pack-import.d.ts.map +0 -1
  76. package/src/pack-import/index.ts +0 -8
  77. package/src/pack-import/pack-import.ts +0 -24
package/README.md CHANGED
@@ -1,590 +1,323 @@
1
1
  # @statewalker/vcs-commands
2
2
 
3
- High-level Git command API for building version control applications.
3
+ High-level Git commands (add, commit, checkout, merge, rebase, stash, fetch, push, clone, ...) over a `WorkingCopy`. A `Git` facade wraps a `WorkingCopy` from `@statewalker/vcs-working-tree` and creates command objects. You configure a command with chainable setters and run it once with `call()`.
4
4
 
5
- ## Overview
5
+ ## Why a command layer sits on top of the working copy
6
6
 
7
- This package provides a Git-like command interface for VCS operations. Rather than working directly with low-level stores, you interact through familiar commands like `add`, `commit`, `push`, and `merge`. Each command encapsulates the complex multi-step workflows into a simple, type-safe API.
7
+ `@statewalker/vcs-core` and `@statewalker/vcs-working-tree` give you objects, refs, an index and a worktree. A Git operation such as "commit" or "merge" touches all of them in a fixed order: resolve HEAD, write a tree from the index, store a commit, move a branch, update the index and the files. This package holds those multi-step workflows so applications do not re-implement them.
8
8
 
9
- The design follows the command pattern with a fluent builder interface. You create commands through a `Git` factory, configure them with chainable methods, and execute with a single `call()`. This approach mirrors how developers interact with Git while providing the type safety and error handling expected from a library.
9
+ Commands talk only to the `WorkingCopy` interfaces (history, checkout/staging, worktree). The same command code runs over memory, file, or SQL storage, in the browser, Node or a worker. The API copies JGit's command pattern, so names and option sets map to Git and JGit concepts you already know.
10
10
 
11
- Commands work with any storage backend that implements the required store interfaces. Whether your repository lives in the filesystem, SQLite, IndexedDB, or memory, the same commands work identically. For remote operations like fetch and push, the package integrates with the transport layer to handle protocol negotiation and data transfer.
12
-
13
- ## Installation
11
+ ## How to use it: build a `WorkingCopy`, wrap it in `Git`
14
12
 
15
13
  ```bash
16
14
  pnpm add @statewalker/vcs-commands
17
15
  ```
18
16
 
19
- **Dependencies:**
20
- - `@statewalker/vcs-core` - Core types, store interfaces, and repository factories
21
- - `@statewalker/vcs-transport` - Remote protocol implementation
22
- - `@statewalker/vcs-utils` - Utility functions
17
+ No peer dependencies.
18
+
19
+ | Entry point | Contents |
20
+ |-------------|----------|
21
+ | `@statewalker/vcs-commands` | Everything below, plus `Git`, `GitCommand`, `TransportCommand`, `ResetMode`, `ListBranchMode`, and re-exported types (`WorkingCopy`, `History`, `Checkout`, `Staging`, `Worktree`, `Blobs`, `Trees`, `Commits`, `Refs`, `Tags`) |
22
+ | `@statewalker/vcs-commands/commands` | Command classes (`AddCommand`, `CommitCommand`, `MergeCommand`, ..., `InitCommand`) and their enums (`CheckoutStatus`, `RebaseOperation`, `TagOption`, `RevFilter`, ...) |
23
+ | `@statewalker/vcs-commands/errors` | Error classes, all extending `GitApiError` |
24
+ | `@statewalker/vcs-commands/results` | Result types, status enums and helpers (`MergeStatus`, `PushStatus`, `isMergeSuccessful`, `isPushSuccessful`, ...) |
23
25
 
24
- ## Quick Start
26
+ An in-memory repository:
25
27
 
26
28
  ```typescript
27
29
  import { Git } from "@statewalker/vcs-commands";
28
- import { createWorkingCopy } from "@statewalker/vcs-core";
29
- import { createNodeFilesApi } from "@statewalker/vcs-utils-node/files";
30
- import * as fs from "node:fs/promises";
30
+ import { createMemoryHistory } from "@statewalker/vcs-core";
31
+ import {
32
+ createMemoryCheckout,
33
+ createMemoryGitStaging,
34
+ createMemoryWorkingCopy,
35
+ createMemoryWorktree,
36
+ } from "@statewalker/vcs-working-tree";
37
+
38
+ const history = createMemoryHistory();
39
+ await history.initialize();
40
+ await history.refs.setSymbolic("HEAD", "refs/heads/main");
31
41
 
32
- // Create a Git-compatible working copy
33
- const files = createNodeFilesApi({ fs, rootDir: "/path/to/repo" });
34
- const workingCopy = await createWorkingCopy(files, ".git");
42
+ const staging = createMemoryGitStaging();
43
+ const checkout = createMemoryCheckout({ staging });
44
+ const worktree = createMemoryWorktree({ blobs: history.blobs, trees: history.trees });
45
+ const workingCopy = createMemoryWorkingCopy({ history, checkout, worktree });
35
46
 
36
- // Create the Git command interface
37
47
  const git = Git.fromWorkingCopy(workingCopy);
38
48
 
39
- // Stage and commit changes
49
+ await worktree.writeContent("README.md", new TextEncoder().encode("# Hello\n"));
40
50
  await git.add().addFilepattern(".").call();
41
- await git.commit().setMessage("Initial commit").call();
51
+ const commit = await git.commit().setMessage("Initial commit").call();
52
+ console.log(commit.id);
42
53
 
43
- // Check status
44
- const status = await git.status().call();
45
- console.log("Clean:", status.isClean());
54
+ console.log("Clean:", (await git.status().call()).isClean());
46
55
 
47
- // Clean up
48
- git.dispose();
56
+ git.close(); // or `using git = ...`: Git implements Disposable
49
57
  ```
50
58
 
51
- ## Public API
59
+ For a Git-compatible on-disk repository, build the `WorkingCopy` from the file-backed classes in `@statewalker/vcs-store-files` (for example `GitWorkingCopy`).
52
60
 
53
- ### Main Export
54
-
55
- ```typescript
56
- import {
57
- // Main entry point
58
- Git,
59
- GitCommand,
60
- TransportCommand,
61
-
62
- // Re-exported core types
63
- type WorkingCopy,
64
- type History,
65
- type Checkout,
66
- type Worktree,
67
- type Staging,
68
-
69
- // Enums
70
- ResetMode,
71
- ListBranchMode,
72
- } from "@statewalker/vcs-commands";
73
- ```
61
+ `Git` methods:
74
62
 
75
- ### Sub-exports
63
+ | Area | Methods |
64
+ |------|---------|
65
+ | Staging | `add()`, `rm()`, `status()`, `clean()` |
66
+ | Commits | `commit()`, `log()`, `reflog()`, `blame()` |
67
+ | Branches | `branchCreate()`, `branchDelete()`, `branchList()`, `branchRename()`, `checkout()` |
68
+ | Tags | `tag()`, `tagDelete()`, `tagList()` |
69
+ | History | `reset()`, `merge()`, `rebase()`, `cherryPick()`, `revert()` |
70
+ | Inspection | `diff()`, `describe()` |
71
+ | Remotes | `fetch()`, `push()`, `pull()`, `clone()`, `lsRemote()`, `remoteAdd()`, `remoteRemove()`, `remoteList()`, `remoteSetUrl()` |
72
+ | Stash | `stashCreate()`, `stashApply()`, `stashDrop()`, `stashList()` |
73
+ | Maintenance | `gc()`, `packRefs()` |
74
+ | Static | `Git.fromWorkingCopy(wc)`, `Git.init()` |
75
+ | Components | `workingCopy`, `history`, `checkoutState`, `worktree` |
76
76
 
77
- | Export Path | Description |
78
- |-------------|-------------|
79
- | `@statewalker/vcs-commands/commands` | Individual command classes |
80
- | `@statewalker/vcs-commands/errors` | Error types |
81
- | `@statewalker/vcs-commands/results` | Result types and enums |
77
+ ## Examples
82
78
 
83
- ### Git Class Methods
84
-
85
- The `Git` class provides factory methods for all commands:
86
-
87
- | Category | Methods |
88
- |----------|---------|
89
- | **Staging** | `add()`, `rm()`, `status()` |
90
- | **Committing** | `commit()`, `log()` |
91
- | **Branches** | `branchCreate()`, `branchDelete()`, `branchList()`, `branchRename()`, `checkout()` |
92
- | **Tags** | `tag()`, `tagDelete()`, `tagList()` |
93
- | **History** | `reset()`, `rebase()`, `merge()`, `cherryPick()`, `revert()` |
94
- | **Inspection** | `diff()`, `describe()` |
95
- | **Remote** | `fetch()`, `push()`, `pull()`, `clone()`, `lsRemote()` |
96
- | **Remotes** | `remoteAdd()`, `remoteRemove()`, `remoteList()`, `remoteSetUrl()` |
97
- | **Stash** | `stashCreate()`, `stashApply()`, `stashDrop()`, `stashList()` |
98
-
99
- ## Usage Examples
100
-
101
- ### Staging and Committing
79
+ ### Staging and committing
102
80
 
103
81
  ```typescript
104
- import { Git } from "@statewalker/vcs-commands";
105
-
106
- // Stage specific files
107
- await git.add()
108
- .addFilepattern("src/")
109
- .addFilepattern("package.json")
110
- .call();
82
+ await git.add().addFilepattern("src/").addFilepattern("package.json").call();
111
83
 
112
- // Stage all changes including deletions
113
- await git.add()
114
- .addFilepattern(".")
115
- .setUpdate(true)
116
- .call();
84
+ // Stage modifications and deletions of tracked files only (git add -u)
85
+ await git.add().addFilepattern(".").setUpdate(true).call();
117
86
 
118
- // Create a commit
119
- const commitId = await git.commit()
120
- .setMessage("Add new feature")
121
- .setAuthor({ name: "Developer", email: "dev@example.com" })
122
- .call();
87
+ const commit = await git
88
+ .commit()
89
+ .setMessage("Add feature")
90
+ .setAuthor("Developer", "dev@example.com")
91
+ .call(); // CommitResult: the Commit fields plus `id`
123
92
 
124
- // Amend the previous commit
125
- await git.commit()
126
- .setMessage("Add new feature (fixed)")
127
- .setAmend(true)
128
- .call();
93
+ await git.commit().setMessage("Add feature (fixed)").setAmend(true).call();
129
94
  ```
130
95
 
131
- ### Branch Operations
96
+ ### Branches and checkout
132
97
 
133
98
  ```typescript
134
- // Create a new branch
135
- await git.branchCreate()
136
- .setName("feature/login")
137
- .call();
99
+ import { ListBranchMode } from "@statewalker/vcs-commands";
138
100
 
139
- // Create and switch to a new branch
140
- await git.branchCreate()
141
- .setName("feature/login")
142
- .setStartPoint("main")
143
- .call();
144
- await git.checkout()
145
- .setName("feature/login")
146
- .call();
101
+ await git.branchCreate().setName("feature/login").setStartPoint("main").call();
102
+ await git.checkout().setName("feature/login").call();
147
103
 
148
- // List all branches
149
- const branches = await git.branchList()
150
- .setListMode(ListBranchMode.ALL)
151
- .call();
152
- for (const branch of branches) {
153
- console.log(branch.name, branch.objectId);
154
- }
104
+ // Create and switch in one step (git checkout -b)
105
+ await git.checkout().setName("feature/new").setCreateBranch(true).call();
155
106
 
156
- // Delete a merged branch
157
- await git.branchDelete()
158
- .setBranchNames("feature/old")
159
- .call();
107
+ const branches = await git.branchList().setListMode(ListBranchMode.ALL).call();
108
+ for (const ref of branches) console.log(ref.name); // "refs/heads/main", ...
160
109
 
161
- // Force delete unmerged branch
162
- await git.branchDelete()
163
- .setBranchNames("feature/abandoned")
164
- .setForce(true)
165
- .call();
110
+ await git.branchDelete().setBranchNames("feature/old").call();
111
+ await git.branchDelete().setBranchNames("feature/abandoned").setForce(true).call();
166
112
  ```
167
113
 
168
- ### Working with History
114
+ `checkout()` returns a `CheckoutResult` with `status` (`CheckoutStatus.OK`, `CONFLICTS`, ...), `updated`, `removed` and `conflicts`. Use `addPath()` to restore single files and `setForced(true)` to discard local changes.
169
115
 
170
- ```typescript
171
- // View commit log
172
- for await (const commit of git.log().setMaxCount(10).call()) {
173
- console.log(`${commit.id.slice(0, 7)} ${commit.message.split("\n")[0]}`);
174
- }
116
+ ### Log and reset
175
117
 
176
- // Log with filters
177
- const commits = git.log()
178
- .setMaxCount(50)
179
- .setAuthor("developer@example.com")
180
- .addPath("src/")
181
- .call();
118
+ ```typescript
119
+ import { ResetMode } from "@statewalker/vcs-commands";
182
120
 
183
- // Reset to previous commit (mixed mode - keeps changes unstaged)
184
- await git.reset()
185
- .setRef("HEAD~1")
186
- .setMode(ResetMode.MIXED)
187
- .call();
121
+ for await (const entry of await git.log().setMaxCount(10).call()) {
122
+ console.log(entry.id.slice(0, 7), entry.message.split("\n")[0]);
123
+ }
124
+ // More filters: addPath(), setSkip(), setSince(), setUntil(),
125
+ // setAuthorFilter(), setCommitterFilter(), setFirstParent(), addRange()
188
126
 
189
- // Hard reset (discards all changes)
190
- await git.reset()
191
- .setRef("main")
192
- .setMode(ResetMode.HARD)
193
- .call();
127
+ await git.reset().setRef("HEAD~1").setMode(ResetMode.MIXED).call();
128
+ await git.reset().setRef("main").setMode(ResetMode.HARD).call();
194
129
  ```
195
130
 
196
- ### Merging and Rebasing
131
+ ### Merge, rebase, cherry-pick, revert
197
132
 
198
133
  ```typescript
199
- import { MergeStatus, FastForwardMode } from "@statewalker/vcs-commands/results";
200
-
201
- // Merge a branch
202
- const result = await git.merge()
203
- .include("feature/login")
204
- .call();
134
+ import { RebaseOperation } from "@statewalker/vcs-commands";
135
+ import { FastForwardMode, MergeStatus } from "@statewalker/vcs-commands/results";
205
136
 
137
+ const result = await git.merge().include("feature/login").call();
206
138
  if (result.status === MergeStatus.CONFLICTING) {
207
139
  console.log("Conflicts in:", result.conflicts);
208
- // Resolve conflicts, then commit
209
140
  }
210
141
 
211
- // Merge with no fast-forward (always create merge commit)
212
- await git.merge()
142
+ await git
143
+ .merge()
213
144
  .include("feature/login")
214
- .setFastForward(FastForwardMode.NO_FF)
145
+ .setFastForwardMode(FastForwardMode.NO_FF)
215
146
  .setMessage("Merge feature/login")
216
147
  .call();
217
148
 
218
- // Rebase onto main
219
- const rebaseResult = await git.rebase()
220
- .setUpstream("main")
221
- .call();
222
-
223
- // Continue after resolving conflicts
224
- await git.rebase()
225
- .setOperation("continue")
226
- .call();
149
+ // setUpstream() takes a commit id; setUpstreamBranch() resolves a name and is async
150
+ const rebase = await (await git.rebase().setUpstreamBranch("main")).call();
151
+ await git.rebase().setOperation(RebaseOperation.CONTINUE).call();
152
+ await git.rebase().setOperation(RebaseOperation.ABORT).call();
227
153
 
228
- // Abort rebase
229
- await git.rebase()
230
- .setOperation("abort")
231
- .call();
154
+ await git.cherryPick().include(commitId).call();
155
+ await git.revert().include(commitId).setNoCommit(true).call();
232
156
  ```
233
157
 
234
- ### Cherry-Pick and Revert
158
+ ### Big and binary files in diff, merge and blame
235
159
 
236
160
  ```typescript
237
- // Cherry-pick a specific commit
238
- const cherryResult = await git.cherryPick()
239
- .include("abc1234")
240
- .call();
161
+ import { DiffFormatter } from "@statewalker/vcs-commands";
241
162
 
242
- // Revert a commit
243
- const revertResult = await git.revert()
244
- .include("def5678")
245
- .call();
163
+ const formatter = new DiffFormatter(history.blobs, { bigFileThreshold: 10 * 2 ** 20 });
164
+ const diff = await formatter.format(entry);
165
+ console.log(formatter.toString(diff)); // "Binary files a/video.mp4 and b/video.mp4 differ"
246
166
 
247
- // Revert without committing (stage only)
248
- await git.revert()
249
- .include("def5678")
250
- .setNoCommit(true)
251
- .call();
167
+ await git.merge().include("feature").setContentMergeStrategy(ContentMergeStrategy.UNION).setBigFileThreshold(10 * 2 ** 20).call();
168
+ await git.blame().setFilePath("data.csv").setBigFileThreshold(10 * 2 ** 20).call();
252
169
  ```
253
170
 
254
- ### Remote Operations
171
+ Diff, merge and blame read sizes from object headers first and never load a file above `bigFileThreshold` (50 MiB by default, git's `core.bigFileThreshold`). They check whether a file is binary as git does, from a NUL byte in its first 8000 bytes, and read only that prefix (`probeBlob` from `@statewalker/vcs-core`). Text under the threshold is still loaded whole, because the diff algorithms need it, by the same single read that checked it (`probeBlob(..., { loadText: true })`).
255
172
 
256
- ```typescript
257
- // Configure a remote
258
- await git.remoteAdd()
259
- .setName("origin")
260
- .setUri("https://github.com/user/repo.git")
261
- .call();
173
+ - `DiffFormatter` shows a big or binary file as `Binary files a/<path> and b/<path> differ` and loads neither side. `oldContent` and `newContent` are set for text files only.
174
+ - `merge()` never content-merges a big or binary file. With `ContentMergeStrategy.OURS` or `THEIRS` it takes that side's file whole, as `git merge -X ours` does; with `UNION`, or without a content strategy, the path is a conflict.
175
+ - `blame()` rejects for a file above the threshold. A parent version above it is not compared, so the lines stay with the child commit, and it is never a rename candidate.
262
176
 
263
- // Fetch from remote
264
- const fetchResult = await git.fetch()
265
- .setRemote("origin")
266
- .setCredentials({ username: "user", password: "token" })
267
- .setProgressCallback((progress) => {
268
- console.log(`${progress.phase}: ${progress.completed}/${progress.total}`);
269
- })
270
- .call();
177
+ ### Remotes
178
+
179
+ ```typescript
180
+ import { isPushSuccessful } from "@statewalker/vcs-commands/results";
271
181
 
272
- console.log(`Fetched ${fetchResult.trackingRefUpdates.length} refs`);
182
+ await git.remoteAdd().setName("origin").setUri("https://github.com/user/repo.git").call();
273
183
 
274
- // Push to remote
275
- const pushResult = await git.push()
184
+ const fetched = await git
185
+ .fetch()
276
186
  .setRemote("origin")
277
- .add("refs/heads/main")
278
187
  .setCredentials({ username: "user", password: "token" })
279
188
  .call();
189
+ console.log(fetched.trackingRefUpdates.length, "refs updated");
280
190
 
281
- if (!pushResult.isSuccessful()) {
282
- console.log("Push failed:", pushResult.messages);
283
- }
191
+ const pushed = await git.push().setRemote("origin").add("refs/heads/main").call();
192
+ if (!isPushSuccessful(pushed)) console.log(pushed.messages);
284
193
 
285
- // Pull (fetch + merge)
286
- await git.pull()
287
- .setRemote("origin")
288
- .setRemoteBranchName("main")
289
- .call();
194
+ await git.pull().setRemote("origin").setRemoteBranchName("main").call();
290
195
  ```
291
196
 
292
- ### Cloning Repositories
197
+ `setRemote()` takes a configured remote name or a URL. Clone writes into the `WorkingCopy` that the `Git` instance wraps, so start from an empty one:
293
198
 
294
199
  ```typescript
295
- import { Git } from "@statewalker/vcs-commands";
296
- import { createWorkingCopy } from "@statewalker/vcs-core";
297
-
298
- // Create an in-memory working copy for the clone
299
- const workingCopy = await createWorkingCopy();
300
-
301
- // Clone a repository
302
- const result = await Git.clone()
303
- .setUri("https://github.com/user/repo.git")
304
- .setWorkingCopy(workingCopy)
200
+ const cloned = await Git.fromWorkingCopy(emptyWorkingCopy)
201
+ .clone()
202
+ .setURI("https://github.com/user/repo.git")
305
203
  .setCredentials({ token: "github_pat_xxx" })
306
- .setProgressCallback((progress) => {
307
- console.log(`${progress.phase}: ${progress.message}`);
308
- })
204
+ .setProgressMonitor((p) => console.log(p.stage, p.current, p.total))
309
205
  .call();
310
-
311
- console.log(`Cloned to branch: ${result.defaultBranch}`);
206
+ console.log(cloned.defaultBranch, cloned.headCommit);
312
207
  ```
313
208
 
314
- ### Stash Operations
209
+ All transport commands share `setCredentials({ username?, password?, token? })`, `setCredentialsProvider(username, password)`, `setHeaders()`, `setTimeout(ms)`, `setProgressMonitor(cb)` and `setProgressMessageCallback(cb)`.
315
210
 
316
- ```typescript
317
- // Create a stash with a message
318
- const stashResult = await git.stashCreate()
319
- .setMessage("WIP: feature work")
320
- .call();
321
-
322
- console.log(`Created stash: ${stashResult.stashRef}`);
211
+ ### Stash
323
212
 
324
- // Include untracked files (like git stash -u)
325
- await git.stashCreate()
326
- .setMessage("WIP with new files")
327
- .setIncludeUntracked(true)
328
- .call();
213
+ ```typescript
214
+ const stashId = await git.stashCreate().setMessage("WIP").call(); // ObjectId | undefined
329
215
 
330
- // List stashes
331
- const stashes = await git.stashList().call();
332
- for (const stash of stashes) {
333
- console.log(`stash@{${stash.index}}: ${stash.message}`);
216
+ for (const entry of await git.stashList().call()) {
217
+ console.log(`stash@{${entry.index}}: ${entry.message}`);
334
218
  }
335
219
 
336
- // Apply latest stash (keeps stash in list)
337
- await git.stashApply()
338
- .setStashRef("stash@{0}")
339
- .call();
340
-
341
- // Pop stash (apply and remove)
342
- await git.stashPop()
343
- .setStashRef("stash@{0}")
344
- .call();
345
-
346
- // Drop a specific stash
347
- await git.stashDrop()
348
- .setStashRef("stash@{1}")
349
- .call();
350
-
351
- // Clear all stashes
352
- await git.stashClear().call();
220
+ await git.stashApply().setStashRef("stash@{0}").call(); // StashApplyResult
221
+ await git.stashDrop().setStashRef(0).call(); // a 0-based index, not a ref string
222
+ await git.stashDrop().setAll(true).call();
353
223
  ```
354
224
 
355
- Stash commits follow Git's structure with 2-3 parents:
356
- - Parent 1: HEAD at time of stash
357
- - Parent 2: Index state commit
358
- - Parent 3 (optional): Untracked files commit (when `includeUntracked: true`)
225
+ There is no `stashPop()`: call `stashApply()`, then `stashDrop()`.
359
226
 
360
- ### Checkout Operations
227
+ ### Tags
361
228
 
362
229
  ```typescript
363
- // Switch to a branch
364
- await git.checkout()
365
- .setName("feature/login")
366
- .call();
367
-
368
- // Create and switch to new branch (like git checkout -b)
369
- await git.checkout()
370
- .setName("feature/new")
371
- .setCreateBranch(true)
372
- .call();
373
-
374
- // Checkout specific commit (detached HEAD)
375
- await git.checkout()
376
- .setName("abc1234")
377
- .call();
378
-
379
- // Checkout specific files from another branch
380
- await git.checkout()
381
- .setName("main")
382
- .addPath("src/config.ts")
383
- .addPath("package.json")
230
+ await git
231
+ .tag()
232
+ .setName("v1.0.0")
233
+ .setMessage("Release 1.0.0")
234
+ .setTagger("Developer", "dev@example.com")
384
235
  .call();
236
+ await git.tag().setName("v0.9.0").setObjectId(commitId).call();
385
237
 
386
- // Force checkout (discard local changes)
387
- await git.checkout()
388
- .setName("main")
389
- .setForce(true)
390
- .call();
238
+ const tags = await git.tagList().call(); // Ref[]
239
+ await git.tagDelete().setTags("v0.9.0").call();
391
240
  ```
392
241
 
393
- Checkout performs three-way conflict detection before switching branches:
242
+ ### Errors
394
243
 
395
244
  ```typescript
396
- import { CheckoutConflictError } from "@statewalker/vcs-commands/errors";
245
+ import { RefNotFoundError } from "@statewalker/vcs-commands/errors";
397
246
 
398
247
  try {
399
- await git.checkout().setName("main").call();
248
+ await git.checkout().setName("nonexistent").call();
400
249
  } catch (error) {
401
- if (error instanceof CheckoutConflictError) {
402
- // Local modifications would be overwritten
403
- console.log("Conflicting paths:");
404
- for (const conflict of error.conflicts) {
405
- console.log(` ${conflict.path}: ${conflict.message}`);
406
- }
407
-
408
- // Options: stash changes, force checkout, or abort
409
- }
250
+ if (error instanceof RefNotFoundError) console.log(error.message); // "Ref not found: nonexistent"
410
251
  }
411
252
  ```
412
253
 
413
- Conflict types detected:
414
- - **DIRTY_WORKTREE**: Modified file would be overwritten
415
- - **DIRTY_INDEX**: Staged changes would be lost
416
- - **UNTRACKED_FILE**: New file would be overwritten
417
-
418
- ### Tags
254
+ | Area | Errors |
255
+ |------|--------|
256
+ | Command | `MissingArgumentError`, `InvalidArgumentError`, `IncompatibleOptionsError`, `NotImplementedError`, `StoreNotAvailableError` |
257
+ | Refs | `RefNotFoundError`, `RefAlreadyExistsError`, `InvalidRefNameError`, `CannotDeleteCurrentBranchError`, `DetachedHeadError`, `NoHeadError`, `NotMergedError` |
258
+ | Add / checkout | `NoFilepatternError`, `PathNotInIndexError`, `PathNotFoundInTreeError`, `NotADirectoryError` |
259
+ | Commit | `NoMessageError`, `EmptyCommitError`, `UnmergedPathsError` |
260
+ | Merge | `MergeConflictError`, `InvalidMergeHeadsError`, `NotFastForwardError`, `MultipleParentsNotAllowedError`, `NoMergeBaseError`, `InvalidMainlineParentError` |
261
+ | Rebase | `NoRebaseInProgressError`, `UpstreamRequiredError`, `CommitNotFoundError` |
262
+ | Remotes / transport | `RemoteAlreadyExistsError`, `RemoteNotFoundError`, `InvalidRemoteError`, `TransportError`, `AuthenticationError`, `PushRejectedException`, `NonFastForwardError` |
263
+ | Stash / tag | `InvalidStashIndexError`, `StashNotFoundError`, `StashApplyFailedError`, `InvalidTagNameError` |
419
264
 
420
- ```typescript
421
- // Create annotated tag
422
- await git.tag()
423
- .setName("v1.0.0")
424
- .setMessage("Release version 1.0.0")
425
- .setTagger({ name: "Developer", email: "dev@example.com" })
426
- .call();
265
+ ## Internals
427
266
 
428
- // Create tag at specific commit
429
- await git.tag()
430
- .setName("v0.9.0")
431
- .setObjectId("abc1234")
432
- .call();
267
+ ### How a command runs
433
268
 
434
- // List tags
435
- const tags = await git.tagList().call();
436
- for (const tag of tags) {
437
- console.log(tag.name);
438
- }
439
-
440
- // Delete tag
441
- await git.tagDelete()
442
- .setTags("v0.9.0")
443
- .call();
444
269
  ```
445
-
446
- ## Error Handling
447
-
448
- Commands throw specific error types for different failure modes:
449
-
450
- ```typescript
451
- import {
452
- RefNotFoundError,
453
- MergeConflictError,
454
- AuthenticationError,
455
- PushRejectedException,
456
- } from "@statewalker/vcs-commands/errors";
457
-
458
- try {
459
- await git.checkout().setName("nonexistent").call();
460
- } catch (error) {
461
- if (error instanceof RefNotFoundError) {
462
- console.log(`Branch not found: ${error.refName}`);
463
- }
464
- }
465
-
466
- try {
467
- await git.merge().include("feature").call();
468
- } catch (error) {
469
- if (error instanceof MergeConflictError) {
470
- console.log("Conflicts:", error.conflicts);
471
- }
472
- }
473
-
474
- try {
475
- await git.push().setRemote("origin").call();
476
- } catch (error) {
477
- if (error instanceof AuthenticationError) {
478
- console.log("Authentication failed");
479
- } else if (error instanceof PushRejectedException) {
480
- console.log("Push rejected:", error.message);
481
- }
482
- }
270
+ Git.fromWorkingCopy(wc)
271
+ |
272
+ +-- git.commit() new CommitCommand(wc)
273
+ .setMessage(...) setters only record options
274
+ .call() checks "callable", then:
275
+ wc.checkout.staging -> writeTree()
276
+ wc.history.commits -> store()
277
+ wc.history.refs -> set(branch)
483
278
  ```
484
279
 
485
- ### Error Categories
280
+ Every command extends `GitCommand<T>`. Remote commands extend `TransportCommand<T>`, which adds credentials, headers, timeout and progress callbacks. `Git` holds no state besides the `WorkingCopy` and a closed flag.
486
281
 
487
- | Category | Errors |
488
- |----------|--------|
489
- | **Command** | `MissingArgumentError`, `InvalidArgumentError`, `NotImplementedError` |
490
- | **Reference** | `RefNotFoundError`, `RefAlreadyExistsError`, `CannotDeleteCurrentBranchError` |
491
- | **Commit** | `NoMessageError`, `EmptyCommitError`, `UnmergedPathsError` |
492
- | **Merge** | `MergeConflictError`, `NotFastForwardError`, `NoMergeBaseError` |
493
- | **Transport** | `AuthenticationError`, `PushRejectedException`, `NonFastForwardError` |
494
- | **Checkout** | `CheckoutConflictError`, `DirCacheCheckoutError` |
495
- | **Stash** | `NoStashError`, `StashDropError` |
282
+ ### Why commands are single-use
496
283
 
497
- ## Result Types
284
+ A command records options in fields and `call()` acts on them. Running it twice would reuse half-consumed state (a resolved upstream, a parsed refspec list), so `call()` marks it spent. A second call throws `Command CommitCommand has already been called`. After `git.close()`, every factory method throws `Git instance is closed`. Closing `Git` does not close the underlying stores.
498
285
 
499
- Commands return rich result objects with status information:
286
+ ### How refs are resolved
500
287
 
501
- ```typescript
502
- import {
503
- MergeStatus,
504
- PushStatus,
505
- RebaseStatus,
506
- } from "@statewalker/vcs-commands/results";
507
-
508
- // Check merge result
509
- const mergeResult = await git.merge().include("feature").call();
510
- switch (mergeResult.status) {
511
- case MergeStatus.FAST_FORWARD:
512
- console.log("Fast-forwarded");
513
- break;
514
- case MergeStatus.MERGED:
515
- console.log("Created merge commit");
516
- break;
517
- case MergeStatus.CONFLICTING:
518
- console.log("Conflicts need resolution");
519
- break;
520
- }
288
+ `resolveRef()` tries, in order: the name as given (`refs/heads/main`, `HEAD`), `refs/heads/<name>`, `refs/tags/<name>`, then a full commit id. Names containing `~` or `^` are walked through parents (`HEAD~2`, `HEAD^2`). Annotated tags are peeled to commits. Abbreviated commit ids are not resolved; they fail with `Ref not found: <name>`.
521
289
 
522
- // Check push result
523
- const pushResult = await git.push().call();
524
- for (const update of pushResult.remoteUpdates) {
525
- if (update.status === PushStatus.OK) {
526
- console.log(`Updated: ${update.remoteName}`);
527
- } else if (update.status === PushStatus.REJECTED_NONFASTFORWARD) {
528
- console.log(`Rejected: ${update.remoteName} (non-fast-forward)`);
529
- }
530
- }
531
- ```
290
+ ### Remote commands use smart HTTP only
532
291
 
533
- ## Configuration
292
+ `fetch`, `push`, `pull`, `clone` and `lsRemote` call the Git smart HTTP client in `@statewalker/vcs-transport`, which uses the global `fetch`. Received packs are imported into `workingCopy.history`. Remotes are stored as `[remote "<name>"]` entries in `WorkingCopy.config` (`.git/config` for a file-backed working copy), so `remoteAdd()` must run on the same `WorkingCopy` before `setRemote("origin")` can resolve. A name that is not configured is passed to the transport as if it were a URL, so a typo shows up as a network error, not as `Invalid remote: <name>`.
534
293
 
535
- ### Transport Options
294
+ ### What breaks, and how it looks
536
295
 
537
- Remote commands support authentication and progress tracking:
538
-
539
- ```typescript
540
- // Username/password authentication
541
- await git.fetch()
542
- .setRemote("origin")
543
- .setCredentials({
544
- username: "user",
545
- password: "password",
546
- })
547
- .call();
296
+ - `push().call()` does not throw on rejection. Check `isPushSuccessful(result)` or each `remoteUpdates[i].status`. `push().callOrThrow()` throws `NonFastForwardError` or `PushRejectedException` instead.
297
+ - Merge conflicts are not thrown: `merge()` returns `status: MergeStatus.CONFLICTING` with `conflicts`. Only some merges throw, for example `Cannot fast-forward merge; branches have diverged` with `FastForwardMode.FF_ONLY`, or `No merge base found`.
298
+ - A `WorkingCopy` without history or staging fails at first use with `WorkingCopy.history is required for commands` or `WorkingCopy.checkout.staging is required for commands`.
299
+ - Writing files with no worktree fails with `Worktree not available for file writes`.
300
+ - Commands that need a commit in an empty repository fail with `HEAD cannot be resolved` (`NoHeadError`).
301
+ - `commit()` without a message fails with `Commit message is required`; with unresolved conflicts, `Cannot commit with unresolved conflicts`.
548
302
 
549
- // Token authentication
550
- await git.push()
551
- .setRemote("origin")
552
- .setCredentials({
553
- token: "github_pat_xxxx",
554
- })
555
- .call();
303
+ ### Constraints
556
304
 
557
- // Custom headers
558
- await git.fetch()
559
- .setRemote("origin")
560
- .setHeaders({
561
- "X-Custom-Header": "value",
562
- })
563
- .call();
305
+ - `status()` compares HEAD with the index only (`added`, `changed`, `removed`, `conflicting`). It does not look at the worktree. For a working-tree status use `createStatusCalculator` from `@statewalker/vcs-working-tree`.
306
+ - `stashCreate()` captures the working state only through `setWorkingTreeProvider(provider)`. Without a provider it stores a stash whose trees are the HEAD tree, even when nothing changed. The package ships no provider implementation.
307
+ - `merge()` supports a single merge head (`Only single-head merges are currently supported`).
308
+ - `fetch()` passes only `setProgressMessageCallback()` to the transport; `setProgressMonitor()` has effect on `clone()` only.
309
+ - `Git.init()` (an `InitCommand`) always creates an in-memory history. `setFilesApi()` only backs the worktree when `setWorktree(true)` is set. Its `InitResult` has `git`, `workingCopy`, `repository`, `initialBranch`, `bare` and `gitDir`.
310
+ - `stashDrop().setStashRef(n)` takes an index; without reflog support only index 0 is valid.
564
311
 
565
- // Progress tracking
566
- await git.clone()
567
- .setUri("https://github.com/user/repo.git")
568
- .setProgressCallback((progress) => {
569
- // Structured progress
570
- console.log(progress.phase, progress.completed, progress.total);
571
- })
572
- .setMessageCallback((message) => {
573
- // Raw server messages
574
- console.log("Server:", message);
575
- })
576
- .call();
577
- ```
312
+ ### Dependencies and why
578
313
 
579
- ## Related Packages
314
+ - `@statewalker/vcs-core`: object stores, refs, commit/tree serialization.
315
+ - `@statewalker/vcs-working-tree`: `WorkingCopy`, `Checkout`, `Staging`, `Worktree` interfaces and memory implementations.
316
+ - `@statewalker/vcs-transport`: smart HTTP fetch, push, clone, ls-remote.
317
+ - `@statewalker/vcs-store-files`, `@statewalker/vcs-store-mem`: used by `InitCommand` to build a default worktree and staging.
318
+ - `@statewalker/vcs-utils`: hashing and byte helpers.
580
319
 
581
- | Package | Description |
582
- |---------|-------------|
583
- | `@statewalker/vcs-core` | Core types, store interfaces, and repository factories |
584
- | `@statewalker/vcs-transport` | Git protocol implementation |
585
- | `@statewalker/vcs-store-sql` | SQLite storage backend |
586
- | `@statewalker/vcs-store-mem` | In-memory storage for testing |
587
- | `@statewalker/vcs-store-kv` | Key-value storage abstraction |
320
+ See [ARCHITECTURE.md](./ARCHITECTURE.md) for the class hierarchy and extension points.
588
321
 
589
322
  ## License
590
323