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.
@@ -24,6 +24,14 @@ var GitError = class extends Error {
24
24
  };
25
25
 
26
26
  // src/parsers/index.ts
27
+ var GIT_PROGRESS_PERCENT_REGEX = /^(.+?):\s*(\d+)%\s*\((\d+)\/(\d+)\)(?:,\s*(done))?/;
28
+ var GIT_PROGRESS_SIMPLE_REGEX = /^(.+?):\s*(\d+)\/(\d+)/;
29
+ var SIZE_REGEX = /^([\d.]+)\s*(B|KB|MB|GB|TB)?$/i;
30
+ var BITRATE_REGEX = /^([\d.]+)\s*(B|KB|MB|GB)\/s$/i;
31
+ var LFS_DOWNLOAD_REGEX = /downloading|filtering/i;
32
+ var LFS_UPLOAD_REGEX = /uploading/i;
33
+ var LFS_CHECKOUT_REGEX = /checking out/i;
34
+ 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;
27
35
  function at(arr, index, context) {
28
36
  const value = arr[index];
29
37
  if (value === void 0) {
@@ -101,7 +109,7 @@ function parsePorcelainV2(stdout) {
101
109
  return entries;
102
110
  }
103
111
  function parseGitProgress(line) {
104
- const match = line.match(/^(.+?):\s*(\d+)%\s*\((\d+)\/(\d+)\)(?:,\s*(done))?/);
112
+ const match = line.match(GIT_PROGRESS_PERCENT_REGEX);
105
113
  if (match) {
106
114
  const percent = match[2];
107
115
  const current = match[3];
@@ -117,7 +125,7 @@ function parseGitProgress(line) {
117
125
  done: match[5] === "done"
118
126
  };
119
127
  }
120
- const simpleMatch = line.match(/^(.+?):\s*(\d+)\/(\d+)/);
128
+ const simpleMatch = line.match(GIT_PROGRESS_SIMPLE_REGEX);
121
129
  if (simpleMatch) {
122
130
  const currentStr = simpleMatch[2];
123
131
  const totalStr = simpleMatch[3];
@@ -137,7 +145,7 @@ function parseGitProgress(line) {
137
145
  return null;
138
146
  }
139
147
  function parseSizeToBytes(sizeStr) {
140
- const match = sizeStr.match(/^([\d.]+)\s*(B|KB|MB|GB|TB)?$/i);
148
+ const match = sizeStr.match(SIZE_REGEX);
141
149
  if (!match) {
142
150
  return 0;
143
151
  }
@@ -153,7 +161,7 @@ function parseSizeToBytes(sizeStr) {
153
161
  return Math.round(value * (multipliers[unit] || 1));
154
162
  }
155
163
  function parseBitrateToBytes(bitrateStr) {
156
- const match = bitrateStr.match(/^([\d.]+)\s*(B|KB|MB|GB)\/s$/i);
164
+ const match = bitrateStr.match(BITRATE_REGEX);
157
165
  if (!match) {
158
166
  return null;
159
167
  }
@@ -169,18 +177,16 @@ function parseBitrateToBytes(bitrateStr) {
169
177
  }
170
178
  function parseLfsStderrProgress(line) {
171
179
  let direction;
172
- if (/downloading|filtering/i.test(line)) {
180
+ if (LFS_DOWNLOAD_REGEX.test(line)) {
173
181
  direction = "download";
174
- } else if (/uploading/i.test(line)) {
182
+ } else if (LFS_UPLOAD_REGEX.test(line)) {
175
183
  direction = "upload";
176
- } else if (/checking out/i.test(line)) {
184
+ } else if (LFS_CHECKOUT_REGEX.test(line)) {
177
185
  direction = "checkout";
178
186
  } else {
179
187
  return null;
180
188
  }
181
- const progressMatch = line.match(
182
- /(\d+)%\s*\((\d+)\/(\d+)\)(?:,\s*([\d.]+\s*(?:B|KB|MB|GB|TB)?)\s*(?:\|\s*([\d.]+\s*(?:B|KB|MB|GB)\/s))?)?/i
183
- );
189
+ const progressMatch = line.match(LFS_PROGRESS_REGEX);
184
190
  if (!progressMatch) {
185
191
  return null;
186
192
  }
@@ -221,6 +227,68 @@ function parseLsRemote(stdout) {
221
227
  }
222
228
  return refs;
223
229
  }
230
+ var LS_TREE_REGEX = /^(\d+)\s+(blob|tree|commit)\s+([a-f0-9]+)\t(.+)$/;
231
+ var LS_TREE_LONG_REGEX = /^(\d+)\s+(blob|tree|commit)\s+([a-f0-9]+)\s+(-|\d+)\t(.+)$/;
232
+ function parseLsTree(stdout, opts) {
233
+ const entries = [];
234
+ const lines = parseLines(stdout);
235
+ for (const line of lines) {
236
+ if (opts?.nameOnly) {
237
+ entries.push({
238
+ mode: "",
239
+ type: "blob",
240
+ hash: "",
241
+ path: line
242
+ });
243
+ continue;
244
+ }
245
+ if (opts?.objectOnly) {
246
+ entries.push({
247
+ mode: "",
248
+ type: "blob",
249
+ hash: line,
250
+ path: ""
251
+ });
252
+ continue;
253
+ }
254
+ if (opts?.long) {
255
+ const longMatch = line.match(LS_TREE_LONG_REGEX);
256
+ if (longMatch) {
257
+ const mode = longMatch[1];
258
+ const type = longMatch[2];
259
+ const hash = longMatch[3];
260
+ const sizeStr = longMatch[4];
261
+ const path = longMatch[5];
262
+ if (mode && type && hash && path) {
263
+ entries.push({
264
+ mode,
265
+ type,
266
+ hash,
267
+ path,
268
+ size: sizeStr === "-" || !sizeStr ? void 0 : Number.parseInt(sizeStr, 10)
269
+ });
270
+ }
271
+ continue;
272
+ }
273
+ }
274
+ const match = line.match(LS_TREE_REGEX);
275
+ if (match) {
276
+ const mode = match[1];
277
+ const type = match[2];
278
+ const hash = match[3];
279
+ const path = match[4];
280
+ if (mode && type && hash && path) {
281
+ entries.push({
282
+ mode,
283
+ type,
284
+ hash,
285
+ path
286
+ });
287
+ }
288
+ }
289
+ }
290
+ return entries;
291
+ }
224
292
  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";
225
293
  function parseGitLog(stdout) {
226
294
  const commits = [];
@@ -230,7 +298,7 @@ function parseGitLog(stdout) {
230
298
  if (fields.length < 11) {
231
299
  continue;
232
300
  }
233
- const hash = fields[0];
301
+ const hash = fields[0]?.trim();
234
302
  const abbrevHash = fields[1];
235
303
  const parentsStr = fields[2];
236
304
  const authorName = fields[3];
@@ -352,6 +420,51 @@ import process2 from "process";
352
420
  var FATAL_ERROR_PATTERN = /fatal:\s*(.+)/i;
353
421
  var ERROR_PATTERN = /error:\s*(.+)/i;
354
422
  var LINE_SEPARATOR_PATTERN = /\r|\n/;
423
+ function toLfsProgress(info) {
424
+ if (!info) {
425
+ return null;
426
+ }
427
+ return {
428
+ direction: info.direction,
429
+ bytesSoFar: info.bytesSoFar,
430
+ bytesTotal: info.bytesTotal,
431
+ bitrate: info.bitrate ?? void 0,
432
+ filesCompleted: info.filesCompleted,
433
+ filesTotal: info.filesTotal,
434
+ percent: info.percent
435
+ };
436
+ }
437
+ function toGitProgress(info, message) {
438
+ if (!info) {
439
+ return null;
440
+ }
441
+ return {
442
+ phase: info.phase,
443
+ current: info.current,
444
+ total: info.total,
445
+ percent: info.percent,
446
+ message
447
+ };
448
+ }
449
+ function processProgressLine(line, onProgress, onLfsProgress) {
450
+ const trimmed = line.trim();
451
+ if (!trimmed) {
452
+ return;
453
+ }
454
+ if (onLfsProgress) {
455
+ const lfsProgress = toLfsProgress(parseLfsStderrProgress(trimmed));
456
+ if (lfsProgress) {
457
+ onLfsProgress(lfsProgress);
458
+ return;
459
+ }
460
+ }
461
+ if (onProgress) {
462
+ const gitProgress = toGitProgress(parseGitProgress(trimmed), trimmed);
463
+ if (gitProgress) {
464
+ onProgress(gitProgress);
465
+ }
466
+ }
467
+ }
355
468
  var CliRunner = class _CliRunner {
356
469
  exec;
357
470
  gitBinary;
@@ -478,73 +591,13 @@ var CliRunner = class _CliRunner {
478
591
  const lines = stderrBuffer.split(LINE_SEPARATOR_PATTERN);
479
592
  stderrBuffer = lines.pop() ?? "";
480
593
  for (const line of lines) {
481
- const trimmed = line.trim();
482
- if (!trimmed) {
483
- continue;
484
- }
485
- if (onLfsProgress) {
486
- const lfsProgressInfo = parseLfsStderrProgress(trimmed);
487
- if (lfsProgressInfo) {
488
- const lfsProgress = {
489
- direction: lfsProgressInfo.direction,
490
- bytesSoFar: lfsProgressInfo.bytesSoFar,
491
- bytesTotal: lfsProgressInfo.bytesTotal,
492
- bitrate: lfsProgressInfo.bitrate ?? void 0,
493
- filesCompleted: lfsProgressInfo.filesCompleted,
494
- filesTotal: lfsProgressInfo.filesTotal,
495
- percent: lfsProgressInfo.percent
496
- };
497
- onLfsProgress(lfsProgress);
498
- continue;
499
- }
500
- }
501
- if (onProgress) {
502
- const gitProgressInfo = parseGitProgress(trimmed);
503
- if (gitProgressInfo) {
504
- const gitProgress = {
505
- phase: gitProgressInfo.phase,
506
- current: gitProgressInfo.current,
507
- total: gitProgressInfo.total,
508
- percent: gitProgressInfo.percent,
509
- message: trimmed
510
- };
511
- onProgress(gitProgress);
512
- }
513
- }
594
+ processProgressLine(line, onProgress, onLfsProgress);
514
595
  }
515
596
  }
516
597
  } : void 0
517
598
  );
518
599
  if (stderrBuffer.trim() && (onProgress || onLfsProgress)) {
519
- const trimmed = stderrBuffer.trim();
520
- if (onLfsProgress) {
521
- const lfsProgressInfo = parseLfsStderrProgress(trimmed);
522
- if (lfsProgressInfo) {
523
- const lfsProgress = {
524
- direction: lfsProgressInfo.direction,
525
- bytesSoFar: lfsProgressInfo.bytesSoFar,
526
- bytesTotal: lfsProgressInfo.bytesTotal,
527
- bitrate: lfsProgressInfo.bitrate ?? void 0,
528
- filesCompleted: lfsProgressInfo.filesCompleted,
529
- filesTotal: lfsProgressInfo.filesTotal,
530
- percent: lfsProgressInfo.percent
531
- };
532
- onLfsProgress(lfsProgress);
533
- }
534
- }
535
- if (onProgress && !onLfsProgress) {
536
- const gitProgressInfo = parseGitProgress(trimmed);
537
- if (gitProgressInfo) {
538
- const gitProgress = {
539
- phase: gitProgressInfo.phase,
540
- current: gitProgressInfo.current,
541
- total: gitProgressInfo.total,
542
- percent: gitProgressInfo.percent,
543
- message: trimmed
544
- };
545
- onProgress(gitProgress);
546
- }
547
- }
600
+ processProgressLine(stderrBuffer, onProgress, onLfsProgress);
548
601
  }
549
602
  return {
550
603
  stdout: result.stdout,
@@ -629,6 +682,196 @@ var CliRunner = class _CliRunner {
629
682
  };
630
683
 
631
684
  // src/impl/bare-repo-impl.ts
685
+ var REMOTE_LINE_PATTERN = /^(\S+)\t(.+?)\s+\((fetch|push)\)$/;
686
+ var PRUNED_REF_PATTERN = /\* \[pruned\] (.+)/;
687
+ function parseRemoteLine(line, remotes) {
688
+ const match = line.match(REMOTE_LINE_PATTERN);
689
+ if (!match) {
690
+ return;
691
+ }
692
+ const name = match[1];
693
+ const url = match[2];
694
+ const type = match[3];
695
+ if (name === void 0 || url === void 0) {
696
+ return;
697
+ }
698
+ const existing = remotes.get(name);
699
+ if (existing) {
700
+ updateRemoteUrl(existing, type, url);
701
+ } else {
702
+ remotes.set(name, {
703
+ name,
704
+ fetchUrl: type === "fetch" ? url : "",
705
+ pushUrl: type === "push" ? url : ""
706
+ });
707
+ }
708
+ }
709
+ function updateRemoteUrl(remote, type, url) {
710
+ if (type === "fetch") {
711
+ remote.fetchUrl = url;
712
+ } else if (type === "push") {
713
+ remote.pushUrl = url;
714
+ }
715
+ }
716
+ function normalizeRemoteUrls(remotes) {
717
+ for (const remote of remotes.values()) {
718
+ if (!remote.fetchUrl && remote.pushUrl) {
719
+ remote.fetchUrl = remote.pushUrl;
720
+ }
721
+ if (!remote.pushUrl && remote.fetchUrl) {
722
+ remote.pushUrl = remote.fetchUrl;
723
+ }
724
+ }
725
+ }
726
+ function addRefOptions(args, opts) {
727
+ if (!opts) {
728
+ return;
729
+ }
730
+ if (opts.verify) {
731
+ args.push("--verify");
732
+ }
733
+ if (opts.short !== void 0) {
734
+ if (typeof opts.short === "number") {
735
+ args.push(`--short=${opts.short}`);
736
+ } else if (opts.short) {
737
+ args.push("--short");
738
+ }
739
+ }
740
+ if (opts.abbrevRef !== void 0) {
741
+ if (opts.abbrevRef === "strict") {
742
+ args.push("--abbrev-ref=strict");
743
+ } else if (opts.abbrevRef === "loose") {
744
+ args.push("--abbrev-ref=loose");
745
+ } else if (opts.abbrevRef) {
746
+ args.push("--abbrev-ref");
747
+ }
748
+ }
749
+ if (opts.symbolic) {
750
+ args.push("--symbolic");
751
+ }
752
+ if (opts.symbolicFullName) {
753
+ args.push("--symbolic-full-name");
754
+ }
755
+ if (opts.quiet) {
756
+ args.push("--quiet");
757
+ }
758
+ }
759
+ var PATH_QUERY_FLAGS = [
760
+ ["gitDir", "--git-dir"],
761
+ ["absoluteGitDir", "--absolute-git-dir"],
762
+ ["gitCommonDir", "--git-common-dir"],
763
+ ["showToplevel", "--show-toplevel"],
764
+ ["showCdup", "--show-cdup"],
765
+ ["showPrefix", "--show-prefix"],
766
+ ["showSuperprojectWorkingTree", "--show-superproject-working-tree"],
767
+ ["sharedIndexPath", "--shared-index-path"]
768
+ ];
769
+ var PATH_QUERY_VALUE_FLAGS = [
770
+ ["gitPath", "--git-path"],
771
+ ["resolveGitDir", "--resolve-git-dir"]
772
+ ];
773
+ var BOOLEAN_QUERY_FLAGS = [
774
+ ["isInsideGitDir", "--is-inside-git-dir"],
775
+ ["isInsideWorkTree", "--is-inside-work-tree"],
776
+ ["isBareRepository", "--is-bare-repository"],
777
+ ["isShallowRepository", "--is-shallow-repository"]
778
+ ];
779
+ var LIST_QUERY_FLAGS = [
780
+ ["all", "--all"],
781
+ ["branches", "--branches"],
782
+ ["tags", "--tags"],
783
+ ["remotes", "--remotes"]
784
+ ];
785
+ function addExcludeOptions(args, opts) {
786
+ if ("exclude" in opts && opts.exclude) {
787
+ args.push(`--exclude=${opts.exclude}`);
788
+ }
789
+ if ("excludeHidden" in opts && opts.excludeHidden) {
790
+ args.push(`--exclude-hidden=${opts.excludeHidden}`);
791
+ }
792
+ }
793
+ function tryAddPathQuery(args, opts) {
794
+ for (const [key, flag] of PATH_QUERY_FLAGS) {
795
+ if (key in opts && opts[key]) {
796
+ args.push(flag);
797
+ return true;
798
+ }
799
+ }
800
+ for (const [key, flag] of PATH_QUERY_VALUE_FLAGS) {
801
+ if (key in opts && typeof opts[key] === "string") {
802
+ args.push(flag, opts[key]);
803
+ return true;
804
+ }
805
+ }
806
+ return false;
807
+ }
808
+ function tryAddBooleanQuery(args, opts) {
809
+ for (const [key, flag] of BOOLEAN_QUERY_FLAGS) {
810
+ if (key in opts && opts[key]) {
811
+ args.push(flag);
812
+ return true;
813
+ }
814
+ }
815
+ return false;
816
+ }
817
+ function tryAddListQuery(args, opts) {
818
+ for (const [key, flag] of LIST_QUERY_FLAGS) {
819
+ if (key in opts && opts[key]) {
820
+ addExcludeOptions(args, opts);
821
+ if (typeof opts[key] === "string") {
822
+ args.push(`${flag}=${opts[key]}`);
823
+ } else {
824
+ args.push(flag);
825
+ }
826
+ return true;
827
+ }
828
+ }
829
+ if ("glob" in opts && typeof opts.glob === "string") {
830
+ addExcludeOptions(args, opts);
831
+ args.push(`--glob=${opts.glob}`);
832
+ return true;
833
+ }
834
+ if ("disambiguate" in opts && typeof opts.disambiguate === "string") {
835
+ args.push(`--disambiguate=${opts.disambiguate}`);
836
+ return true;
837
+ }
838
+ return false;
839
+ }
840
+ function tryAddOtherQuery(args, opts) {
841
+ if ("showObjectFormat" in opts && opts.showObjectFormat) {
842
+ if (opts.showObjectFormat === true) {
843
+ args.push("--show-object-format");
844
+ } else {
845
+ args.push(`--show-object-format=${opts.showObjectFormat}`);
846
+ }
847
+ return true;
848
+ }
849
+ if ("showRefFormat" in opts && opts.showRefFormat) {
850
+ args.push("--show-ref-format");
851
+ return true;
852
+ }
853
+ if ("localEnvVars" in opts && opts.localEnvVars) {
854
+ args.push("--local-env-vars");
855
+ return true;
856
+ }
857
+ return false;
858
+ }
859
+ function isBooleanQuery(opts) {
860
+ for (const [key] of BOOLEAN_QUERY_FLAGS) {
861
+ if (key in opts && opts[key]) {
862
+ return true;
863
+ }
864
+ }
865
+ return false;
866
+ }
867
+ function isListQuery(opts) {
868
+ for (const [key] of LIST_QUERY_FLAGS) {
869
+ if (key in opts && opts[key]) {
870
+ return true;
871
+ }
872
+ }
873
+ return "glob" in opts && !!opts.glob || "disambiguate" in opts && !!opts.disambiguate || "localEnvVars" in opts && !!opts.localEnvVars;
874
+ }
632
875
  var BareRepoImpl = class {
633
876
  gitDir;
634
877
  runner;
@@ -691,6 +934,116 @@ var BareRepoImpl = class {
691
934
  const result = await this.runner.run(this.context, ["rev-parse", "--is-bare-repository"]);
692
935
  return result.exitCode === 0 && result.stdout.trim() === "true";
693
936
  }
937
+ /**
938
+ * List references in a remote repository
939
+ */
940
+ async lsRemote(remote, opts) {
941
+ const args = ["ls-remote"];
942
+ if (opts?.heads) {
943
+ args.push("--heads");
944
+ }
945
+ if (opts?.tags) {
946
+ args.push("--tags");
947
+ }
948
+ if (opts?.refsOnly) {
949
+ args.push("--refs");
950
+ }
951
+ if (opts?.getUrl) {
952
+ args.push("--get-url");
953
+ }
954
+ if (opts?.sort) {
955
+ args.push("--sort", opts.sort);
956
+ }
957
+ if (opts?.symref) {
958
+ args.push("--symref");
959
+ }
960
+ args.push(remote);
961
+ if (opts?.refs && opts.refs.length > 0) {
962
+ args.push(...opts.refs);
963
+ }
964
+ const result = await this.runner.runOrThrow(this.context, args, {
965
+ signal: opts?.signal,
966
+ onProgress: opts?.onProgress
967
+ });
968
+ const refs = parseLsRemote(result.stdout);
969
+ return { refs };
970
+ }
971
+ /**
972
+ * List contents of a tree object
973
+ */
974
+ async lsTree(treeish, opts) {
975
+ const args = ["ls-tree"];
976
+ if (opts?.recursive) {
977
+ args.push("-r");
978
+ }
979
+ if (opts?.treeOnly) {
980
+ args.push("-d");
981
+ }
982
+ if (opts?.showTrees) {
983
+ args.push("-t");
984
+ }
985
+ if (opts?.long) {
986
+ args.push("--long");
987
+ }
988
+ if (opts?.nameOnly) {
989
+ args.push("--name-only");
990
+ }
991
+ if (opts?.objectOnly) {
992
+ args.push("--object-only");
993
+ }
994
+ if (opts?.fullName) {
995
+ args.push("--full-name");
996
+ }
997
+ if (opts?.fullTree) {
998
+ args.push("--full-tree");
999
+ }
1000
+ if (opts?.abbrev !== void 0) {
1001
+ if (opts.abbrev === true) {
1002
+ args.push("--abbrev");
1003
+ } else if (typeof opts.abbrev === "number") {
1004
+ args.push(`--abbrev=${opts.abbrev}`);
1005
+ }
1006
+ }
1007
+ args.push(treeish);
1008
+ if (opts?.paths && opts.paths.length > 0) {
1009
+ args.push("--", ...opts.paths);
1010
+ }
1011
+ const result = await this.runner.runOrThrow(this.context, args, {
1012
+ signal: opts?.signal
1013
+ });
1014
+ return parseLsTree(result.stdout, {
1015
+ nameOnly: opts?.nameOnly,
1016
+ objectOnly: opts?.objectOnly,
1017
+ long: opts?.long
1018
+ });
1019
+ }
1020
+ async revParse(refOrOpts, opts) {
1021
+ const args = ["rev-parse"];
1022
+ if (typeof refOrOpts === "string") {
1023
+ addRefOptions(args, opts);
1024
+ args.push(refOrOpts);
1025
+ const result2 = await this.runner.runOrThrow(this.context, args, {
1026
+ signal: opts?.signal
1027
+ });
1028
+ return result2.stdout.trim();
1029
+ }
1030
+ const queryOpts = refOrOpts;
1031
+ tryAddPathQuery(args, queryOpts) || tryAddBooleanQuery(args, queryOpts) || tryAddListQuery(args, queryOpts) || tryAddOtherQuery(args, queryOpts);
1032
+ if ("pathFormat" in queryOpts && queryOpts.pathFormat) {
1033
+ args.push(`--path-format=${queryOpts.pathFormat}`);
1034
+ }
1035
+ const result = await this.runner.runOrThrow(this.context, args, {
1036
+ signal: refOrOpts.signal
1037
+ });
1038
+ const output = result.stdout.trim();
1039
+ if (isBooleanQuery(queryOpts)) {
1040
+ return output === "true";
1041
+ }
1042
+ if (isListQuery(queryOpts)) {
1043
+ return output ? output.split("\n").filter((line) => line.length > 0) : [];
1044
+ }
1045
+ return output;
1046
+ }
694
1047
  /**
695
1048
  * Fetch from remote
696
1049
  */
@@ -758,37 +1111,9 @@ var BareRepoImpl = class {
758
1111
  });
759
1112
  const remotes = /* @__PURE__ */ new Map();
760
1113
  for (const line of parseLines(result.stdout)) {
761
- const match = line.match(/^(\S+)\t(.+?)\s+\((fetch|push)\)$/);
762
- if (match) {
763
- const name = match[1];
764
- const url = match[2];
765
- const type = match[3];
766
- if (name !== void 0 && url !== void 0) {
767
- const existing = remotes.get(name);
768
- if (existing) {
769
- if (type === "fetch") {
770
- existing.fetchUrl = url;
771
- } else if (type === "push") {
772
- existing.pushUrl = url;
773
- }
774
- } else {
775
- remotes.set(name, {
776
- name,
777
- fetchUrl: type === "fetch" ? url : "",
778
- pushUrl: type === "push" ? url : ""
779
- });
780
- }
781
- }
782
- }
783
- }
784
- for (const remote of remotes.values()) {
785
- if (!remote.fetchUrl && remote.pushUrl) {
786
- remote.fetchUrl = remote.pushUrl;
787
- }
788
- if (!remote.pushUrl && remote.fetchUrl) {
789
- remote.pushUrl = remote.fetchUrl;
790
- }
1114
+ parseRemoteLine(line, remotes);
791
1115
  }
1116
+ normalizeRemoteUrls(remotes);
792
1117
  return Array.from(remotes.values());
793
1118
  }
794
1119
  async remoteAdd(name, url, opts) {
@@ -877,7 +1202,7 @@ var BareRepoImpl = class {
877
1202
  });
878
1203
  const pruned = [];
879
1204
  for (const line of parseLines(result.stdout)) {
880
- const match = line.match(/\* \[pruned\] (.+)/);
1205
+ const match = line.match(PRUNED_REF_PATTERN);
881
1206
  const ref = match?.[1];
882
1207
  if (ref) {
883
1208
  pruned.push(ref);
@@ -1204,6 +1529,89 @@ var WorktreeRepoImpl = class _WorktreeRepoImpl {
1204
1529
  const result = await this.runner.run(this.context, ["rev-parse", "--is-bare-repository"]);
1205
1530
  return result.exitCode === 0 && result.stdout.trim() === "true";
1206
1531
  }
1532
+ /**
1533
+ * List references in a remote repository
1534
+ */
1535
+ async lsRemote(remote, opts) {
1536
+ const args = ["ls-remote"];
1537
+ if (opts?.heads) {
1538
+ args.push("--heads");
1539
+ }
1540
+ if (opts?.tags) {
1541
+ args.push("--tags");
1542
+ }
1543
+ if (opts?.refsOnly) {
1544
+ args.push("--refs");
1545
+ }
1546
+ if (opts?.getUrl) {
1547
+ args.push("--get-url");
1548
+ }
1549
+ if (opts?.sort) {
1550
+ args.push("--sort", opts.sort);
1551
+ }
1552
+ if (opts?.symref) {
1553
+ args.push("--symref");
1554
+ }
1555
+ args.push(remote);
1556
+ if (opts?.refs && opts.refs.length > 0) {
1557
+ args.push(...opts.refs);
1558
+ }
1559
+ const result = await this.runner.runOrThrow(this.context, args, {
1560
+ signal: opts?.signal,
1561
+ onProgress: opts?.onProgress
1562
+ });
1563
+ const refs = parseLsRemote(result.stdout);
1564
+ return { refs };
1565
+ }
1566
+ /**
1567
+ * List contents of a tree object
1568
+ */
1569
+ async lsTree(treeish, opts) {
1570
+ const args = ["ls-tree"];
1571
+ if (opts?.recursive) {
1572
+ args.push("-r");
1573
+ }
1574
+ if (opts?.treeOnly) {
1575
+ args.push("-d");
1576
+ }
1577
+ if (opts?.showTrees) {
1578
+ args.push("-t");
1579
+ }
1580
+ if (opts?.long) {
1581
+ args.push("--long");
1582
+ }
1583
+ if (opts?.nameOnly) {
1584
+ args.push("--name-only");
1585
+ }
1586
+ if (opts?.objectOnly) {
1587
+ args.push("--object-only");
1588
+ }
1589
+ if (opts?.fullName) {
1590
+ args.push("--full-name");
1591
+ }
1592
+ if (opts?.fullTree) {
1593
+ args.push("--full-tree");
1594
+ }
1595
+ if (opts?.abbrev !== void 0) {
1596
+ if (opts.abbrev === true) {
1597
+ args.push("--abbrev");
1598
+ } else if (typeof opts.abbrev === "number") {
1599
+ args.push(`--abbrev=${opts.abbrev}`);
1600
+ }
1601
+ }
1602
+ args.push(treeish);
1603
+ if (opts?.paths && opts.paths.length > 0) {
1604
+ args.push("--", ...opts.paths);
1605
+ }
1606
+ const result = await this.runner.runOrThrow(this.context, args, {
1607
+ signal: opts?.signal
1608
+ });
1609
+ return parseLsTree(result.stdout, {
1610
+ nameOnly: opts?.nameOnly,
1611
+ objectOnly: opts?.objectOnly,
1612
+ long: opts?.long
1613
+ });
1614
+ }
1207
1615
  /**
1208
1616
  * Get repository status
1209
1617
  */
@@ -4099,17 +4507,151 @@ var WorktreeRepoImpl = class _WorktreeRepoImpl {
4099
4507
  });
4100
4508
  return result.stdout;
4101
4509
  }
4102
- // ==========================================================================
4103
- // Plumbing Operations
4104
- // ==========================================================================
4105
- /**
4106
- * Parse revision specification and return the object name (SHA)
4107
- */
4108
- async revParse(ref, opts) {
4109
- const result = await this.runner.runOrThrow(this.context, ["rev-parse", ref], {
4110
- signal: opts?.signal
4510
+ async revParse(refOrOpts, opts) {
4511
+ const args = ["rev-parse"];
4512
+ if (typeof refOrOpts === "string") {
4513
+ if (opts?.verify) {
4514
+ args.push("--verify");
4515
+ }
4516
+ if (opts?.short !== void 0) {
4517
+ if (typeof opts.short === "number") {
4518
+ args.push(`--short=${opts.short}`);
4519
+ } else if (opts.short) {
4520
+ args.push("--short");
4521
+ }
4522
+ }
4523
+ if (opts?.abbrevRef !== void 0) {
4524
+ if (opts.abbrevRef === "strict") {
4525
+ args.push("--abbrev-ref=strict");
4526
+ } else if (opts.abbrevRef === "loose") {
4527
+ args.push("--abbrev-ref=loose");
4528
+ } else if (opts.abbrevRef) {
4529
+ args.push("--abbrev-ref");
4530
+ }
4531
+ }
4532
+ if (opts?.symbolic) {
4533
+ args.push("--symbolic");
4534
+ }
4535
+ if (opts?.symbolicFullName) {
4536
+ args.push("--symbolic-full-name");
4537
+ }
4538
+ if (opts?.quiet) {
4539
+ args.push("--quiet");
4540
+ }
4541
+ args.push(refOrOpts);
4542
+ const result2 = await this.runner.runOrThrow(this.context, args, {
4543
+ signal: opts?.signal
4544
+ });
4545
+ return result2.stdout.trim();
4546
+ }
4547
+ const queryOpts = refOrOpts;
4548
+ if ("gitDir" in queryOpts && queryOpts.gitDir) {
4549
+ args.push("--git-dir");
4550
+ } else if ("absoluteGitDir" in queryOpts && queryOpts.absoluteGitDir) {
4551
+ args.push("--absolute-git-dir");
4552
+ } else if ("gitCommonDir" in queryOpts && queryOpts.gitCommonDir) {
4553
+ args.push("--git-common-dir");
4554
+ } else if ("showToplevel" in queryOpts && queryOpts.showToplevel) {
4555
+ args.push("--show-toplevel");
4556
+ } else if ("showCdup" in queryOpts && queryOpts.showCdup) {
4557
+ args.push("--show-cdup");
4558
+ } else if ("showPrefix" in queryOpts && queryOpts.showPrefix) {
4559
+ args.push("--show-prefix");
4560
+ } else if ("showSuperprojectWorkingTree" in queryOpts && queryOpts.showSuperprojectWorkingTree) {
4561
+ args.push("--show-superproject-working-tree");
4562
+ } else if ("sharedIndexPath" in queryOpts && queryOpts.sharedIndexPath) {
4563
+ args.push("--shared-index-path");
4564
+ } else if ("gitPath" in queryOpts && typeof queryOpts.gitPath === "string") {
4565
+ args.push("--git-path", queryOpts.gitPath);
4566
+ } else if ("resolveGitDir" in queryOpts && typeof queryOpts.resolveGitDir === "string") {
4567
+ args.push("--resolve-git-dir", queryOpts.resolveGitDir);
4568
+ } else if ("isInsideGitDir" in queryOpts && queryOpts.isInsideGitDir) {
4569
+ args.push("--is-inside-git-dir");
4570
+ } else if ("isInsideWorkTree" in queryOpts && queryOpts.isInsideWorkTree) {
4571
+ args.push("--is-inside-work-tree");
4572
+ } else if ("isBareRepository" in queryOpts && queryOpts.isBareRepository) {
4573
+ args.push("--is-bare-repository");
4574
+ } else if ("isShallowRepository" in queryOpts && queryOpts.isShallowRepository) {
4575
+ args.push("--is-shallow-repository");
4576
+ } else if ("all" in queryOpts && queryOpts.all) {
4577
+ if ("exclude" in queryOpts && queryOpts.exclude) {
4578
+ args.push(`--exclude=${queryOpts.exclude}`);
4579
+ }
4580
+ if ("excludeHidden" in queryOpts && queryOpts.excludeHidden) {
4581
+ args.push(`--exclude-hidden=${queryOpts.excludeHidden}`);
4582
+ }
4583
+ args.push("--all");
4584
+ } else if ("branches" in queryOpts && queryOpts.branches) {
4585
+ if ("exclude" in queryOpts && queryOpts.exclude) {
4586
+ args.push(`--exclude=${queryOpts.exclude}`);
4587
+ }
4588
+ if ("excludeHidden" in queryOpts && queryOpts.excludeHidden) {
4589
+ args.push(`--exclude-hidden=${queryOpts.excludeHidden}`);
4590
+ }
4591
+ if (typeof queryOpts.branches === "string") {
4592
+ args.push(`--branches=${queryOpts.branches}`);
4593
+ } else {
4594
+ args.push("--branches");
4595
+ }
4596
+ } else if ("tags" in queryOpts && queryOpts.tags) {
4597
+ if ("exclude" in queryOpts && queryOpts.exclude) {
4598
+ args.push(`--exclude=${queryOpts.exclude}`);
4599
+ }
4600
+ if ("excludeHidden" in queryOpts && queryOpts.excludeHidden) {
4601
+ args.push(`--exclude-hidden=${queryOpts.excludeHidden}`);
4602
+ }
4603
+ if (typeof queryOpts.tags === "string") {
4604
+ args.push(`--tags=${queryOpts.tags}`);
4605
+ } else {
4606
+ args.push("--tags");
4607
+ }
4608
+ } else if ("remotes" in queryOpts && queryOpts.remotes) {
4609
+ if ("exclude" in queryOpts && queryOpts.exclude) {
4610
+ args.push(`--exclude=${queryOpts.exclude}`);
4611
+ }
4612
+ if ("excludeHidden" in queryOpts && queryOpts.excludeHidden) {
4613
+ args.push(`--exclude-hidden=${queryOpts.excludeHidden}`);
4614
+ }
4615
+ if (typeof queryOpts.remotes === "string") {
4616
+ args.push(`--remotes=${queryOpts.remotes}`);
4617
+ } else {
4618
+ args.push("--remotes");
4619
+ }
4620
+ } else if ("glob" in queryOpts && typeof queryOpts.glob === "string") {
4621
+ if ("exclude" in queryOpts && queryOpts.exclude) {
4622
+ args.push(`--exclude=${queryOpts.exclude}`);
4623
+ }
4624
+ if ("excludeHidden" in queryOpts && queryOpts.excludeHidden) {
4625
+ args.push(`--exclude-hidden=${queryOpts.excludeHidden}`);
4626
+ }
4627
+ args.push(`--glob=${queryOpts.glob}`);
4628
+ } else if ("disambiguate" in queryOpts && typeof queryOpts.disambiguate === "string") {
4629
+ args.push(`--disambiguate=${queryOpts.disambiguate}`);
4630
+ } else if ("showObjectFormat" in queryOpts && queryOpts.showObjectFormat) {
4631
+ if (queryOpts.showObjectFormat === true) {
4632
+ args.push("--show-object-format");
4633
+ } else {
4634
+ args.push(`--show-object-format=${queryOpts.showObjectFormat}`);
4635
+ }
4636
+ } else if ("showRefFormat" in queryOpts && queryOpts.showRefFormat) {
4637
+ args.push("--show-ref-format");
4638
+ } else if ("localEnvVars" in queryOpts && queryOpts.localEnvVars) {
4639
+ args.push("--local-env-vars");
4640
+ }
4641
+ if ("pathFormat" in queryOpts && queryOpts.pathFormat) {
4642
+ args.push(`--path-format=${queryOpts.pathFormat}`);
4643
+ }
4644
+ const result = await this.runner.runOrThrow(this.context, args, {
4645
+ signal: queryOpts.signal
4111
4646
  });
4112
- return result.stdout.trim();
4647
+ const output = result.stdout.trim();
4648
+ if ("isInsideGitDir" in queryOpts && queryOpts.isInsideGitDir || "isInsideWorkTree" in queryOpts && queryOpts.isInsideWorkTree || "isBareRepository" in queryOpts && queryOpts.isBareRepository || "isShallowRepository" in queryOpts && queryOpts.isShallowRepository) {
4649
+ return output === "true";
4650
+ }
4651
+ 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) {
4652
+ return output ? output.split("\n").filter((line) => line.length > 0) : [];
4653
+ }
4654
+ return output;
4113
4655
  }
4114
4656
  /**
4115
4657
  * Count the number of commits reachable from a ref
@@ -4663,6 +5205,101 @@ var WorktreeRepoImpl = class _WorktreeRepoImpl {
4663
5205
  };
4664
5206
 
4665
5207
  // src/impl/git-impl.ts
5208
+ var GIT_VERSION_REGEX = /git version (\S+)/;
5209
+ function buildCloneArgs(opts) {
5210
+ const args = ["clone"];
5211
+ if (!opts) {
5212
+ return args;
5213
+ }
5214
+ const booleanFlags = [
5215
+ ["verbose", "--verbose"],
5216
+ ["quiet", "--quiet"],
5217
+ ["bare", "--bare"],
5218
+ ["mirror", "--mirror"],
5219
+ ["rejectShallow", "--reject-shallow"],
5220
+ ["singleBranch", "--single-branch"],
5221
+ ["noCheckout", "--no-checkout"],
5222
+ ["sparse", "--sparse"],
5223
+ ["local", "--local"],
5224
+ ["noHardlinks", "--no-hardlinks"],
5225
+ ["shared", "--shared"],
5226
+ ["dissociate", "--dissociate"],
5227
+ ["recurseSubmodules", "--recurse-submodules"],
5228
+ ["shallowSubmodules", "--shallow-submodules"],
5229
+ ["remoteSubmodules", "--remote-submodules"],
5230
+ ["noTags", "--no-tags"],
5231
+ ["alsoFilterSubmodules", "--also-filter-submodules"],
5232
+ ["ipv4", "--ipv4"],
5233
+ ["ipv6", "--ipv6"]
5234
+ ];
5235
+ for (const [key, flag] of booleanFlags) {
5236
+ if (opts[key]) {
5237
+ args.push(flag);
5238
+ }
5239
+ }
5240
+ const stringFlags = [
5241
+ ["branch", "--branch"],
5242
+ ["reference", "--reference"],
5243
+ ["referenceIfAble", "--reference-if-able"],
5244
+ ["template", "--template"],
5245
+ ["origin", "--origin"],
5246
+ ["separateGitDir", "--separate-git-dir"],
5247
+ ["filter", "--filter"]
5248
+ ];
5249
+ for (const [key, flag] of stringFlags) {
5250
+ const value = opts[key];
5251
+ if (typeof value === "string") {
5252
+ args.push(flag, value);
5253
+ }
5254
+ }
5255
+ if (opts.depth !== void 0) {
5256
+ args.push("--depth", String(opts.depth));
5257
+ }
5258
+ if (opts.jobs !== void 0) {
5259
+ args.push("--jobs", String(opts.jobs));
5260
+ }
5261
+ if (opts.shallowSince) {
5262
+ const since = opts.shallowSince instanceof Date ? opts.shallowSince.toISOString() : opts.shallowSince;
5263
+ args.push("--shallow-since", since);
5264
+ }
5265
+ if (opts.shallowExclude) {
5266
+ const excludes = Array.isArray(opts.shallowExclude) ? opts.shallowExclude : [opts.shallowExclude];
5267
+ for (const exclude of excludes) {
5268
+ args.push("--shallow-exclude", exclude);
5269
+ }
5270
+ }
5271
+ if (opts.config) {
5272
+ for (const [key, value] of Object.entries(opts.config)) {
5273
+ args.push("-c", `${key}=${value}`);
5274
+ }
5275
+ }
5276
+ return args;
5277
+ }
5278
+ var MIN_GIT_VERSION = "2.30.0";
5279
+ var LEGACY_GIT_VERSION = "2.25.0";
5280
+ var VERSION_REGEX = /^(\d+)\.(\d+)\.(\d+)/;
5281
+ function parseVersion(version) {
5282
+ const match = version.match(VERSION_REGEX);
5283
+ if (!match) {
5284
+ return [0, 0, 0];
5285
+ }
5286
+ return [
5287
+ Number.parseInt(match[1], 10),
5288
+ Number.parseInt(match[2], 10),
5289
+ Number.parseInt(match[3], 10)
5290
+ ];
5291
+ }
5292
+ function compareVersions(a, b) {
5293
+ const [aMajor, aMinor, aPatch] = parseVersion(a);
5294
+ const [bMajor, bMinor, bPatch] = parseVersion(b);
5295
+ if (aMajor !== bMajor) {
5296
+ return aMajor - bMajor;
5297
+ }
5298
+ if (aMinor !== bMinor) {
5299
+ return aMinor - bMinor;
5300
+ }
5301
+ return aPatch - bPatch;
5302
+ }
4666
5303
  function toCliRunnerOptions(opts) {
4667
5304
  if (!opts) {
4668
5305
  return {};
@@ -4680,6 +5317,7 @@ function toCliRunnerOptions(opts) {
4680
5317
  var GitImpl = class {
4681
5318
  runner;
4682
5319
  adapters;
5320
+ cachedVersion = null;
4683
5321
  config;
4684
5322
  lfs;
4685
5323
  constructor(options) {
@@ -4768,109 +5406,10 @@ var GitImpl = class {
4768
5406
  return new WorktreeRepoImpl(repoRunner, path, opts);
4769
5407
  }
4770
5408
  async clone(url, path, opts) {
4771
- const args = ["clone"];
5409
+ const args = buildCloneArgs(opts);
4772
5410
  if (opts?.onProgress) {
4773
5411
  args.push("--progress");
4774
5412
  }
4775
- if (opts?.verbose) {
4776
- args.push("--verbose");
4777
- }
4778
- if (opts?.quiet) {
4779
- args.push("--quiet");
4780
- }
4781
- if (opts?.bare) {
4782
- args.push("--bare");
4783
- }
4784
- if (opts?.mirror) {
4785
- args.push("--mirror");
4786
- }
4787
- if (opts?.depth !== void 0) {
4788
- args.push("--depth", String(opts.depth));
4789
- }
4790
- if (opts?.shallowSince) {
4791
- const since = opts.shallowSince instanceof Date ? opts.shallowSince.toISOString() : opts.shallowSince;
4792
- args.push("--shallow-since", since);
4793
- }
4794
- if (opts?.shallowExclude) {
4795
- const excludes = Array.isArray(opts.shallowExclude) ? opts.shallowExclude : [opts.shallowExclude];
4796
- for (const exclude of excludes) {
4797
- args.push("--shallow-exclude", exclude);
4798
- }
4799
- }
4800
- if (opts?.rejectShallow) {
4801
- args.push("--reject-shallow");
4802
- }
4803
- if (opts?.branch) {
4804
- args.push("--branch", opts.branch);
4805
- }
4806
- if (opts?.singleBranch) {
4807
- args.push("--single-branch");
4808
- }
4809
- if (opts?.noCheckout) {
4810
- args.push("--no-checkout");
4811
- }
4812
- if (opts?.sparse) {
4813
- args.push("--sparse");
4814
- }
4815
- if (opts?.local) {
4816
- args.push("--local");
4817
- }
4818
- if (opts?.noHardlinks) {
4819
- args.push("--no-hardlinks");
4820
- }
4821
- if (opts?.shared) {
4822
- args.push("--shared");
4823
- }
4824
- if (opts?.reference) {
4825
- args.push("--reference", opts.reference);
4826
- }
4827
- if (opts?.referenceIfAble) {
4828
- args.push("--reference-if-able", opts.referenceIfAble);
4829
- }
4830
- if (opts?.dissociate) {
4831
- args.push("--dissociate");
4832
- }
4833
- if (opts?.recurseSubmodules) {
4834
- args.push("--recurse-submodules");
4835
- }
4836
- if (opts?.shallowSubmodules) {
4837
- args.push("--shallow-submodules");
4838
- }
4839
- if (opts?.remoteSubmodules) {
4840
- args.push("--remote-submodules");
4841
- }
4842
- if (opts?.jobs !== void 0) {
4843
- args.push("--jobs", String(opts.jobs));
4844
- }
4845
- if (opts?.noTags) {
4846
- args.push("--no-tags");
4847
- }
4848
- if (opts?.template) {
4849
- args.push("--template", opts.template);
4850
- }
4851
- if (opts?.origin) {
4852
- args.push("--origin", opts.origin);
4853
- }
4854
- if (opts?.separateGitDir) {
4855
- args.push("--separate-git-dir", opts.separateGitDir);
4856
- }
4857
- if (opts?.config) {
4858
- for (const [key, value] of Object.entries(opts.config)) {
4859
- args.push("-c", `${key}=${value}`);
4860
- }
4861
- }
4862
- if (opts?.filter) {
4863
- args.push("--filter", opts.filter);
4864
- }
4865
- if (opts?.alsoFilterSubmodules) {
4866
- args.push("--also-filter-submodules");
4867
- }
4868
- if (opts?.ipv4) {
4869
- args.push("--ipv4");
4870
- }
4871
- if (opts?.ipv6) {
4872
- args.push("--ipv6");
4873
- }
4874
5413
  args.push(url, path);
4875
5414
  try {
4876
5415
  await this.runner.runOrThrow({ type: "global" }, args, {
@@ -4910,7 +5449,7 @@ var GitImpl = class {
4910
5449
  args.push(`--shared=${opts.shared}`);
4911
5450
  }
4912
5451
  }
4913
- if (opts?.initialBranch) {
5452
+ if (opts?.initialBranch && await this.supportsInitialBranch()) {
4914
5453
  args.push("--initial-branch", opts.initialBranch);
4915
5454
  }
4916
5455
  if (opts?.objectFormat) {
@@ -4925,6 +5464,16 @@ var GitImpl = class {
4925
5464
  signal: opts?.signal,
4926
5465
  onProgress: opts?.onProgress
4927
5466
  });
5467
+ if (opts?.initialBranch && !await this.supportsInitialBranch()) {
5468
+ const context = opts?.bare ? { type: "bare", gitDir: path } : { type: "worktree", workdir: path };
5469
+ await this.runner.runOrThrow(
5470
+ context,
5471
+ ["symbolic-ref", "HEAD", `refs/heads/${opts.initialBranch}`],
5472
+ {
5473
+ signal: opts?.signal
5474
+ }
5475
+ );
5476
+ }
4928
5477
  } catch (error) {
4929
5478
  if (error instanceof GitError && error.kind === "Aborted" && opts?.cleanupOnAbort !== false) {
4930
5479
  await this.adapters.fs.deleteDirectory(path);
@@ -4971,17 +5520,28 @@ var GitImpl = class {
4971
5520
  * Get git version
4972
5521
  */
4973
5522
  async version(opts) {
5523
+ if (this.cachedVersion) {
5524
+ return this.cachedVersion;
5525
+ }
4974
5526
  const result = await this.runner.runOrThrow({ type: "global" }, ["--version"], {
4975
5527
  signal: opts?.signal
4976
5528
  });
4977
- const match = result.stdout.match(/git version (\S+)/);
4978
- const version = match?.[1];
4979
- return version ?? result.stdout.trim();
5529
+ const match = result.stdout.match(GIT_VERSION_REGEX);
5530
+ const version = match?.[1] ?? result.stdout.trim();
5531
+ this.cachedVersion = version;
5532
+ return version;
5533
+ }
5534
+ /**
5535
+ * Check if Git version supports --initial-branch option (Git 2.28+)
5536
+ */
5537
+ async supportsInitialBranch() {
5538
+ const version = await this.version();
5539
+ return compareVersions(version, "2.28.0") >= 0;
4980
5540
  }
4981
5541
  /**
4982
5542
  * Execute a raw git command (repository-agnostic)
4983
5543
  */
4984
- async raw(argv, opts) {
5544
+ raw(argv, opts) {
4985
5545
  return this.runner.run({ type: "global" }, argv, opts);
4986
5546
  }
4987
5547
  // ==========================================================================
@@ -5167,9 +5727,24 @@ var GitImpl = class {
5167
5727
  return result.stdout.trim();
5168
5728
  }
5169
5729
  };
5170
- function createGit(options) {
5730
+ function createGitSync(options) {
5171
5731
  return new GitImpl(options);
5172
5732
  }
5733
+ async function createGit(options) {
5734
+ const git = new GitImpl(options);
5735
+ if (!options.skipVersionCheck) {
5736
+ const versionString = await git.version();
5737
+ const minVersion = options.useLegacyVersion ? LEGACY_GIT_VERSION : MIN_GIT_VERSION;
5738
+ if (compareVersions(versionString, minVersion) < 0) {
5739
+ throw new GitError(
5740
+ "UnsupportedGitVersion",
5741
+ `Git version ${versionString} is not supported. Minimum required version is ${minVersion}.`,
5742
+ {}
5743
+ );
5744
+ }
5745
+ }
5746
+ return git;
5747
+ }
5173
5748
 
5174
5749
  // src/adapters/node/exec.ts
5175
5750
  import { spawn } from "child_process";
@@ -5328,52 +5903,132 @@ var NodeExecAdapter = class {
5328
5903
  import { access, mkdtemp, open, readFile, rm, writeFile } from "fs/promises";
5329
5904
  import { tmpdir } from "os";
5330
5905
  import { join } from "path";
5906
+
5907
+ // src/internal/file-polling.ts
5908
+ async function runTailPolling(options) {
5909
+ const { adapter, signal, pollInterval = 100, onLine } = options;
5910
+ let position = 0;
5911
+ let buffer = "";
5912
+ while (!signal?.aborted) {
5913
+ const result = await adapter.readChunk(position);
5914
+ if (result !== null && result.data.length > 0) {
5915
+ position = result.newPosition;
5916
+ buffer += result.data;
5917
+ const lines = buffer.split("\n");
5918
+ buffer = lines.pop() ?? "";
5919
+ for (const line of lines) {
5920
+ if (line) {
5921
+ onLine(line);
5922
+ }
5923
+ }
5924
+ }
5925
+ if (!signal?.aborted) {
5926
+ await adapter.sleep(pollInterval);
5927
+ }
5928
+ }
5929
+ }
5930
+ function createTailPolling(options) {
5931
+ const { adapter, signal, pollInterval = 100 } = options;
5932
+ const state = {
5933
+ stopped: false,
5934
+ resolveNext: null,
5935
+ lineQueue: []
5936
+ };
5937
+ const stop = () => {
5938
+ state.stopped = true;
5939
+ if (state.resolveNext) {
5940
+ state.resolveNext({ done: true, value: void 0 });
5941
+ state.resolveNext = null;
5942
+ }
5943
+ };
5944
+ startPollingLoop(adapter, state, signal, pollInterval, stop).catch(() => {
5945
+ });
5946
+ const lines = {
5947
+ [Symbol.asyncIterator]() {
5948
+ return {
5949
+ next() {
5950
+ if (state.stopped) {
5951
+ return Promise.resolve({ done: true, value: void 0 });
5952
+ }
5953
+ if (state.lineQueue.length > 0) {
5954
+ const value = state.lineQueue.shift();
5955
+ if (value !== void 0) {
5956
+ return Promise.resolve({ done: false, value });
5957
+ }
5958
+ }
5959
+ return new Promise((resolve) => {
5960
+ state.resolveNext = resolve;
5961
+ });
5962
+ }
5963
+ };
5964
+ }
5965
+ };
5966
+ return { lines, stop };
5967
+ }
5968
+ async function startPollingLoop(adapter, state, signal, pollInterval, stop) {
5969
+ let position = 0;
5970
+ let buffer = "";
5971
+ while (!(state.stopped || signal?.aborted)) {
5972
+ const result = await adapter.readChunk(position);
5973
+ if (result !== null && result.data.length > 0) {
5974
+ position = result.newPosition;
5975
+ buffer += result.data;
5976
+ const lines = buffer.split("\n");
5977
+ buffer = lines.pop() ?? "";
5978
+ for (const line of lines) {
5979
+ if (line) {
5980
+ if (state.resolveNext) {
5981
+ const resolver = state.resolveNext;
5982
+ state.resolveNext = null;
5983
+ resolver({ done: false, value: line });
5984
+ } else {
5985
+ state.lineQueue.push(line);
5986
+ }
5987
+ }
5988
+ }
5989
+ }
5990
+ await adapter.sleep(pollInterval);
5991
+ }
5992
+ stop();
5993
+ }
5994
+
5995
+ // src/adapters/node/fs.ts
5331
5996
  var NodeFsAdapter = class {
5332
5997
  async createTempFile(prefix = "type-git-") {
5333
5998
  const dir = await mkdtemp(join(tmpdir(), prefix));
5334
5999
  return join(dir, "temp");
5335
6000
  }
5336
6001
  async tail(options) {
5337
- const { filePath, signal, onLine } = options;
5338
- const file = await open(filePath, "r");
5339
- let position = 0;
6002
+ const { filePath, signal, onLine, pollInterval = 100 } = options;
6003
+ const state = { file: null };
5340
6004
  const decoder = new TextDecoder();
5341
- let buffer = "";
5342
- const poll = async () => {
5343
- if (signal?.aborted) {
5344
- await file.close();
5345
- return;
5346
- }
5347
- try {
5348
- const { bytesRead, buffer: chunk } = await file.read({
5349
- buffer: Buffer.alloc(4096),
5350
- position
5351
- });
5352
- if (bytesRead > 0) {
5353
- position += bytesRead;
5354
- buffer += decoder.decode(chunk.subarray(0, bytesRead), { stream: true });
5355
- const lines = buffer.split("\n");
5356
- buffer = lines.pop() ?? "";
5357
- for (const line of lines) {
5358
- if (line) {
5359
- onLine(line);
5360
- }
6005
+ const adapter = {
6006
+ readChunk: async (position) => {
6007
+ try {
6008
+ if (!state.file) {
6009
+ state.file = await open(filePath, "r");
5361
6010
  }
5362
- }
5363
- } catch (error) {
5364
- await file.close();
5365
- throw error;
5366
- }
5367
- if (!signal?.aborted) {
5368
- setTimeout(() => {
5369
- poll().catch(() => {
6011
+ const { bytesRead, buffer: chunk } = await state.file.read({
6012
+ buffer: Buffer.alloc(4096),
6013
+ position
5370
6014
  });
5371
- }, 100);
5372
- } else {
5373
- await file.close();
5374
- }
6015
+ return {
6016
+ data: decoder.decode(chunk.subarray(0, bytesRead), { stream: true }),
6017
+ newPosition: position + bytesRead
6018
+ };
6019
+ } catch {
6020
+ return null;
6021
+ }
6022
+ },
6023
+ sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms))
5375
6024
  };
5376
- await poll();
6025
+ try {
6026
+ await runTailPolling({ adapter, signal, pollInterval, onLine });
6027
+ } finally {
6028
+ if (state.file) {
6029
+ await state.file.close();
6030
+ }
6031
+ }
5377
6032
  }
5378
6033
  async deleteFile(filePath) {
5379
6034
  await rm(filePath, { force: true });
@@ -5397,83 +6052,39 @@ var NodeFsAdapter = class {
5397
6052
  }
5398
6053
  tailStreaming(filePath, options) {
5399
6054
  const { signal, pollInterval = 100 } = options ?? {};
5400
- const state = {
5401
- stopped: false,
5402
- resolveNext: null,
5403
- lineQueue: []
5404
- };
5405
- const stop = () => {
5406
- state.stopped = true;
5407
- if (state.resolveNext) {
5408
- state.resolveNext({ done: true, value: void 0 });
5409
- state.resolveNext = null;
5410
- }
5411
- };
5412
- const startPolling = async () => {
5413
- let file;
5414
- try {
5415
- file = await open(filePath, "r");
5416
- } catch {
5417
- stop();
5418
- return;
5419
- }
5420
- let position = 0;
5421
- const decoder = new TextDecoder();
5422
- let buffer = "";
5423
- while (!(state.stopped || signal?.aborted)) {
6055
+ const state = { file: null };
6056
+ const decoder = new TextDecoder();
6057
+ const adapter = {
6058
+ readChunk: async (position) => {
5424
6059
  try {
5425
- const { bytesRead, buffer: chunk } = await file.read({
6060
+ if (!state.file) {
6061
+ state.file = await open(filePath, "r");
6062
+ }
6063
+ const { bytesRead, buffer: chunk } = await state.file.read({
5426
6064
  buffer: Buffer.alloc(4096),
5427
6065
  position
5428
6066
  });
5429
- if (bytesRead > 0) {
5430
- position += bytesRead;
5431
- buffer += decoder.decode(chunk.subarray(0, bytesRead), { stream: true });
5432
- const lines2 = buffer.split("\n");
5433
- buffer = lines2.pop() ?? "";
5434
- for (const line of lines2) {
5435
- if (line) {
5436
- if (state.resolveNext) {
5437
- const resolver = state.resolveNext;
5438
- state.resolveNext = null;
5439
- resolver({ done: false, value: line });
5440
- } else {
5441
- state.lineQueue.push(line);
5442
- }
5443
- }
5444
- }
5445
- }
6067
+ return {
6068
+ data: decoder.decode(chunk.subarray(0, bytesRead), { stream: true }),
6069
+ newPosition: position + bytesRead
6070
+ };
5446
6071
  } catch {
5447
- break;
6072
+ return null;
5448
6073
  }
5449
- await new Promise((resolve) => setTimeout(resolve, pollInterval));
5450
- }
5451
- await file.close();
5452
- stop();
6074
+ },
6075
+ sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms))
5453
6076
  };
5454
- startPolling().catch(() => {
5455
- });
5456
- const lines = {
5457
- [Symbol.asyncIterator]() {
5458
- return {
5459
- next() {
5460
- if (state.stopped) {
5461
- return Promise.resolve({ done: true, value: void 0 });
5462
- }
5463
- if (state.lineQueue.length > 0) {
5464
- const value = state.lineQueue.shift();
5465
- if (value !== void 0) {
5466
- return Promise.resolve({ done: false, value });
5467
- }
5468
- }
5469
- return new Promise((resolve) => {
5470
- state.resolveNext = resolve;
5471
- });
5472
- }
5473
- };
6077
+ const polling = createTailPolling({ adapter, signal, pollInterval });
6078
+ const originalStop = polling.stop;
6079
+ const enhancedStop = () => {
6080
+ originalStop();
6081
+ if (state.file) {
6082
+ state.file.close().catch(() => {
6083
+ });
6084
+ state.file = null;
5474
6085
  }
5475
6086
  };
5476
- return { lines, stop };
6087
+ return { lines: polling.lines, stop: enhancedStop };
5477
6088
  }
5478
6089
  };
5479
6090
 
@@ -5484,13 +6095,31 @@ function createNodeAdapters() {
5484
6095
  fs: new NodeFsAdapter()
5485
6096
  };
5486
6097
  }
5487
- var TypeGit = class {
6098
+ var TypeGit = class _TypeGit {
5488
6099
  git;
5489
- constructor(options) {
5490
- this.git = createGit({
5491
- ...options,
6100
+ /**
6101
+ * Create a TypeGit instance with Git version check
6102
+ *
6103
+ * @param createOpts - Options including skipVersionCheck
6104
+ * @returns TypeGit instance
6105
+ * @throws GitError with kind 'UnsupportedGitVersion' if Git version is below minimum
6106
+ */
6107
+ static async create(createOpts) {
6108
+ const gitInstance = await createGit({
6109
+ ...createOpts,
5492
6110
  adapters: createNodeAdapters()
5493
6111
  });
6112
+ return new _TypeGit(gitInstance);
6113
+ }
6114
+ constructor(optionsOrGit) {
6115
+ if (optionsOrGit && "open" in optionsOrGit) {
6116
+ this.git = optionsOrGit;
6117
+ } else {
6118
+ this.git = createGitSync({
6119
+ ...optionsOrGit,
6120
+ adapters: createNodeAdapters()
6121
+ });
6122
+ }
5494
6123
  }
5495
6124
  /**
5496
6125
  * Open an existing worktree repository