@statewalker/vcs-commands 0.1.1 → 0.3.1

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 (85) hide show
  1. package/dist/commands/commit-command.d.ts.map +1 -1
  2. package/dist/commands/init-command.d.ts.map +1 -1
  3. package/dist/commands/push-command.d.ts.map +1 -1
  4. package/dist/core-commands/checkout.command.impl.d.ts +1 -1
  5. package/dist/core-commands/checkout.command.impl.d.ts.map +1 -1
  6. package/dist/git-command.d.ts.map +1 -1
  7. package/package.json +19 -14
  8. package/src/commands/add-command.ts +494 -0
  9. package/src/commands/blame-command.ts +1241 -0
  10. package/src/commands/branch-command.ts +487 -0
  11. package/src/commands/checkout-command.ts +681 -0
  12. package/src/commands/cherry-pick-command.ts +544 -0
  13. package/src/commands/clean-command.ts +218 -0
  14. package/src/commands/clone-command.ts +532 -0
  15. package/src/commands/commit-command.ts +529 -0
  16. package/src/commands/describe-command.ts +454 -0
  17. package/src/commands/diff-command.ts +257 -0
  18. package/src/commands/fetch-command.ts +615 -0
  19. package/src/commands/gc-command.ts +155 -0
  20. package/src/commands/index.ts +31 -0
  21. package/src/commands/init-command.ts +365 -0
  22. package/src/commands/log-command.ts +549 -0
  23. package/src/commands/ls-remote-command.ts +237 -0
  24. package/src/commands/merge-command.ts +750 -0
  25. package/src/commands/pack-refs-command.ts +101 -0
  26. package/src/commands/pull-command.ts +258 -0
  27. package/src/commands/push-command.ts +682 -0
  28. package/src/commands/rebase-command.ts +665 -0
  29. package/src/commands/reflog-command.ts +68 -0
  30. package/src/commands/remote-command.ts +385 -0
  31. package/src/commands/reset-command.ts +292 -0
  32. package/src/commands/revert-command.ts +552 -0
  33. package/src/commands/rm-command.ts +178 -0
  34. package/src/commands/stash-apply-command.ts +402 -0
  35. package/src/commands/stash-create-command.ts +339 -0
  36. package/src/commands/stash-drop-command.ts +115 -0
  37. package/src/commands/stash-list-command.ts +116 -0
  38. package/src/commands/status-command.ts +173 -0
  39. package/src/commands/tag-command.ts +378 -0
  40. package/src/commands/tree-restore.ts +126 -0
  41. package/src/core-commands/add.command.impl.ts +274 -0
  42. package/src/core-commands/add.command.ts +81 -0
  43. package/src/core-commands/checkout.command.impl.ts +586 -0
  44. package/src/core-commands/checkout.command.ts +125 -0
  45. package/src/core-commands/index.ts +13 -0
  46. package/src/errors/add-errors.ts +20 -0
  47. package/src/errors/checkout-errors.ts +42 -0
  48. package/src/errors/command-errors.ts +68 -0
  49. package/src/errors/commit-errors.ts +40 -0
  50. package/src/errors/git-api-error.ts +11 -0
  51. package/src/errors/index.ts +12 -0
  52. package/src/errors/merge-errors.ts +94 -0
  53. package/src/errors/rebase-errors.ts +34 -0
  54. package/src/errors/ref-errors.ts +100 -0
  55. package/src/errors/remote-errors.ts +27 -0
  56. package/src/errors/stash-errors.ts +42 -0
  57. package/src/errors/tag-errors.ts +16 -0
  58. package/src/errors/transport-errors.ts +68 -0
  59. package/src/git-command.ts +421 -0
  60. package/src/git.ts +910 -0
  61. package/src/index.ts +18 -0
  62. package/src/pack-import/index.ts +8 -0
  63. package/src/pack-import/pack-import.ts +24 -0
  64. package/src/remote-config/index.ts +12 -0
  65. package/src/remote-config/remote-config-store.ts +285 -0
  66. package/src/rename/index.ts +5 -0
  67. package/src/rename/similarity-index.ts +185 -0
  68. package/src/results/cherry-pick-result.ts +35 -0
  69. package/src/results/clone-result.ts +25 -0
  70. package/src/results/diff-entry.ts +162 -0
  71. package/src/results/diff-formatter.ts +416 -0
  72. package/src/results/fetch-result.ts +91 -0
  73. package/src/results/index.ts +13 -0
  74. package/src/results/init-result.ts +29 -0
  75. package/src/results/merge-result.ts +135 -0
  76. package/src/results/pull-result.ts +27 -0
  77. package/src/results/push-result.ts +86 -0
  78. package/src/results/rebase-result.ts +140 -0
  79. package/src/results/revert-result.ts +35 -0
  80. package/src/results/stash-result.ts +60 -0
  81. package/src/results/status-result.ts +65 -0
  82. package/src/transport-command.ts +125 -0
  83. package/src/tree-merge/index.ts +8 -0
  84. package/src/tree-merge/tree-merge.ts +249 -0
  85. package/src/types.ts +70 -0
@@ -0,0 +1,529 @@
1
+ import type { Commit, ObjectId, PersonIdent } from "@statewalker/vcs-core";
2
+ import { isSymbolicRef } from "@statewalker/vcs-core";
3
+ import type { Worktree } from "@statewalker/vcs-working-tree";
4
+
5
+ import {
6
+ EmptyCommitError,
7
+ IncompatibleOptionsError,
8
+ NoHeadError,
9
+ NoMessageError,
10
+ RefNotFoundError,
11
+ StoreNotAvailableError,
12
+ UnmergedPathsError,
13
+ } from "../errors/index.js";
14
+ import { GitCommand } from "../git-command.js";
15
+ import { AddCommand } from "./add-command.js";
16
+
17
+ /**
18
+ * Result of a commit operation.
19
+ *
20
+ * Extends Commit with the ID of the created commit.
21
+ * JGit's CommitCommand returns RevCommit which includes getId().
22
+ */
23
+ export interface CommitResult extends Commit {
24
+ /** The ObjectId of the created commit */
25
+ id: ObjectId;
26
+ }
27
+
28
+ /**
29
+ * Get current timezone offset as string (+HHMM or -HHMM).
30
+ */
31
+ function getTimezoneOffset(): string {
32
+ const offset = new Date().getTimezoneOffset();
33
+ const sign = offset <= 0 ? "+" : "-";
34
+ const absOffset = Math.abs(offset);
35
+ const hours = Math.floor(absOffset / 60)
36
+ .toString()
37
+ .padStart(2, "0");
38
+ const minutes = (absOffset % 60).toString().padStart(2, "0");
39
+ return `${sign}${hours}${minutes}`;
40
+ }
41
+
42
+ /**
43
+ * Create a commit from staged changes.
44
+ *
45
+ * Equivalent to `git commit`.
46
+ *
47
+ * Based on JGit's CommitCommand.
48
+ *
49
+ * @example
50
+ * ```typescript
51
+ * // Simple commit
52
+ * const commit = await git.commit()
53
+ * .setMessage("Fix bug in parser")
54
+ * .call();
55
+ *
56
+ * // Commit with author
57
+ * const commit = await git.commit()
58
+ * .setMessage("Add feature")
59
+ * .setAuthor("John Doe", "john@example.com")
60
+ * .call();
61
+ *
62
+ * // Amend previous commit
63
+ * const commit = await git.commit()
64
+ * .setMessage("Updated message")
65
+ * .setAmend(true)
66
+ * .call();
67
+ *
68
+ * // Allow empty commit
69
+ * const commit = await git.commit()
70
+ * .setMessage("Empty commit")
71
+ * .setAllowEmpty(true)
72
+ * .call();
73
+ *
74
+ * // Commit only specific paths
75
+ * const commit = await git.commit()
76
+ * .setMessage("Partial commit")
77
+ * .setOnly("src/file.ts", "tests/file.test.ts")
78
+ * .call();
79
+ *
80
+ * // Auto-stage and commit tracked changes (requires worktree)
81
+ * const commit = await git.commit()
82
+ * .setMessage("All changes")
83
+ * .setAll(true)
84
+ * .setWorktree(worktree)
85
+ * .call();
86
+ * ```
87
+ */
88
+ export class CommitCommand extends GitCommand<CommitResult> {
89
+ private message?: string;
90
+ private author?: PersonIdent;
91
+ private committer?: PersonIdent;
92
+ private amend = false;
93
+ private allowEmpty = false;
94
+ private parents: ObjectId[] = [];
95
+ private onlyPaths: string[] = [];
96
+ private all = false;
97
+ private worktreeIterator: Worktree | undefined;
98
+
99
+ /**
100
+ * Set the commit message.
101
+ *
102
+ * @param message Commit message
103
+ */
104
+ setMessage(message: string): this {
105
+ this.checkCallable();
106
+ this.message = message;
107
+ return this;
108
+ }
109
+
110
+ /**
111
+ * Set the author identity.
112
+ *
113
+ * @param name Author name
114
+ * @param email Author email
115
+ */
116
+ setAuthor(name: string, email: string): this {
117
+ this.checkCallable();
118
+ this.author = {
119
+ name,
120
+ email,
121
+ timestamp: Math.floor(Date.now() / 1000),
122
+ tzOffset: getTimezoneOffset(),
123
+ };
124
+ return this;
125
+ }
126
+
127
+ /**
128
+ * Set the author identity from a PersonIdent.
129
+ *
130
+ * @param author Author identity
131
+ */
132
+ setAuthorIdent(author: PersonIdent): this {
133
+ this.checkCallable();
134
+ this.author = author;
135
+ return this;
136
+ }
137
+
138
+ /**
139
+ * Set the committer identity.
140
+ *
141
+ * @param name Committer name
142
+ * @param email Committer email
143
+ */
144
+ setCommitter(name: string, email: string): this {
145
+ this.checkCallable();
146
+ this.committer = {
147
+ name,
148
+ email,
149
+ timestamp: Math.floor(Date.now() / 1000),
150
+ tzOffset: getTimezoneOffset(),
151
+ };
152
+ return this;
153
+ }
154
+
155
+ /**
156
+ * Set the committer identity from a PersonIdent.
157
+ *
158
+ * @param committer Committer identity
159
+ */
160
+ setCommitterIdent(committer: PersonIdent): this {
161
+ this.checkCallable();
162
+ this.committer = committer;
163
+ return this;
164
+ }
165
+
166
+ /**
167
+ * Set whether to amend the previous commit.
168
+ *
169
+ * @param amend Whether to amend
170
+ */
171
+ setAmend(amend: boolean): this {
172
+ this.checkCallable();
173
+ this.amend = amend;
174
+ return this;
175
+ }
176
+
177
+ /**
178
+ * Set whether to allow an empty commit.
179
+ *
180
+ * @param allowEmpty Whether to allow empty commits
181
+ */
182
+ setAllowEmpty(allowEmpty: boolean): this {
183
+ this.checkCallable();
184
+ this.allowEmpty = allowEmpty;
185
+ return this;
186
+ }
187
+
188
+ /**
189
+ * Set explicit parent commits.
190
+ *
191
+ * Normally parents are determined automatically, but this
192
+ * can be used for merge commits or special cases.
193
+ *
194
+ * @param parents Parent commit IDs
195
+ */
196
+ setParentIds(...parents: ObjectId[]): this {
197
+ this.checkCallable();
198
+ this.parents = parents;
199
+ return this;
200
+ }
201
+
202
+ /**
203
+ * Set paths to commit (--only mode).
204
+ *
205
+ * When set, only the specified paths are taken from the staging area.
206
+ * All other paths are taken from the parent commit's tree. This allows
207
+ * partial commits without affecting unstaged changes to other files.
208
+ *
209
+ * Cannot be combined with setAll().
210
+ *
211
+ * @param paths Paths to include in commit
212
+ * @throws Error if combined with --all mode
213
+ */
214
+ setOnly(...paths: string[]): this {
215
+ this.checkCallable();
216
+ // JGit: --all and --only are mutually exclusive
217
+ if (this.all && paths.length > 0) {
218
+ throw new IncompatibleOptionsError(["--only", "--all"]);
219
+ }
220
+ this.onlyPaths = paths;
221
+ return this;
222
+ }
223
+
224
+ /**
225
+ * Set whether to auto-stage modified tracked files before committing.
226
+ *
227
+ * If true, stages all modified and deleted tracked files before
228
+ * creating the commit. Requires a working tree iterator.
229
+ *
230
+ * Cannot be combined with setOnly().
231
+ *
232
+ * Equivalent to `git commit -a` or `git commit --all`.
233
+ *
234
+ * @param all Whether to auto-stage tracked changes
235
+ * @returns this for chaining
236
+ * @throws Error if combined with --only paths
237
+ */
238
+ setAll(all: boolean): this {
239
+ this.checkCallable();
240
+ // JGit: --all and --only are mutually exclusive
241
+ if (all && this.onlyPaths.length > 0) {
242
+ throw new IncompatibleOptionsError(["--all", "--only"]);
243
+ }
244
+ this.all = all;
245
+ return this;
246
+ }
247
+
248
+ /**
249
+ * Whether --all mode is enabled.
250
+ */
251
+ isAll(): boolean {
252
+ return this.all;
253
+ }
254
+
255
+ /**
256
+ * Set a custom working tree iterator.
257
+ *
258
+ * Required when using setAll(true) if the store doesn't have
259
+ * a built-in working tree.
260
+ *
261
+ * @param iterator Custom working tree iterator
262
+ * @returns this for chaining
263
+ */
264
+ setWorktree(iterator: Worktree): this {
265
+ this.checkCallable();
266
+ this.worktreeIterator = iterator;
267
+ return this;
268
+ }
269
+
270
+ /**
271
+ * Execute the commit.
272
+ *
273
+ * @returns The created commit with its ID
274
+ * @throws NoMessageError if message is not set and not amending
275
+ * @throws UnmergedPathsError if there are unresolved conflicts
276
+ * @throws EmptyCommitError if nothing to commit and allowEmpty is false
277
+ */
278
+ async call(): Promise<CommitResult> {
279
+ this.checkCallable();
280
+
281
+ // Handle --all flag: auto-stage modified tracked files
282
+ if (this.all) {
283
+ await this.stageTrackedChanges();
284
+ }
285
+
286
+ // Check message
287
+ if (!this.message && !this.amend) {
288
+ throw new NoMessageError();
289
+ }
290
+
291
+ // Check for conflicts
292
+ if (await this.staging.hasConflicts()) {
293
+ const conflictPaths = await this.staging.getConflictedPaths();
294
+ throw new UnmergedPathsError(conflictPaths);
295
+ }
296
+
297
+ // Get message (from amend or new)
298
+ let finalMessage = this.message;
299
+ let previousCommit: Commit | undefined;
300
+
301
+ if (this.amend) {
302
+ const headId = await this.resolveHead();
303
+ previousCommit = await this.commits.load(headId);
304
+ if (!previousCommit) {
305
+ throw new NoHeadError("Cannot amend: HEAD commit not found");
306
+ }
307
+ if (!finalMessage) {
308
+ finalMessage = previousCommit.message;
309
+ }
310
+ }
311
+
312
+ if (!finalMessage) {
313
+ throw new NoMessageError();
314
+ }
315
+
316
+ // Determine author and committer
317
+ const defaultIdent: PersonIdent = {
318
+ name: "Unknown",
319
+ email: "unknown@example.com",
320
+ timestamp: Math.floor(Date.now() / 1000),
321
+ tzOffset: getTimezoneOffset(),
322
+ };
323
+
324
+ let author = this.author;
325
+ let committer = this.committer;
326
+
327
+ if (this.amend && previousCommit) {
328
+ // Keep original author when amending unless explicitly set
329
+ if (!author) {
330
+ author = previousCommit.author;
331
+ }
332
+ }
333
+
334
+ if (!author) {
335
+ author = committer ?? defaultIdent;
336
+ }
337
+ if (!committer) {
338
+ committer = author;
339
+ }
340
+
341
+ // Determine parents
342
+ let parents: ObjectId[];
343
+ if (this.parents.length > 0) {
344
+ parents = this.parents;
345
+ } else if (this.amend) {
346
+ // Use amended commit's parents
347
+ const headId = await this.resolveHead();
348
+ const headCommit = await this.commits.load(headId);
349
+ if (!headCommit) {
350
+ throw new NoHeadError("Cannot amend: HEAD commit not found");
351
+ }
352
+ parents = headCommit.parents;
353
+ } else {
354
+ // Normal commit - HEAD as parent (if exists)
355
+ try {
356
+ const headId = await this.resolveHead();
357
+ parents = [headId];
358
+ } catch {
359
+ // Initial commit
360
+ parents = [];
361
+ }
362
+ }
363
+
364
+ // Generate tree from staging area
365
+ let treeId: ObjectId;
366
+
367
+ if (this.onlyPaths.length > 0 && parents.length > 0) {
368
+ // --only mode: combine parent tree with specified paths from staging
369
+ treeId = await this.buildOnlyTree(parents[0]);
370
+ } else {
371
+ // Normal mode: use full staging area
372
+ treeId = await this.staging.writeTree(this.trees);
373
+ }
374
+
375
+ // Check for empty commit
376
+ if (!this.allowEmpty && parents.length > 0) {
377
+ const parentCommit = await this.commits.load(parents[0]);
378
+ if (parentCommit && parentCommit.tree === treeId) {
379
+ throw new EmptyCommitError();
380
+ }
381
+ }
382
+
383
+ // Create commit
384
+ const commit: Commit = {
385
+ tree: treeId,
386
+ parents,
387
+ author,
388
+ committer,
389
+ message: finalMessage,
390
+ };
391
+
392
+ const commitId = await this.commits.store(commit);
393
+
394
+ // Update HEAD/branch ref
395
+ const head = await this.refsStore.get("HEAD");
396
+ if (head && isSymbolicRef(head)) {
397
+ // HEAD points to a branch - update the branch
398
+ await this.refsStore.set(head.target, commitId);
399
+ } else {
400
+ // Detached HEAD - update HEAD directly
401
+ await this.refsStore.set("HEAD", commitId);
402
+ }
403
+
404
+ this.setCallable(false);
405
+
406
+ // Return commit with its ID (like JGit's RevCommit)
407
+ return { ...commit, id: commitId };
408
+ }
409
+
410
+ /**
411
+ * Build tree for --only mode.
412
+ *
413
+ * Combines parent tree with specified paths from staging area.
414
+ *
415
+ * @param parentCommitId Parent commit ID
416
+ * @returns Tree ObjectId
417
+ */
418
+ private async buildOnlyTree(parentCommitId: ObjectId): Promise<ObjectId> {
419
+ const parentCommit = await this.commits.load(parentCommitId);
420
+ if (!parentCommit) {
421
+ throw new RefNotFoundError(parentCommitId, "Parent commit not found");
422
+ }
423
+
424
+ // Collect staging entries for onlyPaths
425
+ const onlyPathSet = new Set(this.onlyPaths);
426
+ const stagingEntriesMap = new Map<string, { objectId: ObjectId; mode: number }>();
427
+
428
+ for await (const entry of this.staging.entries()) {
429
+ if (onlyPathSet.has(entry.path) && entry.stage === 0) {
430
+ stagingEntriesMap.set(entry.path, {
431
+ objectId: entry.objectId,
432
+ mode: entry.mode,
433
+ });
434
+ }
435
+ }
436
+
437
+ // Create builder and populate with filtered tree
438
+ const builder = this.staging.createBuilder();
439
+
440
+ // Walk parent tree and add entries NOT in onlyPaths
441
+ await this.addTreeFiltered(builder, parentCommit.tree, "", onlyPathSet);
442
+
443
+ // Add staging entries for onlyPaths
444
+ for (const [path, { objectId, mode }] of stagingEntriesMap) {
445
+ builder.add({
446
+ path,
447
+ mode,
448
+ objectId,
449
+ size: 0,
450
+ mtime: Date.now(),
451
+ });
452
+ }
453
+
454
+ await builder.finish();
455
+
456
+ // Now write tree from staging
457
+ return await this.staging.writeTree(this.trees);
458
+ }
459
+
460
+ /**
461
+ * Recursively walk tree and add entries to builder, excluding specified paths.
462
+ */
463
+ private async addTreeFiltered(
464
+ builder: ReturnType<typeof this.staging.createBuilder>,
465
+ treeId: ObjectId,
466
+ prefix: string,
467
+ excludePaths: Set<string>,
468
+ ): Promise<void> {
469
+ for await (const entry of this.trees.loadTree(treeId)) {
470
+ const fullPath = prefix ? `${prefix}/${entry.name}` : entry.name;
471
+
472
+ // Check if this is a tree (directory)
473
+ const isTree = (entry.mode & 0o170000) === 0o040000;
474
+
475
+ if (isTree) {
476
+ // Recursively process subtree
477
+ await this.addTreeFiltered(builder, entry.id, fullPath, excludePaths);
478
+ } else {
479
+ // Only add if not in excluded paths
480
+ if (!excludePaths.has(fullPath)) {
481
+ builder.add({
482
+ path: fullPath,
483
+ mode: entry.mode,
484
+ objectId: entry.id,
485
+ size: 0,
486
+ mtime: Date.now(),
487
+ });
488
+ }
489
+ }
490
+ }
491
+ }
492
+
493
+ /**
494
+ * Stage all modified/deleted tracked files.
495
+ *
496
+ * Uses AddCommand with setUpdate(true) to stage changes,
497
+ * equivalent to `git add -u .` which JGit does for --all.
498
+ */
499
+ private async stageTrackedChanges(): Promise<void> {
500
+ // Get working tree iterator
501
+ const worktree = this.getWorktreeIterator();
502
+ if (!worktree) {
503
+ throw new StoreNotAvailableError(
504
+ "Worktree",
505
+ "Working tree iterator required for --all mode. " +
506
+ "Ensure WorkingCopy has worktree or call setWorktreeStore().",
507
+ );
508
+ }
509
+
510
+ // Use AddCommand to stage all modified tracked files
511
+ const addCommand = new AddCommand(this._workingCopy);
512
+ addCommand.addFilepattern(".");
513
+ addCommand.setUpdate(true);
514
+ addCommand.setWorktreeStore(worktree);
515
+ await addCommand.call();
516
+ }
517
+
518
+ /**
519
+ * Get working tree iterator from store or explicitly set.
520
+ */
521
+ private getWorktreeIterator(): Worktree | undefined {
522
+ if (this.worktreeIterator) {
523
+ return this.worktreeIterator;
524
+ }
525
+
526
+ // Get worktree from WorkingCopy
527
+ return this.worktreeAccess;
528
+ }
529
+ }