type-git 0.0.3 → 0.1.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.
package/dist/index.cjs CHANGED
@@ -34,10 +34,13 @@ __export(src_exports, {
34
34
  GIT_LOG_FORMAT: () => GIT_LOG_FORMAT,
35
35
  GitArgumentError: () => GitArgumentError,
36
36
  GitError: () => GitError,
37
+ LEGACY_GIT_VERSION: () => LEGACY_GIT_VERSION,
38
+ MIN_GIT_VERSION: () => MIN_GIT_VERSION,
37
39
  NodeExecAdapter: () => NodeExecAdapter,
38
40
  NodeFsAdapter: () => NodeFsAdapter,
39
41
  TypeGit: () => TypeGit,
40
42
  createGit: () => createGit,
43
+ createGitSync: () => createGitSync,
41
44
  createNodeAdapters: () => createNodeAdapters,
42
45
  detectErrorCategory: () => detectErrorCategory,
43
46
  isNonEmpty: () => isNonEmpty,
@@ -49,6 +52,7 @@ __export(src_exports, {
49
52
  parseLfsProgress: () => parseLfsProgress,
50
53
  parseLines: () => parseLines,
51
54
  parseLsRemote: () => parseLsRemote,
55
+ parseLsTree: () => parseLsTree,
52
56
  parsePorcelainV2: () => parsePorcelainV2,
53
57
  parseRecords: () => parseRecords,
54
58
  parseWorktreeList: () => parseWorktreeList
@@ -96,6 +100,16 @@ var GitArgumentError = class extends Error {
96
100
  };
97
101
 
98
102
  // src/parsers/index.ts
103
+ var GIT_PROGRESS_PERCENT_REGEX = /^(.+?):\s*(\d+)%\s*\((\d+)\/(\d+)\)(?:,\s*(done))?/;
104
+ var GIT_PROGRESS_SIMPLE_REGEX = /^(.+?):\s*(\d+)\/(\d+)/;
105
+ var WHITESPACE_REGEX = /\s+/;
106
+ var BYTES_RATIO_REGEX = /^(\d+)\/(\d+)$/;
107
+ var SIZE_REGEX = /^([\d.]+)\s*(B|KB|MB|GB|TB)?$/i;
108
+ var BITRATE_REGEX = /^([\d.]+)\s*(B|KB|MB|GB)\/s$/i;
109
+ var LFS_DOWNLOAD_REGEX = /downloading|filtering/i;
110
+ var LFS_UPLOAD_REGEX = /uploading/i;
111
+ var LFS_CHECKOUT_REGEX = /checking out/i;
112
+ var LFS_PROGRESS_REGEX = /(\d+)%\s*\((\d+)\/(\d+)\)(?:,\s*([\d.]+\s*(?:B|KB|MB|GB|TB)?)\s*(?:\|\s*([\d.]+\s*(?:B|KB|MB|GB)\/s))?)?/i;
99
113
  function at(arr, index, context) {
100
114
  const value = arr[index];
101
115
  if (value === void 0) {
@@ -208,7 +222,7 @@ function parsePorcelainV2(stdout) {
208
222
  return entries;
209
223
  }
210
224
  function parseGitProgress(line) {
211
- const match = line.match(/^(.+?):\s*(\d+)%\s*\((\d+)\/(\d+)\)(?:,\s*(done))?/);
225
+ const match = line.match(GIT_PROGRESS_PERCENT_REGEX);
212
226
  if (match) {
213
227
  const percent = match[2];
214
228
  const current = match[3];
@@ -224,7 +238,7 @@ function parseGitProgress(line) {
224
238
  done: match[5] === "done"
225
239
  };
226
240
  }
227
- const simpleMatch = line.match(/^(.+?):\s*(\d+)\/(\d+)/);
241
+ const simpleMatch = line.match(GIT_PROGRESS_SIMPLE_REGEX);
228
242
  if (simpleMatch) {
229
243
  const currentStr = simpleMatch[2];
230
244
  const totalStr = simpleMatch[3];
@@ -244,7 +258,7 @@ function parseGitProgress(line) {
244
258
  return null;
245
259
  }
246
260
  function parseLfsProgress(line) {
247
- const parts = line.trim().split(/\s+/);
261
+ const parts = line.trim().split(WHITESPACE_REGEX);
248
262
  if (parts.length < 4) {
249
263
  return null;
250
264
  }
@@ -259,7 +273,7 @@ function parseLfsProgress(line) {
259
273
  if (oid === void 0 || bytesStr === void 0 || transferredStr === void 0) {
260
274
  return null;
261
275
  }
262
- const bytesMatch = bytesStr.match(/^(\d+)\/(\d+)$/);
276
+ const bytesMatch = bytesStr.match(BYTES_RATIO_REGEX);
263
277
  if (!bytesMatch) {
264
278
  return null;
265
279
  }
@@ -277,7 +291,7 @@ function parseLfsProgress(line) {
277
291
  };
278
292
  }
279
293
  function parseSizeToBytes(sizeStr) {
280
- const match = sizeStr.match(/^([\d.]+)\s*(B|KB|MB|GB|TB)?$/i);
294
+ const match = sizeStr.match(SIZE_REGEX);
281
295
  if (!match) {
282
296
  return 0;
283
297
  }
@@ -293,7 +307,7 @@ function parseSizeToBytes(sizeStr) {
293
307
  return Math.round(value * (multipliers[unit] || 1));
294
308
  }
295
309
  function parseBitrateToBytes(bitrateStr) {
296
- const match = bitrateStr.match(/^([\d.]+)\s*(B|KB|MB|GB)\/s$/i);
310
+ const match = bitrateStr.match(BITRATE_REGEX);
297
311
  if (!match) {
298
312
  return null;
299
313
  }
@@ -309,18 +323,16 @@ function parseBitrateToBytes(bitrateStr) {
309
323
  }
310
324
  function parseLfsStderrProgress(line) {
311
325
  let direction;
312
- if (/downloading|filtering/i.test(line)) {
326
+ if (LFS_DOWNLOAD_REGEX.test(line)) {
313
327
  direction = "download";
314
- } else if (/uploading/i.test(line)) {
328
+ } else if (LFS_UPLOAD_REGEX.test(line)) {
315
329
  direction = "upload";
316
- } else if (/checking out/i.test(line)) {
330
+ } else if (LFS_CHECKOUT_REGEX.test(line)) {
317
331
  direction = "checkout";
318
332
  } else {
319
333
  return null;
320
334
  }
321
- const progressMatch = line.match(
322
- /(\d+)%\s*\((\d+)\/(\d+)\)(?:,\s*([\d.]+\s*(?:B|KB|MB|GB|TB)?)\s*(?:\|\s*([\d.]+\s*(?:B|KB|MB|GB)\/s))?)?/i
323
- );
335
+ const progressMatch = line.match(LFS_PROGRESS_REGEX);
324
336
  if (!progressMatch) {
325
337
  return null;
326
338
  }
@@ -361,6 +373,68 @@ function parseLsRemote(stdout) {
361
373
  }
362
374
  return refs;
363
375
  }
376
+ var LS_TREE_REGEX = /^(\d+)\s+(blob|tree|commit)\s+([a-f0-9]+)\t(.+)$/;
377
+ var LS_TREE_LONG_REGEX = /^(\d+)\s+(blob|tree|commit)\s+([a-f0-9]+)\s+(-|\d+)\t(.+)$/;
378
+ function parseLsTree(stdout, opts) {
379
+ const entries = [];
380
+ const lines = parseLines(stdout);
381
+ for (const line of lines) {
382
+ if (opts?.nameOnly) {
383
+ entries.push({
384
+ mode: "",
385
+ type: "blob",
386
+ hash: "",
387
+ path: line
388
+ });
389
+ continue;
390
+ }
391
+ if (opts?.objectOnly) {
392
+ entries.push({
393
+ mode: "",
394
+ type: "blob",
395
+ hash: line,
396
+ path: ""
397
+ });
398
+ continue;
399
+ }
400
+ if (opts?.long) {
401
+ const longMatch = line.match(LS_TREE_LONG_REGEX);
402
+ if (longMatch) {
403
+ const mode = longMatch[1];
404
+ const type = longMatch[2];
405
+ const hash = longMatch[3];
406
+ const sizeStr = longMatch[4];
407
+ const path = longMatch[5];
408
+ if (mode && type && hash && path) {
409
+ entries.push({
410
+ mode,
411
+ type,
412
+ hash,
413
+ path,
414
+ size: sizeStr === "-" || !sizeStr ? void 0 : Number.parseInt(sizeStr, 10)
415
+ });
416
+ }
417
+ continue;
418
+ }
419
+ }
420
+ const match = line.match(LS_TREE_REGEX);
421
+ if (match) {
422
+ const mode = match[1];
423
+ const type = match[2];
424
+ const hash = match[3];
425
+ const path = match[4];
426
+ if (mode && type && hash && path) {
427
+ entries.push({
428
+ mode,
429
+ type,
430
+ hash,
431
+ path
432
+ });
433
+ }
434
+ }
435
+ }
436
+ return entries;
437
+ }
364
438
  var GIT_LOG_FORMAT = "%H%x00%h%x00%P%x00%an%x00%ae%x00%at%x00%cn%x00%ce%x00%ct%x00%s%x00%b%x01";
365
439
  function parseGitLog(stdout) {
366
440
  const commits = [];
@@ -370,7 +444,7 @@ function parseGitLog(stdout) {
370
444
  if (fields.length < 11) {
371
445
  continue;
372
446
  }
373
- const hash = fields[0];
447
+ const hash = fields[0]?.trim();
374
448
  const abbrevHash = fields[1];
375
449
  const parentsStr = fields[2];
376
450
  const authorName = fields[3];
@@ -492,6 +566,51 @@ var import_node_process = __toESM(require("process"), 1);
492
566
  var FATAL_ERROR_PATTERN = /fatal:\s*(.+)/i;
493
567
  var ERROR_PATTERN = /error:\s*(.+)/i;
494
568
  var LINE_SEPARATOR_PATTERN = /\r|\n/;
569
+ function toLfsProgress(info) {
570
+ if (!info) {
571
+ return null;
572
+ }
573
+ return {
574
+ direction: info.direction,
575
+ bytesSoFar: info.bytesSoFar,
576
+ bytesTotal: info.bytesTotal,
577
+ bitrate: info.bitrate ?? void 0,
578
+ filesCompleted: info.filesCompleted,
579
+ filesTotal: info.filesTotal,
580
+ percent: info.percent
581
+ };
582
+ }
583
+ function toGitProgress(info, message) {
584
+ if (!info) {
585
+ return null;
586
+ }
587
+ return {
588
+ phase: info.phase,
589
+ current: info.current,
590
+ total: info.total,
591
+ percent: info.percent,
592
+ message
593
+ };
594
+ }
595
+ function processProgressLine(line, onProgress, onLfsProgress) {
596
+ const trimmed = line.trim();
597
+ if (!trimmed) {
598
+ return;
599
+ }
600
+ if (onLfsProgress) {
601
+ const lfsProgress = toLfsProgress(parseLfsStderrProgress(trimmed));
602
+ if (lfsProgress) {
603
+ onLfsProgress(lfsProgress);
604
+ return;
605
+ }
606
+ }
607
+ if (onProgress) {
608
+ const gitProgress = toGitProgress(parseGitProgress(trimmed), trimmed);
609
+ if (gitProgress) {
610
+ onProgress(gitProgress);
611
+ }
612
+ }
613
+ }
495
614
  var CliRunner = class _CliRunner {
496
615
  exec;
497
616
  gitBinary;
@@ -618,73 +737,13 @@ var CliRunner = class _CliRunner {
618
737
  const lines = stderrBuffer.split(LINE_SEPARATOR_PATTERN);
619
738
  stderrBuffer = lines.pop() ?? "";
620
739
  for (const line of lines) {
621
- const trimmed = line.trim();
622
- if (!trimmed) {
623
- continue;
624
- }
625
- if (onLfsProgress) {
626
- const lfsProgressInfo = parseLfsStderrProgress(trimmed);
627
- if (lfsProgressInfo) {
628
- const lfsProgress = {
629
- direction: lfsProgressInfo.direction,
630
- bytesSoFar: lfsProgressInfo.bytesSoFar,
631
- bytesTotal: lfsProgressInfo.bytesTotal,
632
- bitrate: lfsProgressInfo.bitrate ?? void 0,
633
- filesCompleted: lfsProgressInfo.filesCompleted,
634
- filesTotal: lfsProgressInfo.filesTotal,
635
- percent: lfsProgressInfo.percent
636
- };
637
- onLfsProgress(lfsProgress);
638
- continue;
639
- }
640
- }
641
- if (onProgress) {
642
- const gitProgressInfo = parseGitProgress(trimmed);
643
- if (gitProgressInfo) {
644
- const gitProgress = {
645
- phase: gitProgressInfo.phase,
646
- current: gitProgressInfo.current,
647
- total: gitProgressInfo.total,
648
- percent: gitProgressInfo.percent,
649
- message: trimmed
650
- };
651
- onProgress(gitProgress);
652
- }
653
- }
740
+ processProgressLine(line, onProgress, onLfsProgress);
654
741
  }
655
742
  }
656
743
  } : void 0
657
744
  );
658
745
  if (stderrBuffer.trim() && (onProgress || onLfsProgress)) {
659
- const trimmed = stderrBuffer.trim();
660
- if (onLfsProgress) {
661
- const lfsProgressInfo = parseLfsStderrProgress(trimmed);
662
- if (lfsProgressInfo) {
663
- const lfsProgress = {
664
- direction: lfsProgressInfo.direction,
665
- bytesSoFar: lfsProgressInfo.bytesSoFar,
666
- bytesTotal: lfsProgressInfo.bytesTotal,
667
- bitrate: lfsProgressInfo.bitrate ?? void 0,
668
- filesCompleted: lfsProgressInfo.filesCompleted,
669
- filesTotal: lfsProgressInfo.filesTotal,
670
- percent: lfsProgressInfo.percent
671
- };
672
- onLfsProgress(lfsProgress);
673
- }
674
- }
675
- if (onProgress && !onLfsProgress) {
676
- const gitProgressInfo = parseGitProgress(trimmed);
677
- if (gitProgressInfo) {
678
- const gitProgress = {
679
- phase: gitProgressInfo.phase,
680
- current: gitProgressInfo.current,
681
- total: gitProgressInfo.total,
682
- percent: gitProgressInfo.percent,
683
- message: trimmed
684
- };
685
- onProgress(gitProgress);
686
- }
687
- }
746
+ processProgressLine(stderrBuffer, onProgress, onLfsProgress);
688
747
  }
689
748
  return {
690
749
  stdout: result.stdout,
@@ -769,6 +828,196 @@ var CliRunner = class _CliRunner {
769
828
  };
770
829
 
771
830
  // src/impl/bare-repo-impl.ts
831
+ var REMOTE_LINE_PATTERN = /^(\S+)\t(.+?)\s+\((fetch|push)\)$/;
832
+ var PRUNED_REF_PATTERN = /\* \[pruned\] (.+)/;
833
+ function parseRemoteLine(line, remotes) {
834
+ const match = line.match(REMOTE_LINE_PATTERN);
835
+ if (!match) {
836
+ return;
837
+ }
838
+ const name = match[1];
839
+ const url = match[2];
840
+ const type = match[3];
841
+ if (name === void 0 || url === void 0) {
842
+ return;
843
+ }
844
+ const existing = remotes.get(name);
845
+ if (existing) {
846
+ updateRemoteUrl(existing, type, url);
847
+ } else {
848
+ remotes.set(name, {
849
+ name,
850
+ fetchUrl: type === "fetch" ? url : "",
851
+ pushUrl: type === "push" ? url : ""
852
+ });
853
+ }
854
+ }
855
+ function updateRemoteUrl(remote, type, url) {
856
+ if (type === "fetch") {
857
+ remote.fetchUrl = url;
858
+ } else if (type === "push") {
859
+ remote.pushUrl = url;
860
+ }
861
+ }
862
+ function normalizeRemoteUrls(remotes) {
863
+ for (const remote of remotes.values()) {
864
+ if (!remote.fetchUrl && remote.pushUrl) {
865
+ remote.fetchUrl = remote.pushUrl;
866
+ }
867
+ if (!remote.pushUrl && remote.fetchUrl) {
868
+ remote.pushUrl = remote.fetchUrl;
869
+ }
870
+ }
871
+ }
872
+ function addRefOptions(args, opts) {
873
+ if (!opts) {
874
+ return;
875
+ }
876
+ if (opts.verify) {
877
+ args.push("--verify");
878
+ }
879
+ if (opts.short !== void 0) {
880
+ if (typeof opts.short === "number") {
881
+ args.push(`--short=${opts.short}`);
882
+ } else if (opts.short) {
883
+ args.push("--short");
884
+ }
885
+ }
886
+ if (opts.abbrevRef !== void 0) {
887
+ if (opts.abbrevRef === "strict") {
888
+ args.push("--abbrev-ref=strict");
889
+ } else if (opts.abbrevRef === "loose") {
890
+ args.push("--abbrev-ref=loose");
891
+ } else if (opts.abbrevRef) {
892
+ args.push("--abbrev-ref");
893
+ }
894
+ }
895
+ if (opts.symbolic) {
896
+ args.push("--symbolic");
897
+ }
898
+ if (opts.symbolicFullName) {
899
+ args.push("--symbolic-full-name");
900
+ }
901
+ if (opts.quiet) {
902
+ args.push("--quiet");
903
+ }
904
+ }
905
+ var PATH_QUERY_FLAGS = [
906
+ ["gitDir", "--git-dir"],
907
+ ["absoluteGitDir", "--absolute-git-dir"],
908
+ ["gitCommonDir", "--git-common-dir"],
909
+ ["showToplevel", "--show-toplevel"],
910
+ ["showCdup", "--show-cdup"],
911
+ ["showPrefix", "--show-prefix"],
912
+ ["showSuperprojectWorkingTree", "--show-superproject-working-tree"],
913
+ ["sharedIndexPath", "--shared-index-path"]
914
+ ];
915
+ var PATH_QUERY_VALUE_FLAGS = [
916
+ ["gitPath", "--git-path"],
917
+ ["resolveGitDir", "--resolve-git-dir"]
918
+ ];
919
+ var BOOLEAN_QUERY_FLAGS = [
920
+ ["isInsideGitDir", "--is-inside-git-dir"],
921
+ ["isInsideWorkTree", "--is-inside-work-tree"],
922
+ ["isBareRepository", "--is-bare-repository"],
923
+ ["isShallowRepository", "--is-shallow-repository"]
924
+ ];
925
+ var LIST_QUERY_FLAGS = [
926
+ ["all", "--all"],
927
+ ["branches", "--branches"],
928
+ ["tags", "--tags"],
929
+ ["remotes", "--remotes"]
930
+ ];
931
+ function addExcludeOptions(args, opts) {
932
+ if ("exclude" in opts && opts.exclude) {
933
+ args.push(`--exclude=${opts.exclude}`);
934
+ }
935
+ if ("excludeHidden" in opts && opts.excludeHidden) {
936
+ args.push(`--exclude-hidden=${opts.excludeHidden}`);
937
+ }
938
+ }
939
+ function tryAddPathQuery(args, opts) {
940
+ for (const [key, flag] of PATH_QUERY_FLAGS) {
941
+ if (key in opts && opts[key]) {
942
+ args.push(flag);
943
+ return true;
944
+ }
945
+ }
946
+ for (const [key, flag] of PATH_QUERY_VALUE_FLAGS) {
947
+ if (key in opts && typeof opts[key] === "string") {
948
+ args.push(flag, opts[key]);
949
+ return true;
950
+ }
951
+ }
952
+ return false;
953
+ }
954
+ function tryAddBooleanQuery(args, opts) {
955
+ for (const [key, flag] of BOOLEAN_QUERY_FLAGS) {
956
+ if (key in opts && opts[key]) {
957
+ args.push(flag);
958
+ return true;
959
+ }
960
+ }
961
+ return false;
962
+ }
963
+ function tryAddListQuery(args, opts) {
964
+ for (const [key, flag] of LIST_QUERY_FLAGS) {
965
+ if (key in opts && opts[key]) {
966
+ addExcludeOptions(args, opts);
967
+ if (typeof opts[key] === "string") {
968
+ args.push(`${flag}=${opts[key]}`);
969
+ } else {
970
+ args.push(flag);
971
+ }
972
+ return true;
973
+ }
974
+ }
975
+ if ("glob" in opts && typeof opts.glob === "string") {
976
+ addExcludeOptions(args, opts);
977
+ args.push(`--glob=${opts.glob}`);
978
+ return true;
979
+ }
980
+ if ("disambiguate" in opts && typeof opts.disambiguate === "string") {
981
+ args.push(`--disambiguate=${opts.disambiguate}`);
982
+ return true;
983
+ }
984
+ return false;
985
+ }
986
+ function tryAddOtherQuery(args, opts) {
987
+ if ("showObjectFormat" in opts && opts.showObjectFormat) {
988
+ if (opts.showObjectFormat === true) {
989
+ args.push("--show-object-format");
990
+ } else {
991
+ args.push(`--show-object-format=${opts.showObjectFormat}`);
992
+ }
993
+ return true;
994
+ }
995
+ if ("showRefFormat" in opts && opts.showRefFormat) {
996
+ args.push("--show-ref-format");
997
+ return true;
998
+ }
999
+ if ("localEnvVars" in opts && opts.localEnvVars) {
1000
+ args.push("--local-env-vars");
1001
+ return true;
1002
+ }
1003
+ return false;
1004
+ }
1005
+ function isBooleanQuery(opts) {
1006
+ for (const [key] of BOOLEAN_QUERY_FLAGS) {
1007
+ if (key in opts && opts[key]) {
1008
+ return true;
1009
+ }
1010
+ }
1011
+ return false;
1012
+ }
1013
+ function isListQuery(opts) {
1014
+ for (const [key] of LIST_QUERY_FLAGS) {
1015
+ if (key in opts && opts[key]) {
1016
+ return true;
1017
+ }
1018
+ }
1019
+ return "glob" in opts && !!opts.glob || "disambiguate" in opts && !!opts.disambiguate || "localEnvVars" in opts && !!opts.localEnvVars;
1020
+ }
772
1021
  var BareRepoImpl = class {
773
1022
  gitDir;
774
1023
  runner;
@@ -831,6 +1080,116 @@ var BareRepoImpl = class {
831
1080
  const result = await this.runner.run(this.context, ["rev-parse", "--is-bare-repository"]);
832
1081
  return result.exitCode === 0 && result.stdout.trim() === "true";
833
1082
  }
1083
+ /**
1084
+ * List references in a remote repository
1085
+ */
1086
+ async lsRemote(remote, opts) {
1087
+ const args = ["ls-remote"];
1088
+ if (opts?.heads) {
1089
+ args.push("--heads");
1090
+ }
1091
+ if (opts?.tags) {
1092
+ args.push("--tags");
1093
+ }
1094
+ if (opts?.refsOnly) {
1095
+ args.push("--refs");
1096
+ }
1097
+ if (opts?.getUrl) {
1098
+ args.push("--get-url");
1099
+ }
1100
+ if (opts?.sort) {
1101
+ args.push("--sort", opts.sort);
1102
+ }
1103
+ if (opts?.symref) {
1104
+ args.push("--symref");
1105
+ }
1106
+ args.push(remote);
1107
+ if (opts?.refs && opts.refs.length > 0) {
1108
+ args.push(...opts.refs);
1109
+ }
1110
+ const result = await this.runner.runOrThrow(this.context, args, {
1111
+ signal: opts?.signal,
1112
+ onProgress: opts?.onProgress
1113
+ });
1114
+ const refs = parseLsRemote(result.stdout);
1115
+ return { refs };
1116
+ }
1117
+ /**
1118
+ * List contents of a tree object
1119
+ */
1120
+ async lsTree(treeish, opts) {
1121
+ const args = ["ls-tree"];
1122
+ if (opts?.recursive) {
1123
+ args.push("-r");
1124
+ }
1125
+ if (opts?.treeOnly) {
1126
+ args.push("-d");
1127
+ }
1128
+ if (opts?.showTrees) {
1129
+ args.push("-t");
1130
+ }
1131
+ if (opts?.long) {
1132
+ args.push("--long");
1133
+ }
1134
+ if (opts?.nameOnly) {
1135
+ args.push("--name-only");
1136
+ }
1137
+ if (opts?.objectOnly) {
1138
+ args.push("--object-only");
1139
+ }
1140
+ if (opts?.fullName) {
1141
+ args.push("--full-name");
1142
+ }
1143
+ if (opts?.fullTree) {
1144
+ args.push("--full-tree");
1145
+ }
1146
+ if (opts?.abbrev !== void 0) {
1147
+ if (opts.abbrev === true) {
1148
+ args.push("--abbrev");
1149
+ } else if (typeof opts.abbrev === "number") {
1150
+ args.push(`--abbrev=${opts.abbrev}`);
1151
+ }
1152
+ }
1153
+ args.push(treeish);
1154
+ if (opts?.paths && opts.paths.length > 0) {
1155
+ args.push("--", ...opts.paths);
1156
+ }
1157
+ const result = await this.runner.runOrThrow(this.context, args, {
1158
+ signal: opts?.signal
1159
+ });
1160
+ return parseLsTree(result.stdout, {
1161
+ nameOnly: opts?.nameOnly,
1162
+ objectOnly: opts?.objectOnly,
1163
+ long: opts?.long
1164
+ });
1165
+ }
1166
+ async revParse(refOrOpts, opts) {
1167
+ const args = ["rev-parse"];
1168
+ if (typeof refOrOpts === "string") {
1169
+ addRefOptions(args, opts);
1170
+ args.push(refOrOpts);
1171
+ const result2 = await this.runner.runOrThrow(this.context, args, {
1172
+ signal: opts?.signal
1173
+ });
1174
+ return result2.stdout.trim();
1175
+ }
1176
+ const queryOpts = refOrOpts;
1177
+ tryAddPathQuery(args, queryOpts) || tryAddBooleanQuery(args, queryOpts) || tryAddListQuery(args, queryOpts) || tryAddOtherQuery(args, queryOpts);
1178
+ if ("pathFormat" in queryOpts && queryOpts.pathFormat) {
1179
+ args.push(`--path-format=${queryOpts.pathFormat}`);
1180
+ }
1181
+ const result = await this.runner.runOrThrow(this.context, args, {
1182
+ signal: refOrOpts.signal
1183
+ });
1184
+ const output = result.stdout.trim();
1185
+ if (isBooleanQuery(queryOpts)) {
1186
+ return output === "true";
1187
+ }
1188
+ if (isListQuery(queryOpts)) {
1189
+ return output ? output.split("\n").filter((line) => line.length > 0) : [];
1190
+ }
1191
+ return output;
1192
+ }
834
1193
  /**
835
1194
  * Fetch from remote
836
1195
  */
@@ -898,37 +1257,9 @@ var BareRepoImpl = class {
898
1257
  });
899
1258
  const remotes = /* @__PURE__ */ new Map();
900
1259
  for (const line of parseLines(result.stdout)) {
901
- const match = line.match(/^(\S+)\t(.+?)\s+\((fetch|push)\)$/);
902
- if (match) {
903
- const name = match[1];
904
- const url = match[2];
905
- const type = match[3];
906
- if (name !== void 0 && url !== void 0) {
907
- const existing = remotes.get(name);
908
- if (existing) {
909
- if (type === "fetch") {
910
- existing.fetchUrl = url;
911
- } else if (type === "push") {
912
- existing.pushUrl = url;
913
- }
914
- } else {
915
- remotes.set(name, {
916
- name,
917
- fetchUrl: type === "fetch" ? url : "",
918
- pushUrl: type === "push" ? url : ""
919
- });
920
- }
921
- }
922
- }
923
- }
924
- for (const remote of remotes.values()) {
925
- if (!remote.fetchUrl && remote.pushUrl) {
926
- remote.fetchUrl = remote.pushUrl;
927
- }
928
- if (!remote.pushUrl && remote.fetchUrl) {
929
- remote.pushUrl = remote.fetchUrl;
930
- }
1260
+ parseRemoteLine(line, remotes);
931
1261
  }
1262
+ normalizeRemoteUrls(remotes);
932
1263
  return Array.from(remotes.values());
933
1264
  }
934
1265
  async remoteAdd(name, url, opts) {
@@ -1017,7 +1348,7 @@ var BareRepoImpl = class {
1017
1348
  });
1018
1349
  const pruned = [];
1019
1350
  for (const line of parseLines(result.stdout)) {
1020
- const match = line.match(/\* \[pruned\] (.+)/);
1351
+ const match = line.match(PRUNED_REF_PATTERN);
1021
1352
  const ref = match?.[1];
1022
1353
  if (ref) {
1023
1354
  pruned.push(ref);
@@ -1344,6 +1675,89 @@ var WorktreeRepoImpl = class _WorktreeRepoImpl {
1344
1675
  const result = await this.runner.run(this.context, ["rev-parse", "--is-bare-repository"]);
1345
1676
  return result.exitCode === 0 && result.stdout.trim() === "true";
1346
1677
  }
1678
+ /**
1679
+ * List references in a remote repository
1680
+ */
1681
+ async lsRemote(remote, opts) {
1682
+ const args = ["ls-remote"];
1683
+ if (opts?.heads) {
1684
+ args.push("--heads");
1685
+ }
1686
+ if (opts?.tags) {
1687
+ args.push("--tags");
1688
+ }
1689
+ if (opts?.refsOnly) {
1690
+ args.push("--refs");
1691
+ }
1692
+ if (opts?.getUrl) {
1693
+ args.push("--get-url");
1694
+ }
1695
+ if (opts?.sort) {
1696
+ args.push("--sort", opts.sort);
1697
+ }
1698
+ if (opts?.symref) {
1699
+ args.push("--symref");
1700
+ }
1701
+ args.push(remote);
1702
+ if (opts?.refs && opts.refs.length > 0) {
1703
+ args.push(...opts.refs);
1704
+ }
1705
+ const result = await this.runner.runOrThrow(this.context, args, {
1706
+ signal: opts?.signal,
1707
+ onProgress: opts?.onProgress
1708
+ });
1709
+ const refs = parseLsRemote(result.stdout);
1710
+ return { refs };
1711
+ }
1712
+ /**
1713
+ * List contents of a tree object
1714
+ */
1715
+ async lsTree(treeish, opts) {
1716
+ const args = ["ls-tree"];
1717
+ if (opts?.recursive) {
1718
+ args.push("-r");
1719
+ }
1720
+ if (opts?.treeOnly) {
1721
+ args.push("-d");
1722
+ }
1723
+ if (opts?.showTrees) {
1724
+ args.push("-t");
1725
+ }
1726
+ if (opts?.long) {
1727
+ args.push("--long");
1728
+ }
1729
+ if (opts?.nameOnly) {
1730
+ args.push("--name-only");
1731
+ }
1732
+ if (opts?.objectOnly) {
1733
+ args.push("--object-only");
1734
+ }
1735
+ if (opts?.fullName) {
1736
+ args.push("--full-name");
1737
+ }
1738
+ if (opts?.fullTree) {
1739
+ args.push("--full-tree");
1740
+ }
1741
+ if (opts?.abbrev !== void 0) {
1742
+ if (opts.abbrev === true) {
1743
+ args.push("--abbrev");
1744
+ } else if (typeof opts.abbrev === "number") {
1745
+ args.push(`--abbrev=${opts.abbrev}`);
1746
+ }
1747
+ }
1748
+ args.push(treeish);
1749
+ if (opts?.paths && opts.paths.length > 0) {
1750
+ args.push("--", ...opts.paths);
1751
+ }
1752
+ const result = await this.runner.runOrThrow(this.context, args, {
1753
+ signal: opts?.signal
1754
+ });
1755
+ return parseLsTree(result.stdout, {
1756
+ nameOnly: opts?.nameOnly,
1757
+ objectOnly: opts?.objectOnly,
1758
+ long: opts?.long
1759
+ });
1760
+ }
1347
1761
  /**
1348
1762
  * Get repository status
1349
1763
  */
@@ -4239,17 +4653,151 @@ var WorktreeRepoImpl = class _WorktreeRepoImpl {
4239
4653
  });
4240
4654
  return result.stdout;
4241
4655
  }
4242
- // ==========================================================================
4243
- // Plumbing Operations
4244
- // ==========================================================================
4245
- /**
4246
- * Parse revision specification and return the object name (SHA)
4247
- */
4248
- async revParse(ref, opts) {
4249
- const result = await this.runner.runOrThrow(this.context, ["rev-parse", ref], {
4250
- signal: opts?.signal
4656
+ async revParse(refOrOpts, opts) {
4657
+ const args = ["rev-parse"];
4658
+ if (typeof refOrOpts === "string") {
4659
+ if (opts?.verify) {
4660
+ args.push("--verify");
4661
+ }
4662
+ if (opts?.short !== void 0) {
4663
+ if (typeof opts.short === "number") {
4664
+ args.push(`--short=${opts.short}`);
4665
+ } else if (opts.short) {
4666
+ args.push("--short");
4667
+ }
4668
+ }
4669
+ if (opts?.abbrevRef !== void 0) {
4670
+ if (opts.abbrevRef === "strict") {
4671
+ args.push("--abbrev-ref=strict");
4672
+ } else if (opts.abbrevRef === "loose") {
4673
+ args.push("--abbrev-ref=loose");
4674
+ } else if (opts.abbrevRef) {
4675
+ args.push("--abbrev-ref");
4676
+ }
4677
+ }
4678
+ if (opts?.symbolic) {
4679
+ args.push("--symbolic");
4680
+ }
4681
+ if (opts?.symbolicFullName) {
4682
+ args.push("--symbolic-full-name");
4683
+ }
4684
+ if (opts?.quiet) {
4685
+ args.push("--quiet");
4686
+ }
4687
+ args.push(refOrOpts);
4688
+ const result2 = await this.runner.runOrThrow(this.context, args, {
4689
+ signal: opts?.signal
4690
+ });
4691
+ return result2.stdout.trim();
4692
+ }
4693
+ const queryOpts = refOrOpts;
4694
+ if ("gitDir" in queryOpts && queryOpts.gitDir) {
4695
+ args.push("--git-dir");
4696
+ } else if ("absoluteGitDir" in queryOpts && queryOpts.absoluteGitDir) {
4697
+ args.push("--absolute-git-dir");
4698
+ } else if ("gitCommonDir" in queryOpts && queryOpts.gitCommonDir) {
4699
+ args.push("--git-common-dir");
4700
+ } else if ("showToplevel" in queryOpts && queryOpts.showToplevel) {
4701
+ args.push("--show-toplevel");
4702
+ } else if ("showCdup" in queryOpts && queryOpts.showCdup) {
4703
+ args.push("--show-cdup");
4704
+ } else if ("showPrefix" in queryOpts && queryOpts.showPrefix) {
4705
+ args.push("--show-prefix");
4706
+ } else if ("showSuperprojectWorkingTree" in queryOpts && queryOpts.showSuperprojectWorkingTree) {
4707
+ args.push("--show-superproject-working-tree");
4708
+ } else if ("sharedIndexPath" in queryOpts && queryOpts.sharedIndexPath) {
4709
+ args.push("--shared-index-path");
4710
+ } else if ("gitPath" in queryOpts && typeof queryOpts.gitPath === "string") {
4711
+ args.push("--git-path", queryOpts.gitPath);
4712
+ } else if ("resolveGitDir" in queryOpts && typeof queryOpts.resolveGitDir === "string") {
4713
+ args.push("--resolve-git-dir", queryOpts.resolveGitDir);
4714
+ } else if ("isInsideGitDir" in queryOpts && queryOpts.isInsideGitDir) {
4715
+ args.push("--is-inside-git-dir");
4716
+ } else if ("isInsideWorkTree" in queryOpts && queryOpts.isInsideWorkTree) {
4717
+ args.push("--is-inside-work-tree");
4718
+ } else if ("isBareRepository" in queryOpts && queryOpts.isBareRepository) {
4719
+ args.push("--is-bare-repository");
4720
+ } else if ("isShallowRepository" in queryOpts && queryOpts.isShallowRepository) {
4721
+ args.push("--is-shallow-repository");
4722
+ } else if ("all" in queryOpts && queryOpts.all) {
4723
+ if ("exclude" in queryOpts && queryOpts.exclude) {
4724
+ args.push(`--exclude=${queryOpts.exclude}`);
4725
+ }
4726
+ if ("excludeHidden" in queryOpts && queryOpts.excludeHidden) {
4727
+ args.push(`--exclude-hidden=${queryOpts.excludeHidden}`);
4728
+ }
4729
+ args.push("--all");
4730
+ } else if ("branches" in queryOpts && queryOpts.branches) {
4731
+ if ("exclude" in queryOpts && queryOpts.exclude) {
4732
+ args.push(`--exclude=${queryOpts.exclude}`);
4733
+ }
4734
+ if ("excludeHidden" in queryOpts && queryOpts.excludeHidden) {
4735
+ args.push(`--exclude-hidden=${queryOpts.excludeHidden}`);
4736
+ }
4737
+ if (typeof queryOpts.branches === "string") {
4738
+ args.push(`--branches=${queryOpts.branches}`);
4739
+ } else {
4740
+ args.push("--branches");
4741
+ }
4742
+ } else if ("tags" in queryOpts && queryOpts.tags) {
4743
+ if ("exclude" in queryOpts && queryOpts.exclude) {
4744
+ args.push(`--exclude=${queryOpts.exclude}`);
4745
+ }
4746
+ if ("excludeHidden" in queryOpts && queryOpts.excludeHidden) {
4747
+ args.push(`--exclude-hidden=${queryOpts.excludeHidden}`);
4748
+ }
4749
+ if (typeof queryOpts.tags === "string") {
4750
+ args.push(`--tags=${queryOpts.tags}`);
4751
+ } else {
4752
+ args.push("--tags");
4753
+ }
4754
+ } else if ("remotes" in queryOpts && queryOpts.remotes) {
4755
+ if ("exclude" in queryOpts && queryOpts.exclude) {
4756
+ args.push(`--exclude=${queryOpts.exclude}`);
4757
+ }
4758
+ if ("excludeHidden" in queryOpts && queryOpts.excludeHidden) {
4759
+ args.push(`--exclude-hidden=${queryOpts.excludeHidden}`);
4760
+ }
4761
+ if (typeof queryOpts.remotes === "string") {
4762
+ args.push(`--remotes=${queryOpts.remotes}`);
4763
+ } else {
4764
+ args.push("--remotes");
4765
+ }
4766
+ } else if ("glob" in queryOpts && typeof queryOpts.glob === "string") {
4767
+ if ("exclude" in queryOpts && queryOpts.exclude) {
4768
+ args.push(`--exclude=${queryOpts.exclude}`);
4769
+ }
4770
+ if ("excludeHidden" in queryOpts && queryOpts.excludeHidden) {
4771
+ args.push(`--exclude-hidden=${queryOpts.excludeHidden}`);
4772
+ }
4773
+ args.push(`--glob=${queryOpts.glob}`);
4774
+ } else if ("disambiguate" in queryOpts && typeof queryOpts.disambiguate === "string") {
4775
+ args.push(`--disambiguate=${queryOpts.disambiguate}`);
4776
+ } else if ("showObjectFormat" in queryOpts && queryOpts.showObjectFormat) {
4777
+ if (queryOpts.showObjectFormat === true) {
4778
+ args.push("--show-object-format");
4779
+ } else {
4780
+ args.push(`--show-object-format=${queryOpts.showObjectFormat}`);
4781
+ }
4782
+ } else if ("showRefFormat" in queryOpts && queryOpts.showRefFormat) {
4783
+ args.push("--show-ref-format");
4784
+ } else if ("localEnvVars" in queryOpts && queryOpts.localEnvVars) {
4785
+ args.push("--local-env-vars");
4786
+ }
4787
+ if ("pathFormat" in queryOpts && queryOpts.pathFormat) {
4788
+ args.push(`--path-format=${queryOpts.pathFormat}`);
4789
+ }
4790
+ const result = await this.runner.runOrThrow(this.context, args, {
4791
+ signal: queryOpts.signal
4251
4792
  });
4252
- return result.stdout.trim();
4793
+ const output = result.stdout.trim();
4794
+ if ("isInsideGitDir" in queryOpts && queryOpts.isInsideGitDir || "isInsideWorkTree" in queryOpts && queryOpts.isInsideWorkTree || "isBareRepository" in queryOpts && queryOpts.isBareRepository || "isShallowRepository" in queryOpts && queryOpts.isShallowRepository) {
4795
+ return output === "true";
4796
+ }
4797
+ if ("all" in queryOpts && queryOpts.all || "branches" in queryOpts && queryOpts.branches || "tags" in queryOpts && queryOpts.tags || "remotes" in queryOpts && queryOpts.remotes || "glob" in queryOpts && queryOpts.glob || "disambiguate" in queryOpts && queryOpts.disambiguate || "localEnvVars" in queryOpts && queryOpts.localEnvVars) {
4798
+ return output ? output.split("\n").filter((line) => line.length > 0) : [];
4799
+ }
4800
+ return output;
4253
4801
  }
4254
4802
  /**
4255
4803
  * Count the number of commits reachable from a ref
@@ -4803,6 +5351,101 @@ var WorktreeRepoImpl = class _WorktreeRepoImpl {
4803
5351
  };
4804
5352
 
4805
5353
  // src/impl/git-impl.ts
5354
+ var GIT_VERSION_REGEX = /git version (\S+)/;
5355
+ function buildCloneArgs(opts) {
5356
+ const args = ["clone"];
5357
+ if (!opts) {
5358
+ return args;
5359
+ }
5360
+ const booleanFlags = [
5361
+ ["verbose", "--verbose"],
5362
+ ["quiet", "--quiet"],
5363
+ ["bare", "--bare"],
5364
+ ["mirror", "--mirror"],
5365
+ ["rejectShallow", "--reject-shallow"],
5366
+ ["singleBranch", "--single-branch"],
5367
+ ["noCheckout", "--no-checkout"],
5368
+ ["sparse", "--sparse"],
5369
+ ["local", "--local"],
5370
+ ["noHardlinks", "--no-hardlinks"],
5371
+ ["shared", "--shared"],
5372
+ ["dissociate", "--dissociate"],
5373
+ ["recurseSubmodules", "--recurse-submodules"],
5374
+ ["shallowSubmodules", "--shallow-submodules"],
5375
+ ["remoteSubmodules", "--remote-submodules"],
5376
+ ["noTags", "--no-tags"],
5377
+ ["alsoFilterSubmodules", "--also-filter-submodules"],
5378
+ ["ipv4", "--ipv4"],
5379
+ ["ipv6", "--ipv6"]
5380
+ ];
5381
+ for (const [key, flag] of booleanFlags) {
5382
+ if (opts[key]) {
5383
+ args.push(flag);
5384
+ }
5385
+ }
5386
+ const stringFlags = [
5387
+ ["branch", "--branch"],
5388
+ ["reference", "--reference"],
5389
+ ["referenceIfAble", "--reference-if-able"],
5390
+ ["template", "--template"],
5391
+ ["origin", "--origin"],
5392
+ ["separateGitDir", "--separate-git-dir"],
5393
+ ["filter", "--filter"]
5394
+ ];
5395
+ for (const [key, flag] of stringFlags) {
5396
+ const value = opts[key];
5397
+ if (typeof value === "string") {
5398
+ args.push(flag, value);
5399
+ }
5400
+ }
5401
+ if (opts.depth !== void 0) {
5402
+ args.push("--depth", String(opts.depth));
5403
+ }
5404
+ if (opts.jobs !== void 0) {
5405
+ args.push("--jobs", String(opts.jobs));
5406
+ }
5407
+ if (opts.shallowSince) {
5408
+ const since = opts.shallowSince instanceof Date ? opts.shallowSince.toISOString() : opts.shallowSince;
5409
+ args.push("--shallow-since", since);
5410
+ }
5411
+ if (opts.shallowExclude) {
5412
+ const excludes = Array.isArray(opts.shallowExclude) ? opts.shallowExclude : [opts.shallowExclude];
5413
+ for (const exclude of excludes) {
5414
+ args.push("--shallow-exclude", exclude);
5415
+ }
5416
+ }
5417
+ if (opts.config) {
5418
+ for (const [key, value] of Object.entries(opts.config)) {
5419
+ args.push("-c", `${key}=${value}`);
5420
+ }
5421
+ }
5422
+ return args;
5423
+ }
5424
+ var MIN_GIT_VERSION = "2.30.0";
5425
+ var LEGACY_GIT_VERSION = "2.25.0";
5426
+ var VERSION_REGEX = /^(\d+)\.(\d+)\.(\d+)/;
5427
+ function parseVersion(version) {
5428
+ const match = version.match(VERSION_REGEX);
5429
+ if (!match) {
5430
+ return [0, 0, 0];
5431
+ }
5432
+ return [
5433
+ Number.parseInt(match[1], 10),
5434
+ Number.parseInt(match[2], 10),
5435
+ Number.parseInt(match[3], 10)
5436
+ ];
5437
+ }
5438
+ function compareVersions(a, b) {
5439
+ const [aMajor, aMinor, aPatch] = parseVersion(a);
5440
+ const [bMajor, bMinor, bPatch] = parseVersion(b);
5441
+ if (aMajor !== bMajor) {
5442
+ return aMajor - bMajor;
5443
+ }
5444
+ if (aMinor !== bMinor) {
5445
+ return aMinor - bMinor;
5446
+ }
5447
+ return aPatch - bPatch;
5448
+ }
4806
5449
  function toCliRunnerOptions(opts) {
4807
5450
  if (!opts) {
4808
5451
  return {};
@@ -4820,6 +5463,7 @@ function toCliRunnerOptions(opts) {
4820
5463
  var GitImpl = class {
4821
5464
  runner;
4822
5465
  adapters;
5466
+ cachedVersion = null;
4823
5467
  config;
4824
5468
  lfs;
4825
5469
  constructor(options) {
@@ -4908,109 +5552,10 @@ var GitImpl = class {
4908
5552
  return new WorktreeRepoImpl(repoRunner, path, opts);
4909
5553
  }
4910
5554
  async clone(url, path, opts) {
4911
- const args = ["clone"];
5555
+ const args = buildCloneArgs(opts);
4912
5556
  if (opts?.onProgress) {
4913
5557
  args.push("--progress");
4914
5558
  }
4915
- if (opts?.verbose) {
4916
- args.push("--verbose");
4917
- }
4918
- if (opts?.quiet) {
4919
- args.push("--quiet");
4920
- }
4921
- if (opts?.bare) {
4922
- args.push("--bare");
4923
- }
4924
- if (opts?.mirror) {
4925
- args.push("--mirror");
4926
- }
4927
- if (opts?.depth !== void 0) {
4928
- args.push("--depth", String(opts.depth));
4929
- }
4930
- if (opts?.shallowSince) {
4931
- const since = opts.shallowSince instanceof Date ? opts.shallowSince.toISOString() : opts.shallowSince;
4932
- args.push("--shallow-since", since);
4933
- }
4934
- if (opts?.shallowExclude) {
4935
- const excludes = Array.isArray(opts.shallowExclude) ? opts.shallowExclude : [opts.shallowExclude];
4936
- for (const exclude of excludes) {
4937
- args.push("--shallow-exclude", exclude);
4938
- }
4939
- }
4940
- if (opts?.rejectShallow) {
4941
- args.push("--reject-shallow");
4942
- }
4943
- if (opts?.branch) {
4944
- args.push("--branch", opts.branch);
4945
- }
4946
- if (opts?.singleBranch) {
4947
- args.push("--single-branch");
4948
- }
4949
- if (opts?.noCheckout) {
4950
- args.push("--no-checkout");
4951
- }
4952
- if (opts?.sparse) {
4953
- args.push("--sparse");
4954
- }
4955
- if (opts?.local) {
4956
- args.push("--local");
4957
- }
4958
- if (opts?.noHardlinks) {
4959
- args.push("--no-hardlinks");
4960
- }
4961
- if (opts?.shared) {
4962
- args.push("--shared");
4963
- }
4964
- if (opts?.reference) {
4965
- args.push("--reference", opts.reference);
4966
- }
4967
- if (opts?.referenceIfAble) {
4968
- args.push("--reference-if-able", opts.referenceIfAble);
4969
- }
4970
- if (opts?.dissociate) {
4971
- args.push("--dissociate");
4972
- }
4973
- if (opts?.recurseSubmodules) {
4974
- args.push("--recurse-submodules");
4975
- }
4976
- if (opts?.shallowSubmodules) {
4977
- args.push("--shallow-submodules");
4978
- }
4979
- if (opts?.remoteSubmodules) {
4980
- args.push("--remote-submodules");
4981
- }
4982
- if (opts?.jobs !== void 0) {
4983
- args.push("--jobs", String(opts.jobs));
4984
- }
4985
- if (opts?.noTags) {
4986
- args.push("--no-tags");
4987
- }
4988
- if (opts?.template) {
4989
- args.push("--template", opts.template);
4990
- }
4991
- if (opts?.origin) {
4992
- args.push("--origin", opts.origin);
4993
- }
4994
- if (opts?.separateGitDir) {
4995
- args.push("--separate-git-dir", opts.separateGitDir);
4996
- }
4997
- if (opts?.config) {
4998
- for (const [key, value] of Object.entries(opts.config)) {
4999
- args.push("-c", `${key}=${value}`);
5000
- }
5001
- }
5002
- if (opts?.filter) {
5003
- args.push("--filter", opts.filter);
5004
- }
5005
- if (opts?.alsoFilterSubmodules) {
5006
- args.push("--also-filter-submodules");
5007
- }
5008
- if (opts?.ipv4) {
5009
- args.push("--ipv4");
5010
- }
5011
- if (opts?.ipv6) {
5012
- args.push("--ipv6");
5013
- }
5014
5559
  args.push(url, path);
5015
5560
  try {
5016
5561
  await this.runner.runOrThrow({ type: "global" }, args, {
@@ -5050,7 +5595,7 @@ var GitImpl = class {
5050
5595
  args.push(`--shared=${opts.shared}`);
5051
5596
  }
5052
5597
  }
5053
- if (opts?.initialBranch) {
5598
+ if (opts?.initialBranch && await this.supportsInitialBranch()) {
5054
5599
  args.push("--initial-branch", opts.initialBranch);
5055
5600
  }
5056
5601
  if (opts?.objectFormat) {
@@ -5065,6 +5610,16 @@ var GitImpl = class {
5065
5610
  signal: opts?.signal,
5066
5611
  onProgress: opts?.onProgress
5067
5612
  });
5613
+ if (opts?.initialBranch && !await this.supportsInitialBranch()) {
5614
+ const context = opts?.bare ? { type: "bare", gitDir: path } : { type: "worktree", workdir: path };
5615
+ await this.runner.runOrThrow(
5616
+ context,
5617
+ ["symbolic-ref", "HEAD", `refs/heads/${opts.initialBranch}`],
5618
+ {
5619
+ signal: opts?.signal
5620
+ }
5621
+ );
5622
+ }
5068
5623
  } catch (error) {
5069
5624
  if (error instanceof GitError && error.kind === "Aborted" && opts?.cleanupOnAbort !== false) {
5070
5625
  await this.adapters.fs.deleteDirectory(path);
@@ -5111,17 +5666,28 @@ var GitImpl = class {
5111
5666
  * Get git version
5112
5667
  */
5113
5668
  async version(opts) {
5669
+ if (this.cachedVersion) {
5670
+ return this.cachedVersion;
5671
+ }
5114
5672
  const result = await this.runner.runOrThrow({ type: "global" }, ["--version"], {
5115
5673
  signal: opts?.signal
5116
5674
  });
5117
- const match = result.stdout.match(/git version (\S+)/);
5118
- const version = match?.[1];
5119
- return version ?? result.stdout.trim();
5675
+ const match = result.stdout.match(GIT_VERSION_REGEX);
5676
+ const version = match?.[1] ?? result.stdout.trim();
5677
+ this.cachedVersion = version;
5678
+ return version;
5679
+ }
5680
+ /**
5681
+ * Check if Git version supports --initial-branch option (Git 2.28+)
5682
+ */
5683
+ async supportsInitialBranch() {
5684
+ const version = await this.version();
5685
+ return compareVersions(version, "2.28.0") >= 0;
5120
5686
  }
5121
5687
  /**
5122
5688
  * Execute a raw git command (repository-agnostic)
5123
5689
  */
5124
- async raw(argv, opts) {
5690
+ raw(argv, opts) {
5125
5691
  return this.runner.run({ type: "global" }, argv, opts);
5126
5692
  }
5127
5693
  // ==========================================================================
@@ -5307,9 +5873,24 @@ var GitImpl = class {
5307
5873
  return result.stdout.trim();
5308
5874
  }
5309
5875
  };
5310
- function createGit(options) {
5876
+ function createGitSync(options) {
5311
5877
  return new GitImpl(options);
5312
5878
  }
5879
+ async function createGit(options) {
5880
+ const git = new GitImpl(options);
5881
+ if (!options.skipVersionCheck) {
5882
+ const versionString = await git.version();
5883
+ const minVersion = options.useLegacyVersion ? LEGACY_GIT_VERSION : MIN_GIT_VERSION;
5884
+ if (compareVersions(versionString, minVersion) < 0) {
5885
+ throw new GitError(
5886
+ "UnsupportedGitVersion",
5887
+ `Git version ${versionString} is not supported. Minimum required version is ${minVersion}.`,
5888
+ {}
5889
+ );
5890
+ }
5891
+ }
5892
+ return git;
5893
+ }
5313
5894
 
5314
5895
  // src/adapters/node/exec.ts
5315
5896
  var import_node_child_process = require("child_process");
@@ -5468,52 +6049,132 @@ var NodeExecAdapter = class {
5468
6049
  var import_promises = require("fs/promises");
5469
6050
  var import_node_os = require("os");
5470
6051
  var import_node_path = require("path");
6052
+
6053
+ // src/internal/file-polling.ts
6054
+ async function runTailPolling(options) {
6055
+ const { adapter, signal, pollInterval = 100, onLine } = options;
6056
+ let position = 0;
6057
+ let buffer = "";
6058
+ while (!signal?.aborted) {
6059
+ const result = await adapter.readChunk(position);
6060
+ if (result !== null && result.data.length > 0) {
6061
+ position = result.newPosition;
6062
+ buffer += result.data;
6063
+ const lines = buffer.split("\n");
6064
+ buffer = lines.pop() ?? "";
6065
+ for (const line of lines) {
6066
+ if (line) {
6067
+ onLine(line);
6068
+ }
6069
+ }
6070
+ }
6071
+ if (!signal?.aborted) {
6072
+ await adapter.sleep(pollInterval);
6073
+ }
6074
+ }
6075
+ }
6076
+ function createTailPolling(options) {
6077
+ const { adapter, signal, pollInterval = 100 } = options;
6078
+ const state = {
6079
+ stopped: false,
6080
+ resolveNext: null,
6081
+ lineQueue: []
6082
+ };
6083
+ const stop = () => {
6084
+ state.stopped = true;
6085
+ if (state.resolveNext) {
6086
+ state.resolveNext({ done: true, value: void 0 });
6087
+ state.resolveNext = null;
6088
+ }
6089
+ };
6090
+ startPollingLoop(adapter, state, signal, pollInterval, stop).catch(() => {
6091
+ });
6092
+ const lines = {
6093
+ [Symbol.asyncIterator]() {
6094
+ return {
6095
+ next() {
6096
+ if (state.stopped) {
6097
+ return Promise.resolve({ done: true, value: void 0 });
6098
+ }
6099
+ if (state.lineQueue.length > 0) {
6100
+ const value = state.lineQueue.shift();
6101
+ if (value !== void 0) {
6102
+ return Promise.resolve({ done: false, value });
6103
+ }
6104
+ }
6105
+ return new Promise((resolve) => {
6106
+ state.resolveNext = resolve;
6107
+ });
6108
+ }
6109
+ };
6110
+ }
6111
+ };
6112
+ return { lines, stop };
6113
+ }
6114
+ async function startPollingLoop(adapter, state, signal, pollInterval, stop) {
6115
+ let position = 0;
6116
+ let buffer = "";
6117
+ while (!(state.stopped || signal?.aborted)) {
6118
+ const result = await adapter.readChunk(position);
6119
+ if (result !== null && result.data.length > 0) {
6120
+ position = result.newPosition;
6121
+ buffer += result.data;
6122
+ const lines = buffer.split("\n");
6123
+ buffer = lines.pop() ?? "";
6124
+ for (const line of lines) {
6125
+ if (line) {
6126
+ if (state.resolveNext) {
6127
+ const resolver = state.resolveNext;
6128
+ state.resolveNext = null;
6129
+ resolver({ done: false, value: line });
6130
+ } else {
6131
+ state.lineQueue.push(line);
6132
+ }
6133
+ }
6134
+ }
6135
+ }
6136
+ await adapter.sleep(pollInterval);
6137
+ }
6138
+ stop();
6139
+ }
6140
+
6141
+ // src/adapters/node/fs.ts
5471
6142
  var NodeFsAdapter = class {
5472
6143
  async createTempFile(prefix = "type-git-") {
5473
6144
  const dir = await (0, import_promises.mkdtemp)((0, import_node_path.join)((0, import_node_os.tmpdir)(), prefix));
5474
6145
  return (0, import_node_path.join)(dir, "temp");
5475
6146
  }
5476
6147
  async tail(options) {
5477
- const { filePath, signal, onLine } = options;
5478
- const file = await (0, import_promises.open)(filePath, "r");
5479
- let position = 0;
6148
+ const { filePath, signal, onLine, pollInterval = 100 } = options;
6149
+ const state = { file: null };
5480
6150
  const decoder = new TextDecoder();
5481
- let buffer = "";
5482
- const poll = async () => {
5483
- if (signal?.aborted) {
5484
- await file.close();
5485
- return;
5486
- }
5487
- try {
5488
- const { bytesRead, buffer: chunk } = await file.read({
5489
- buffer: Buffer.alloc(4096),
5490
- position
5491
- });
5492
- if (bytesRead > 0) {
5493
- position += bytesRead;
5494
- buffer += decoder.decode(chunk.subarray(0, bytesRead), { stream: true });
5495
- const lines = buffer.split("\n");
5496
- buffer = lines.pop() ?? "";
5497
- for (const line of lines) {
5498
- if (line) {
5499
- onLine(line);
5500
- }
6151
+ const adapter = {
6152
+ readChunk: async (position) => {
6153
+ try {
6154
+ if (!state.file) {
6155
+ state.file = await (0, import_promises.open)(filePath, "r");
5501
6156
  }
5502
- }
5503
- } catch (error) {
5504
- await file.close();
5505
- throw error;
5506
- }
5507
- if (!signal?.aborted) {
5508
- setTimeout(() => {
5509
- poll().catch(() => {
6157
+ const { bytesRead, buffer: chunk } = await state.file.read({
6158
+ buffer: Buffer.alloc(4096),
6159
+ position
5510
6160
  });
5511
- }, 100);
5512
- } else {
5513
- await file.close();
5514
- }
6161
+ return {
6162
+ data: decoder.decode(chunk.subarray(0, bytesRead), { stream: true }),
6163
+ newPosition: position + bytesRead
6164
+ };
6165
+ } catch {
6166
+ return null;
6167
+ }
6168
+ },
6169
+ sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms))
5515
6170
  };
5516
- await poll();
6171
+ try {
6172
+ await runTailPolling({ adapter, signal, pollInterval, onLine });
6173
+ } finally {
6174
+ if (state.file) {
6175
+ await state.file.close();
6176
+ }
6177
+ }
5517
6178
  }
5518
6179
  async deleteFile(filePath) {
5519
6180
  await (0, import_promises.rm)(filePath, { force: true });
@@ -5537,83 +6198,39 @@ var NodeFsAdapter = class {
5537
6198
  }
5538
6199
  tailStreaming(filePath, options) {
5539
6200
  const { signal, pollInterval = 100 } = options ?? {};
5540
- const state = {
5541
- stopped: false,
5542
- resolveNext: null,
5543
- lineQueue: []
5544
- };
5545
- const stop = () => {
5546
- state.stopped = true;
5547
- if (state.resolveNext) {
5548
- state.resolveNext({ done: true, value: void 0 });
5549
- state.resolveNext = null;
5550
- }
5551
- };
5552
- const startPolling = async () => {
5553
- let file;
5554
- try {
5555
- file = await (0, import_promises.open)(filePath, "r");
5556
- } catch {
5557
- stop();
5558
- return;
5559
- }
5560
- let position = 0;
5561
- const decoder = new TextDecoder();
5562
- let buffer = "";
5563
- while (!(state.stopped || signal?.aborted)) {
6201
+ const state = { file: null };
6202
+ const decoder = new TextDecoder();
6203
+ const adapter = {
6204
+ readChunk: async (position) => {
5564
6205
  try {
5565
- const { bytesRead, buffer: chunk } = await file.read({
6206
+ if (!state.file) {
6207
+ state.file = await (0, import_promises.open)(filePath, "r");
6208
+ }
6209
+ const { bytesRead, buffer: chunk } = await state.file.read({
5566
6210
  buffer: Buffer.alloc(4096),
5567
6211
  position
5568
6212
  });
5569
- if (bytesRead > 0) {
5570
- position += bytesRead;
5571
- buffer += decoder.decode(chunk.subarray(0, bytesRead), { stream: true });
5572
- const lines2 = buffer.split("\n");
5573
- buffer = lines2.pop() ?? "";
5574
- for (const line of lines2) {
5575
- if (line) {
5576
- if (state.resolveNext) {
5577
- const resolver = state.resolveNext;
5578
- state.resolveNext = null;
5579
- resolver({ done: false, value: line });
5580
- } else {
5581
- state.lineQueue.push(line);
5582
- }
5583
- }
5584
- }
5585
- }
6213
+ return {
6214
+ data: decoder.decode(chunk.subarray(0, bytesRead), { stream: true }),
6215
+ newPosition: position + bytesRead
6216
+ };
5586
6217
  } catch {
5587
- break;
6218
+ return null;
5588
6219
  }
5589
- await new Promise((resolve) => setTimeout(resolve, pollInterval));
5590
- }
5591
- await file.close();
5592
- stop();
6220
+ },
6221
+ sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms))
5593
6222
  };
5594
- startPolling().catch(() => {
5595
- });
5596
- const lines = {
5597
- [Symbol.asyncIterator]() {
5598
- return {
5599
- next() {
5600
- if (state.stopped) {
5601
- return Promise.resolve({ done: true, value: void 0 });
5602
- }
5603
- if (state.lineQueue.length > 0) {
5604
- const value = state.lineQueue.shift();
5605
- if (value !== void 0) {
5606
- return Promise.resolve({ done: false, value });
5607
- }
5608
- }
5609
- return new Promise((resolve) => {
5610
- state.resolveNext = resolve;
5611
- });
5612
- }
5613
- };
6223
+ const polling = createTailPolling({ adapter, signal, pollInterval });
6224
+ const originalStop = polling.stop;
6225
+ const enhancedStop = () => {
6226
+ originalStop();
6227
+ if (state.file) {
6228
+ state.file.close().catch(() => {
6229
+ });
6230
+ state.file = null;
5614
6231
  }
5615
6232
  };
5616
- return { lines, stop };
6233
+ return { lines: polling.lines, stop: enhancedStop };
5617
6234
  }
5618
6235
  };
5619
6236
 
@@ -5624,13 +6241,31 @@ function createNodeAdapters() {
5624
6241
  fs: new NodeFsAdapter()
5625
6242
  };
5626
6243
  }
5627
- var TypeGit = class {
6244
+ var TypeGit = class _TypeGit {
5628
6245
  git;
5629
- constructor(options) {
5630
- this.git = createGit({
5631
- ...options,
6246
+ /**
6247
+ * Create a TypeGit instance with Git version check
6248
+ *
6249
+ * @param createOpts - Options including skipVersionCheck
6250
+ * @returns TypeGit instance
6251
+ * @throws GitError with kind 'UnsupportedGitVersion' if Git version is below minimum
6252
+ */
6253
+ static async create(createOpts) {
6254
+ const gitInstance = await createGit({
6255
+ ...createOpts,
5632
6256
  adapters: createNodeAdapters()
5633
6257
  });
6258
+ return new _TypeGit(gitInstance);
6259
+ }
6260
+ constructor(optionsOrGit) {
6261
+ if (optionsOrGit && "open" in optionsOrGit) {
6262
+ this.git = optionsOrGit;
6263
+ } else {
6264
+ this.git = createGitSync({
6265
+ ...optionsOrGit,
6266
+ adapters: createNodeAdapters()
6267
+ });
6268
+ }
5634
6269
  }
5635
6270
  /**
5636
6271
  * Open an existing worktree repository
@@ -5722,10 +6357,13 @@ var TypeGit = class {
5722
6357
  GIT_LOG_FORMAT,
5723
6358
  GitArgumentError,
5724
6359
  GitError,
6360
+ LEGACY_GIT_VERSION,
6361
+ MIN_GIT_VERSION,
5725
6362
  NodeExecAdapter,
5726
6363
  NodeFsAdapter,
5727
6364
  TypeGit,
5728
6365
  createGit,
6366
+ createGitSync,
5729
6367
  createNodeAdapters,
5730
6368
  detectErrorCategory,
5731
6369
  isNonEmpty,
@@ -5737,6 +6375,7 @@ var TypeGit = class {
5737
6375
  parseLfsProgress,
5738
6376
  parseLines,
5739
6377
  parseLsRemote,
6378
+ parseLsTree,
5740
6379
  parsePorcelainV2,
5741
6380
  parseRecords,
5742
6381
  parseWorktreeList