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.js CHANGED
@@ -39,6 +39,16 @@ var GitArgumentError = class extends Error {
39
39
  };
40
40
 
41
41
  // src/parsers/index.ts
42
+ var GIT_PROGRESS_PERCENT_REGEX = /^(.+?):\s*(\d+)%\s*\((\d+)\/(\d+)\)(?:,\s*(done))?/;
43
+ var GIT_PROGRESS_SIMPLE_REGEX = /^(.+?):\s*(\d+)\/(\d+)/;
44
+ var WHITESPACE_REGEX = /\s+/;
45
+ var BYTES_RATIO_REGEX = /^(\d+)\/(\d+)$/;
46
+ var SIZE_REGEX = /^([\d.]+)\s*(B|KB|MB|GB|TB)?$/i;
47
+ var BITRATE_REGEX = /^([\d.]+)\s*(B|KB|MB|GB)\/s$/i;
48
+ var LFS_DOWNLOAD_REGEX = /downloading|filtering/i;
49
+ var LFS_UPLOAD_REGEX = /uploading/i;
50
+ var LFS_CHECKOUT_REGEX = /checking out/i;
51
+ 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;
42
52
  function at(arr, index, context) {
43
53
  const value = arr[index];
44
54
  if (value === void 0) {
@@ -151,7 +161,7 @@ function parsePorcelainV2(stdout) {
151
161
  return entries;
152
162
  }
153
163
  function parseGitProgress(line) {
154
- const match = line.match(/^(.+?):\s*(\d+)%\s*\((\d+)\/(\d+)\)(?:,\s*(done))?/);
164
+ const match = line.match(GIT_PROGRESS_PERCENT_REGEX);
155
165
  if (match) {
156
166
  const percent = match[2];
157
167
  const current = match[3];
@@ -167,7 +177,7 @@ function parseGitProgress(line) {
167
177
  done: match[5] === "done"
168
178
  };
169
179
  }
170
- const simpleMatch = line.match(/^(.+?):\s*(\d+)\/(\d+)/);
180
+ const simpleMatch = line.match(GIT_PROGRESS_SIMPLE_REGEX);
171
181
  if (simpleMatch) {
172
182
  const currentStr = simpleMatch[2];
173
183
  const totalStr = simpleMatch[3];
@@ -187,7 +197,7 @@ function parseGitProgress(line) {
187
197
  return null;
188
198
  }
189
199
  function parseLfsProgress(line) {
190
- const parts = line.trim().split(/\s+/);
200
+ const parts = line.trim().split(WHITESPACE_REGEX);
191
201
  if (parts.length < 4) {
192
202
  return null;
193
203
  }
@@ -202,7 +212,7 @@ function parseLfsProgress(line) {
202
212
  if (oid === void 0 || bytesStr === void 0 || transferredStr === void 0) {
203
213
  return null;
204
214
  }
205
- const bytesMatch = bytesStr.match(/^(\d+)\/(\d+)$/);
215
+ const bytesMatch = bytesStr.match(BYTES_RATIO_REGEX);
206
216
  if (!bytesMatch) {
207
217
  return null;
208
218
  }
@@ -220,7 +230,7 @@ function parseLfsProgress(line) {
220
230
  };
221
231
  }
222
232
  function parseSizeToBytes(sizeStr) {
223
- const match = sizeStr.match(/^([\d.]+)\s*(B|KB|MB|GB|TB)?$/i);
233
+ const match = sizeStr.match(SIZE_REGEX);
224
234
  if (!match) {
225
235
  return 0;
226
236
  }
@@ -236,7 +246,7 @@ function parseSizeToBytes(sizeStr) {
236
246
  return Math.round(value * (multipliers[unit] || 1));
237
247
  }
238
248
  function parseBitrateToBytes(bitrateStr) {
239
- const match = bitrateStr.match(/^([\d.]+)\s*(B|KB|MB|GB)\/s$/i);
249
+ const match = bitrateStr.match(BITRATE_REGEX);
240
250
  if (!match) {
241
251
  return null;
242
252
  }
@@ -252,18 +262,16 @@ function parseBitrateToBytes(bitrateStr) {
252
262
  }
253
263
  function parseLfsStderrProgress(line) {
254
264
  let direction;
255
- if (/downloading|filtering/i.test(line)) {
265
+ if (LFS_DOWNLOAD_REGEX.test(line)) {
256
266
  direction = "download";
257
- } else if (/uploading/i.test(line)) {
267
+ } else if (LFS_UPLOAD_REGEX.test(line)) {
258
268
  direction = "upload";
259
- } else if (/checking out/i.test(line)) {
269
+ } else if (LFS_CHECKOUT_REGEX.test(line)) {
260
270
  direction = "checkout";
261
271
  } else {
262
272
  return null;
263
273
  }
264
- const progressMatch = line.match(
265
- /(\d+)%\s*\((\d+)\/(\d+)\)(?:,\s*([\d.]+\s*(?:B|KB|MB|GB|TB)?)\s*(?:\|\s*([\d.]+\s*(?:B|KB|MB|GB)\/s))?)?/i
266
- );
274
+ const progressMatch = line.match(LFS_PROGRESS_REGEX);
267
275
  if (!progressMatch) {
268
276
  return null;
269
277
  }
@@ -304,6 +312,68 @@ function parseLsRemote(stdout) {
304
312
  }
305
313
  return refs;
306
314
  }
315
+ var LS_TREE_REGEX = /^(\d+)\s+(blob|tree|commit)\s+([a-f0-9]+)\t(.+)$/;
316
+ var LS_TREE_LONG_REGEX = /^(\d+)\s+(blob|tree|commit)\s+([a-f0-9]+)\s+(-|\d+)\t(.+)$/;
317
+ function parseLsTree(stdout, opts) {
318
+ const entries = [];
319
+ const lines = parseLines(stdout);
320
+ for (const line of lines) {
321
+ if (opts?.nameOnly) {
322
+ entries.push({
323
+ mode: "",
324
+ type: "blob",
325
+ hash: "",
326
+ path: line
327
+ });
328
+ continue;
329
+ }
330
+ if (opts?.objectOnly) {
331
+ entries.push({
332
+ mode: "",
333
+ type: "blob",
334
+ hash: line,
335
+ path: ""
336
+ });
337
+ continue;
338
+ }
339
+ if (opts?.long) {
340
+ const longMatch = line.match(LS_TREE_LONG_REGEX);
341
+ if (longMatch) {
342
+ const mode = longMatch[1];
343
+ const type = longMatch[2];
344
+ const hash = longMatch[3];
345
+ const sizeStr = longMatch[4];
346
+ const path = longMatch[5];
347
+ if (mode && type && hash && path) {
348
+ entries.push({
349
+ mode,
350
+ type,
351
+ hash,
352
+ path,
353
+ size: sizeStr === "-" || !sizeStr ? void 0 : Number.parseInt(sizeStr, 10)
354
+ });
355
+ }
356
+ continue;
357
+ }
358
+ }
359
+ const match = line.match(LS_TREE_REGEX);
360
+ if (match) {
361
+ const mode = match[1];
362
+ const type = match[2];
363
+ const hash = match[3];
364
+ const path = match[4];
365
+ if (mode && type && hash && path) {
366
+ entries.push({
367
+ mode,
368
+ type,
369
+ hash,
370
+ path
371
+ });
372
+ }
373
+ }
374
+ }
375
+ return entries;
376
+ }
307
377
  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";
308
378
  function parseGitLog(stdout) {
309
379
  const commits = [];
@@ -313,7 +383,7 @@ function parseGitLog(stdout) {
313
383
  if (fields.length < 11) {
314
384
  continue;
315
385
  }
316
- const hash = fields[0];
386
+ const hash = fields[0]?.trim();
317
387
  const abbrevHash = fields[1];
318
388
  const parentsStr = fields[2];
319
389
  const authorName = fields[3];
@@ -435,6 +505,51 @@ import process2 from "process";
435
505
  var FATAL_ERROR_PATTERN = /fatal:\s*(.+)/i;
436
506
  var ERROR_PATTERN = /error:\s*(.+)/i;
437
507
  var LINE_SEPARATOR_PATTERN = /\r|\n/;
508
+ function toLfsProgress(info) {
509
+ if (!info) {
510
+ return null;
511
+ }
512
+ return {
513
+ direction: info.direction,
514
+ bytesSoFar: info.bytesSoFar,
515
+ bytesTotal: info.bytesTotal,
516
+ bitrate: info.bitrate ?? void 0,
517
+ filesCompleted: info.filesCompleted,
518
+ filesTotal: info.filesTotal,
519
+ percent: info.percent
520
+ };
521
+ }
522
+ function toGitProgress(info, message) {
523
+ if (!info) {
524
+ return null;
525
+ }
526
+ return {
527
+ phase: info.phase,
528
+ current: info.current,
529
+ total: info.total,
530
+ percent: info.percent,
531
+ message
532
+ };
533
+ }
534
+ function processProgressLine(line, onProgress, onLfsProgress) {
535
+ const trimmed = line.trim();
536
+ if (!trimmed) {
537
+ return;
538
+ }
539
+ if (onLfsProgress) {
540
+ const lfsProgress = toLfsProgress(parseLfsStderrProgress(trimmed));
541
+ if (lfsProgress) {
542
+ onLfsProgress(lfsProgress);
543
+ return;
544
+ }
545
+ }
546
+ if (onProgress) {
547
+ const gitProgress = toGitProgress(parseGitProgress(trimmed), trimmed);
548
+ if (gitProgress) {
549
+ onProgress(gitProgress);
550
+ }
551
+ }
552
+ }
438
553
  var CliRunner = class _CliRunner {
439
554
  exec;
440
555
  gitBinary;
@@ -561,73 +676,13 @@ var CliRunner = class _CliRunner {
561
676
  const lines = stderrBuffer.split(LINE_SEPARATOR_PATTERN);
562
677
  stderrBuffer = lines.pop() ?? "";
563
678
  for (const line of lines) {
564
- const trimmed = line.trim();
565
- if (!trimmed) {
566
- continue;
567
- }
568
- if (onLfsProgress) {
569
- const lfsProgressInfo = parseLfsStderrProgress(trimmed);
570
- if (lfsProgressInfo) {
571
- const lfsProgress = {
572
- direction: lfsProgressInfo.direction,
573
- bytesSoFar: lfsProgressInfo.bytesSoFar,
574
- bytesTotal: lfsProgressInfo.bytesTotal,
575
- bitrate: lfsProgressInfo.bitrate ?? void 0,
576
- filesCompleted: lfsProgressInfo.filesCompleted,
577
- filesTotal: lfsProgressInfo.filesTotal,
578
- percent: lfsProgressInfo.percent
579
- };
580
- onLfsProgress(lfsProgress);
581
- continue;
582
- }
583
- }
584
- if (onProgress) {
585
- const gitProgressInfo = parseGitProgress(trimmed);
586
- if (gitProgressInfo) {
587
- const gitProgress = {
588
- phase: gitProgressInfo.phase,
589
- current: gitProgressInfo.current,
590
- total: gitProgressInfo.total,
591
- percent: gitProgressInfo.percent,
592
- message: trimmed
593
- };
594
- onProgress(gitProgress);
595
- }
596
- }
679
+ processProgressLine(line, onProgress, onLfsProgress);
597
680
  }
598
681
  }
599
682
  } : void 0
600
683
  );
601
684
  if (stderrBuffer.trim() && (onProgress || onLfsProgress)) {
602
- const trimmed = stderrBuffer.trim();
603
- if (onLfsProgress) {
604
- const lfsProgressInfo = parseLfsStderrProgress(trimmed);
605
- if (lfsProgressInfo) {
606
- const lfsProgress = {
607
- direction: lfsProgressInfo.direction,
608
- bytesSoFar: lfsProgressInfo.bytesSoFar,
609
- bytesTotal: lfsProgressInfo.bytesTotal,
610
- bitrate: lfsProgressInfo.bitrate ?? void 0,
611
- filesCompleted: lfsProgressInfo.filesCompleted,
612
- filesTotal: lfsProgressInfo.filesTotal,
613
- percent: lfsProgressInfo.percent
614
- };
615
- onLfsProgress(lfsProgress);
616
- }
617
- }
618
- if (onProgress && !onLfsProgress) {
619
- const gitProgressInfo = parseGitProgress(trimmed);
620
- if (gitProgressInfo) {
621
- const gitProgress = {
622
- phase: gitProgressInfo.phase,
623
- current: gitProgressInfo.current,
624
- total: gitProgressInfo.total,
625
- percent: gitProgressInfo.percent,
626
- message: trimmed
627
- };
628
- onProgress(gitProgress);
629
- }
630
- }
685
+ processProgressLine(stderrBuffer, onProgress, onLfsProgress);
631
686
  }
632
687
  return {
633
688
  stdout: result.stdout,
@@ -712,6 +767,196 @@ var CliRunner = class _CliRunner {
712
767
  };
713
768
 
714
769
  // src/impl/bare-repo-impl.ts
770
+ var REMOTE_LINE_PATTERN = /^(\S+)\t(.+?)\s+\((fetch|push)\)$/;
771
+ var PRUNED_REF_PATTERN = /\* \[pruned\] (.+)/;
772
+ function parseRemoteLine(line, remotes) {
773
+ const match = line.match(REMOTE_LINE_PATTERN);
774
+ if (!match) {
775
+ return;
776
+ }
777
+ const name = match[1];
778
+ const url = match[2];
779
+ const type = match[3];
780
+ if (name === void 0 || url === void 0) {
781
+ return;
782
+ }
783
+ const existing = remotes.get(name);
784
+ if (existing) {
785
+ updateRemoteUrl(existing, type, url);
786
+ } else {
787
+ remotes.set(name, {
788
+ name,
789
+ fetchUrl: type === "fetch" ? url : "",
790
+ pushUrl: type === "push" ? url : ""
791
+ });
792
+ }
793
+ }
794
+ function updateRemoteUrl(remote, type, url) {
795
+ if (type === "fetch") {
796
+ remote.fetchUrl = url;
797
+ } else if (type === "push") {
798
+ remote.pushUrl = url;
799
+ }
800
+ }
801
+ function normalizeRemoteUrls(remotes) {
802
+ for (const remote of remotes.values()) {
803
+ if (!remote.fetchUrl && remote.pushUrl) {
804
+ remote.fetchUrl = remote.pushUrl;
805
+ }
806
+ if (!remote.pushUrl && remote.fetchUrl) {
807
+ remote.pushUrl = remote.fetchUrl;
808
+ }
809
+ }
810
+ }
811
+ function addRefOptions(args, opts) {
812
+ if (!opts) {
813
+ return;
814
+ }
815
+ if (opts.verify) {
816
+ args.push("--verify");
817
+ }
818
+ if (opts.short !== void 0) {
819
+ if (typeof opts.short === "number") {
820
+ args.push(`--short=${opts.short}`);
821
+ } else if (opts.short) {
822
+ args.push("--short");
823
+ }
824
+ }
825
+ if (opts.abbrevRef !== void 0) {
826
+ if (opts.abbrevRef === "strict") {
827
+ args.push("--abbrev-ref=strict");
828
+ } else if (opts.abbrevRef === "loose") {
829
+ args.push("--abbrev-ref=loose");
830
+ } else if (opts.abbrevRef) {
831
+ args.push("--abbrev-ref");
832
+ }
833
+ }
834
+ if (opts.symbolic) {
835
+ args.push("--symbolic");
836
+ }
837
+ if (opts.symbolicFullName) {
838
+ args.push("--symbolic-full-name");
839
+ }
840
+ if (opts.quiet) {
841
+ args.push("--quiet");
842
+ }
843
+ }
844
+ var PATH_QUERY_FLAGS = [
845
+ ["gitDir", "--git-dir"],
846
+ ["absoluteGitDir", "--absolute-git-dir"],
847
+ ["gitCommonDir", "--git-common-dir"],
848
+ ["showToplevel", "--show-toplevel"],
849
+ ["showCdup", "--show-cdup"],
850
+ ["showPrefix", "--show-prefix"],
851
+ ["showSuperprojectWorkingTree", "--show-superproject-working-tree"],
852
+ ["sharedIndexPath", "--shared-index-path"]
853
+ ];
854
+ var PATH_QUERY_VALUE_FLAGS = [
855
+ ["gitPath", "--git-path"],
856
+ ["resolveGitDir", "--resolve-git-dir"]
857
+ ];
858
+ var BOOLEAN_QUERY_FLAGS = [
859
+ ["isInsideGitDir", "--is-inside-git-dir"],
860
+ ["isInsideWorkTree", "--is-inside-work-tree"],
861
+ ["isBareRepository", "--is-bare-repository"],
862
+ ["isShallowRepository", "--is-shallow-repository"]
863
+ ];
864
+ var LIST_QUERY_FLAGS = [
865
+ ["all", "--all"],
866
+ ["branches", "--branches"],
867
+ ["tags", "--tags"],
868
+ ["remotes", "--remotes"]
869
+ ];
870
+ function addExcludeOptions(args, opts) {
871
+ if ("exclude" in opts && opts.exclude) {
872
+ args.push(`--exclude=${opts.exclude}`);
873
+ }
874
+ if ("excludeHidden" in opts && opts.excludeHidden) {
875
+ args.push(`--exclude-hidden=${opts.excludeHidden}`);
876
+ }
877
+ }
878
+ function tryAddPathQuery(args, opts) {
879
+ for (const [key, flag] of PATH_QUERY_FLAGS) {
880
+ if (key in opts && opts[key]) {
881
+ args.push(flag);
882
+ return true;
883
+ }
884
+ }
885
+ for (const [key, flag] of PATH_QUERY_VALUE_FLAGS) {
886
+ if (key in opts && typeof opts[key] === "string") {
887
+ args.push(flag, opts[key]);
888
+ return true;
889
+ }
890
+ }
891
+ return false;
892
+ }
893
+ function tryAddBooleanQuery(args, opts) {
894
+ for (const [key, flag] of BOOLEAN_QUERY_FLAGS) {
895
+ if (key in opts && opts[key]) {
896
+ args.push(flag);
897
+ return true;
898
+ }
899
+ }
900
+ return false;
901
+ }
902
+ function tryAddListQuery(args, opts) {
903
+ for (const [key, flag] of LIST_QUERY_FLAGS) {
904
+ if (key in opts && opts[key]) {
905
+ addExcludeOptions(args, opts);
906
+ if (typeof opts[key] === "string") {
907
+ args.push(`${flag}=${opts[key]}`);
908
+ } else {
909
+ args.push(flag);
910
+ }
911
+ return true;
912
+ }
913
+ }
914
+ if ("glob" in opts && typeof opts.glob === "string") {
915
+ addExcludeOptions(args, opts);
916
+ args.push(`--glob=${opts.glob}`);
917
+ return true;
918
+ }
919
+ if ("disambiguate" in opts && typeof opts.disambiguate === "string") {
920
+ args.push(`--disambiguate=${opts.disambiguate}`);
921
+ return true;
922
+ }
923
+ return false;
924
+ }
925
+ function tryAddOtherQuery(args, opts) {
926
+ if ("showObjectFormat" in opts && opts.showObjectFormat) {
927
+ if (opts.showObjectFormat === true) {
928
+ args.push("--show-object-format");
929
+ } else {
930
+ args.push(`--show-object-format=${opts.showObjectFormat}`);
931
+ }
932
+ return true;
933
+ }
934
+ if ("showRefFormat" in opts && opts.showRefFormat) {
935
+ args.push("--show-ref-format");
936
+ return true;
937
+ }
938
+ if ("localEnvVars" in opts && opts.localEnvVars) {
939
+ args.push("--local-env-vars");
940
+ return true;
941
+ }
942
+ return false;
943
+ }
944
+ function isBooleanQuery(opts) {
945
+ for (const [key] of BOOLEAN_QUERY_FLAGS) {
946
+ if (key in opts && opts[key]) {
947
+ return true;
948
+ }
949
+ }
950
+ return false;
951
+ }
952
+ function isListQuery(opts) {
953
+ for (const [key] of LIST_QUERY_FLAGS) {
954
+ if (key in opts && opts[key]) {
955
+ return true;
956
+ }
957
+ }
958
+ return "glob" in opts && !!opts.glob || "disambiguate" in opts && !!opts.disambiguate || "localEnvVars" in opts && !!opts.localEnvVars;
959
+ }
715
960
  var BareRepoImpl = class {
716
961
  gitDir;
717
962
  runner;
@@ -774,6 +1019,116 @@ var BareRepoImpl = class {
774
1019
  const result = await this.runner.run(this.context, ["rev-parse", "--is-bare-repository"]);
775
1020
  return result.exitCode === 0 && result.stdout.trim() === "true";
776
1021
  }
1022
+ /**
1023
+ * List references in a remote repository
1024
+ */
1025
+ async lsRemote(remote, opts) {
1026
+ const args = ["ls-remote"];
1027
+ if (opts?.heads) {
1028
+ args.push("--heads");
1029
+ }
1030
+ if (opts?.tags) {
1031
+ args.push("--tags");
1032
+ }
1033
+ if (opts?.refsOnly) {
1034
+ args.push("--refs");
1035
+ }
1036
+ if (opts?.getUrl) {
1037
+ args.push("--get-url");
1038
+ }
1039
+ if (opts?.sort) {
1040
+ args.push("--sort", opts.sort);
1041
+ }
1042
+ if (opts?.symref) {
1043
+ args.push("--symref");
1044
+ }
1045
+ args.push(remote);
1046
+ if (opts?.refs && opts.refs.length > 0) {
1047
+ args.push(...opts.refs);
1048
+ }
1049
+ const result = await this.runner.runOrThrow(this.context, args, {
1050
+ signal: opts?.signal,
1051
+ onProgress: opts?.onProgress
1052
+ });
1053
+ const refs = parseLsRemote(result.stdout);
1054
+ return { refs };
1055
+ }
1056
+ /**
1057
+ * List contents of a tree object
1058
+ */
1059
+ async lsTree(treeish, opts) {
1060
+ const args = ["ls-tree"];
1061
+ if (opts?.recursive) {
1062
+ args.push("-r");
1063
+ }
1064
+ if (opts?.treeOnly) {
1065
+ args.push("-d");
1066
+ }
1067
+ if (opts?.showTrees) {
1068
+ args.push("-t");
1069
+ }
1070
+ if (opts?.long) {
1071
+ args.push("--long");
1072
+ }
1073
+ if (opts?.nameOnly) {
1074
+ args.push("--name-only");
1075
+ }
1076
+ if (opts?.objectOnly) {
1077
+ args.push("--object-only");
1078
+ }
1079
+ if (opts?.fullName) {
1080
+ args.push("--full-name");
1081
+ }
1082
+ if (opts?.fullTree) {
1083
+ args.push("--full-tree");
1084
+ }
1085
+ if (opts?.abbrev !== void 0) {
1086
+ if (opts.abbrev === true) {
1087
+ args.push("--abbrev");
1088
+ } else if (typeof opts.abbrev === "number") {
1089
+ args.push(`--abbrev=${opts.abbrev}`);
1090
+ }
1091
+ }
1092
+ args.push(treeish);
1093
+ if (opts?.paths && opts.paths.length > 0) {
1094
+ args.push("--", ...opts.paths);
1095
+ }
1096
+ const result = await this.runner.runOrThrow(this.context, args, {
1097
+ signal: opts?.signal
1098
+ });
1099
+ return parseLsTree(result.stdout, {
1100
+ nameOnly: opts?.nameOnly,
1101
+ objectOnly: opts?.objectOnly,
1102
+ long: opts?.long
1103
+ });
1104
+ }
1105
+ async revParse(refOrOpts, opts) {
1106
+ const args = ["rev-parse"];
1107
+ if (typeof refOrOpts === "string") {
1108
+ addRefOptions(args, opts);
1109
+ args.push(refOrOpts);
1110
+ const result2 = await this.runner.runOrThrow(this.context, args, {
1111
+ signal: opts?.signal
1112
+ });
1113
+ return result2.stdout.trim();
1114
+ }
1115
+ const queryOpts = refOrOpts;
1116
+ tryAddPathQuery(args, queryOpts) || tryAddBooleanQuery(args, queryOpts) || tryAddListQuery(args, queryOpts) || tryAddOtherQuery(args, queryOpts);
1117
+ if ("pathFormat" in queryOpts && queryOpts.pathFormat) {
1118
+ args.push(`--path-format=${queryOpts.pathFormat}`);
1119
+ }
1120
+ const result = await this.runner.runOrThrow(this.context, args, {
1121
+ signal: refOrOpts.signal
1122
+ });
1123
+ const output = result.stdout.trim();
1124
+ if (isBooleanQuery(queryOpts)) {
1125
+ return output === "true";
1126
+ }
1127
+ if (isListQuery(queryOpts)) {
1128
+ return output ? output.split("\n").filter((line) => line.length > 0) : [];
1129
+ }
1130
+ return output;
1131
+ }
777
1132
  /**
778
1133
  * Fetch from remote
779
1134
  */
@@ -841,37 +1196,9 @@ var BareRepoImpl = class {
841
1196
  });
842
1197
  const remotes = /* @__PURE__ */ new Map();
843
1198
  for (const line of parseLines(result.stdout)) {
844
- const match = line.match(/^(\S+)\t(.+?)\s+\((fetch|push)\)$/);
845
- if (match) {
846
- const name = match[1];
847
- const url = match[2];
848
- const type = match[3];
849
- if (name !== void 0 && url !== void 0) {
850
- const existing = remotes.get(name);
851
- if (existing) {
852
- if (type === "fetch") {
853
- existing.fetchUrl = url;
854
- } else if (type === "push") {
855
- existing.pushUrl = url;
856
- }
857
- } else {
858
- remotes.set(name, {
859
- name,
860
- fetchUrl: type === "fetch" ? url : "",
861
- pushUrl: type === "push" ? url : ""
862
- });
863
- }
864
- }
865
- }
866
- }
867
- for (const remote of remotes.values()) {
868
- if (!remote.fetchUrl && remote.pushUrl) {
869
- remote.fetchUrl = remote.pushUrl;
870
- }
871
- if (!remote.pushUrl && remote.fetchUrl) {
872
- remote.pushUrl = remote.fetchUrl;
873
- }
1199
+ parseRemoteLine(line, remotes);
874
1200
  }
1201
+ normalizeRemoteUrls(remotes);
875
1202
  return Array.from(remotes.values());
876
1203
  }
877
1204
  async remoteAdd(name, url, opts) {
@@ -960,7 +1287,7 @@ var BareRepoImpl = class {
960
1287
  });
961
1288
  const pruned = [];
962
1289
  for (const line of parseLines(result.stdout)) {
963
- const match = line.match(/\* \[pruned\] (.+)/);
1290
+ const match = line.match(PRUNED_REF_PATTERN);
964
1291
  const ref = match?.[1];
965
1292
  if (ref) {
966
1293
  pruned.push(ref);
@@ -1287,6 +1614,89 @@ var WorktreeRepoImpl = class _WorktreeRepoImpl {
1287
1614
  const result = await this.runner.run(this.context, ["rev-parse", "--is-bare-repository"]);
1288
1615
  return result.exitCode === 0 && result.stdout.trim() === "true";
1289
1616
  }
1617
+ /**
1618
+ * List references in a remote repository
1619
+ */
1620
+ async lsRemote(remote, opts) {
1621
+ const args = ["ls-remote"];
1622
+ if (opts?.heads) {
1623
+ args.push("--heads");
1624
+ }
1625
+ if (opts?.tags) {
1626
+ args.push("--tags");
1627
+ }
1628
+ if (opts?.refsOnly) {
1629
+ args.push("--refs");
1630
+ }
1631
+ if (opts?.getUrl) {
1632
+ args.push("--get-url");
1633
+ }
1634
+ if (opts?.sort) {
1635
+ args.push("--sort", opts.sort);
1636
+ }
1637
+ if (opts?.symref) {
1638
+ args.push("--symref");
1639
+ }
1640
+ args.push(remote);
1641
+ if (opts?.refs && opts.refs.length > 0) {
1642
+ args.push(...opts.refs);
1643
+ }
1644
+ const result = await this.runner.runOrThrow(this.context, args, {
1645
+ signal: opts?.signal,
1646
+ onProgress: opts?.onProgress
1647
+ });
1648
+ const refs = parseLsRemote(result.stdout);
1649
+ return { refs };
1650
+ }
1651
+ /**
1652
+ * List contents of a tree object
1653
+ */
1654
+ async lsTree(treeish, opts) {
1655
+ const args = ["ls-tree"];
1656
+ if (opts?.recursive) {
1657
+ args.push("-r");
1658
+ }
1659
+ if (opts?.treeOnly) {
1660
+ args.push("-d");
1661
+ }
1662
+ if (opts?.showTrees) {
1663
+ args.push("-t");
1664
+ }
1665
+ if (opts?.long) {
1666
+ args.push("--long");
1667
+ }
1668
+ if (opts?.nameOnly) {
1669
+ args.push("--name-only");
1670
+ }
1671
+ if (opts?.objectOnly) {
1672
+ args.push("--object-only");
1673
+ }
1674
+ if (opts?.fullName) {
1675
+ args.push("--full-name");
1676
+ }
1677
+ if (opts?.fullTree) {
1678
+ args.push("--full-tree");
1679
+ }
1680
+ if (opts?.abbrev !== void 0) {
1681
+ if (opts.abbrev === true) {
1682
+ args.push("--abbrev");
1683
+ } else if (typeof opts.abbrev === "number") {
1684
+ args.push(`--abbrev=${opts.abbrev}`);
1685
+ }
1686
+ }
1687
+ args.push(treeish);
1688
+ if (opts?.paths && opts.paths.length > 0) {
1689
+ args.push("--", ...opts.paths);
1690
+ }
1691
+ const result = await this.runner.runOrThrow(this.context, args, {
1692
+ signal: opts?.signal
1693
+ });
1694
+ return parseLsTree(result.stdout, {
1695
+ nameOnly: opts?.nameOnly,
1696
+ objectOnly: opts?.objectOnly,
1697
+ long: opts?.long
1698
+ });
1699
+ }
1290
1700
  /**
1291
1701
  * Get repository status
1292
1702
  */
@@ -4182,17 +4592,151 @@ var WorktreeRepoImpl = class _WorktreeRepoImpl {
4182
4592
  });
4183
4593
  return result.stdout;
4184
4594
  }
4185
- // ==========================================================================
4186
- // Plumbing Operations
4187
- // ==========================================================================
4188
- /**
4189
- * Parse revision specification and return the object name (SHA)
4190
- */
4191
- async revParse(ref, opts) {
4192
- const result = await this.runner.runOrThrow(this.context, ["rev-parse", ref], {
4193
- signal: opts?.signal
4595
+ async revParse(refOrOpts, opts) {
4596
+ const args = ["rev-parse"];
4597
+ if (typeof refOrOpts === "string") {
4598
+ if (opts?.verify) {
4599
+ args.push("--verify");
4600
+ }
4601
+ if (opts?.short !== void 0) {
4602
+ if (typeof opts.short === "number") {
4603
+ args.push(`--short=${opts.short}`);
4604
+ } else if (opts.short) {
4605
+ args.push("--short");
4606
+ }
4607
+ }
4608
+ if (opts?.abbrevRef !== void 0) {
4609
+ if (opts.abbrevRef === "strict") {
4610
+ args.push("--abbrev-ref=strict");
4611
+ } else if (opts.abbrevRef === "loose") {
4612
+ args.push("--abbrev-ref=loose");
4613
+ } else if (opts.abbrevRef) {
4614
+ args.push("--abbrev-ref");
4615
+ }
4616
+ }
4617
+ if (opts?.symbolic) {
4618
+ args.push("--symbolic");
4619
+ }
4620
+ if (opts?.symbolicFullName) {
4621
+ args.push("--symbolic-full-name");
4622
+ }
4623
+ if (opts?.quiet) {
4624
+ args.push("--quiet");
4625
+ }
4626
+ args.push(refOrOpts);
4627
+ const result2 = await this.runner.runOrThrow(this.context, args, {
4628
+ signal: opts?.signal
4629
+ });
4630
+ return result2.stdout.trim();
4631
+ }
4632
+ const queryOpts = refOrOpts;
4633
+ if ("gitDir" in queryOpts && queryOpts.gitDir) {
4634
+ args.push("--git-dir");
4635
+ } else if ("absoluteGitDir" in queryOpts && queryOpts.absoluteGitDir) {
4636
+ args.push("--absolute-git-dir");
4637
+ } else if ("gitCommonDir" in queryOpts && queryOpts.gitCommonDir) {
4638
+ args.push("--git-common-dir");
4639
+ } else if ("showToplevel" in queryOpts && queryOpts.showToplevel) {
4640
+ args.push("--show-toplevel");
4641
+ } else if ("showCdup" in queryOpts && queryOpts.showCdup) {
4642
+ args.push("--show-cdup");
4643
+ } else if ("showPrefix" in queryOpts && queryOpts.showPrefix) {
4644
+ args.push("--show-prefix");
4645
+ } else if ("showSuperprojectWorkingTree" in queryOpts && queryOpts.showSuperprojectWorkingTree) {
4646
+ args.push("--show-superproject-working-tree");
4647
+ } else if ("sharedIndexPath" in queryOpts && queryOpts.sharedIndexPath) {
4648
+ args.push("--shared-index-path");
4649
+ } else if ("gitPath" in queryOpts && typeof queryOpts.gitPath === "string") {
4650
+ args.push("--git-path", queryOpts.gitPath);
4651
+ } else if ("resolveGitDir" in queryOpts && typeof queryOpts.resolveGitDir === "string") {
4652
+ args.push("--resolve-git-dir", queryOpts.resolveGitDir);
4653
+ } else if ("isInsideGitDir" in queryOpts && queryOpts.isInsideGitDir) {
4654
+ args.push("--is-inside-git-dir");
4655
+ } else if ("isInsideWorkTree" in queryOpts && queryOpts.isInsideWorkTree) {
4656
+ args.push("--is-inside-work-tree");
4657
+ } else if ("isBareRepository" in queryOpts && queryOpts.isBareRepository) {
4658
+ args.push("--is-bare-repository");
4659
+ } else if ("isShallowRepository" in queryOpts && queryOpts.isShallowRepository) {
4660
+ args.push("--is-shallow-repository");
4661
+ } else if ("all" in queryOpts && queryOpts.all) {
4662
+ if ("exclude" in queryOpts && queryOpts.exclude) {
4663
+ args.push(`--exclude=${queryOpts.exclude}`);
4664
+ }
4665
+ if ("excludeHidden" in queryOpts && queryOpts.excludeHidden) {
4666
+ args.push(`--exclude-hidden=${queryOpts.excludeHidden}`);
4667
+ }
4668
+ args.push("--all");
4669
+ } else if ("branches" in queryOpts && queryOpts.branches) {
4670
+ if ("exclude" in queryOpts && queryOpts.exclude) {
4671
+ args.push(`--exclude=${queryOpts.exclude}`);
4672
+ }
4673
+ if ("excludeHidden" in queryOpts && queryOpts.excludeHidden) {
4674
+ args.push(`--exclude-hidden=${queryOpts.excludeHidden}`);
4675
+ }
4676
+ if (typeof queryOpts.branches === "string") {
4677
+ args.push(`--branches=${queryOpts.branches}`);
4678
+ } else {
4679
+ args.push("--branches");
4680
+ }
4681
+ } else if ("tags" in queryOpts && queryOpts.tags) {
4682
+ if ("exclude" in queryOpts && queryOpts.exclude) {
4683
+ args.push(`--exclude=${queryOpts.exclude}`);
4684
+ }
4685
+ if ("excludeHidden" in queryOpts && queryOpts.excludeHidden) {
4686
+ args.push(`--exclude-hidden=${queryOpts.excludeHidden}`);
4687
+ }
4688
+ if (typeof queryOpts.tags === "string") {
4689
+ args.push(`--tags=${queryOpts.tags}`);
4690
+ } else {
4691
+ args.push("--tags");
4692
+ }
4693
+ } else if ("remotes" in queryOpts && queryOpts.remotes) {
4694
+ if ("exclude" in queryOpts && queryOpts.exclude) {
4695
+ args.push(`--exclude=${queryOpts.exclude}`);
4696
+ }
4697
+ if ("excludeHidden" in queryOpts && queryOpts.excludeHidden) {
4698
+ args.push(`--exclude-hidden=${queryOpts.excludeHidden}`);
4699
+ }
4700
+ if (typeof queryOpts.remotes === "string") {
4701
+ args.push(`--remotes=${queryOpts.remotes}`);
4702
+ } else {
4703
+ args.push("--remotes");
4704
+ }
4705
+ } else if ("glob" in queryOpts && typeof queryOpts.glob === "string") {
4706
+ if ("exclude" in queryOpts && queryOpts.exclude) {
4707
+ args.push(`--exclude=${queryOpts.exclude}`);
4708
+ }
4709
+ if ("excludeHidden" in queryOpts && queryOpts.excludeHidden) {
4710
+ args.push(`--exclude-hidden=${queryOpts.excludeHidden}`);
4711
+ }
4712
+ args.push(`--glob=${queryOpts.glob}`);
4713
+ } else if ("disambiguate" in queryOpts && typeof queryOpts.disambiguate === "string") {
4714
+ args.push(`--disambiguate=${queryOpts.disambiguate}`);
4715
+ } else if ("showObjectFormat" in queryOpts && queryOpts.showObjectFormat) {
4716
+ if (queryOpts.showObjectFormat === true) {
4717
+ args.push("--show-object-format");
4718
+ } else {
4719
+ args.push(`--show-object-format=${queryOpts.showObjectFormat}`);
4720
+ }
4721
+ } else if ("showRefFormat" in queryOpts && queryOpts.showRefFormat) {
4722
+ args.push("--show-ref-format");
4723
+ } else if ("localEnvVars" in queryOpts && queryOpts.localEnvVars) {
4724
+ args.push("--local-env-vars");
4725
+ }
4726
+ if ("pathFormat" in queryOpts && queryOpts.pathFormat) {
4727
+ args.push(`--path-format=${queryOpts.pathFormat}`);
4728
+ }
4729
+ const result = await this.runner.runOrThrow(this.context, args, {
4730
+ signal: queryOpts.signal
4194
4731
  });
4195
- return result.stdout.trim();
4732
+ const output = result.stdout.trim();
4733
+ if ("isInsideGitDir" in queryOpts && queryOpts.isInsideGitDir || "isInsideWorkTree" in queryOpts && queryOpts.isInsideWorkTree || "isBareRepository" in queryOpts && queryOpts.isBareRepository || "isShallowRepository" in queryOpts && queryOpts.isShallowRepository) {
4734
+ return output === "true";
4735
+ }
4736
+ 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) {
4737
+ return output ? output.split("\n").filter((line) => line.length > 0) : [];
4738
+ }
4739
+ return output;
4196
4740
  }
4197
4741
  /**
4198
4742
  * Count the number of commits reachable from a ref
@@ -4746,6 +5290,101 @@ var WorktreeRepoImpl = class _WorktreeRepoImpl {
4746
5290
  };
4747
5291
 
4748
5292
  // src/impl/git-impl.ts
5293
+ var GIT_VERSION_REGEX = /git version (\S+)/;
5294
+ function buildCloneArgs(opts) {
5295
+ const args = ["clone"];
5296
+ if (!opts) {
5297
+ return args;
5298
+ }
5299
+ const booleanFlags = [
5300
+ ["verbose", "--verbose"],
5301
+ ["quiet", "--quiet"],
5302
+ ["bare", "--bare"],
5303
+ ["mirror", "--mirror"],
5304
+ ["rejectShallow", "--reject-shallow"],
5305
+ ["singleBranch", "--single-branch"],
5306
+ ["noCheckout", "--no-checkout"],
5307
+ ["sparse", "--sparse"],
5308
+ ["local", "--local"],
5309
+ ["noHardlinks", "--no-hardlinks"],
5310
+ ["shared", "--shared"],
5311
+ ["dissociate", "--dissociate"],
5312
+ ["recurseSubmodules", "--recurse-submodules"],
5313
+ ["shallowSubmodules", "--shallow-submodules"],
5314
+ ["remoteSubmodules", "--remote-submodules"],
5315
+ ["noTags", "--no-tags"],
5316
+ ["alsoFilterSubmodules", "--also-filter-submodules"],
5317
+ ["ipv4", "--ipv4"],
5318
+ ["ipv6", "--ipv6"]
5319
+ ];
5320
+ for (const [key, flag] of booleanFlags) {
5321
+ if (opts[key]) {
5322
+ args.push(flag);
5323
+ }
5324
+ }
5325
+ const stringFlags = [
5326
+ ["branch", "--branch"],
5327
+ ["reference", "--reference"],
5328
+ ["referenceIfAble", "--reference-if-able"],
5329
+ ["template", "--template"],
5330
+ ["origin", "--origin"],
5331
+ ["separateGitDir", "--separate-git-dir"],
5332
+ ["filter", "--filter"]
5333
+ ];
5334
+ for (const [key, flag] of stringFlags) {
5335
+ const value = opts[key];
5336
+ if (typeof value === "string") {
5337
+ args.push(flag, value);
5338
+ }
5339
+ }
5340
+ if (opts.depth !== void 0) {
5341
+ args.push("--depth", String(opts.depth));
5342
+ }
5343
+ if (opts.jobs !== void 0) {
5344
+ args.push("--jobs", String(opts.jobs));
5345
+ }
5346
+ if (opts.shallowSince) {
5347
+ const since = opts.shallowSince instanceof Date ? opts.shallowSince.toISOString() : opts.shallowSince;
5348
+ args.push("--shallow-since", since);
5349
+ }
5350
+ if (opts.shallowExclude) {
5351
+ const excludes = Array.isArray(opts.shallowExclude) ? opts.shallowExclude : [opts.shallowExclude];
5352
+ for (const exclude of excludes) {
5353
+ args.push("--shallow-exclude", exclude);
5354
+ }
5355
+ }
5356
+ if (opts.config) {
5357
+ for (const [key, value] of Object.entries(opts.config)) {
5358
+ args.push("-c", `${key}=${value}`);
5359
+ }
5360
+ }
5361
+ return args;
5362
+ }
5363
+ var MIN_GIT_VERSION = "2.30.0";
5364
+ var LEGACY_GIT_VERSION = "2.25.0";
5365
+ var VERSION_REGEX = /^(\d+)\.(\d+)\.(\d+)/;
5366
+ function parseVersion(version) {
5367
+ const match = version.match(VERSION_REGEX);
5368
+ if (!match) {
5369
+ return [0, 0, 0];
5370
+ }
5371
+ return [
5372
+ Number.parseInt(match[1], 10),
5373
+ Number.parseInt(match[2], 10),
5374
+ Number.parseInt(match[3], 10)
5375
+ ];
5376
+ }
5377
+ function compareVersions(a, b) {
5378
+ const [aMajor, aMinor, aPatch] = parseVersion(a);
5379
+ const [bMajor, bMinor, bPatch] = parseVersion(b);
5380
+ if (aMajor !== bMajor) {
5381
+ return aMajor - bMajor;
5382
+ }
5383
+ if (aMinor !== bMinor) {
5384
+ return aMinor - bMinor;
5385
+ }
5386
+ return aPatch - bPatch;
5387
+ }
4749
5388
  function toCliRunnerOptions(opts) {
4750
5389
  if (!opts) {
4751
5390
  return {};
@@ -4763,6 +5402,7 @@ function toCliRunnerOptions(opts) {
4763
5402
  var GitImpl = class {
4764
5403
  runner;
4765
5404
  adapters;
5405
+ cachedVersion = null;
4766
5406
  config;
4767
5407
  lfs;
4768
5408
  constructor(options) {
@@ -4851,109 +5491,10 @@ var GitImpl = class {
4851
5491
  return new WorktreeRepoImpl(repoRunner, path, opts);
4852
5492
  }
4853
5493
  async clone(url, path, opts) {
4854
- const args = ["clone"];
5494
+ const args = buildCloneArgs(opts);
4855
5495
  if (opts?.onProgress) {
4856
5496
  args.push("--progress");
4857
5497
  }
4858
- if (opts?.verbose) {
4859
- args.push("--verbose");
4860
- }
4861
- if (opts?.quiet) {
4862
- args.push("--quiet");
4863
- }
4864
- if (opts?.bare) {
4865
- args.push("--bare");
4866
- }
4867
- if (opts?.mirror) {
4868
- args.push("--mirror");
4869
- }
4870
- if (opts?.depth !== void 0) {
4871
- args.push("--depth", String(opts.depth));
4872
- }
4873
- if (opts?.shallowSince) {
4874
- const since = opts.shallowSince instanceof Date ? opts.shallowSince.toISOString() : opts.shallowSince;
4875
- args.push("--shallow-since", since);
4876
- }
4877
- if (opts?.shallowExclude) {
4878
- const excludes = Array.isArray(opts.shallowExclude) ? opts.shallowExclude : [opts.shallowExclude];
4879
- for (const exclude of excludes) {
4880
- args.push("--shallow-exclude", exclude);
4881
- }
4882
- }
4883
- if (opts?.rejectShallow) {
4884
- args.push("--reject-shallow");
4885
- }
4886
- if (opts?.branch) {
4887
- args.push("--branch", opts.branch);
4888
- }
4889
- if (opts?.singleBranch) {
4890
- args.push("--single-branch");
4891
- }
4892
- if (opts?.noCheckout) {
4893
- args.push("--no-checkout");
4894
- }
4895
- if (opts?.sparse) {
4896
- args.push("--sparse");
4897
- }
4898
- if (opts?.local) {
4899
- args.push("--local");
4900
- }
4901
- if (opts?.noHardlinks) {
4902
- args.push("--no-hardlinks");
4903
- }
4904
- if (opts?.shared) {
4905
- args.push("--shared");
4906
- }
4907
- if (opts?.reference) {
4908
- args.push("--reference", opts.reference);
4909
- }
4910
- if (opts?.referenceIfAble) {
4911
- args.push("--reference-if-able", opts.referenceIfAble);
4912
- }
4913
- if (opts?.dissociate) {
4914
- args.push("--dissociate");
4915
- }
4916
- if (opts?.recurseSubmodules) {
4917
- args.push("--recurse-submodules");
4918
- }
4919
- if (opts?.shallowSubmodules) {
4920
- args.push("--shallow-submodules");
4921
- }
4922
- if (opts?.remoteSubmodules) {
4923
- args.push("--remote-submodules");
4924
- }
4925
- if (opts?.jobs !== void 0) {
4926
- args.push("--jobs", String(opts.jobs));
4927
- }
4928
- if (opts?.noTags) {
4929
- args.push("--no-tags");
4930
- }
4931
- if (opts?.template) {
4932
- args.push("--template", opts.template);
4933
- }
4934
- if (opts?.origin) {
4935
- args.push("--origin", opts.origin);
4936
- }
4937
- if (opts?.separateGitDir) {
4938
- args.push("--separate-git-dir", opts.separateGitDir);
4939
- }
4940
- if (opts?.config) {
4941
- for (const [key, value] of Object.entries(opts.config)) {
4942
- args.push("-c", `${key}=${value}`);
4943
- }
4944
- }
4945
- if (opts?.filter) {
4946
- args.push("--filter", opts.filter);
4947
- }
4948
- if (opts?.alsoFilterSubmodules) {
4949
- args.push("--also-filter-submodules");
4950
- }
4951
- if (opts?.ipv4) {
4952
- args.push("--ipv4");
4953
- }
4954
- if (opts?.ipv6) {
4955
- args.push("--ipv6");
4956
- }
4957
5498
  args.push(url, path);
4958
5499
  try {
4959
5500
  await this.runner.runOrThrow({ type: "global" }, args, {
@@ -4993,7 +5534,7 @@ var GitImpl = class {
4993
5534
  args.push(`--shared=${opts.shared}`);
4994
5535
  }
4995
5536
  }
4996
- if (opts?.initialBranch) {
5537
+ if (opts?.initialBranch && await this.supportsInitialBranch()) {
4997
5538
  args.push("--initial-branch", opts.initialBranch);
4998
5539
  }
4999
5540
  if (opts?.objectFormat) {
@@ -5008,6 +5549,16 @@ var GitImpl = class {
5008
5549
  signal: opts?.signal,
5009
5550
  onProgress: opts?.onProgress
5010
5551
  });
5552
+ if (opts?.initialBranch && !await this.supportsInitialBranch()) {
5553
+ const context = opts?.bare ? { type: "bare", gitDir: path } : { type: "worktree", workdir: path };
5554
+ await this.runner.runOrThrow(
5555
+ context,
5556
+ ["symbolic-ref", "HEAD", `refs/heads/${opts.initialBranch}`],
5557
+ {
5558
+ signal: opts?.signal
5559
+ }
5560
+ );
5561
+ }
5011
5562
  } catch (error) {
5012
5563
  if (error instanceof GitError && error.kind === "Aborted" && opts?.cleanupOnAbort !== false) {
5013
5564
  await this.adapters.fs.deleteDirectory(path);
@@ -5054,17 +5605,28 @@ var GitImpl = class {
5054
5605
  * Get git version
5055
5606
  */
5056
5607
  async version(opts) {
5608
+ if (this.cachedVersion) {
5609
+ return this.cachedVersion;
5610
+ }
5057
5611
  const result = await this.runner.runOrThrow({ type: "global" }, ["--version"], {
5058
5612
  signal: opts?.signal
5059
5613
  });
5060
- const match = result.stdout.match(/git version (\S+)/);
5061
- const version = match?.[1];
5062
- return version ?? result.stdout.trim();
5614
+ const match = result.stdout.match(GIT_VERSION_REGEX);
5615
+ const version = match?.[1] ?? result.stdout.trim();
5616
+ this.cachedVersion = version;
5617
+ return version;
5618
+ }
5619
+ /**
5620
+ * Check if Git version supports --initial-branch option (Git 2.28+)
5621
+ */
5622
+ async supportsInitialBranch() {
5623
+ const version = await this.version();
5624
+ return compareVersions(version, "2.28.0") >= 0;
5063
5625
  }
5064
5626
  /**
5065
5627
  * Execute a raw git command (repository-agnostic)
5066
5628
  */
5067
- async raw(argv, opts) {
5629
+ raw(argv, opts) {
5068
5630
  return this.runner.run({ type: "global" }, argv, opts);
5069
5631
  }
5070
5632
  // ==========================================================================
@@ -5250,9 +5812,24 @@ var GitImpl = class {
5250
5812
  return result.stdout.trim();
5251
5813
  }
5252
5814
  };
5253
- function createGit(options) {
5815
+ function createGitSync(options) {
5254
5816
  return new GitImpl(options);
5255
5817
  }
5818
+ async function createGit(options) {
5819
+ const git = new GitImpl(options);
5820
+ if (!options.skipVersionCheck) {
5821
+ const versionString = await git.version();
5822
+ const minVersion = options.useLegacyVersion ? LEGACY_GIT_VERSION : MIN_GIT_VERSION;
5823
+ if (compareVersions(versionString, minVersion) < 0) {
5824
+ throw new GitError(
5825
+ "UnsupportedGitVersion",
5826
+ `Git version ${versionString} is not supported. Minimum required version is ${minVersion}.`,
5827
+ {}
5828
+ );
5829
+ }
5830
+ }
5831
+ return git;
5832
+ }
5256
5833
 
5257
5834
  // src/adapters/node/exec.ts
5258
5835
  import { spawn } from "child_process";
@@ -5411,52 +5988,132 @@ var NodeExecAdapter = class {
5411
5988
  import { access, mkdtemp, open, readFile, rm, writeFile } from "fs/promises";
5412
5989
  import { tmpdir } from "os";
5413
5990
  import { join } from "path";
5991
+
5992
+ // src/internal/file-polling.ts
5993
+ async function runTailPolling(options) {
5994
+ const { adapter, signal, pollInterval = 100, onLine } = options;
5995
+ let position = 0;
5996
+ let buffer = "";
5997
+ while (!signal?.aborted) {
5998
+ const result = await adapter.readChunk(position);
5999
+ if (result !== null && result.data.length > 0) {
6000
+ position = result.newPosition;
6001
+ buffer += result.data;
6002
+ const lines = buffer.split("\n");
6003
+ buffer = lines.pop() ?? "";
6004
+ for (const line of lines) {
6005
+ if (line) {
6006
+ onLine(line);
6007
+ }
6008
+ }
6009
+ }
6010
+ if (!signal?.aborted) {
6011
+ await adapter.sleep(pollInterval);
6012
+ }
6013
+ }
6014
+ }
6015
+ function createTailPolling(options) {
6016
+ const { adapter, signal, pollInterval = 100 } = options;
6017
+ const state = {
6018
+ stopped: false,
6019
+ resolveNext: null,
6020
+ lineQueue: []
6021
+ };
6022
+ const stop = () => {
6023
+ state.stopped = true;
6024
+ if (state.resolveNext) {
6025
+ state.resolveNext({ done: true, value: void 0 });
6026
+ state.resolveNext = null;
6027
+ }
6028
+ };
6029
+ startPollingLoop(adapter, state, signal, pollInterval, stop).catch(() => {
6030
+ });
6031
+ const lines = {
6032
+ [Symbol.asyncIterator]() {
6033
+ return {
6034
+ next() {
6035
+ if (state.stopped) {
6036
+ return Promise.resolve({ done: true, value: void 0 });
6037
+ }
6038
+ if (state.lineQueue.length > 0) {
6039
+ const value = state.lineQueue.shift();
6040
+ if (value !== void 0) {
6041
+ return Promise.resolve({ done: false, value });
6042
+ }
6043
+ }
6044
+ return new Promise((resolve) => {
6045
+ state.resolveNext = resolve;
6046
+ });
6047
+ }
6048
+ };
6049
+ }
6050
+ };
6051
+ return { lines, stop };
6052
+ }
6053
+ async function startPollingLoop(adapter, state, signal, pollInterval, stop) {
6054
+ let position = 0;
6055
+ let buffer = "";
6056
+ while (!(state.stopped || signal?.aborted)) {
6057
+ const result = await adapter.readChunk(position);
6058
+ if (result !== null && result.data.length > 0) {
6059
+ position = result.newPosition;
6060
+ buffer += result.data;
6061
+ const lines = buffer.split("\n");
6062
+ buffer = lines.pop() ?? "";
6063
+ for (const line of lines) {
6064
+ if (line) {
6065
+ if (state.resolveNext) {
6066
+ const resolver = state.resolveNext;
6067
+ state.resolveNext = null;
6068
+ resolver({ done: false, value: line });
6069
+ } else {
6070
+ state.lineQueue.push(line);
6071
+ }
6072
+ }
6073
+ }
6074
+ }
6075
+ await adapter.sleep(pollInterval);
6076
+ }
6077
+ stop();
6078
+ }
6079
+
6080
+ // src/adapters/node/fs.ts
5414
6081
  var NodeFsAdapter = class {
5415
6082
  async createTempFile(prefix = "type-git-") {
5416
6083
  const dir = await mkdtemp(join(tmpdir(), prefix));
5417
6084
  return join(dir, "temp");
5418
6085
  }
5419
6086
  async tail(options) {
5420
- const { filePath, signal, onLine } = options;
5421
- const file = await open(filePath, "r");
5422
- let position = 0;
6087
+ const { filePath, signal, onLine, pollInterval = 100 } = options;
6088
+ const state = { file: null };
5423
6089
  const decoder = new TextDecoder();
5424
- let buffer = "";
5425
- const poll = async () => {
5426
- if (signal?.aborted) {
5427
- await file.close();
5428
- return;
5429
- }
5430
- try {
5431
- const { bytesRead, buffer: chunk } = await file.read({
5432
- buffer: Buffer.alloc(4096),
5433
- position
5434
- });
5435
- if (bytesRead > 0) {
5436
- position += bytesRead;
5437
- buffer += decoder.decode(chunk.subarray(0, bytesRead), { stream: true });
5438
- const lines = buffer.split("\n");
5439
- buffer = lines.pop() ?? "";
5440
- for (const line of lines) {
5441
- if (line) {
5442
- onLine(line);
5443
- }
6090
+ const adapter = {
6091
+ readChunk: async (position) => {
6092
+ try {
6093
+ if (!state.file) {
6094
+ state.file = await open(filePath, "r");
5444
6095
  }
5445
- }
5446
- } catch (error) {
5447
- await file.close();
5448
- throw error;
5449
- }
5450
- if (!signal?.aborted) {
5451
- setTimeout(() => {
5452
- poll().catch(() => {
6096
+ const { bytesRead, buffer: chunk } = await state.file.read({
6097
+ buffer: Buffer.alloc(4096),
6098
+ position
5453
6099
  });
5454
- }, 100);
5455
- } else {
5456
- await file.close();
5457
- }
6100
+ return {
6101
+ data: decoder.decode(chunk.subarray(0, bytesRead), { stream: true }),
6102
+ newPosition: position + bytesRead
6103
+ };
6104
+ } catch {
6105
+ return null;
6106
+ }
6107
+ },
6108
+ sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms))
5458
6109
  };
5459
- await poll();
6110
+ try {
6111
+ await runTailPolling({ adapter, signal, pollInterval, onLine });
6112
+ } finally {
6113
+ if (state.file) {
6114
+ await state.file.close();
6115
+ }
6116
+ }
5460
6117
  }
5461
6118
  async deleteFile(filePath) {
5462
6119
  await rm(filePath, { force: true });
@@ -5480,83 +6137,39 @@ var NodeFsAdapter = class {
5480
6137
  }
5481
6138
  tailStreaming(filePath, options) {
5482
6139
  const { signal, pollInterval = 100 } = options ?? {};
5483
- const state = {
5484
- stopped: false,
5485
- resolveNext: null,
5486
- lineQueue: []
5487
- };
5488
- const stop = () => {
5489
- state.stopped = true;
5490
- if (state.resolveNext) {
5491
- state.resolveNext({ done: true, value: void 0 });
5492
- state.resolveNext = null;
5493
- }
5494
- };
5495
- const startPolling = async () => {
5496
- let file;
5497
- try {
5498
- file = await open(filePath, "r");
5499
- } catch {
5500
- stop();
5501
- return;
5502
- }
5503
- let position = 0;
5504
- const decoder = new TextDecoder();
5505
- let buffer = "";
5506
- while (!(state.stopped || signal?.aborted)) {
6140
+ const state = { file: null };
6141
+ const decoder = new TextDecoder();
6142
+ const adapter = {
6143
+ readChunk: async (position) => {
5507
6144
  try {
5508
- const { bytesRead, buffer: chunk } = await file.read({
6145
+ if (!state.file) {
6146
+ state.file = await open(filePath, "r");
6147
+ }
6148
+ const { bytesRead, buffer: chunk } = await state.file.read({
5509
6149
  buffer: Buffer.alloc(4096),
5510
6150
  position
5511
6151
  });
5512
- if (bytesRead > 0) {
5513
- position += bytesRead;
5514
- buffer += decoder.decode(chunk.subarray(0, bytesRead), { stream: true });
5515
- const lines2 = buffer.split("\n");
5516
- buffer = lines2.pop() ?? "";
5517
- for (const line of lines2) {
5518
- if (line) {
5519
- if (state.resolveNext) {
5520
- const resolver = state.resolveNext;
5521
- state.resolveNext = null;
5522
- resolver({ done: false, value: line });
5523
- } else {
5524
- state.lineQueue.push(line);
5525
- }
5526
- }
5527
- }
5528
- }
6152
+ return {
6153
+ data: decoder.decode(chunk.subarray(0, bytesRead), { stream: true }),
6154
+ newPosition: position + bytesRead
6155
+ };
5529
6156
  } catch {
5530
- break;
6157
+ return null;
5531
6158
  }
5532
- await new Promise((resolve) => setTimeout(resolve, pollInterval));
5533
- }
5534
- await file.close();
5535
- stop();
6159
+ },
6160
+ sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms))
5536
6161
  };
5537
- startPolling().catch(() => {
5538
- });
5539
- const lines = {
5540
- [Symbol.asyncIterator]() {
5541
- return {
5542
- next() {
5543
- if (state.stopped) {
5544
- return Promise.resolve({ done: true, value: void 0 });
5545
- }
5546
- if (state.lineQueue.length > 0) {
5547
- const value = state.lineQueue.shift();
5548
- if (value !== void 0) {
5549
- return Promise.resolve({ done: false, value });
5550
- }
5551
- }
5552
- return new Promise((resolve) => {
5553
- state.resolveNext = resolve;
5554
- });
5555
- }
5556
- };
6162
+ const polling = createTailPolling({ adapter, signal, pollInterval });
6163
+ const originalStop = polling.stop;
6164
+ const enhancedStop = () => {
6165
+ originalStop();
6166
+ if (state.file) {
6167
+ state.file.close().catch(() => {
6168
+ });
6169
+ state.file = null;
5557
6170
  }
5558
6171
  };
5559
- return { lines, stop };
6172
+ return { lines: polling.lines, stop: enhancedStop };
5560
6173
  }
5561
6174
  };
5562
6175
 
@@ -5567,13 +6180,31 @@ function createNodeAdapters() {
5567
6180
  fs: new NodeFsAdapter()
5568
6181
  };
5569
6182
  }
5570
- var TypeGit = class {
6183
+ var TypeGit = class _TypeGit {
5571
6184
  git;
5572
- constructor(options) {
5573
- this.git = createGit({
5574
- ...options,
6185
+ /**
6186
+ * Create a TypeGit instance with Git version check
6187
+ *
6188
+ * @param createOpts - Options including skipVersionCheck
6189
+ * @returns TypeGit instance
6190
+ * @throws GitError with kind 'UnsupportedGitVersion' if Git version is below minimum
6191
+ */
6192
+ static async create(createOpts) {
6193
+ const gitInstance = await createGit({
6194
+ ...createOpts,
5575
6195
  adapters: createNodeAdapters()
5576
6196
  });
6197
+ return new _TypeGit(gitInstance);
6198
+ }
6199
+ constructor(optionsOrGit) {
6200
+ if (optionsOrGit && "open" in optionsOrGit) {
6201
+ this.git = optionsOrGit;
6202
+ } else {
6203
+ this.git = createGitSync({
6204
+ ...optionsOrGit,
6205
+ adapters: createNodeAdapters()
6206
+ });
6207
+ }
5577
6208
  }
5578
6209
  /**
5579
6210
  * Open an existing worktree repository
@@ -5664,10 +6295,13 @@ export {
5664
6295
  GIT_LOG_FORMAT,
5665
6296
  GitArgumentError,
5666
6297
  GitError,
6298
+ LEGACY_GIT_VERSION,
6299
+ MIN_GIT_VERSION,
5667
6300
  NodeExecAdapter,
5668
6301
  NodeFsAdapter,
5669
6302
  TypeGit,
5670
6303
  createGit,
6304
+ createGitSync,
5671
6305
  createNodeAdapters,
5672
6306
  detectErrorCategory,
5673
6307
  isNonEmpty,
@@ -5679,6 +6313,7 @@ export {
5679
6313
  parseLfsProgress,
5680
6314
  parseLines,
5681
6315
  parseLsRemote,
6316
+ parseLsTree,
5682
6317
  parsePorcelainV2,
5683
6318
  parseRecords,
5684
6319
  parseWorktreeList