@statewalker/vcs-commands 0.3.2 → 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 +19 -0
  2. package/dist/commands/add-command.d.ts +0 -6
  3. package/dist/commands/add-command.d.ts.map +1 -1
  4. package/dist/commands/blame-command.d.ts +14 -0
  5. package/dist/commands/blame-command.d.ts.map +1 -1
  6. package/dist/commands/branch-command.d.ts.map +1 -1
  7. package/dist/commands/checkout-command.d.ts.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 +13 -12
  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
@@ -1,5 +1,5 @@
1
1
  import type { ObjectId, Ref } from "@statewalker/vcs-core";
2
- import { isSymbolicRef } from "@statewalker/vcs-core";
2
+ import { compareRefNames, isSymbolicRef, isValidBranchName } from "@statewalker/vcs-core";
3
3
 
4
4
  import {
5
5
  CannotDeleteCurrentBranchError,
@@ -11,57 +11,6 @@ import {
11
11
  import { GitCommand } from "../git-command.js";
12
12
  import { ListBranchMode } from "../types.js";
13
13
 
14
- /**
15
- * Validate a branch name according to Git rules.
16
- *
17
- * @param name Branch name to validate
18
- * @returns true if valid
19
- */
20
- function isValidBranchName(name: string): boolean {
21
- // Cannot be empty
22
- if (!name || name.length === 0) {
23
- return false;
24
- }
25
-
26
- // Cannot start or end with /
27
- if (name.startsWith("/") || name.endsWith("/")) {
28
- return false;
29
- }
30
-
31
- // Cannot contain ..
32
- if (name.includes("..")) {
33
- return false;
34
- }
35
-
36
- // Cannot contain special characters (control chars, space, ~^:?*[\)
37
- // biome-ignore lint/suspicious/noControlCharactersInRegex: Git ref validation requires checking for control characters
38
- if (/[\x00-\x1f\x7f ~^:?*[\\]/.test(name)) {
39
- return false;
40
- }
41
-
42
- // Cannot end with .lock
43
- if (name.endsWith(".lock")) {
44
- return false;
45
- }
46
-
47
- // Cannot start with -
48
- if (name.startsWith("-")) {
49
- return false;
50
- }
51
-
52
- // Cannot be @
53
- if (name === "@") {
54
- return false;
55
- }
56
-
57
- // Cannot contain @{
58
- if (name.includes("@{")) {
59
- return false;
60
- }
61
-
62
- return true;
63
- }
64
-
65
14
  /**
66
15
  * Create a new branch.
67
16
  *
@@ -372,7 +321,7 @@ export class ListBranchCommand extends GitCommand<Ref[]> {
372
321
  }
373
322
 
374
323
  // Sort by name
375
- branches.sort((a, b) => a.name.localeCompare(b.name));
324
+ branches.sort((a, b) => compareRefNames(a.name, b.name));
376
325
 
377
326
  return branches;
378
327
  }
@@ -33,10 +33,11 @@
33
33
  * ```
34
34
  */
35
35
 
36
- import { FileMode, type ObjectId, type Ref } from "@statewalker/vcs-core";
36
+ import { FileMode, isValidBranchName, type ObjectId, type Ref } from "@statewalker/vcs-core";
37
37
  import { UpdateStagingEntry } from "@statewalker/vcs-working-tree";
38
38
 
39
39
  import {
40
+ InvalidRefNameError,
40
41
  MissingArgumentError,
41
42
  NotADirectoryError,
42
43
  PathNotFoundInTreeError,
@@ -370,6 +371,9 @@ export class CheckoutCommand extends GitCommand<CheckoutResult> {
370
371
 
371
372
  // Create branch if requested
372
373
  if (this.createBranch) {
374
+ if (!isValidBranchName(this.name)) {
375
+ throw new InvalidRefNameError(this.name);
376
+ }
373
377
  const startPointId = this.startPoint
374
378
  ? await this.resolveCommitId(this.startPoint)
375
379
  : await this.resolveCommitId("HEAD");
@@ -486,17 +490,9 @@ export class CheckoutCommand extends GitCommand<CheckoutResult> {
486
490
  await worktree.mkdir(parentDir);
487
491
  }
488
492
 
489
- // Load blob content
490
- const chunks: Uint8Array[] = [];
493
+ // Stream the blob into the file (an empty file when the blob is missing)
491
494
  const blobContent = await this.blobs.load(entry.id);
492
- if (blobContent) {
493
- for await (const chunk of blobContent) {
494
- chunks.push(chunk);
495
- }
496
- }
497
-
498
- // Write file using worktree interface
499
- await worktree.writeContent(relativePath, chunks);
495
+ await worktree.writeContent(relativePath, blobContent ?? []);
500
496
  }
501
497
  }
502
498
  }
@@ -1,3 +1,4 @@
1
+ import { isValidWorktreePath } from "@statewalker/vcs-core";
1
2
  import { GitCommand } from "../git-command.js";
2
3
 
3
4
  /**
@@ -174,6 +175,12 @@ export class CleanCommand extends GitCommand<CleanResult> {
174
175
  continue;
175
176
  }
176
177
 
178
+ // A name that spells `.git` (`.GIT`, `git~1`, …) is refused by the worktree (git's
179
+ // verify_path): leave it in place rather than abort the whole clean on it.
180
+ if (!isValidWorktreePath(entryTyped.path)) {
181
+ continue;
182
+ }
183
+
177
184
  // This file is untracked and should be cleaned
178
185
  const displayPath = entryTyped.isDirectory ? `${entryTyped.path}/` : entryTyped.path;
179
186
  cleaned.add(displayPath);
@@ -1,20 +1,16 @@
1
1
  import type { ObjectId } from "@statewalker/vcs-core";
2
2
  import {
3
- type CloneOptions as TransportCloneOptions,
4
- clone as transportClone,
3
+ createRepositoryFacade,
4
+ createTransportRefStore,
5
+ type RefspecResolver,
6
+ fetch as transportFetch,
5
7
  } from "@statewalker/vcs-transport";
6
- import { bytesToHex } from "@statewalker/vcs-utils/hash/utils";
7
8
 
8
- import { InvalidArgumentError, InvalidRemoteError } from "../errors/index.js";
9
- import { importPackIntoHistory } from "../pack-import/index.js";
9
+ import { InvalidArgumentError, InvalidRemoteError, RefNotFoundError } from "../errors/index.js";
10
10
  import type { CloneResult } from "../results/clone-result.js";
11
- import {
12
- type FetchResult,
13
- RefUpdateStatus,
14
- type TrackingRefUpdate,
15
- } from "../results/fetch-result.js";
11
+ import type { FetchResult, TrackingRefUpdate } from "../results/fetch-result.js";
16
12
  import { TransportCommand } from "../transport-command.js";
17
- import { TagOption } from "./fetch-command.js";
13
+ import { TagOption, toTagMode, toTrackingRefUpdate } from "./fetch-command.js";
18
14
 
19
15
  /**
20
16
  * Clone a remote repository.
@@ -332,93 +328,128 @@ export class CloneCommand extends TransportCommand<CloneResult> {
332
328
  }
333
329
 
334
330
  // Determine clone branch strategy
335
- const branchToClone = this.determineBranchToClone();
331
+ const branchToClone = toBranchName(this.determineBranchToClone());
332
+ const history = this._workingCopy.history;
333
+
334
+ // git clone's refspecs: tracking refs, local heads (bare), every ref (mirror)
335
+ const tracking = (branch: string) =>
336
+ this.bare ? `refs/heads/${branch}` : `refs/remotes/${this.remoteName}/${branch}`;
337
+ // git: a shallow clone is a single-branch clone of the remote HEAD's branch
338
+ const singleBranch =
339
+ !this.mirror &&
340
+ (branchToClone !== undefined ||
341
+ this.depth !== undefined ||
342
+ this.shallowSince !== undefined ||
343
+ this.shallowExcludes.length > 0);
344
+ let detachedTag: string | undefined;
345
+ let refspecs: string[] | RefspecResolver;
346
+ if (this.mirror) {
347
+ refspecs = ["+refs/*:refs/*"];
348
+ } else if (branchToClone !== undefined) {
349
+ // --branch names a branch, or else a tag (checked out as a detached HEAD)
350
+ const b = branchToClone;
351
+ refspecs = {
352
+ prefixes: [`refs/heads/${b}`, `refs/tags/${b}`],
353
+ resolve: (remoteRefs) => {
354
+ if (remoteRefs.some((r) => r.name === `refs/heads/${b}` && r.oid)) {
355
+ return [`+refs/heads/${b}:${tracking(b)}`];
356
+ }
357
+ if (remoteRefs.some((r) => r.name === `refs/tags/${b}` && r.oid)) {
358
+ detachedTag = `refs/tags/${b}`;
359
+ return [`+refs/tags/${b}:refs/tags/${b}`];
360
+ }
361
+ throw new RefNotFoundError(
362
+ `refs/heads/${b}`,
363
+ `Remote branch ${b} not found in upstream ${this.remoteName}`,
364
+ );
365
+ },
366
+ };
367
+ } else if (singleBranch) {
368
+ refspecs = {
369
+ prefixes: ["refs/heads/"],
370
+ resolve: (remoteRefs) => {
371
+ const head = remoteRefs.find((r) => r.name === "HEAD")?.symref;
372
+ const name = toBranchName(head);
373
+ return name && head?.startsWith("refs/heads/")
374
+ ? [`+${head}:${tracking(name)}`]
375
+ : [`+refs/heads/*:${tracking("*")}`];
376
+ },
377
+ };
378
+ } else {
379
+ refspecs = [`+refs/heads/*:${tracking("*")}`];
380
+ }
381
+ // git clone takes every tag, unless one branch is cloned (then tags follow) or --no-tags
382
+ const tags =
383
+ this.tagOption === TagOption.AUTO_FOLLOW && !singleBranch && !this.mirror
384
+ ? "all"
385
+ : toTagMode(this.tagOption);
336
386
 
337
- // Execute clone via transport
338
- const options: TransportCloneOptions = {
387
+ const result = await transportFetch({
339
388
  url: this.uri,
340
- branch: branchToClone,
341
- depth: this.depth,
342
- bare: this.bare,
343
- remoteName: this.remoteName,
344
389
  auth: this.credentials,
345
390
  headers: this.headers,
346
391
  timeout: this.timeout,
347
- onProgress: this.progressCallback,
348
- onProgressMessage: this.progressMessageCallback,
349
- };
350
-
351
- const transportResult = await transportClone(options);
352
-
353
- // Store pack data
354
- if (transportResult.packData.length > 0) {
355
- await this.storePack(transportResult.packData);
356
- }
357
-
358
- // Update refs based on clone mode
359
- const trackingUpdates: TrackingRefUpdate[] = [];
360
- for (const [refName, objectId] of transportResult.refs) {
361
- const objectIdHex = bytesToHex(objectId);
362
-
363
- // Filter refs based on tag option
364
- if (this.shouldSkipRef(refName)) {
365
- continue;
366
- }
367
-
368
- // For mirror mode, refs are stored directly without remotes prefix
369
- const localRefName = this.mirror ? this.toMirrorRefName(refName) : refName;
370
-
371
- await this.refsStore.set(localRefName, objectIdHex);
372
- trackingUpdates.push({
373
- localRef: localRefName,
374
- remoteRef: refName,
375
- newObjectId: objectIdHex,
376
- status: RefUpdateStatus.NEW,
377
- });
378
- }
392
+ repository: createRepositoryFacade({ history }),
393
+ refStore: createTransportRefStore(history.refs),
394
+ refspecs,
395
+ tags,
396
+ depth: this.depth,
397
+ deepenSince: this.shallowSince,
398
+ deepenNot: this.shallowExcludes.length > 0 ? this.shallowExcludes : undefined,
399
+ onProgress: this.progressMessageCallback,
400
+ reflogMessage: `clone: from ${this.uri}`,
401
+ });
402
+ const trackingUpdates: TrackingRefUpdate[] = result.refUpdates.map(toTrackingRefUpdate);
379
403
 
380
404
  // Set up HEAD and default branch.
381
405
  //
382
406
  // Two forms, deliberately kept apart: the advertised form goes out on
383
407
  // FetchResult unchanged (it is what the remote said), while the ref work
384
408
  // below and CloneResult use the bare branch name.
385
- const advertisedDefaultBranch = transportResult.defaultBranch;
386
- const defaultBranch = toBranchName(advertisedDefaultBranch);
409
+ const advertisedDefaultBranch = result.defaultBranch;
410
+ let defaultBranch = branchToClone ?? toBranchName(advertisedDefaultBranch);
387
411
  let headCommit: ObjectId | undefined;
388
412
 
389
- if (defaultBranch && !this.bare) {
390
- // Create local branch from the tip the clone just wrote. Look under the
391
- // remote-tracking name first, then under the local branch name: the ref
392
- // loop above stores each ref under its advertised name, so which of the
393
- // two exists depends on the refspec the remote advertised through.
413
+ if (detachedTag) {
414
+ // git clone --branch <tag>: a detached HEAD at the tag's commit
415
+ defaultBranch = toBranchName(advertisedDefaultBranch);
416
+ const tag = await this.refsStore.resolve(detachedTag);
417
+ let id = tag?.objectId;
418
+ for (let i = 0; id && i < 16; i++) {
419
+ const target = await history.tags.getTarget(id);
420
+ if (!target || !(await history.tags.has(id))) break;
421
+ id = target;
422
+ }
423
+ if (id) {
424
+ await this.refsStore.set("HEAD", id);
425
+ headCommit = id;
426
+ if (!this.bare && !this.noCheckout) await this.checkoutHead(id);
427
+ }
428
+ } else if (defaultBranch && !this.bare) {
429
+ // The local branch starts at the tracking ref the clone just wrote
394
430
  const localRef = `refs/heads/${defaultBranch}`;
395
- const tip =
396
- (await this.refsStore.resolve(`refs/remotes/${this.remoteName}/${defaultBranch}`)) ??
397
- (await this.refsStore.resolve(localRef));
398
-
431
+ const tip = await this.refsStore.resolve(`refs/remotes/${this.remoteName}/${defaultBranch}`);
399
432
  if (tip?.objectId) {
400
433
  await this.refsStore.set(localRef, tip.objectId);
401
434
  headCommit = tip.objectId;
402
-
403
- // Set HEAD to point to local branch
404
- await this.refsStore.setSymbolic("HEAD", localRef);
405
-
406
- // Set up staging area from HEAD tree
407
435
  if (!this.noCheckout) {
408
436
  await this.checkoutHead(tip.objectId);
409
437
  }
410
438
  }
439
+ // HEAD names the default branch, born or not (an empty remote's unborn HEAD)
440
+ await this.refsStore.setSymbolic("HEAD", localRef);
411
441
  } else if (this.bare || this.mirror) {
412
442
  // For bare/mirror repos, HEAD points to default branch
413
443
  if (defaultBranch) {
414
444
  await this.refsStore.setSymbolic("HEAD", `refs/heads/${defaultBranch}`);
445
+ headCommit = (await this.refsStore.resolve("HEAD"))?.objectId;
415
446
  }
416
447
  }
417
448
 
418
449
  // Build fetch result
419
450
  const advertisedRefs = new Map<string, ObjectId>();
420
- for (const [refName, objectId] of transportResult.refs) {
421
- advertisedRefs.set(refName, bytesToHex(objectId));
451
+ for (const ref of result.remoteRefs) {
452
+ if (ref.oid) advertisedRefs.set(ref.name, ref.oid);
422
453
  }
423
454
 
424
455
  const fetchResult: FetchResult = {
@@ -426,8 +457,8 @@ export class CloneCommand extends TransportCommand<CloneResult> {
426
457
  advertisedRefs,
427
458
  trackingRefUpdates: trackingUpdates,
428
459
  defaultBranch: advertisedDefaultBranch,
429
- bytesReceived: transportResult.bytesReceived,
430
- isEmpty: transportResult.isEmpty,
460
+ bytesReceived: result.packBytes,
461
+ isEmpty: result.isEmpty,
431
462
  messages: [],
432
463
  };
433
464
 
@@ -456,50 +487,12 @@ export class CloneCommand extends TransportCommand<CloneResult> {
456
487
 
457
488
  // If specific branches are set, use the first one
458
489
  if (this.branchesToClone.length > 0) {
459
- // Extract branch name from full ref if provided
460
- const first = this.branchesToClone[0];
461
- if (first.startsWith("refs/heads/")) {
462
- return first.slice("refs/heads/".length);
463
- }
464
- return first;
490
+ return this.branchesToClone[0];
465
491
  }
466
492
 
467
493
  return undefined;
468
494
  }
469
495
 
470
- /**
471
- * Check if a ref should be skipped based on tag option.
472
- */
473
- private shouldSkipRef(refName: string): boolean {
474
- // Skip tags if NO_TAGS option is set
475
- if (this.tagOption === TagOption.NO_TAGS && refName.startsWith("refs/tags/")) {
476
- return true;
477
- }
478
- return false;
479
- }
480
-
481
- /**
482
- * Convert a remote ref name to mirror ref name.
483
- */
484
- private toMirrorRefName(refName: string): string {
485
- // For mirror clones, refs/remotes/origin/* becomes refs/heads/*
486
- const remotePrefix = `refs/remotes/${this.remoteName}/`;
487
- if (refName.startsWith(remotePrefix)) {
488
- return `refs/heads/${refName.slice(remotePrefix.length)}`;
489
- }
490
- return refName;
491
- }
492
-
493
- /**
494
- * Store received pack data.
495
- *
496
- * Unpacks the pack into the working copy's history, so the objects the
497
- * cloned refs point at are actually available locally.
498
- */
499
- private async storePack(packData: Uint8Array): Promise<void> {
500
- await importPackIntoHistory(this._workingCopy.history, packData);
501
- }
502
-
503
496
  /**
504
497
  * Checkout HEAD commit to staging area.
505
498
  */