@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
@@ -3,15 +3,19 @@ import type { ObjectId } from "@statewalker/vcs-core";
3
3
  // (dist/index.js); its subpaths resolve for types but not at runtime.
4
4
  import { isSymbolicRef } from "@statewalker/vcs-core";
5
5
  import {
6
- expandFromSource,
6
+ createRepositoryFacade,
7
+ createTransportRefStore,
8
+ expandFromDestination,
9
+ type FetchRefUpdate,
10
+ matchDestination,
7
11
  matchSource,
8
12
  parseRefSpec,
9
13
  type RefSpec,
14
+ type TagMode,
10
15
  fetch as transportFetch,
11
16
  } from "@statewalker/vcs-transport";
12
17
 
13
18
  import { InvalidArgumentError, InvalidRemoteError } from "../errors/index.js";
14
- import { importPackIntoHistory } from "../pack-import/index.js";
15
19
  import { RemoteConfigStore } from "../remote-config/index.js";
16
20
  import {
17
21
  type FetchResult,
@@ -71,7 +75,6 @@ export class FetchCommand extends TransportCommand<FetchResult> {
71
75
  private remote = "origin";
72
76
  private refSpecs: string[] = [];
73
77
  private removeDeletedRefs = false;
74
- // biome-ignore lint/correctness/noUnusedPrivateClassMembers: Set by setTagOpt(), to be used in call()
75
78
  private tagOption: TagOption = TagOption.AUTO_FOLLOW;
76
79
  private thin = true;
77
80
  private depth?: number;
@@ -334,6 +337,12 @@ export class FetchCommand extends TransportCommand<FetchResult> {
334
337
  /**
335
338
  * Execute the fetch operation.
336
339
  *
340
+ * Runs the transport's fetch client (git's fetch-pack): the local refs are offered as
341
+ * haves, so only the objects the working copy lacks are downloaded; shallow options and
342
+ * the shallow file are honoured; tags follow the tag option; each tracking ref is
343
+ * updated when it fast-forwards or its refspec (or {@link setForceUpdate}) forces it, and
344
+ * rejected otherwise.
345
+ *
337
346
  * @returns Fetch result with updated refs
338
347
  * @throws InvalidRemoteError if remote cannot be resolved
339
348
  */
@@ -347,114 +356,58 @@ export class FetchCommand extends TransportCommand<FetchResult> {
347
356
  throw new InvalidRemoteError(this.remote);
348
357
  }
349
358
 
350
- // Parse refspecs for source→destination mapping
351
- const parsedSpecs = this.effectiveRefSpecs().map((s) => parseRefSpec(s));
352
-
353
- // Save old ref values before fetch for status computation
354
- const oldRefValues = new Map<string, string | undefined>();
355
- for await (const ref of this.refsStore.list()) {
356
- if (!isSymbolicRef(ref) && ref.objectId) {
357
- oldRefValues.set(ref.name, ref.objectId);
358
- }
359
- }
359
+ // git: without a refspec the remote's HEAD is fetched, and no ref is written (nor any
360
+ // tag); explicit refspecs must name refs the remote has, configured ones may not
361
+ const fromConfig = this.refSpecs.length === 0;
362
+ const configured = this.effectiveRefSpecs();
363
+ const refspecs = configured.length > 0 ? configured : ["HEAD"];
364
+ const history = this._workingCopy.history;
360
365
 
361
- // Execute fetch using high-level fetch API
362
- const transportResult = await transportFetch({
366
+ const result = await transportFetch({
363
367
  url: remoteUrl,
364
368
  auth: this.credentials,
365
369
  headers: this.headers,
366
370
  timeout: this.timeout,
371
+ repository: createRepositoryFacade({ history }),
372
+ refStore: createTransportRefStore(history.refs),
373
+ refspecs,
374
+ missingRefsOk: fromConfig && configured.length > 0,
375
+ tags: toTagMode(this.tagOption),
367
376
  depth: this.depth,
368
- onProgressMessage: this.progressMessageCallback,
377
+ deepenSince: this.shallowSince,
378
+ deepenNot: this.shallowExcludes.length > 0 ? this.shallowExcludes : undefined,
379
+ unshallow: this.unshallow || undefined,
380
+ force: this.forceUpdate,
381
+ dryRun: this.dryRun,
382
+ onProgress: this.progressMessageCallback,
383
+ reflogMessage: `fetch: ${remoteUrl}`,
369
384
  });
370
385
 
371
- // Convert refs from Uint8Array to hex strings
372
- const bytesToHex = (bytes: Uint8Array): string =>
373
- Array.from(bytes)
374
- .map((b) => b.toString(16).padStart(2, "0"))
375
- .join("");
376
-
377
386
  const advertisedRefs = new Map<string, ObjectId>();
378
- for (const [refName, objectId] of transportResult.refs) {
379
- advertisedRefs.set(refName, bytesToHex(objectId));
380
- }
381
-
382
- // Build tracking ref updates by mapping server refs through refspecs
383
- const trackingUpdates: TrackingRefUpdate[] = [];
384
- for (const [serverRefName, objectIdBytes] of transportResult.refs) {
385
- const objectId = bytesToHex(objectIdBytes);
386
-
387
- // Map server ref name to local ref name via refspecs
388
- const localRefName = this.mapServerRef(serverRefName, parsedSpecs);
389
- if (!localRefName) continue;
390
-
391
- const isForce = this.forceUpdate || this.isRefSpecForced(serverRefName, parsedSpecs);
392
- const update = await this.computeRefUpdate(
393
- localRefName,
394
- serverRefName,
395
- objectId,
396
- oldRefValues,
397
- isForce,
398
- );
399
-
400
- // Write the mapped ref to local store (unless dry-run)
401
- if (!this.dryRun) {
402
- await this.refsStore.set(localRefName, objectId);
403
- }
404
-
405
- trackingUpdates.push(update);
387
+ for (const ref of result.remoteRefs) {
388
+ if (ref.oid) advertisedRefs.set(ref.name, ref.oid);
406
389
  }
390
+ const trackingUpdates = result.refUpdates.map(toTrackingRefUpdate);
407
391
 
408
392
  // Handle prune
409
393
  if (!this.dryRun && this.removeDeletedRefs) {
410
- const pruned = await this.pruneDeletedRefs(transportResult.refs);
411
- trackingUpdates.push(...pruned);
412
- }
413
-
414
- // Store pack data
415
- if (transportResult.packData.length > 0 && !this.dryRun) {
416
- await this.storePack(transportResult.packData);
394
+ const parsed = refspecs.map((s) => parseRefSpec(s));
395
+ trackingUpdates.push(
396
+ ...(await this.pruneDeletedRefs(new Set(advertisedRefs.keys()), parsed)),
397
+ );
417
398
  }
418
399
 
419
400
  return {
420
401
  uri: remoteUrl,
421
402
  advertisedRefs,
422
403
  trackingRefUpdates: trackingUpdates,
423
- defaultBranch: transportResult.defaultBranch,
424
- bytesReceived: transportResult.bytesReceived,
425
- isEmpty: transportResult.isEmpty,
404
+ defaultBranch: result.defaultBranch,
405
+ bytesReceived: result.packBytes,
406
+ isEmpty: result.isEmpty,
426
407
  messages: [],
427
408
  };
428
409
  }
429
410
 
430
- /**
431
- * Map a server ref name to a local ref name using parsed refspecs.
432
- * Returns undefined if no refspec matches.
433
- */
434
- private mapServerRef(serverRef: string, specs: RefSpec[]): string | undefined {
435
- for (const spec of specs) {
436
- if (spec.negative) continue;
437
- if (!spec.source || !spec.destination) continue;
438
- if (!matchSource(spec, serverRef)) continue;
439
-
440
- const expanded = expandFromSource(spec, serverRef);
441
- return expanded.destination ?? undefined;
442
- }
443
- return undefined;
444
- }
445
-
446
- /**
447
- * Check if any matching refspec has the force flag for a given server ref.
448
- */
449
- private isRefSpecForced(serverRef: string, specs: RefSpec[]): boolean {
450
- for (const spec of specs) {
451
- if (spec.negative) continue;
452
- if (!spec.source) continue;
453
- if (matchSource(spec, serverRef) && spec.force) return true;
454
- }
455
- return false;
456
- }
457
-
458
411
  /**
459
412
  * The refspecs this fetch runs with.
460
413
  *
@@ -486,130 +439,83 @@ export class FetchCommand extends TransportCommand<FetchResult> {
486
439
  }
487
440
 
488
441
  /**
489
- * Compute ref update status using pre-fetch ref values.
490
- *
491
- * Uses saved pre-fetch values to correctly determine
492
- * NEW vs NO_CHANGE vs FAST_FORWARD status.
493
- */
494
- private async computeRefUpdate(
495
- localRef: string,
496
- remoteRef: string,
497
- newObjectId: ObjectId,
498
- oldRefValues: Map<string, string | undefined>,
499
- force: boolean,
500
- ): Promise<TrackingRefUpdate> {
501
- const oldObjectId = oldRefValues.get(localRef);
502
-
503
- let status: RefUpdateStatus;
504
- if (!oldObjectId) {
505
- status = RefUpdateStatus.NEW;
506
- } else if (oldObjectId === newObjectId) {
507
- status = RefUpdateStatus.NO_CHANGE;
508
- } else if (force) {
509
- status = RefUpdateStatus.FORCED;
510
- } else {
511
- // Check if fast-forward
512
- const isAncestor = await this.isAncestor(oldObjectId, newObjectId);
513
- status = isAncestor ? RefUpdateStatus.FAST_FORWARD : RefUpdateStatus.REJECTED;
514
- }
515
-
516
- return {
517
- localRef,
518
- remoteRef,
519
- oldObjectId,
520
- newObjectId,
521
- status,
522
- };
523
- }
524
-
525
- /**
526
- * Check if one commit is an ancestor of another.
527
- */
528
- private async isAncestor(ancestor: ObjectId, descendant: ObjectId): Promise<boolean> {
529
- // Walk from descendant back to see if we hit ancestor
530
- const visited = new Set<ObjectId>();
531
- const queue: ObjectId[] = [descendant];
532
-
533
- while (queue.length > 0) {
534
- const current = queue.shift();
535
- if (current === undefined) break;
536
- if (current === ancestor) {
537
- return true;
538
- }
539
- if (visited.has(current)) {
540
- continue;
541
- }
542
- visited.add(current);
543
-
544
- try {
545
- const commit = await this.commits.load(current);
546
- if (commit) {
547
- queue.push(...commit.parents);
548
- }
549
- } catch {
550
- // Commit not found, skip
551
- }
552
-
553
- // Limit walk depth for performance
554
- if (visited.size > 10000) {
555
- break;
556
- }
557
- }
558
-
559
- return false;
560
- }
561
-
562
- /**
563
- * Prune refs that no longer exist on remote.
442
+ * Prune local refs that a refspec maps from a remote ref that no longer exists (git's
443
+ * `--prune`): for each refspec with a destination, the local refs matching the
444
+ * destination whose source is not among the remote refs are deleted, unless a negative
445
+ * refspec excludes that source (git's query_matches_negative_refspec).
564
446
  */
565
447
  private async pruneDeletedRefs(
566
- remoteRefs: Map<string, Uint8Array>,
448
+ remoteRefNames: Set<string>,
449
+ specs: RefSpec[],
567
450
  ): Promise<TrackingRefUpdate[]> {
568
451
  const updates: TrackingRefUpdate[] = [];
569
- const prefix = `refs/remotes/${this.remote}/`;
570
-
571
- // Get remote ref names for comparison
572
- const remoteRefNames = new Set<string>();
573
- for (const refName of remoteRefs.keys()) {
574
- remoteRefNames.add(refName);
575
- }
576
-
577
- // Find local tracking refs that don't exist on remote
578
- for await (const ref of this.refsStore.list(prefix)) {
579
- // Skip symbolic refs
580
- if (isSymbolicRef(ref)) {
581
- continue;
582
- }
583
-
584
- // Derive remote ref name
585
- const localName = ref.name.slice(prefix.length);
586
- const remoteRefName = `refs/heads/${localName}`;
587
-
588
- if (!remoteRefNames.has(ref.name) && !remoteRefNames.has(remoteRefName)) {
589
- // Delete the local tracking ref
452
+ const done = new Set<string>();
453
+ const negative = specs.filter((s) => s.negative && s.source);
454
+ for (const spec of specs) {
455
+ if (spec.negative || !spec.source || !spec.destination) continue;
456
+ const prefix = spec.wildcard
457
+ ? spec.destination.slice(0, spec.destination.indexOf("*"))
458
+ : spec.destination;
459
+ for await (const ref of this.refsStore.list(prefix)) {
460
+ if (isSymbolicRef(ref) || done.has(ref.name)) continue;
461
+ let source: string | null;
462
+ if (spec.wildcard) {
463
+ if (!matchDestination(spec, ref.name)) continue;
464
+ source = expandFromDestination(spec, ref.name).source;
465
+ } else {
466
+ if (ref.name !== spec.destination) continue;
467
+ source = spec.source;
468
+ }
469
+ if (!source || remoteRefNames.has(source)) continue;
470
+ if (negative.some((n) => matchSource(n, source))) continue;
471
+ done.add(ref.name);
590
472
  await this.refsStore.delete(ref.name);
591
473
  updates.push({
592
474
  localRef: ref.name,
593
- remoteRef: remoteRefName,
475
+ remoteRef: source,
594
476
  oldObjectId: ref.objectId,
595
477
  newObjectId: "", // Empty indicates deletion
596
478
  status: RefUpdateStatus.DELETED,
597
479
  });
598
480
  }
599
481
  }
600
-
601
482
  return updates;
602
483
  }
484
+ }
603
485
 
604
- /**
605
- * Store received pack data.
606
- *
607
- * Unpacks the pack into the working copy's history, so the objects the
608
- * freshly written tracking refs point at are actually available locally.
609
- * Import is idempotent: the stores are content-addressed, so re-importing
610
- * a pack rewrites the same object IDs.
611
- */
612
- private async storePack(packData: Uint8Array): Promise<void> {
613
- await importPackIntoHistory(this._workingCopy.history, packData);
486
+ /** The transport's tag mode for a {@link TagOption}. */
487
+ export function toTagMode(option: TagOption): TagMode {
488
+ switch (option) {
489
+ case TagOption.FETCH_TAGS:
490
+ return "all";
491
+ case TagOption.NO_TAGS:
492
+ return "none";
493
+ default:
494
+ return "auto";
614
495
  }
615
496
  }
497
+
498
+ /** A transport ref update as a {@link TrackingRefUpdate}. */
499
+ export function toTrackingRefUpdate(update: FetchRefUpdate): TrackingRefUpdate {
500
+ const status =
501
+ update.status === "new"
502
+ ? RefUpdateStatus.NEW
503
+ : update.status === "up-to-date"
504
+ ? RefUpdateStatus.NO_CHANGE
505
+ : update.status === "fast-forward"
506
+ ? RefUpdateStatus.FAST_FORWARD
507
+ : update.status === "forced"
508
+ ? RefUpdateStatus.FORCED
509
+ : update.reason === "non-fast-forward" || update.reason === "would clobber existing tag"
510
+ ? RefUpdateStatus.REJECTED
511
+ : RefUpdateStatus.LOCK_FAILURE;
512
+ return {
513
+ localRef: update.localRef,
514
+ remoteRef: update.remoteRef,
515
+ oldObjectId: update.oldOid,
516
+ newObjectId: update.newOid,
517
+ status,
518
+ summary: update.summary,
519
+ reason: update.reason,
520
+ };
521
+ }
@@ -123,7 +123,7 @@ export class GarbageCollectCommand extends GitCommand<GCCommandResult> {
123
123
 
124
124
  // Run garbage collection if GCController is available
125
125
  // Note: This requires access to the Repository's gc property
126
- // For now, we'll check if the RefStore supports the gc operations
126
+ // For now, we'll check if the ref store supports the gc operations
127
127
 
128
128
  // Check if refs support packRefs
129
129
  if (this._packRefs && this.refsStore.packRefs) {
@@ -1,5 +1,14 @@
1
- import { createInMemoryFilesApi, createMemoryHistory, type FilesApi } from "@statewalker/vcs-core";
2
- import { createFileWorktree } from "@statewalker/vcs-store-files";
1
+ import {
2
+ createInMemoryFilesApi,
3
+ createMemoryHistory,
4
+ type FilesApi,
5
+ type History,
6
+ } from "@statewalker/vcs-core";
7
+ import {
8
+ createFileWorktree,
9
+ createGitFilesHistoryFromFiles,
10
+ FileStagingStore,
11
+ } from "@statewalker/vcs-store-files";
3
12
  import { MemoryStagingStore } from "@statewalker/vcs-store-mem";
4
13
  import {
5
14
  createMemoryCheckout,
@@ -219,15 +228,57 @@ export class InitCommand {
219
228
  // Determine git directory
220
229
  const gitDir = this.resolveGitDir();
221
230
 
222
- // Create the history (repository)
223
- const history = createMemoryHistory();
224
- await history.initialize();
225
-
226
- // Set initial branch by creating symbolic ref for HEAD
227
- await history.refs.setSymbolic("HEAD", `refs/heads/${this.initialBranch}`);
228
-
229
- // Create staging store (use provided or default to MemoryStagingStore)
230
- const staging = this.stagingStore ?? new MemoryStagingStore();
231
+ // Create the history (repository). With a FilesApi it lives in `gitDir` on those files,
232
+ // in git's layout, so it survives a reload and native git can read it; like `git init`
233
+ // on an existing repository, a second init keeps its HEAD, config and objects. Without
234
+ // one it stays in memory.
235
+ let history: History;
236
+ let staging: Staging;
237
+ if (this.files) {
238
+ const dir = gitDir.replace(/\/+$/, "") || ".";
239
+ const isFile = async (path: string) => (await files.stats(path))?.kind === "file";
240
+ const hasHead = await isFile(`${dir}/HEAD`);
241
+ // A repository with a config but no HEAD (damaged or half-made) is opened, not
242
+ // re-created: creating rewrites the config, and its remotes and settings with it.
243
+ const fresh = !hasHead && !(await isFile(`${dir}/config`));
244
+ const open = (create: boolean) =>
245
+ createGitFilesHistoryFromFiles({
246
+ files,
247
+ gitDir,
248
+ create,
249
+ defaultBranch: this.initialBranch,
250
+ });
251
+ if (fresh && this.bare && dir !== ".") {
252
+ // The directory layout writes `core.bare = true` only for a gitDir of "."; set it
253
+ // before opening, so what reads the config (reflog defaults) sees a bare repository.
254
+ await open(true);
255
+ await markBare(files, `${dir}/config`);
256
+ history = await open(false);
257
+ } else {
258
+ history = await open(fresh);
259
+ }
260
+ await history.initialize();
261
+ if (!hasHead && !fresh) {
262
+ await history.refs.setSymbolic("HEAD", `refs/heads/${this.initialBranch}`);
263
+ }
264
+ // The index lives in the repository too: a reopened repository keeps what was staged
265
+ // (its last commit's files), so the next commit does not drop them.
266
+ if (this.stagingStore) {
267
+ staging = this.stagingStore;
268
+ } else if (this.bare) {
269
+ staging = new MemoryStagingStore();
270
+ } else {
271
+ const fileStaging = new FileStagingStore(files, `${dir}/index`);
272
+ await fileStaging.read();
273
+ staging = fileStaging;
274
+ }
275
+ } else {
276
+ history = createMemoryHistory();
277
+ await history.initialize();
278
+ // Set initial branch by creating symbolic ref for HEAD
279
+ await history.refs.setSymbolic("HEAD", `refs/heads/${this.initialBranch}`);
280
+ staging = this.stagingStore ?? new MemoryStagingStore();
281
+ }
231
282
 
232
283
  // Create worktree if enabled and not bare
233
284
  let worktree: Worktree | undefined;
@@ -363,3 +414,24 @@ export class InitCommand {
363
414
  this.callable = value;
364
415
  }
365
416
  }
417
+
418
+ /** Sets `core.bare = true` in a config file written by the git directory layout. */
419
+ async function markBare(files: FilesApi, configPath: string): Promise<void> {
420
+ const chunks: Uint8Array[] = [];
421
+ for await (const chunk of files.read(configPath)) chunks.push(chunk);
422
+ const text = new TextDecoder().decode(concatChunks(chunks));
423
+ const updated = /^\s*bare\s*=/m.test(text)
424
+ ? text.replace(/^(\s*bare\s*=\s*)\S+/m, "$1true")
425
+ : text.replace(/^\[core\]\s*$/m, "[core]\n\tbare = true");
426
+ await files.write(configPath, [new TextEncoder().encode(updated)]);
427
+ }
428
+
429
+ function concatChunks(chunks: Uint8Array[]): Uint8Array {
430
+ const out = new Uint8Array(chunks.reduce((n, c) => n + c.length, 0));
431
+ let offset = 0;
432
+ for (const c of chunks) {
433
+ out.set(c, offset);
434
+ offset += c.length;
435
+ }
436
+ return out;
437
+ }
@@ -1,5 +1,10 @@
1
1
  import type { Commit, ObjectId, TreeEntry } from "@statewalker/vcs-core";
2
- import { FileMode, isSymbolicRef } from "@statewalker/vcs-core";
2
+ import {
3
+ DEFAULT_BIG_FILE_THRESHOLD,
4
+ FileMode,
5
+ isSymbolicRef,
6
+ probeBlob,
7
+ } from "@statewalker/vcs-core";
3
8
  import {
4
9
  merge3Way,
5
10
  MergeContentStrategy as UtilsMergeContentStrategy,
@@ -68,6 +73,7 @@ export class MergeCommand extends GitCommand<MergeResult> {
68
73
  private squash = false;
69
74
  private commit = true;
70
75
  private message?: string;
76
+ private bigFileThreshold = DEFAULT_BIG_FILE_THRESHOLD;
71
77
 
72
78
  /**
73
79
  * Add a commit/branch to merge.
@@ -129,6 +135,22 @@ export class MergeCommand extends GitCommand<MergeResult> {
129
135
  return this;
130
136
  }
131
137
 
138
+ /**
139
+ * Set the size above which files are binary to the content merge (git's
140
+ * `core.bigFileThreshold`, default 50 MiB).
141
+ *
142
+ * A binary file (over the threshold, or a NUL byte in its first 8000 bytes) is
143
+ * never content-merged and never loaded: as git does, OURS and THEIRS take that
144
+ * side's file whole, and UNION reports a conflict.
145
+ *
146
+ * @param threshold Size in bytes
147
+ */
148
+ setBigFileThreshold(threshold: number): this {
149
+ this.checkCallable();
150
+ this.bigFileThreshold = threshold;
151
+ return this;
152
+ }
153
+
132
154
  /**
133
155
  * Set squash mode.
134
156
  *
@@ -518,10 +540,22 @@ export class MergeCommand extends GitCommand<MergeResult> {
518
540
  }
519
541
 
520
542
  try {
521
- // Load content from all three versions
522
- const baseContent = base ? await this.collectBlobContent(base.id) : new Uint8Array(0);
523
- const oursContent = await this.collectBlobContent(ours.id);
524
- const theirsContent = await this.collectBlobContent(theirs.id);
543
+ // Binary or big files are never content-merged (git's ll_binary_merge)
544
+ const contents = await this.loadTexts([base?.id, ours.id, theirs.id]);
545
+ if (!contents) {
546
+ switch (this.contentStrategy) {
547
+ case ContentMergeStrategy.OURS:
548
+ return ours;
549
+ case ContentMergeStrategy.THEIRS:
550
+ return { ...theirs, name: ours.name };
551
+ default:
552
+ return undefined;
553
+ }
554
+ }
555
+
556
+ // Load content from all three versions (text under the threshold)
557
+ // (read once, by the probe)
558
+ const [baseContent, oursContent, theirsContent] = contents;
525
559
 
526
560
  // Convert ContentMergeStrategy to utils MergeContentStrategy
527
561
  const strategy = this.convertContentStrategy(this.contentStrategy);
@@ -531,7 +565,10 @@ export class MergeCommand extends GitCommand<MergeResult> {
531
565
 
532
566
  // If using OURS/THEIRS/UNION, conflicts are auto-resolved
533
567
  // Store the merged content
534
- const mergedBlobId = await this.blobs.store([mergeResult.content]);
568
+ const mergedBlobId = await this.blobs.store(
569
+ [mergeResult.content],
570
+ mergeResult.content.length,
571
+ );
535
572
 
536
573
  return {
537
574
  name: ours.name,
@@ -545,30 +582,26 @@ export class MergeCommand extends GitCommand<MergeResult> {
545
582
  }
546
583
 
547
584
  /**
548
- * Collect all bytes from a blob into a single Uint8Array.
585
+ * The blobs' contents, each read once; nothing when one is binary or over the
586
+ * threshold (then the rest are not read). A missing id is empty content.
549
587
  */
550
- private async collectBlobContent(blobId: ObjectId): Promise<Uint8Array> {
551
- const chunks: Uint8Array[] = [];
552
- const blobContent = await this.blobs.load(blobId);
553
- if (blobContent) {
554
- for await (const chunk of blobContent) {
555
- chunks.push(chunk);
588
+ private async loadTexts(
589
+ ids: [ObjectId | undefined, ObjectId, ObjectId],
590
+ ): Promise<[Uint8Array, Uint8Array, Uint8Array] | undefined> {
591
+ const out: Uint8Array[] = [];
592
+ for (const id of ids) {
593
+ if (!id) {
594
+ out.push(new Uint8Array(0));
595
+ continue;
556
596
  }
597
+ const probe = await probeBlob(this.blobs, id, {
598
+ bigFileThreshold: this.bigFileThreshold,
599
+ loadText: true,
600
+ });
601
+ if (probe.binary || !probe.content) return undefined;
602
+ out.push(probe.content);
557
603
  }
558
- if (chunks.length === 0) {
559
- return new Uint8Array(0);
560
- }
561
- if (chunks.length === 1) {
562
- return chunks[0];
563
- }
564
- const totalLength = chunks.reduce((sum, chunk) => sum + chunk.length, 0);
565
- const result = new Uint8Array(totalLength);
566
- let offset = 0;
567
- for (const chunk of chunks) {
568
- result.set(chunk, offset);
569
- offset += chunk.length;
570
- }
571
- return result;
604
+ return out as [Uint8Array, Uint8Array, Uint8Array];
572
605
  }
573
606
 
574
607
  /**
@@ -69,9 +69,9 @@ export class PackRefsCommand extends GitCommand<PackRefsResult> {
69
69
  this.checkCallable();
70
70
  this.setCallable(false);
71
71
 
72
- // Check if RefStore supports packRefs
72
+ // Check if the ref store supports packRefs
73
73
  if (!this.refsStore.packRefs) {
74
- throw new Error("RefStore does not support packRefs");
74
+ throw new Error("This ref store does not support packRefs");
75
75
  }
76
76
 
77
77
  let refsPacked = 0;