@statewalker/vcs-commands 0.3.1 → 0.3.2

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 (2) hide show
  1. package/README.md +180 -466
  2. package/package.json +16 -12
package/README.md CHANGED
@@ -1,590 +1,304 @@
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();
42
-
43
- // Check status
44
- const status = await git.status().call();
45
- console.log("Clean:", status.isClean());
46
-
47
- // Clean up
48
- git.dispose();
49
- ```
50
-
51
- ## Public API
51
+ const commit = await git.commit().setMessage("Initial commit").call();
52
+ console.log(commit.id);
52
53
 
53
- ### Main Export
54
+ console.log("Clean:", (await git.status().call()).isClean());
54
55
 
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";
56
+ git.close(); // or `using git = ...`: Git implements Disposable
73
57
  ```
74
58
 
75
- ### Sub-exports
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 |
82
-
83
- ### Git Class Methods
59
+ For a Git-compatible on-disk repository, build the `WorkingCopy` from the file-backed classes in `@statewalker/vcs-store-files` (for example `GitWorkingCopy`).
84
60
 
85
- The `Git` class provides factory methods for all commands:
61
+ `Git` methods:
86
62
 
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()` |
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` |
98
76
 
99
- ## Usage Examples
77
+ ## Examples
100
78
 
101
- ### Staging and Committing
79
+ ### Staging and committing
102
80
 
103
81
  ```typescript
104
- import { Git } from "@statewalker/vcs-commands";
82
+ await git.add().addFilepattern("src/").addFilepattern("package.json").call();
105
83
 
106
- // Stage specific files
107
- await git.add()
108
- .addFilepattern("src/")
109
- .addFilepattern("package.json")
110
- .call();
84
+ // Stage modifications and deletions of tracked files only (git add -u)
85
+ await git.add().addFilepattern(".").setUpdate(true).call();
111
86
 
112
- // Stage all changes including deletions
113
- await git.add()
114
- .addFilepattern(".")
115
- .setUpdate(true)
116
- .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`
117
92
 
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();
123
-
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
+ ### Remotes
235
159
 
236
160
  ```typescript
237
- // Cherry-pick a specific commit
238
- const cherryResult = await git.cherryPick()
239
- .include("abc1234")
240
- .call();
241
-
242
- // Revert a commit
243
- const revertResult = await git.revert()
244
- .include("def5678")
245
- .call();
246
-
247
- // Revert without committing (stage only)
248
- await git.revert()
249
- .include("def5678")
250
- .setNoCommit(true)
251
- .call();
252
- ```
161
+ import { isPushSuccessful } from "@statewalker/vcs-commands/results";
253
162
 
254
- ### Remote Operations
163
+ await git.remoteAdd().setName("origin").setUri("https://github.com/user/repo.git").call();
255
164
 
256
- ```typescript
257
- // Configure a remote
258
- await git.remoteAdd()
259
- .setName("origin")
260
- .setUri("https://github.com/user/repo.git")
261
- .call();
262
-
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();
271
-
272
- console.log(`Fetched ${fetchResult.trackingRefUpdates.length} refs`);
273
-
274
- // Push to remote
275
- const pushResult = await git.push()
165
+ const fetched = await git
166
+ .fetch()
276
167
  .setRemote("origin")
277
- .add("refs/heads/main")
278
168
  .setCredentials({ username: "user", password: "token" })
279
169
  .call();
170
+ console.log(fetched.trackingRefUpdates.length, "refs updated");
280
171
 
281
- if (!pushResult.isSuccessful()) {
282
- console.log("Push failed:", pushResult.messages);
283
- }
172
+ const pushed = await git.push().setRemote("origin").add("refs/heads/main").call();
173
+ if (!isPushSuccessful(pushed)) console.log(pushed.messages);
284
174
 
285
- // Pull (fetch + merge)
286
- await git.pull()
287
- .setRemote("origin")
288
- .setRemoteBranchName("main")
289
- .call();
175
+ await git.pull().setRemote("origin").setRemoteBranchName("main").call();
290
176
  ```
291
177
 
292
- ### Cloning Repositories
178
+ `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
179
 
294
180
  ```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)
181
+ const cloned = await Git.fromWorkingCopy(emptyWorkingCopy)
182
+ .clone()
183
+ .setURI("https://github.com/user/repo.git")
305
184
  .setCredentials({ token: "github_pat_xxx" })
306
- .setProgressCallback((progress) => {
307
- console.log(`${progress.phase}: ${progress.message}`);
308
- })
185
+ .setProgressMonitor((p) => console.log(p.stage, p.current, p.total))
309
186
  .call();
310
-
311
- console.log(`Cloned to branch: ${result.defaultBranch}`);
187
+ console.log(cloned.defaultBranch, cloned.headCommit);
312
188
  ```
313
189
 
314
- ### Stash Operations
190
+ All transport commands share `setCredentials({ username?, password?, token? })`, `setCredentialsProvider(username, password)`, `setHeaders()`, `setTimeout(ms)`, `setProgressMonitor(cb)` and `setProgressMessageCallback(cb)`.
315
191
 
316
- ```typescript
317
- // Create a stash with a message
318
- const stashResult = await git.stashCreate()
319
- .setMessage("WIP: feature work")
320
- .call();
192
+ ### Stash
321
193
 
322
- console.log(`Created stash: ${stashResult.stashRef}`);
323
-
324
- // Include untracked files (like git stash -u)
325
- await git.stashCreate()
326
- .setMessage("WIP with new files")
327
- .setIncludeUntracked(true)
328
- .call();
194
+ ```typescript
195
+ const stashId = await git.stashCreate().setMessage("WIP").call(); // ObjectId | undefined
329
196
 
330
- // List stashes
331
- const stashes = await git.stashList().call();
332
- for (const stash of stashes) {
333
- console.log(`stash@{${stash.index}}: ${stash.message}`);
197
+ for (const entry of await git.stashList().call()) {
198
+ console.log(`stash@{${entry.index}}: ${entry.message}`);
334
199
  }
335
200
 
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();
201
+ await git.stashApply().setStashRef("stash@{0}").call(); // StashApplyResult
202
+ await git.stashDrop().setStashRef(0).call(); // a 0-based index, not a ref string
203
+ await git.stashDrop().setAll(true).call();
353
204
  ```
354
205
 
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`)
206
+ There is no `stashPop()`: call `stashApply()`, then `stashDrop()`.
359
207
 
360
- ### Checkout Operations
208
+ ### Tags
361
209
 
362
210
  ```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")
211
+ await git
212
+ .tag()
213
+ .setName("v1.0.0")
214
+ .setMessage("Release 1.0.0")
215
+ .setTagger("Developer", "dev@example.com")
384
216
  .call();
217
+ await git.tag().setName("v0.9.0").setObjectId(commitId).call();
385
218
 
386
- // Force checkout (discard local changes)
387
- await git.checkout()
388
- .setName("main")
389
- .setForce(true)
390
- .call();
219
+ const tags = await git.tagList().call(); // Ref[]
220
+ await git.tagDelete().setTags("v0.9.0").call();
391
221
  ```
392
222
 
393
- Checkout performs three-way conflict detection before switching branches:
223
+ ### Errors
394
224
 
395
225
  ```typescript
396
- import { CheckoutConflictError } from "@statewalker/vcs-commands/errors";
226
+ import { RefNotFoundError } from "@statewalker/vcs-commands/errors";
397
227
 
398
228
  try {
399
- await git.checkout().setName("main").call();
229
+ await git.checkout().setName("nonexistent").call();
400
230
  } 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
- }
231
+ if (error instanceof RefNotFoundError) console.log(error.message); // "Ref not found: nonexistent"
410
232
  }
411
233
  ```
412
234
 
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
235
+ | Area | Errors |
236
+ |------|--------|
237
+ | Command | `MissingArgumentError`, `InvalidArgumentError`, `IncompatibleOptionsError`, `NotImplementedError`, `StoreNotAvailableError` |
238
+ | Refs | `RefNotFoundError`, `RefAlreadyExistsError`, `InvalidRefNameError`, `CannotDeleteCurrentBranchError`, `DetachedHeadError`, `NoHeadError`, `NotMergedError` |
239
+ | Add / checkout | `NoFilepatternError`, `PathNotInIndexError`, `PathNotFoundInTreeError`, `NotADirectoryError` |
240
+ | Commit | `NoMessageError`, `EmptyCommitError`, `UnmergedPathsError` |
241
+ | Merge | `MergeConflictError`, `InvalidMergeHeadsError`, `NotFastForwardError`, `MultipleParentsNotAllowedError`, `NoMergeBaseError`, `InvalidMainlineParentError` |
242
+ | Rebase | `NoRebaseInProgressError`, `UpstreamRequiredError`, `CommitNotFoundError` |
243
+ | Remotes / transport | `RemoteAlreadyExistsError`, `RemoteNotFoundError`, `InvalidRemoteError`, `TransportError`, `AuthenticationError`, `PushRejectedException`, `NonFastForwardError` |
244
+ | Stash / tag | `InvalidStashIndexError`, `StashNotFoundError`, `StashApplyFailedError`, `InvalidTagNameError` |
417
245
 
418
- ### Tags
246
+ ## Internals
419
247
 
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();
248
+ ### How a command runs
427
249
 
428
- // Create tag at specific commit
429
- await git.tag()
430
- .setName("v0.9.0")
431
- .setObjectId("abc1234")
432
- .call();
433
-
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
250
  ```
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
- }
251
+ Git.fromWorkingCopy(wc)
252
+ |
253
+ +-- git.commit() new CommitCommand(wc)
254
+ .setMessage(...) setters only record options
255
+ .call() checks "callable", then:
256
+ wc.checkout.staging -> writeTree()
257
+ wc.history.commits -> store()
258
+ wc.history.refs -> set(branch)
483
259
  ```
484
260
 
485
- ### Error Categories
261
+ 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
262
 
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` |
263
+ ### Why commands are single-use
496
264
 
497
- ## Result Types
265
+ 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
266
 
499
- Commands return rich result objects with status information:
267
+ ### How refs are resolved
500
268
 
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
- }
269
+ `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
270
 
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
- ```
271
+ ### Remote commands use smart HTTP only
532
272
 
533
- ## Configuration
273
+ `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
274
 
535
- ### Transport Options
275
+ ### What breaks, and how it looks
536
276
 
537
- Remote commands support authentication and progress tracking:
277
+ - `push().call()` does not throw on rejection. Check `isPushSuccessful(result)` or each `remoteUpdates[i].status`. `push().callOrThrow()` throws `NonFastForwardError` or `PushRejectedException` instead.
278
+ - 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`.
279
+ - 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`.
280
+ - Writing files with no worktree fails with `Worktree not available for file writes`.
281
+ - Commands that need a commit in an empty repository fail with `HEAD cannot be resolved` (`NoHeadError`).
282
+ - `commit()` without a message fails with `Commit message is required`; with unresolved conflicts, `Cannot commit with unresolved conflicts`.
538
283
 
539
- ```typescript
540
- // Username/password authentication
541
- await git.fetch()
542
- .setRemote("origin")
543
- .setCredentials({
544
- username: "user",
545
- password: "password",
546
- })
547
- .call();
284
+ ### Constraints
548
285
 
549
- // Token authentication
550
- await git.push()
551
- .setRemote("origin")
552
- .setCredentials({
553
- token: "github_pat_xxxx",
554
- })
555
- .call();
286
+ - `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`.
287
+ - `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.
288
+ - `merge()` supports a single merge head (`Only single-head merges are currently supported`).
289
+ - `fetch()` passes only `setProgressMessageCallback()` to the transport; `setProgressMonitor()` has effect on `clone()` only.
290
+ - `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`.
291
+ - `stashDrop().setStashRef(n)` takes an index; without reflog support only index 0 is valid.
556
292
 
557
- // Custom headers
558
- await git.fetch()
559
- .setRemote("origin")
560
- .setHeaders({
561
- "X-Custom-Header": "value",
562
- })
563
- .call();
564
-
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
- ```
293
+ ### Dependencies and why
578
294
 
579
- ## Related Packages
295
+ - `@statewalker/vcs-core`: object stores, refs, commit/tree serialization.
296
+ - `@statewalker/vcs-working-tree`: `WorkingCopy`, `Checkout`, `Staging`, `Worktree` interfaces and memory implementations.
297
+ - `@statewalker/vcs-transport`: smart HTTP fetch, push, clone, ls-remote.
298
+ - `@statewalker/vcs-store-files`, `@statewalker/vcs-store-mem`: used by `InitCommand` to build a default worktree and staging.
299
+ - `@statewalker/vcs-utils`: hashing and byte helpers.
580
300
 
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 |
301
+ See [ARCHITECTURE.md](./ARCHITECTURE.md) for the class hierarchy and extension points.
588
302
 
589
303
  ## License
590
304
 
package/package.json CHANGED
@@ -1,12 +1,16 @@
1
1
  {
2
2
  "name": "@statewalker/vcs-commands",
3
- "version": "0.3.1",
3
+ "version": "0.3.2",
4
4
  "description": "Git-like VCS commands (commit, checkout, merge, diff, log)",
5
+ "bugs": {
6
+ "url": "https://github.com/statewalker/webrun-vcs/issues"
7
+ },
8
+ "homepage": "https://github.com/statewalker/webrun-vcs/tree/main/packages/vcs-commands#readme",
5
9
  "license": "MIT",
6
10
  "repository": {
7
11
  "type": "git",
8
- "url": "https://github.com/statewalker/webrun-vcs.git",
9
- "directory": "packages/commands"
12
+ "url": "git+https://github.com/statewalker/webrun-vcs.git",
13
+ "directory": "packages/vcs-commands"
10
14
  },
11
15
  "private": false,
12
16
  "publishConfig": {
@@ -42,21 +46,21 @@
42
46
  "src"
43
47
  ],
44
48
  "dependencies": {
45
- "@statewalker/vcs-core": "^0.3.1",
46
- "@statewalker/vcs-store-files": "^0.3.1",
47
- "@statewalker/vcs-store-mem": "^0.3.1",
48
- "@statewalker/vcs-transport": "^0.3.1",
49
- "@statewalker/vcs-utils": "^0.3.1",
50
- "@statewalker/vcs-working-tree": "^0.3.1"
49
+ "@statewalker/vcs-core": "^0.3.3",
50
+ "@statewalker/vcs-store-mem": "^0.3.2",
51
+ "@statewalker/vcs-store-files": "^0.3.2",
52
+ "@statewalker/vcs-utils": "^0.3.2",
53
+ "@statewalker/vcs-transport": "^0.3.2",
54
+ "@statewalker/vcs-working-tree": "^0.3.2"
51
55
  },
52
56
  "devDependencies": {
53
57
  "@types/node": "^26.6.4",
54
58
  "rolldown": "^1.2.12",
55
59
  "typescript": "^7.0.2",
56
60
  "vitest": "^5.0.3",
57
- "@statewalker/vcs-transport-adapters": "^0.3.1",
58
- "@statewalker/vcs-utils-node": "^0.3.1",
59
- "@statewalker/vcs-store-sql": "^0.3.1"
61
+ "@statewalker/vcs-transport-adapters": "^0.3.3",
62
+ "@statewalker/vcs-utils-node": "^0.3.2",
63
+ "@statewalker/vcs-store-sql": "^0.3.2"
60
64
  },
61
65
  "scripts": {
62
66
  "build": "rm -rf dist && rolldown -c && tsc --emitDeclarationOnly --declaration",