type-git 0.3.0-beta.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -38,6 +38,267 @@ var GitArgumentError = class extends Error {
38
38
  }
39
39
  };
40
40
 
41
+ // src/core/option-rules.ts
42
+ var OPTION_RULES = {
43
+ clone: {
44
+ exclusive: [
45
+ ["ipv4", "ipv6"],
46
+ ["depth", "shallowSince"],
47
+ ["depth", "shallowExclude"],
48
+ ["bare", "separateGitDir"],
49
+ ["mirror", "separateGitDir"]
50
+ ],
51
+ unsupported: []
52
+ },
53
+ init: { exclusive: [["bare", "separateGitDir"]], unsupported: [] },
54
+ lsRemote: { exclusive: [], unsupported: ["getUrl", "symref"] },
55
+ lsTree: { exclusive: [["nameOnly", "objectOnly", "long"]], unsupported: [] },
56
+ status: { exclusive: [["noRenames", "findRenames"]], unsupported: ["verbose"] },
57
+ log: {
58
+ exclusive: [
59
+ ["merges", "noMerges"],
60
+ ["since", "after"],
61
+ ["until", "before"]
62
+ ],
63
+ unsupported: [
64
+ "source",
65
+ "decorate",
66
+ "decorateRefs",
67
+ "decorateRefsExclude",
68
+ "stat",
69
+ "shortstat",
70
+ "nameOnly",
71
+ "nameStatus"
72
+ ]
73
+ },
74
+ fetch: {
75
+ exclusive: [
76
+ ["ipv4", "ipv6"],
77
+ ["tags", "noTags"],
78
+ ["depth", "deepen", "unshallow"],
79
+ ["depth", "shallowSince"],
80
+ ["depth", "shallowExclude"],
81
+ ["all", "remote"],
82
+ ["all", "refspec"]
83
+ ],
84
+ unsupported: ["multiple"]
85
+ },
86
+ push: {
87
+ exclusive: [
88
+ ["ipv4", "ipv6"],
89
+ ["force", "forceWithLease"],
90
+ ["all", "mirror", "refspec"],
91
+ ["all", "tags"],
92
+ ["branches", "mirror", "refspec"],
93
+ ["branches", "tags"],
94
+ ["mirror", "tags"],
95
+ ["remote", "repo"]
96
+ ],
97
+ unsupported: []
98
+ },
99
+ add: { exclusive: [["all", "update"]], unsupported: ["interactive", "patch"] },
100
+ checkoutBranch: {
101
+ exclusive: [["createBranch", "forceCreateBranch", "detach", "orphan"]],
102
+ unsupported: []
103
+ },
104
+ checkoutPath: {
105
+ exclusive: [
106
+ ["ours", "theirs"],
107
+ ["source", "ours"],
108
+ ["source", "theirs"]
109
+ ],
110
+ unsupported: []
111
+ },
112
+ commit: {
113
+ exclusive: [
114
+ ["message", "file", "reuseMessage"],
115
+ ["fixup", "squash"],
116
+ ["include", "only", "all"],
117
+ ["gpgSign", "noGpgSign"]
118
+ ],
119
+ unsupported: ["dryRun", "reeditMessage"]
120
+ },
121
+ diff: {
122
+ exclusive: [
123
+ ["nameOnly", "nameStatus", "stat", "numstat", "patchWithRaw", "patchWithStat"],
124
+ ["nameOnly", "patch"],
125
+ ["nameStatus", "patch"],
126
+ ["nameOnly", "wordDiff"],
127
+ ["nameStatus", "wordDiff"],
128
+ ["nameOnly", "context"],
129
+ ["nameStatus", "context"]
130
+ ],
131
+ unsupported: ["noIndex"]
132
+ },
133
+ merge: {
134
+ controls: ["abort", "continue", "quit"],
135
+ exclusive: [
136
+ ["abort", "continue", "quit"],
137
+ ["noDiffstat", "stat"]
138
+ ],
139
+ unsupported: []
140
+ },
141
+ pull: {
142
+ exclusive: [
143
+ ["ipv4", "ipv6"],
144
+ ["noStat", "stat"],
145
+ ["depth", "deepen", "unshallow"],
146
+ ["depth", "shallowSince"],
147
+ ["depth", "shallowExclude"]
148
+ ],
149
+ unsupported: []
150
+ },
151
+ switch: {
152
+ exclusive: [
153
+ ["create", "forceCreate", "detach", "orphan"],
154
+ ["discard", "merge"],
155
+ ["force", "merge"]
156
+ ],
157
+ unsupported: []
158
+ },
159
+ cherryPick: {
160
+ controls: ["abort", "continue", "skip"],
161
+ exclusive: [["abort", "continue", "skip"]],
162
+ unsupported: ["noVerify"]
163
+ },
164
+ revert: {
165
+ controls: ["abort", "continue", "skip"],
166
+ exclusive: [["abort", "continue", "skip"]],
167
+ unsupported: ["noVerify"]
168
+ },
169
+ rebase: {
170
+ controls: ["abort", "continue", "skip"],
171
+ exclusive: [
172
+ ["abort", "continue", "skip"],
173
+ ["keepBase", "onto"],
174
+ ["keepBase", "root"],
175
+ ["apply", "rebaseMerges"],
176
+ ["apply", "strategy"],
177
+ ["apply", "exec"]
178
+ ],
179
+ unsupported: ["interactive"]
180
+ },
181
+ restore: {
182
+ exclusive: [
183
+ ["ours", "theirs"],
184
+ ["source", "ours"],
185
+ ["source", "theirs"],
186
+ ["source", "merge"],
187
+ ["source", "conflict"]
188
+ ],
189
+ unsupported: []
190
+ },
191
+ clean: { exclusive: [["ignored", "onlyIgnored"]], unsupported: [] },
192
+ worktreeAdd: {
193
+ exclusive: [
194
+ ["branch", "detach"],
195
+ ["orphan", "detach"]
196
+ ],
197
+ unsupported: []
198
+ },
199
+ remoteSetHead: { exclusive: [["auto", "delete"]], unsupported: [] },
200
+ configGet: { exclusive: [["all", "default"]], unsupported: [] },
201
+ configList: { exclusive: [], unsupported: ["nameOnly"] },
202
+ lfsPull: { exclusive: [], unsupported: ["ref"] },
203
+ lfsPush: { exclusive: [["ref", "objectId"]], unsupported: [] },
204
+ lfsFetch: {
205
+ exclusive: [
206
+ ["all", "include"],
207
+ ["all", "exclude"],
208
+ ["all", "recent"]
209
+ ],
210
+ unsupported: []
211
+ },
212
+ lfsStatus: { exclusive: [], unsupported: ["porcelain"] },
213
+ lfsLsFiles: { exclusive: [], unsupported: ["debug", "nameOnly"] }
214
+ };
215
+ function validateOptions(name, options) {
216
+ if (!options) {
217
+ return;
218
+ }
219
+ const values = options;
220
+ const rule = OPTION_RULES[name];
221
+ if ((name === "lfsStatus" || name === "lfsLsFiles") && values.json !== void 0 && values.json !== true) {
222
+ throw new GitArgumentError(`${name}: the typed API uses JSON`);
223
+ }
224
+ if (name === "status" && values.porcelain !== void 0 && values.porcelain !== 2) {
225
+ throw new GitArgumentError("status: the typed API uses porcelain v2");
226
+ }
227
+ if ((name === "status" || name === "diff") && values.nullTerminated !== void 0 && values.nullTerminated !== true) {
228
+ throw new GitArgumentError(`${name}: the typed API uses NUL-delimited paths`);
229
+ }
230
+ for (const key of rule.unsupported) {
231
+ if (values[key] !== void 0) {
232
+ throw new GitArgumentError(
233
+ `${name}: ${key} is not supported by the typed API; use raw() for this output or operation`
234
+ );
235
+ }
236
+ }
237
+ if (rule.controls?.some((key) => values[key] === true)) {
238
+ const ignored = Object.keys(values).filter(
239
+ (key) => !(rule.controls?.includes(key) || ["signal", "onProgress", "onLfsProgress"].includes(key)) && values[key] !== void 0 && values[key] !== false
240
+ );
241
+ if (ignored.length > 0) {
242
+ throw new GitArgumentError(`${name}: control operations cannot take ${ignored.join(", ")}`);
243
+ }
244
+ }
245
+ for (const group of rule.exclusive) {
246
+ const active = group.filter((key) => values[key] !== void 0 && values[key] !== false);
247
+ if (active.length > 1) {
248
+ throw new GitArgumentError(`${name}: ${active.join(", ")} cannot be used together`);
249
+ }
250
+ }
251
+ for (const key of ["depth", "deepen", "jobs", "mainline"]) {
252
+ const value = values[key];
253
+ if (value !== void 0 && (!Number.isSafeInteger(value) || value < 1)) {
254
+ throw new GitArgumentError(`${name}: ${key} must be a positive safe integer`);
255
+ }
256
+ }
257
+ for (const key of ["maxCount", "skip", "context", "renameLimit", "abbrev"]) {
258
+ const value = values[key];
259
+ if (value !== void 0 && typeof value !== "boolean" && (!Number.isSafeInteger(value) || value < 0)) {
260
+ throw new GitArgumentError(`${name}: ${key} must be a non-negative safe integer`);
261
+ }
262
+ }
263
+ }
264
+ var REV_PARSE_QUERY_KEYS = [
265
+ "gitDir",
266
+ "absoluteGitDir",
267
+ "gitCommonDir",
268
+ "showToplevel",
269
+ "showCdup",
270
+ "showPrefix",
271
+ "showSuperprojectWorkingTree",
272
+ "sharedIndexPath",
273
+ "gitPath",
274
+ "resolveGitDir",
275
+ "isInsideGitDir",
276
+ "isInsideWorkTree",
277
+ "isBareRepository",
278
+ "isShallowRepository",
279
+ "all",
280
+ "branches",
281
+ "tags",
282
+ "remotes",
283
+ "glob",
284
+ "disambiguate",
285
+ "showObjectFormat",
286
+ "showRefFormat",
287
+ "localEnvVars"
288
+ ];
289
+ function validateRevParseQuery(query) {
290
+ const values = query;
291
+ const selected = REV_PARSE_QUERY_KEYS.filter((key) => values[key] !== void 0);
292
+ if (selected.length !== 1 || values[selected[0]] !== true && typeof values[selected[0]] !== "string") {
293
+ throw new GitArgumentError("revParse: specify exactly one query");
294
+ }
295
+ }
296
+ function validatePathInput(name, paths, opts) {
297
+ if (opts?.pathspecFromFile !== void 0 && (typeof paths === "string" || paths.length > 0)) {
298
+ throw new GitArgumentError(`${name}: pass an empty path list when using pathspecFromFile`);
299
+ }
300
+ }
301
+
41
302
  // src/parsers/index.ts
42
303
  var GIT_PROGRESS_PERCENT_REGEX = /^(.+?):\s*(\d+)%\s*\((\d+)\/(\d+)\)(?:,\s*(done))?/;
43
304
  var GIT_PROGRESS_SIMPLE_REGEX = /^(.+?):\s*(\d+)\/(\d+)/;
@@ -49,13 +310,6 @@ var LFS_DOWNLOAD_REGEX = /downloading|filtering/i;
49
310
  var LFS_UPLOAD_REGEX = /uploading/i;
50
311
  var LFS_CHECKOUT_REGEX = /checking out/i;
51
312
  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;
52
- function at(arr, index, context) {
53
- const value = arr[index];
54
- if (value === void 0) {
55
- throw new Error(`Parse error: expected element at index ${index} in ${context}`);
56
- }
57
- return value;
58
- }
59
313
  function parseLines(stdout, options) {
60
314
  const { keepEmpty = false, trim = true } = options ?? {};
61
315
  const lines = stdout.split("\n");
@@ -66,9 +320,6 @@ function parseRecords(stdout, delimiter = "\0") {
66
320
  return [];
67
321
  }
68
322
  const normalized = stdout.endsWith(delimiter) ? stdout.slice(0, -delimiter.length) : stdout;
69
- if (!normalized) {
70
- return [];
71
- }
72
323
  return normalized.split(delimiter);
73
324
  }
74
325
  function parseJson(stdout, options) {
@@ -96,65 +347,123 @@ function parseKeyValue(stdout, options) {
96
347
  }
97
348
  return result;
98
349
  }
350
+ function decodePath(path) {
351
+ if (!path.startsWith('"')) {
352
+ return path;
353
+ }
354
+ if (!path.endsWith('"')) {
355
+ throw new GitError("ParseError", "Unterminated quoted path");
356
+ }
357
+ const bytes = [];
358
+ const encoder = new TextEncoder();
359
+ const escapes = {
360
+ a: "\x07",
361
+ b: "\b",
362
+ f: "\f",
363
+ n: "\n",
364
+ r: "\r",
365
+ t: " ",
366
+ v: "\v",
367
+ '"': '"',
368
+ "\\": "\\"
369
+ };
370
+ const value = path.slice(1, -1);
371
+ for (let i = 0; i < value.length; ) {
372
+ if (value[i] === "\\") {
373
+ const octal = value.slice(i + 1).match(/^[0-7]{1,3}/)?.[0];
374
+ if (octal) {
375
+ bytes.push(Number.parseInt(octal, 8));
376
+ i += octal.length + 1;
377
+ continue;
378
+ }
379
+ const escaped = escapes[value[i + 1] ?? ""];
380
+ if (escaped === void 0) {
381
+ throw new GitError("ParseError", "Invalid quoted path escape");
382
+ }
383
+ bytes.push(...encoder.encode(escaped));
384
+ i += 2;
385
+ } else {
386
+ const char = String.fromCodePoint(value.codePointAt(i));
387
+ bytes.push(...encoder.encode(char));
388
+ i += char.length;
389
+ }
390
+ }
391
+ return new TextDecoder().decode(new Uint8Array(bytes));
392
+ }
99
393
  function parsePorcelainV2(stdout) {
100
394
  const entries = [];
101
- const lines = parseLines(stdout);
102
- for (const line of lines) {
103
- if (line.startsWith("1 ")) {
104
- const parts = line.split(" ");
105
- const pathPart = parts.slice(8).join(" ");
106
- entries.push({
107
- type: "changed",
108
- xy: at(parts, 1, "porcelain-v2 ordinary"),
109
- sub: at(parts, 2, "porcelain-v2 ordinary"),
110
- mH: at(parts, 3, "porcelain-v2 ordinary"),
111
- mI: at(parts, 4, "porcelain-v2 ordinary"),
112
- mW: at(parts, 5, "porcelain-v2 ordinary"),
113
- hH: at(parts, 6, "porcelain-v2 ordinary"),
114
- hI: at(parts, 7, "porcelain-v2 ordinary"),
115
- path: pathPart
116
- });
117
- } else if (line.startsWith("2 ")) {
118
- const parts = line.split(" ");
119
- const pathPart = parts.slice(9).join(" ");
120
- const pathParts = pathPart.split(" ");
395
+ const nul = stdout.includes("\0");
396
+ const records = nul ? parseRecords(stdout) : parseLines(stdout, { trim: false });
397
+ for (let i = 0; i < records.length; i++) {
398
+ const line = records[i];
399
+ if (line.startsWith("# ")) {
400
+ continue;
401
+ }
402
+ const kind = line[0];
403
+ if (kind === "?" || kind === "!") {
404
+ if (line[1] !== " " || line.length < 3) {
405
+ throw new GitError("ParseError", "Invalid status path");
406
+ }
121
407
  entries.push({
122
- type: "changed",
123
- xy: at(parts, 1, "porcelain-v2 renamed"),
124
- sub: at(parts, 2, "porcelain-v2 renamed"),
125
- mH: at(parts, 3, "porcelain-v2 renamed"),
126
- mI: at(parts, 4, "porcelain-v2 renamed"),
127
- mW: at(parts, 5, "porcelain-v2 renamed"),
128
- hH: at(parts, 6, "porcelain-v2 renamed"),
129
- hI: at(parts, 7, "porcelain-v2 renamed"),
130
- path: at(pathParts, 0, "porcelain-v2 renamed path"),
131
- origPath: pathParts[1]
408
+ type: kind === "?" ? "untracked" : "ignored",
409
+ path: nul ? line.slice(2) : decodePath(line.slice(2))
132
410
  });
133
- } else if (line.startsWith("u ")) {
134
- const parts = line.split(" ");
135
- const pathPart = parts.slice(10).join(" ");
411
+ continue;
412
+ }
413
+ if (kind !== "1" && kind !== "2" && kind !== "u") {
414
+ throw new GitError("ParseError", "Unknown status record");
415
+ }
416
+ const count = kind === "u" ? 10 : kind === "2" ? 9 : 8;
417
+ const parts = line.split(" ");
418
+ if (parts.length <= count || parts[1]?.length !== 2) {
419
+ throw new GitError("ParseError", "Invalid status record");
420
+ }
421
+ let path = parts.slice(count).join(" ");
422
+ let origPath;
423
+ if (kind === "2") {
424
+ if (nul) {
425
+ origPath = records[++i];
426
+ } else {
427
+ const tab = path.indexOf(" ");
428
+ if (tab < 0) {
429
+ throw new GitError("ParseError", "Missing rename source");
430
+ }
431
+ origPath = decodePath(path.slice(tab + 1));
432
+ path = path.slice(0, tab);
433
+ }
434
+ if (origPath === void 0) {
435
+ throw new GitError("ParseError", "Missing rename source");
436
+ }
437
+ }
438
+ if (!nul) {
439
+ path = decodePath(path);
440
+ }
441
+ if (kind === "u") {
136
442
  entries.push({
137
443
  type: "unmerged",
138
- xy: at(parts, 1, "porcelain-v2 unmerged"),
139
- sub: at(parts, 2, "porcelain-v2 unmerged"),
140
- m1: at(parts, 3, "porcelain-v2 unmerged"),
141
- m2: at(parts, 4, "porcelain-v2 unmerged"),
142
- m3: at(parts, 5, "porcelain-v2 unmerged"),
143
- mW: at(parts, 6, "porcelain-v2 unmerged"),
144
- h1: at(parts, 7, "porcelain-v2 unmerged"),
145
- h2: at(parts, 8, "porcelain-v2 unmerged"),
146
- h3: at(parts, 9, "porcelain-v2 unmerged"),
147
- path: pathPart
444
+ xy: parts[1],
445
+ sub: parts[2],
446
+ m1: parts[3],
447
+ m2: parts[4],
448
+ m3: parts[5],
449
+ mW: parts[6],
450
+ h1: parts[7],
451
+ h2: parts[8],
452
+ h3: parts[9],
453
+ path
148
454
  });
149
- } else if (line.startsWith("? ")) {
150
- entries.push({
151
- type: "untracked",
152
- path: line.slice(2)
153
- });
154
- } else if (line.startsWith("! ")) {
455
+ } else {
155
456
  entries.push({
156
- type: "ignored",
157
- path: line.slice(2)
457
+ type: "changed",
458
+ xy: parts[1],
459
+ sub: parts[2],
460
+ mH: parts[3],
461
+ mI: parts[4],
462
+ mW: parts[5],
463
+ hH: parts[6],
464
+ hI: parts[7],
465
+ path,
466
+ ...origPath !== void 0 ? { origPath } : {}
158
467
  });
159
468
  }
160
469
  }
@@ -312,109 +621,71 @@ function parseLsRemote(stdout) {
312
621
  }
313
622
  return refs;
314
623
  }
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(.+)$/;
624
+ var LS_TREE_REGEX = /^(\d+)\s+(blob|tree|commit)\s+([a-f0-9]+)\t([\s\S]+)$/;
625
+ var LS_TREE_LONG_REGEX = /^(\d+)\s+(blob|tree|commit)\s+([a-f0-9]+)\s+(-|\d+)\t([\s\S]+)$/;
317
626
  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
- }
627
+ const nul = stdout.includes("\0");
628
+ const records = nul ? parseRecords(stdout) : parseLines(stdout, { trim: false });
629
+ if (opts?.nameOnly) {
630
+ return records.map((path) => nul ? path : decodePath(path));
631
+ }
632
+ if (opts?.objectOnly) {
633
+ return records;
634
+ }
635
+ return records.map((line) => {
636
+ const match = line.match(opts?.long ? LS_TREE_LONG_REGEX : LS_TREE_REGEX);
637
+ if (!match) {
638
+ throw new GitError("ParseError", "Invalid ls-tree record", { stdout: line });
358
639
  }
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
- }
640
+ const path = match[opts?.long ? 5 : 4];
641
+ const size = opts?.long && match[4] !== "-" ? Number(match[4]) : void 0;
642
+ if (size !== void 0 && !Number.isSafeInteger(size)) {
643
+ throw new GitError("ParseError", "Invalid tree object size");
373
644
  }
374
- }
375
- return entries;
645
+ return {
646
+ mode: match[1],
647
+ type: match[2],
648
+ hash: match[3],
649
+ path: nul ? path : decodePath(path),
650
+ ...size !== void 0 ? { size } : {}
651
+ };
652
+ });
376
653
  }
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";
654
+ 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";
378
655
  function parseGitLog(stdout) {
656
+ if (!stdout) {
657
+ return [];
658
+ }
659
+ const fields = parseRecords(stdout);
660
+ if (fields.length % 11 !== 0) {
661
+ throw new GitError("ParseError", "Invalid git log field count");
662
+ }
379
663
  const commits = [];
380
- const records = stdout.split("").filter((r) => r.trim());
381
- for (const record of records) {
382
- const fields = record.split("\0");
383
- if (fields.length < 11) {
384
- continue;
385
- }
386
- const hash = fields[0]?.trim();
387
- const abbrevHash = fields[1];
388
- const parentsStr = fields[2];
389
- const authorName = fields[3];
390
- const authorEmail = fields[4];
391
- const authorTimestampStr = fields[5];
392
- const committerName = fields[6];
393
- const committerEmail = fields[7];
394
- const committerTimestampStr = fields[8];
395
- const subject = fields[9];
396
- if (hash === void 0 || abbrevHash === void 0 || authorName === void 0 || authorEmail === void 0 || authorTimestampStr === void 0 || committerName === void 0 || committerEmail === void 0 || committerTimestampStr === void 0 || subject === void 0) {
397
- continue;
664
+ for (let i = 0; i < fields.length; i += 11) {
665
+ const authorTimestamp = Number(fields[i + 5]);
666
+ const committerTimestamp = Number(fields[i + 8]);
667
+ if (!(fields[i] && Number.isSafeInteger(authorTimestamp) && Number.isSafeInteger(committerTimestamp))) {
668
+ throw new GitError("ParseError", "Invalid git log metadata");
398
669
  }
399
670
  commits.push({
400
- hash,
401
- abbrevHash,
402
- parents: parentsStr ? parentsStr.split(" ").filter(Boolean) : [],
403
- authorName,
404
- authorEmail,
405
- authorTimestamp: Number.parseInt(authorTimestampStr, 10),
406
- committerName,
407
- committerEmail,
408
- committerTimestamp: Number.parseInt(committerTimestampStr, 10),
409
- subject,
410
- body: fields[10]?.trim() ?? ""
671
+ hash: fields[i],
672
+ abbrevHash: fields[i + 1],
673
+ parents: fields[i + 2]?.split(" ").filter(Boolean) ?? [],
674
+ authorName: fields[i + 3],
675
+ authorEmail: fields[i + 4],
676
+ authorTimestamp,
677
+ committerName: fields[i + 6],
678
+ committerEmail: fields[i + 7],
679
+ committerTimestamp,
680
+ subject: fields[i + 9],
681
+ body: fields[i + 10]
411
682
  });
412
683
  }
413
684
  return commits;
414
685
  }
415
686
  function parseWorktreeList(stdout) {
416
687
  const worktrees = [];
417
- const lines = parseLines(stdout, { keepEmpty: true });
688
+ const lines = parseLines(stdout, { keepEmpty: true, trim: false });
418
689
  let current = null;
419
690
  for (const line of lines) {
420
691
  if (line.startsWith("worktree ")) {
@@ -428,7 +699,7 @@ function parseWorktreeList(stdout) {
428
699
  });
429
700
  }
430
701
  current = {
431
- path: line.slice("worktree ".length),
702
+ path: decodePath(line.slice("worktree ".length)),
432
703
  locked: false,
433
704
  prunable: false
434
705
  };
@@ -500,6 +771,132 @@ function detectErrorCategory(stderr) {
500
771
  return "unknown";
501
772
  }
502
773
 
774
+ // src/internal/config.ts
775
+ var CONFIG_ENUMS = {
776
+ "core.autocrlf": ["true", "false", "input"],
777
+ "core.filemode": ["true", "false"],
778
+ "core.ignorecase": ["true", "false"],
779
+ "core.bare": ["true", "false"],
780
+ "core.logallrefupdates": ["true", "false", "always"],
781
+ "core.quotepath": ["true", "false"],
782
+ "commit.gpgsign": ["true", "false"],
783
+ "tag.gpgsign": ["true", "false"],
784
+ "tag.forcesignannotated": ["true", "false"],
785
+ "push.default": ["nothing", "current", "upstream", "tracking", "simple", "matching"],
786
+ "push.followTags": ["true", "false"],
787
+ "push.autoSetupRemote": ["true", "false"],
788
+ "push.gpgSign": ["true", "false", "if-asked"],
789
+ "pull.rebase": ["true", "false", "merges", "interactive"],
790
+ "pull.ff": ["true", "false", "only"],
791
+ "fetch.prune": ["true", "false"],
792
+ "fetch.pruneTags": ["true", "false"],
793
+ "merge.ff": ["true", "false", "only"],
794
+ "merge.conflictstyle": ["merge", "diff3", "zdiff3"],
795
+ "rebase.autoStash": ["true", "false"],
796
+ "rebase.autoSquash": ["true", "false"],
797
+ "rebase.updateRefs": ["true", "false"],
798
+ "diff.algorithm": ["default", "minimal", "patience", "histogram"],
799
+ "diff.colorMoved": ["no", "default", "plain", "blocks", "zebra", "dimmed-zebra"],
800
+ "color.ui": ["auto", "always", "never", "true", "false"],
801
+ "gpg.format": ["openpgp", "x509", "ssh"],
802
+ "http.sslVerify": ["true", "false"]
803
+ };
804
+ function configValue(key, value, implicit = false) {
805
+ const allowed = CONFIG_ENUMS[key];
806
+ if (!allowed) {
807
+ return value;
808
+ }
809
+ let normalized = value.toLowerCase();
810
+ if (allowed.includes("true") && allowed.includes("false")) {
811
+ if (normalized === "") {
812
+ normalized = implicit ? "true" : "false";
813
+ }
814
+ if (/^[+-]?\d+[kmg]?$/i.test(normalized)) {
815
+ normalized = Number.parseInt(normalized, 10) === 0 ? "false" : "true";
816
+ }
817
+ if (["yes", "on", "1"].includes(normalized)) {
818
+ normalized = "true";
819
+ }
820
+ if (["no", "off", "0"].includes(normalized)) {
821
+ normalized = "false";
822
+ }
823
+ }
824
+ if (!allowed.includes(normalized)) {
825
+ throw new GitError("ParseError", `Invalid value for ${key}: expected ${allowed.join(" | ")}`);
826
+ }
827
+ return normalized;
828
+ }
829
+ async function readConfig(runner, context, key, opts) {
830
+ validateOptions("configGet", opts);
831
+ const args = ["config", ...context.type === "global" ? ["--global"] : [], "--null"];
832
+ if (opts?.type) {
833
+ args.push(`--type=${opts.type}`);
834
+ }
835
+ if (opts?.default !== void 0) {
836
+ args.push("--default", opts.default);
837
+ }
838
+ args.push(opts?.all ? "--get-all" : "--get", key);
839
+ const result = await runner.run(context, args, opts);
840
+ if (result.exitCode === 1 && !result.aborted) {
841
+ return opts?.all ? [] : void 0;
842
+ }
843
+ runner.checkResult(context, args, result);
844
+ const values = parseRecords(result.stdout);
845
+ return opts?.all ? values : values[0];
846
+ }
847
+ async function listConfig(runner, context, opts) {
848
+ validateOptions("configList", opts);
849
+ const args = ["config", ...context.type === "global" ? ["--global"] : [], "--null", "--list"];
850
+ if (opts?.showOrigin) {
851
+ args.push("--show-origin");
852
+ }
853
+ if (opts?.showScope) {
854
+ args.push("--show-scope");
855
+ }
856
+ if (opts?.includes !== void 0) {
857
+ args.push(opts.includes ? "--includes" : "--no-includes");
858
+ }
859
+ const result = await runner.runOrThrow(context, args, opts);
860
+ const records = parseRecords(result.stdout);
861
+ const entries = [];
862
+ for (let i = 0; i < records.length; ) {
863
+ const scope = opts?.showScope ? records[i++] : void 0;
864
+ const origin = opts?.showOrigin ? records[i++] : void 0;
865
+ const entry = records[i++];
866
+ if (entry === void 0) {
867
+ throw new GitError("ParseError", "Incomplete config record");
868
+ }
869
+ const separator = entry.indexOf("\n");
870
+ entries.push({
871
+ key: separator < 0 ? entry : entry.slice(0, separator),
872
+ value: separator < 0 ? "" : entry.slice(separator + 1),
873
+ ...scope !== void 0 ? { scope } : {},
874
+ ...origin !== void 0 ? { origin } : {}
875
+ });
876
+ }
877
+ return entries;
878
+ }
879
+ async function readTypedConfig(runner, context, key, opts, all = false) {
880
+ const pattern = `^${key.toLowerCase().replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}$`;
881
+ const args = [
882
+ "config",
883
+ ...context.type === "global" ? ["--global"] : [],
884
+ "--null",
885
+ "--get-regexp",
886
+ pattern
887
+ ];
888
+ const result = await runner.run(context, args, opts);
889
+ if (result.exitCode === 1 && !result.aborted) {
890
+ return [];
891
+ }
892
+ runner.checkResult(context, args, result);
893
+ const records = parseRecords(result.stdout);
894
+ return (all ? records : records.slice(-1)).map((record2) => {
895
+ const separator = record2.indexOf("\n");
896
+ return configValue(key, separator < 0 ? "" : record2.slice(separator + 1), separator < 0);
897
+ });
898
+ }
899
+
503
900
  // src/runner/cli-runner.ts
504
901
  import process2 from "process";
505
902
 
@@ -810,6 +1207,9 @@ var CliRunner = class _CliRunner {
810
1207
  async run(context, args, opts) {
811
1208
  const argv = this.buildArgv(context, args);
812
1209
  const { signal, onProgress, onLfsProgress, env: envOverride } = opts ?? {};
1210
+ if (signal?.aborted) {
1211
+ return { stdout: "", stderr: "", exitCode: -1, aborted: true };
1212
+ }
813
1213
  const env = this.buildEnv();
814
1214
  if (envOverride) {
815
1215
  Object.assign(env, envOverride);
@@ -870,7 +1270,17 @@ var CliRunner = class _CliRunner {
870
1270
  duration: endTimestamp - startTimestamp
871
1271
  });
872
1272
  }
873
- throw error;
1273
+ if (error instanceof GitError) {
1274
+ throw error;
1275
+ }
1276
+ throw new GitError(
1277
+ signal?.aborted ? "Aborted" : "SpawnFailed",
1278
+ error instanceof Error ? error.message : String(error),
1279
+ {
1280
+ argv,
1281
+ ...context.type === "worktree" ? { workdir: context.workdir } : context.type === "bare" ? { gitDir: context.gitDir } : {}
1282
+ }
1283
+ );
874
1284
  }
875
1285
  if (this.audit?.onAudit) {
876
1286
  const endTimestamp = Date.now();
@@ -975,6 +1385,12 @@ var CliRunner = class _CliRunner {
975
1385
  /**
976
1386
  * Run a command and throw on error
977
1387
  */
1388
+ checkResult(context, args, result) {
1389
+ const error = this.mapError(result, context, this.buildArgv(context, args));
1390
+ if (error) {
1391
+ throw error;
1392
+ }
1393
+ }
978
1394
  async runOrThrow(context, args, opts) {
979
1395
  const result = await this.run(context, args, opts);
980
1396
  const error = this.mapError(result, context, this.buildArgv(context, args));
@@ -985,6 +1401,230 @@ var CliRunner = class _CliRunner {
985
1401
  }
986
1402
  };
987
1403
 
1404
+ // src/internal/transport.ts
1405
+ async function fetch(runner, context, opts) {
1406
+ validateOptions("fetch", opts);
1407
+ const args = ["fetch"];
1408
+ if (opts?.onProgress) {
1409
+ args.push("--progress");
1410
+ }
1411
+ if (opts?.verbose) {
1412
+ args.push("--verbose");
1413
+ }
1414
+ if (opts?.quiet) {
1415
+ args.push("--quiet");
1416
+ }
1417
+ if (opts?.all) {
1418
+ args.push("--all");
1419
+ }
1420
+ if (opts?.setUpstream) {
1421
+ args.push("--set-upstream");
1422
+ }
1423
+ if (opts?.append) {
1424
+ args.push("--append");
1425
+ }
1426
+ if (opts?.atomic) {
1427
+ args.push("--atomic");
1428
+ }
1429
+ if (opts?.force) {
1430
+ args.push("--force");
1431
+ }
1432
+ if (opts?.prune) {
1433
+ args.push("--prune");
1434
+ }
1435
+ if (opts?.pruneTags) {
1436
+ args.push("--prune-tags");
1437
+ }
1438
+ if (opts?.tags) {
1439
+ args.push("--tags");
1440
+ } else if (opts?.noTags) {
1441
+ args.push("--no-tags");
1442
+ }
1443
+ if (opts?.jobs !== void 0) {
1444
+ args.push(`--jobs=${opts.jobs}`);
1445
+ }
1446
+ if (opts?.prefetch) {
1447
+ args.push("--prefetch");
1448
+ }
1449
+ if (opts?.recurseSubmodules !== void 0) {
1450
+ if (opts.recurseSubmodules === true || opts.recurseSubmodules === "yes") {
1451
+ args.push("--recurse-submodules=yes");
1452
+ } else if (opts.recurseSubmodules === "on-demand") {
1453
+ args.push("--recurse-submodules=on-demand");
1454
+ } else if (opts.recurseSubmodules === "no" || opts.recurseSubmodules === false) {
1455
+ args.push("--recurse-submodules=no");
1456
+ }
1457
+ }
1458
+ if (opts?.dryRun) {
1459
+ args.push("--dry-run");
1460
+ }
1461
+ if (opts?.writeFetchHead === false) {
1462
+ args.push("--no-write-fetch-head");
1463
+ }
1464
+ if (opts?.keep) {
1465
+ args.push("--keep");
1466
+ }
1467
+ if (opts?.updateHeadOk) {
1468
+ args.push("--update-head-ok");
1469
+ }
1470
+ if (opts?.depth !== void 0) {
1471
+ args.push(`--depth=${opts.depth}`);
1472
+ }
1473
+ if (opts?.shallowSince) {
1474
+ const since = opts.shallowSince instanceof Date ? opts.shallowSince.toISOString() : opts.shallowSince;
1475
+ args.push(`--shallow-since=${since}`);
1476
+ }
1477
+ if (opts?.shallowExclude) {
1478
+ const excludes = Array.isArray(opts.shallowExclude) ? opts.shallowExclude : [opts.shallowExclude];
1479
+ for (const exclude of excludes) {
1480
+ args.push(`--shallow-exclude=${exclude}`);
1481
+ }
1482
+ }
1483
+ if (opts?.deepen !== void 0) {
1484
+ args.push(`--deepen=${opts.deepen}`);
1485
+ }
1486
+ if (opts?.unshallow) {
1487
+ args.push("--unshallow");
1488
+ }
1489
+ if (opts?.refetch) {
1490
+ args.push("--refetch");
1491
+ }
1492
+ if (opts?.updateShallow) {
1493
+ args.push("--update-shallow");
1494
+ }
1495
+ if (opts?.refmap) {
1496
+ args.push(`--refmap=${opts.refmap}`);
1497
+ }
1498
+ if (opts?.ipv4) {
1499
+ args.push("--ipv4");
1500
+ }
1501
+ if (opts?.ipv6) {
1502
+ args.push("--ipv6");
1503
+ }
1504
+ if (opts?.filter) {
1505
+ args.push(`--filter=${opts.filter}`);
1506
+ }
1507
+ if (opts?.showForcedUpdates === false) {
1508
+ args.push("--no-show-forced-updates");
1509
+ }
1510
+ if (opts?.writeCommitGraph) {
1511
+ args.push("--write-commit-graph");
1512
+ }
1513
+ if (opts?.remote) {
1514
+ args.push(opts.remote);
1515
+ }
1516
+ if (opts?.refspec) {
1517
+ const refspecs = Array.isArray(opts.refspec) ? opts.refspec : [opts.refspec];
1518
+ args.push(...refspecs);
1519
+ }
1520
+ await runner.runOrThrow(context, args, {
1521
+ signal: opts?.signal,
1522
+ onProgress: opts?.onProgress
1523
+ });
1524
+ }
1525
+ async function push(runner, context, opts) {
1526
+ validateOptions("push", opts);
1527
+ const args = ["push"];
1528
+ if (opts?.onProgress || opts?.onLfsProgress) {
1529
+ args.push("--progress");
1530
+ }
1531
+ if (opts?.verbose) {
1532
+ args.push("--verbose");
1533
+ }
1534
+ if (opts?.quiet) {
1535
+ args.push("--quiet");
1536
+ }
1537
+ if (opts?.repo) {
1538
+ args.push(`--repo=${opts.repo}`);
1539
+ }
1540
+ if (opts?.all) {
1541
+ args.push("--all");
1542
+ } else if (opts?.branches) {
1543
+ args.push("--branches");
1544
+ }
1545
+ if (opts?.mirror) {
1546
+ args.push("--mirror");
1547
+ }
1548
+ if (opts?.deleteRefs) {
1549
+ args.push("--delete");
1550
+ }
1551
+ if (opts?.force) {
1552
+ args.push("--force");
1553
+ } else if (opts?.forceWithLease !== void 0 && opts.forceWithLease !== false) {
1554
+ if (opts.forceWithLease === true) {
1555
+ args.push("--force-with-lease");
1556
+ } else {
1557
+ const leaseOpts = opts.forceWithLease;
1558
+ if (leaseOpts.expect !== void 0) {
1559
+ args.push(`--force-with-lease=${leaseOpts.refname}:${leaseOpts.expect}`);
1560
+ } else {
1561
+ args.push(`--force-with-lease=${leaseOpts.refname}`);
1562
+ }
1563
+ }
1564
+ }
1565
+ if (opts?.forceIfIncludes) {
1566
+ args.push("--force-if-includes");
1567
+ }
1568
+ if (opts?.dryRun) {
1569
+ args.push("--dry-run");
1570
+ }
1571
+ if (opts?.recurseSubmodules) {
1572
+ args.push(`--recurse-submodules=${opts.recurseSubmodules}`);
1573
+ }
1574
+ if (opts?.thin === false) {
1575
+ args.push("--no-thin");
1576
+ }
1577
+ if (opts?.prune) {
1578
+ args.push("--prune");
1579
+ }
1580
+ if (opts?.tags) {
1581
+ args.push("--tags");
1582
+ }
1583
+ if (opts?.followTags) {
1584
+ args.push("--follow-tags");
1585
+ }
1586
+ if (opts?.atomic) {
1587
+ args.push("--atomic");
1588
+ }
1589
+ if (opts?.pushOption) {
1590
+ const pushOptions = Array.isArray(opts.pushOption) ? opts.pushOption : [opts.pushOption];
1591
+ for (const opt of pushOptions) {
1592
+ args.push("--push-option", opt);
1593
+ }
1594
+ }
1595
+ if (opts?.setUpstream) {
1596
+ args.push("--set-upstream");
1597
+ }
1598
+ if (opts?.noVerify) {
1599
+ args.push("--no-verify");
1600
+ }
1601
+ if (opts?.signed !== void 0) {
1602
+ if (opts.signed === true) {
1603
+ args.push("--signed");
1604
+ } else if (opts.signed === "if-asked") {
1605
+ args.push("--signed=if-asked");
1606
+ }
1607
+ }
1608
+ if (opts?.ipv4) {
1609
+ args.push("--ipv4");
1610
+ }
1611
+ if (opts?.ipv6) {
1612
+ args.push("--ipv6");
1613
+ }
1614
+ if (opts?.remote) {
1615
+ args.push(opts.remote);
1616
+ }
1617
+ if (opts?.refspec) {
1618
+ const refspecs = Array.isArray(opts.refspec) ? opts.refspec : [opts.refspec];
1619
+ args.push(...refspecs);
1620
+ }
1621
+ await runner.runOrThrow(context, args, {
1622
+ signal: opts?.signal,
1623
+ onProgress: opts?.onProgress,
1624
+ onLfsProgress: opts?.onLfsProgress
1625
+ });
1626
+ }
1627
+
988
1628
  // src/impl/bare-repo-impl.ts
989
1629
  var REMOTE_LINE_PATTERN = /^(\S+)\t(.+?)\s+\((fetch|push)\)$/;
990
1630
  var PRUNED_REF_PATTERN = /\* \[pruned\] (.+)/;
@@ -1177,6 +1817,7 @@ function isListQuery(opts) {
1177
1817
  return "glob" in opts && !!opts.glob || "disambiguate" in opts && !!opts.disambiguate || "localEnvVars" in opts && !!opts.localEnvVars;
1178
1818
  }
1179
1819
  var BareRepoImpl = class {
1820
+ kind = "bare";
1180
1821
  gitDir;
1181
1822
  runner;
1182
1823
  remote;
@@ -1242,6 +1883,7 @@ var BareRepoImpl = class {
1242
1883
  * List references in a remote repository
1243
1884
  */
1244
1885
  async lsRemote(remote, opts) {
1886
+ validateOptions("lsRemote", opts);
1245
1887
  const args = ["ls-remote"];
1246
1888
  if (opts?.heads) {
1247
1889
  args.push("--heads");
@@ -1252,15 +1894,9 @@ var BareRepoImpl = class {
1252
1894
  if (opts?.refsOnly) {
1253
1895
  args.push("--refs");
1254
1896
  }
1255
- if (opts?.getUrl) {
1256
- args.push("--get-url");
1257
- }
1258
1897
  if (opts?.sort) {
1259
1898
  args.push("--sort", opts.sort);
1260
1899
  }
1261
- if (opts?.symref) {
1262
- args.push("--symref");
1263
- }
1264
1900
  args.push(remote);
1265
1901
  if (opts?.refs && opts.refs.length > 0) {
1266
1902
  args.push(...opts.refs);
@@ -1272,11 +1908,9 @@ var BareRepoImpl = class {
1272
1908
  const refs = parseLsRemote(result.stdout);
1273
1909
  return { refs };
1274
1910
  }
1275
- /**
1276
- * List contents of a tree object
1277
- */
1278
1911
  async lsTree(treeish, opts) {
1279
- const args = ["ls-tree"];
1912
+ validateOptions("lsTree", opts);
1913
+ const args = ["ls-tree", "-z"];
1280
1914
  if (opts?.recursive) {
1281
1915
  args.push("-r");
1282
1916
  }
@@ -1289,12 +1923,6 @@ var BareRepoImpl = class {
1289
1923
  if (opts?.long) {
1290
1924
  args.push("--long");
1291
1925
  }
1292
- if (opts?.nameOnly) {
1293
- args.push("--name-only");
1294
- }
1295
- if (opts?.objectOnly) {
1296
- args.push("--object-only");
1297
- }
1298
1926
  if (opts?.fullName) {
1299
1927
  args.push("--full-name");
1300
1928
  }
@@ -1315,11 +1943,14 @@ var BareRepoImpl = class {
1315
1943
  const result = await this.runner.runOrThrow(this.context, args, {
1316
1944
  signal: opts?.signal
1317
1945
  });
1318
- return parseLsTree(result.stdout, {
1319
- nameOnly: opts?.nameOnly,
1320
- objectOnly: opts?.objectOnly,
1321
- long: opts?.long
1322
- });
1946
+ const entries = parseLsTree(result.stdout, { long: opts?.long });
1947
+ if (opts?.nameOnly) {
1948
+ return entries.map((entry) => entry.path);
1949
+ }
1950
+ if (opts?.objectOnly) {
1951
+ return entries.map((entry) => entry.hash);
1952
+ }
1953
+ return entries;
1323
1954
  }
1324
1955
  async revParse(refOrOpts, opts) {
1325
1956
  const args = ["rev-parse"];
@@ -1331,11 +1962,12 @@ var BareRepoImpl = class {
1331
1962
  });
1332
1963
  return result2.stdout.trim();
1333
1964
  }
1965
+ validateRevParseQuery(refOrOpts);
1966
+ if ("pathFormat" in refOrOpts && refOrOpts.pathFormat) {
1967
+ args.push(`--path-format=${refOrOpts.pathFormat}`);
1968
+ }
1334
1969
  const queryOpts = refOrOpts;
1335
1970
  tryAddPathQuery(args, queryOpts) || tryAddBooleanQuery(args, queryOpts) || tryAddListQuery(args, queryOpts) || tryAddOtherQuery(args, queryOpts);
1336
- if ("pathFormat" in queryOpts && queryOpts.pathFormat) {
1337
- args.push(`--path-format=${queryOpts.pathFormat}`);
1338
- }
1339
1971
  const result = await this.runner.runOrThrow(this.context, args, {
1340
1972
  signal: refOrOpts.signal
1341
1973
  });
@@ -1352,60 +1984,13 @@ var BareRepoImpl = class {
1352
1984
  * Fetch from remote
1353
1985
  */
1354
1986
  async fetch(opts) {
1355
- const args = ["fetch"];
1356
- if (opts?.onProgress) {
1357
- args.push("--progress");
1358
- }
1359
- if (opts?.prune) {
1360
- args.push("--prune");
1361
- }
1362
- if (opts?.tags) {
1363
- args.push("--tags");
1364
- }
1365
- if (opts?.depth !== void 0) {
1366
- args.push(`--depth=${opts.depth}`);
1367
- }
1368
- if (opts?.remote) {
1369
- args.push(opts.remote);
1370
- }
1371
- if (opts?.refspec) {
1372
- const refspecs = Array.isArray(opts.refspec) ? opts.refspec : [opts.refspec];
1373
- args.push(...refspecs);
1374
- }
1375
- await this.runner.runOrThrow(this.context, args, {
1376
- signal: opts?.signal,
1377
- onProgress: opts?.onProgress
1378
- });
1987
+ return fetch(this.runner, this.context, opts);
1379
1988
  }
1380
1989
  /**
1381
1990
  * Push to remote
1382
1991
  */
1383
1992
  async push(opts) {
1384
- const args = ["push"];
1385
- if (opts?.onProgress || opts?.onLfsProgress) {
1386
- args.push("--progress");
1387
- }
1388
- if (opts?.force) {
1389
- args.push("--force");
1390
- }
1391
- if (opts?.tags) {
1392
- args.push("--tags");
1393
- }
1394
- if (opts?.setUpstream) {
1395
- args.push("--set-upstream");
1396
- }
1397
- if (opts?.remote) {
1398
- args.push(opts.remote);
1399
- }
1400
- if (opts?.refspec) {
1401
- const refspecs = Array.isArray(opts.refspec) ? opts.refspec : [opts.refspec];
1402
- args.push(...refspecs);
1403
- }
1404
- await this.runner.runOrThrow(this.context, args, {
1405
- signal: opts?.signal,
1406
- onProgress: opts?.onProgress,
1407
- onLfsProgress: opts?.onLfsProgress
1408
- });
1993
+ return push(this.runner, this.context, opts);
1409
1994
  }
1410
1995
  // ==========================================================================
1411
1996
  // Remote Operations
@@ -1471,6 +2056,7 @@ var BareRepoImpl = class {
1471
2056
  });
1472
2057
  }
1473
2058
  async remoteSetHead(remote, branch, opts) {
2059
+ validateOptions("remoteSetHead", opts);
1474
2060
  const args = ["remote", "set-head"];
1475
2061
  if (opts?.auto) {
1476
2062
  args.push("--auto");
@@ -1544,25 +2130,14 @@ var BareRepoImpl = class {
1544
2130
  * Get a typed config value
1545
2131
  */
1546
2132
  async configGet(key, opts) {
1547
- const result = await this.runner.run(this.context, ["config", "--get", key], {
1548
- signal: opts?.signal
1549
- });
1550
- if (result.exitCode !== 0) {
1551
- return void 0;
1552
- }
1553
- return result.stdout.trim();
2133
+ const values = await readTypedConfig(this.runner, this.context, key, opts);
2134
+ return values.at(-1);
1554
2135
  }
1555
2136
  /**
1556
2137
  * Get all values for a typed multi-valued config key
1557
2138
  */
1558
2139
  async configGetAll(key, opts) {
1559
- const result = await this.runner.run(this.context, ["config", "--get-all", key], {
1560
- signal: opts?.signal
1561
- });
1562
- if (result.exitCode !== 0) {
1563
- return [];
1564
- }
1565
- return parseLines(result.stdout);
2140
+ return readTypedConfig(this.runner, this.context, key, opts, true);
1566
2141
  }
1567
2142
  /**
1568
2143
  * Set a typed config value
@@ -1588,27 +2163,8 @@ var BareRepoImpl = class {
1588
2163
  signal: opts?.signal
1589
2164
  });
1590
2165
  }
1591
- /**
1592
- * Get a raw config value (for arbitrary keys)
1593
- */
1594
2166
  async configGetRaw(key, opts) {
1595
- const args = ["config"];
1596
- if (opts?.all) {
1597
- args.push("--get-all");
1598
- } else {
1599
- args.push("--get");
1600
- }
1601
- args.push(key);
1602
- const result = await this.runner.run(this.context, args, {
1603
- signal: opts?.signal
1604
- });
1605
- if (result.exitCode !== 0) {
1606
- return void 0;
1607
- }
1608
- if (opts?.all) {
1609
- return parseLines(result.stdout);
1610
- }
1611
- return result.stdout.trim();
2167
+ return readConfig(this.runner, this.context, key, opts);
1612
2168
  }
1613
2169
  /**
1614
2170
  * Set a raw config value (for arbitrary keys)
@@ -1635,47 +2191,7 @@ var BareRepoImpl = class {
1635
2191
  * List all config values
1636
2192
  */
1637
2193
  async configList(opts) {
1638
- const args = ["config", "--list"];
1639
- if (opts?.showOrigin) {
1640
- args.push("--show-origin");
1641
- }
1642
- if (opts?.showScope) {
1643
- args.push("--show-scope");
1644
- }
1645
- if (opts?.includes) {
1646
- args.push("--includes");
1647
- }
1648
- if (opts?.nameOnly) {
1649
- args.push("--name-only");
1650
- }
1651
- const result = await this.runner.runOrThrow(this.context, args, {
1652
- signal: opts?.signal
1653
- });
1654
- const entries = [];
1655
- for (const line of parseLines(result.stdout)) {
1656
- let keyValue = line;
1657
- if (opts?.showOrigin || opts?.showScope) {
1658
- const tabIndex = line.lastIndexOf(" ");
1659
- if (tabIndex !== -1) {
1660
- keyValue = line.slice(tabIndex + 1);
1661
- }
1662
- }
1663
- if (opts?.nameOnly) {
1664
- entries.push({
1665
- key: keyValue,
1666
- value: ""
1667
- });
1668
- } else {
1669
- const eqIndex = keyValue.indexOf("=");
1670
- if (eqIndex !== -1) {
1671
- entries.push({
1672
- key: keyValue.slice(0, eqIndex),
1673
- value: keyValue.slice(eqIndex + 1)
1674
- });
1675
- }
1676
- }
1677
- }
1678
- return entries;
2194
+ return listConfig(this.runner, this.context, opts);
1679
2195
  }
1680
2196
  async configRenameSection(oldName, newName, opts) {
1681
2197
  await this.runner.runOrThrow(this.context, ["config", "--rename-section", oldName, newName], {
@@ -1689,6 +2205,58 @@ var BareRepoImpl = class {
1689
2205
  }
1690
2206
  };
1691
2207
 
2208
+ // src/internal/lfs-output.ts
2209
+ function record(value) {
2210
+ return value !== null && typeof value === "object" && !Array.isArray(value);
2211
+ }
2212
+ function data(stdout) {
2213
+ try {
2214
+ const value = JSON.parse(stdout);
2215
+ if (record(value)) {
2216
+ return value;
2217
+ }
2218
+ } catch {
2219
+ }
2220
+ throw new GitError("ParseError", "Invalid Git LFS JSON", { stdout });
2221
+ }
2222
+ function validSize(value) {
2223
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
2224
+ }
2225
+ function parseLfsStatusJson(stdout) {
2226
+ const files = data(stdout).files;
2227
+ if (!record(files)) {
2228
+ throw new GitError("ParseError", "Missing Git LFS status files");
2229
+ }
2230
+ return {
2231
+ files: Object.entries(files).map(([name, value]) => {
2232
+ if (!record(value) || typeof value.status !== "string" || value.size !== void 0 && !validSize(value.size)) {
2233
+ throw new GitError("ParseError", "Invalid Git LFS status entry");
2234
+ }
2235
+ return { name, status: value.status, ...validSize(value.size) ? { size: value.size } : {} };
2236
+ })
2237
+ };
2238
+ }
2239
+ function parseLfsFilesJson(stdout) {
2240
+ const files = data(stdout).files;
2241
+ if (files === null) {
2242
+ return [];
2243
+ }
2244
+ if (!Array.isArray(files)) {
2245
+ throw new GitError("ParseError", "Missing Git LFS file list");
2246
+ }
2247
+ return files.map((value) => {
2248
+ if (!record(value) || typeof value.name !== "string" || typeof value.oid !== "string" || !/^[a-f0-9]{64}$/.test(value.oid) || typeof value.checkout !== "boolean" || !validSize(value.size)) {
2249
+ throw new GitError("ParseError", "Invalid Git LFS file entry");
2250
+ }
2251
+ return {
2252
+ path: value.name,
2253
+ oid: value.oid,
2254
+ size: value.size,
2255
+ status: value.checkout ? "checked-out" : "not-checked-out"
2256
+ };
2257
+ });
2258
+ }
2259
+
1692
2260
  // src/internal/concurrency.ts
1693
2261
  async function runWithConcurrency(items, run, options) {
1694
2262
  const { concurrency, warmupCount = 0 } = options;
@@ -1737,6 +2305,7 @@ var PRE_UPLOAD_DEFAULT_BATCH_SIZE = 200;
1737
2305
  var PRE_UPLOAD_DEFAULT_CONCURRENCY = 4;
1738
2306
  var PRE_UPLOAD_WARMUP_BATCH_COUNT = 1;
1739
2307
  var WorktreeRepoImpl = class _WorktreeRepoImpl {
2308
+ kind = "worktree";
1740
2309
  workdir;
1741
2310
  runner;
1742
2311
  _lfsMode = "enabled";
@@ -1884,6 +2453,7 @@ var WorktreeRepoImpl = class _WorktreeRepoImpl {
1884
2453
  * List references in a remote repository
1885
2454
  */
1886
2455
  async lsRemote(remote, opts) {
2456
+ validateOptions("lsRemote", opts);
1887
2457
  const args = ["ls-remote"];
1888
2458
  if (opts?.heads) {
1889
2459
  args.push("--heads");
@@ -1894,15 +2464,9 @@ var WorktreeRepoImpl = class _WorktreeRepoImpl {
1894
2464
  if (opts?.refsOnly) {
1895
2465
  args.push("--refs");
1896
2466
  }
1897
- if (opts?.getUrl) {
1898
- args.push("--get-url");
1899
- }
1900
2467
  if (opts?.sort) {
1901
2468
  args.push("--sort", opts.sort);
1902
2469
  }
1903
- if (opts?.symref) {
1904
- args.push("--symref");
1905
- }
1906
2470
  args.push(remote);
1907
2471
  if (opts?.refs && opts.refs.length > 0) {
1908
2472
  args.push(...opts.refs);
@@ -1914,11 +2478,9 @@ var WorktreeRepoImpl = class _WorktreeRepoImpl {
1914
2478
  const refs = parseLsRemote(result.stdout);
1915
2479
  return { refs };
1916
2480
  }
1917
- /**
1918
- * List contents of a tree object
1919
- */
1920
2481
  async lsTree(treeish, opts) {
1921
- const args = ["ls-tree"];
2482
+ validateOptions("lsTree", opts);
2483
+ const args = ["ls-tree", "-z"];
1922
2484
  if (opts?.recursive) {
1923
2485
  args.push("-r");
1924
2486
  }
@@ -1931,12 +2493,6 @@ var WorktreeRepoImpl = class _WorktreeRepoImpl {
1931
2493
  if (opts?.long) {
1932
2494
  args.push("--long");
1933
2495
  }
1934
- if (opts?.nameOnly) {
1935
- args.push("--name-only");
1936
- }
1937
- if (opts?.objectOnly) {
1938
- args.push("--object-only");
1939
- }
1940
2496
  if (opts?.fullName) {
1941
2497
  args.push("--full-name");
1942
2498
  }
@@ -1957,20 +2513,21 @@ var WorktreeRepoImpl = class _WorktreeRepoImpl {
1957
2513
  const result = await this.runner.runOrThrow(this.context, args, {
1958
2514
  signal: opts?.signal
1959
2515
  });
1960
- return parseLsTree(result.stdout, {
1961
- nameOnly: opts?.nameOnly,
1962
- objectOnly: opts?.objectOnly,
1963
- long: opts?.long
1964
- });
2516
+ const entries = parseLsTree(result.stdout, { long: opts?.long });
2517
+ if (opts?.nameOnly) {
2518
+ return entries.map((entry) => entry.path);
2519
+ }
2520
+ if (opts?.objectOnly) {
2521
+ return entries.map((entry) => entry.hash);
2522
+ }
2523
+ return entries;
1965
2524
  }
1966
2525
  /**
1967
2526
  * Get repository status
1968
2527
  */
1969
2528
  async status(opts) {
1970
- const args = ["status", "--porcelain=v2"];
1971
- if (opts?.verbose) {
1972
- args.push("--verbose");
1973
- }
2529
+ validateOptions("status", opts);
2530
+ const args = ["status", "--porcelain=v2", "-z"];
1974
2531
  if (opts?.untracked) {
1975
2532
  switch (opts.untracked) {
1976
2533
  case "no":
@@ -1991,9 +2548,6 @@ var WorktreeRepoImpl = class _WorktreeRepoImpl {
1991
2548
  if (opts?.aheadBehind === false) {
1992
2549
  args.push("--no-ahead-behind");
1993
2550
  }
1994
- if (opts?.nullTerminated) {
1995
- args.push("-z");
1996
- }
1997
2551
  if (opts?.ignored) {
1998
2552
  switch (opts.ignored) {
1999
2553
  case "traditional":
@@ -2025,81 +2579,60 @@ var WorktreeRepoImpl = class _WorktreeRepoImpl {
2025
2579
  return this.parseStatus(result.stdout);
2026
2580
  }
2027
2581
  parseStatus(stdout) {
2028
- const lines = parseLines(stdout);
2029
- const entries = [];
2030
- let branch;
2031
- let upstream;
2032
- let ahead;
2033
- let behind;
2034
- for (const line of lines) {
2035
- if (line.startsWith("# branch.head ")) {
2036
- branch = line.slice("# branch.head ".length);
2037
- } else if (line.startsWith("# branch.upstream ")) {
2038
- upstream = line.slice("# branch.upstream ".length);
2039
- } else if (line.startsWith("# branch.ab ")) {
2040
- const match = line.match(/# branch\.ab \+(\d+) -(\d+)/);
2041
- const aheadStr = match?.[1];
2042
- const behindStr = match?.[2];
2043
- if (aheadStr !== void 0 && behindStr !== void 0) {
2044
- ahead = Number.parseInt(aheadStr, 10);
2045
- behind = Number.parseInt(behindStr, 10);
2046
- }
2047
- } else if (line.startsWith("1 ") || line.startsWith("2 ")) {
2048
- const parsed = parsePorcelainV2(line);
2049
- const entry = parsed[0];
2050
- if (entry?.type === "changed") {
2051
- const indexStatus = entry.xy[0];
2052
- const workdirStatus = entry.xy[1];
2053
- if (indexStatus !== void 0 && workdirStatus !== void 0) {
2054
- entries.push({
2055
- path: entry.path,
2056
- index: indexStatus,
2057
- workdir: workdirStatus,
2058
- originalPath: entry.origPath
2059
- });
2060
- }
2061
- }
2062
- } else if (line.startsWith("u ")) {
2063
- const parsed = parsePorcelainV2(line);
2064
- const entry = parsed[0];
2065
- if (entry?.type === "unmerged") {
2066
- const indexStatus = entry.xy[0];
2067
- const workdirStatus = entry.xy[1];
2068
- if (indexStatus !== void 0 && workdirStatus !== void 0) {
2069
- entries.push({
2070
- path: entry.path,
2071
- index: indexStatus,
2072
- workdir: workdirStatus
2073
- });
2074
- }
2582
+ const result = {
2583
+ entries: parsePorcelainV2(stdout).map((entry) => {
2584
+ if (entry.type === "untracked" || entry.type === "ignored") {
2585
+ const status = entry.type === "untracked" ? "?" : "!";
2586
+ return { path: entry.path, index: status, workdir: status };
2075
2587
  }
2076
- } else if (line.startsWith("? ")) {
2077
- entries.push({
2078
- path: line.slice(2),
2079
- index: "?",
2080
- workdir: "?"
2081
- });
2082
- } else if (line.startsWith("! ")) {
2083
- entries.push({
2084
- path: line.slice(2),
2085
- index: "!",
2086
- workdir: "!"
2087
- });
2588
+ return {
2589
+ path: entry.path,
2590
+ index: entry.xy[0],
2591
+ workdir: entry.xy[1],
2592
+ ..."origPath" in entry && entry.origPath !== void 0 ? { originalPath: entry.origPath } : {}
2593
+ };
2594
+ })
2595
+ };
2596
+ const records = stdout.includes("\0") ? parseRecords(stdout) : parseLines(stdout, { trim: false });
2597
+ for (let i = 0; i < records.length; i++) {
2598
+ const line = records[i];
2599
+ if (line.startsWith("2 ") && stdout.includes("\0")) {
2600
+ i++;
2601
+ continue;
2602
+ }
2603
+ if (line.startsWith("# branch.head ")) {
2604
+ result.branch = line.slice(14);
2605
+ }
2606
+ if (line.startsWith("# branch.upstream ")) {
2607
+ result.upstream = line.slice(18);
2608
+ }
2609
+ const ab = line.match(/^# branch\.ab \+(\d+) -(\d+)$/);
2610
+ if (ab) {
2611
+ result.ahead = Number(ab[1]);
2612
+ result.behind = Number(ab[2]);
2613
+ }
2614
+ if (line.startsWith("# stash ")) {
2615
+ result.stash = Number(line.slice(8));
2088
2616
  }
2089
2617
  }
2090
- return {
2091
- entries,
2092
- branch,
2093
- upstream,
2094
- ahead,
2095
- behind
2096
- };
2618
+ return result;
2097
2619
  }
2098
2620
  /**
2099
2621
  * Get commit log
2100
2622
  */
2101
2623
  async log(opts) {
2102
- const args = ["log", `--format=${GIT_LOG_FORMAT}`];
2624
+ validateOptions("log", opts);
2625
+ const format = opts?.useMailmap ? GIT_LOG_FORMAT.replace("%an", "%aN").replace("%ae", "%aE").replace("%cn", "%cN").replace("%ce", "%cE") : GIT_LOG_FORMAT;
2626
+ const args = [
2627
+ "log",
2628
+ "-z",
2629
+ "--no-patch",
2630
+ "--no-notes",
2631
+ "--no-show-signature",
2632
+ "--no-color",
2633
+ "--encoding=UTF-8",
2634
+ `--format=${format}`
2635
+ ];
2103
2636
  if (opts?.maxCount !== void 0) {
2104
2637
  args.push(`-n${opts.maxCount}`);
2105
2638
  }
@@ -2132,33 +2665,9 @@ var WorktreeRepoImpl = class _WorktreeRepoImpl {
2132
2665
  if (opts?.firstParent) {
2133
2666
  args.push("--first-parent");
2134
2667
  }
2135
- if (opts?.source) {
2136
- args.push("--source");
2137
- }
2138
2668
  if (opts?.useMailmap) {
2139
2669
  args.push("--use-mailmap");
2140
2670
  }
2141
- if (opts?.decorateRefs) {
2142
- args.push(`--decorate-refs=${opts.decorateRefs}`);
2143
- }
2144
- if (opts?.decorateRefsExclude) {
2145
- args.push(`--decorate-refs-exclude=${opts.decorateRefsExclude}`);
2146
- }
2147
- if (opts?.decorate) {
2148
- args.push(`--decorate=${opts.decorate}`);
2149
- }
2150
- if (opts?.stat) {
2151
- args.push("--stat");
2152
- }
2153
- if (opts?.shortstat) {
2154
- args.push("--shortstat");
2155
- }
2156
- if (opts?.nameOnly) {
2157
- args.push("--name-only");
2158
- }
2159
- if (opts?.nameStatus) {
2160
- args.push("--name-status");
2161
- }
2162
2671
  if (opts?.merges) {
2163
2672
  args.push("--merges");
2164
2673
  }
@@ -2200,230 +2709,13 @@ var WorktreeRepoImpl = class _WorktreeRepoImpl {
2200
2709
  * Fetch from remote
2201
2710
  */
2202
2711
  async fetch(opts) {
2203
- const args = ["fetch"];
2204
- if (opts?.onProgress) {
2205
- args.push("--progress");
2206
- }
2207
- if (opts?.verbose) {
2208
- args.push("--verbose");
2209
- }
2210
- if (opts?.quiet) {
2211
- args.push("--quiet");
2212
- }
2213
- if (opts?.all) {
2214
- args.push("--all");
2215
- }
2216
- if (opts?.setUpstream) {
2217
- args.push("--set-upstream");
2218
- }
2219
- if (opts?.append) {
2220
- args.push("--append");
2221
- }
2222
- if (opts?.atomic) {
2223
- args.push("--atomic");
2224
- }
2225
- if (opts?.force) {
2226
- args.push("--force");
2227
- }
2228
- if (opts?.multiple) {
2229
- args.push("--multiple");
2230
- }
2231
- if (opts?.prune) {
2232
- args.push("--prune");
2233
- }
2234
- if (opts?.pruneTags) {
2235
- args.push("--prune-tags");
2236
- }
2237
- if (opts?.tags) {
2238
- args.push("--tags");
2239
- } else if (opts?.noTags) {
2240
- args.push("--no-tags");
2241
- }
2242
- if (opts?.jobs !== void 0) {
2243
- args.push(`--jobs=${opts.jobs}`);
2244
- }
2245
- if (opts?.prefetch) {
2246
- args.push("--prefetch");
2247
- }
2248
- if (opts?.recurseSubmodules !== void 0) {
2249
- if (opts.recurseSubmodules === true || opts.recurseSubmodules === "yes") {
2250
- args.push("--recurse-submodules=yes");
2251
- } else if (opts.recurseSubmodules === "on-demand") {
2252
- args.push("--recurse-submodules=on-demand");
2253
- } else if (opts.recurseSubmodules === "no" || opts.recurseSubmodules === false) {
2254
- args.push("--recurse-submodules=no");
2255
- }
2256
- }
2257
- if (opts?.dryRun) {
2258
- args.push("--dry-run");
2259
- }
2260
- if (opts?.writeFetchHead === false) {
2261
- args.push("--no-write-fetch-head");
2262
- }
2263
- if (opts?.keep) {
2264
- args.push("--keep");
2265
- }
2266
- if (opts?.updateHeadOk) {
2267
- args.push("--update-head-ok");
2268
- }
2269
- if (opts?.depth !== void 0) {
2270
- args.push(`--depth=${opts.depth}`);
2271
- }
2272
- if (opts?.shallowSince) {
2273
- const since = opts.shallowSince instanceof Date ? opts.shallowSince.toISOString() : opts.shallowSince;
2274
- args.push(`--shallow-since=${since}`);
2275
- }
2276
- if (opts?.shallowExclude) {
2277
- const excludes = Array.isArray(opts.shallowExclude) ? opts.shallowExclude : [opts.shallowExclude];
2278
- for (const exclude of excludes) {
2279
- args.push(`--shallow-exclude=${exclude}`);
2280
- }
2281
- }
2282
- if (opts?.deepen !== void 0) {
2283
- args.push(`--deepen=${opts.deepen}`);
2284
- }
2285
- if (opts?.unshallow) {
2286
- args.push("--unshallow");
2287
- }
2288
- if (opts?.refetch) {
2289
- args.push("--refetch");
2290
- }
2291
- if (opts?.updateShallow) {
2292
- args.push("--update-shallow");
2293
- }
2294
- if (opts?.refmap) {
2295
- args.push(`--refmap=${opts.refmap}`);
2296
- }
2297
- if (opts?.ipv4) {
2298
- args.push("--ipv4");
2299
- }
2300
- if (opts?.ipv6) {
2301
- args.push("--ipv6");
2302
- }
2303
- if (opts?.filter) {
2304
- args.push(`--filter=${opts.filter}`);
2305
- }
2306
- if (opts?.showForcedUpdates === false) {
2307
- args.push("--no-show-forced-updates");
2308
- }
2309
- if (opts?.writeCommitGraph) {
2310
- args.push("--write-commit-graph");
2311
- }
2312
- if (opts?.remote) {
2313
- args.push(opts.remote);
2314
- }
2315
- if (opts?.refspec) {
2316
- const refspecs = Array.isArray(opts.refspec) ? opts.refspec : [opts.refspec];
2317
- args.push(...refspecs);
2318
- }
2319
- await this.runner.runOrThrow(this.context, args, {
2320
- signal: opts?.signal,
2321
- onProgress: opts?.onProgress
2322
- });
2712
+ return fetch(this.runner, this.context, opts);
2323
2713
  }
2324
2714
  /**
2325
2715
  * Push to remote
2326
2716
  */
2327
2717
  async push(opts) {
2328
- const args = ["push"];
2329
- if (opts?.onProgress || opts?.onLfsProgress) {
2330
- args.push("--progress");
2331
- }
2332
- if (opts?.verbose) {
2333
- args.push("--verbose");
2334
- }
2335
- if (opts?.quiet) {
2336
- args.push("--quiet");
2337
- }
2338
- if (opts?.repo) {
2339
- args.push(`--repo=${opts.repo}`);
2340
- }
2341
- if (opts?.all) {
2342
- args.push("--all");
2343
- } else if (opts?.branches) {
2344
- args.push("--branches");
2345
- }
2346
- if (opts?.mirror) {
2347
- args.push("--mirror");
2348
- }
2349
- if (opts?.deleteRefs) {
2350
- args.push("--delete");
2351
- }
2352
- if (opts?.force) {
2353
- args.push("--force");
2354
- } else if (opts?.forceWithLease !== void 0 && opts.forceWithLease !== false) {
2355
- if (opts.forceWithLease === true) {
2356
- args.push("--force-with-lease");
2357
- } else {
2358
- const leaseOpts = opts.forceWithLease;
2359
- if (leaseOpts.expect !== void 0) {
2360
- args.push(`--force-with-lease=${leaseOpts.refname}:${leaseOpts.expect}`);
2361
- } else {
2362
- args.push(`--force-with-lease=${leaseOpts.refname}`);
2363
- }
2364
- }
2365
- }
2366
- if (opts?.forceIfIncludes) {
2367
- args.push("--force-if-includes");
2368
- }
2369
- if (opts?.dryRun) {
2370
- args.push("--dry-run");
2371
- }
2372
- if (opts?.recurseSubmodules) {
2373
- args.push(`--recurse-submodules=${opts.recurseSubmodules}`);
2374
- }
2375
- if (opts?.thin === false) {
2376
- args.push("--no-thin");
2377
- }
2378
- if (opts?.prune) {
2379
- args.push("--prune");
2380
- }
2381
- if (opts?.tags) {
2382
- args.push("--tags");
2383
- }
2384
- if (opts?.followTags) {
2385
- args.push("--follow-tags");
2386
- }
2387
- if (opts?.atomic) {
2388
- args.push("--atomic");
2389
- }
2390
- if (opts?.pushOption) {
2391
- const pushOptions = Array.isArray(opts.pushOption) ? opts.pushOption : [opts.pushOption];
2392
- for (const opt of pushOptions) {
2393
- args.push("--push-option", opt);
2394
- }
2395
- }
2396
- if (opts?.setUpstream) {
2397
- args.push("--set-upstream");
2398
- }
2399
- if (opts?.noVerify) {
2400
- args.push("--no-verify");
2401
- }
2402
- if (opts?.signed !== void 0) {
2403
- if (opts.signed === true) {
2404
- args.push("--signed");
2405
- } else if (opts.signed === "if-asked") {
2406
- args.push("--signed=if-asked");
2407
- }
2408
- }
2409
- if (opts?.ipv4) {
2410
- args.push("--ipv4");
2411
- }
2412
- if (opts?.ipv6) {
2413
- args.push("--ipv6");
2414
- }
2415
- if (opts?.remote) {
2416
- args.push(opts.remote);
2417
- }
2418
- if (opts?.refspec) {
2419
- const refspecs = Array.isArray(opts.refspec) ? opts.refspec : [opts.refspec];
2420
- args.push(...refspecs);
2421
- }
2422
- await this.runner.runOrThrow(this.context, args, {
2423
- signal: opts?.signal,
2424
- onProgress: opts?.onProgress,
2425
- onLfsProgress: opts?.onLfsProgress
2426
- });
2718
+ return push(this.runner, this.context, opts);
2427
2719
  }
2428
2720
  /**
2429
2721
  * Configure LFS mode for this repository
@@ -2458,6 +2750,7 @@ var WorktreeRepoImpl = class _WorktreeRepoImpl {
2458
2750
  // LFS Operations
2459
2751
  // ==========================================================================
2460
2752
  async lfsPull(opts) {
2753
+ validateOptions("lfsPull", opts);
2461
2754
  if (this._lfsMode === "disabled") {
2462
2755
  return;
2463
2756
  }
@@ -2465,13 +2758,10 @@ var WorktreeRepoImpl = class _WorktreeRepoImpl {
2465
2758
  if (opts?.remote) {
2466
2759
  args.push(opts.remote);
2467
2760
  }
2468
- if (opts?.ref) {
2469
- args.push(opts.ref);
2470
- }
2471
- if (opts?.include && opts.include.length > 0) {
2761
+ if (opts?.include !== void 0) {
2472
2762
  args.push("--include", opts.include.join(","));
2473
2763
  }
2474
- if (opts?.exclude && opts.exclude.length > 0) {
2764
+ if (opts?.exclude !== void 0) {
2475
2765
  args.push("--exclude", opts.exclude.join(","));
2476
2766
  }
2477
2767
  await this.runner.runOrThrow(this.context, args, {
@@ -2481,6 +2771,7 @@ var WorktreeRepoImpl = class _WorktreeRepoImpl {
2481
2771
  });
2482
2772
  }
2483
2773
  async lfsPush(opts) {
2774
+ validateOptions("lfsPush", opts);
2484
2775
  if (this._lfsMode === "disabled") {
2485
2776
  return;
2486
2777
  }
@@ -2514,33 +2805,9 @@ var WorktreeRepoImpl = class _WorktreeRepoImpl {
2514
2805
  });
2515
2806
  }
2516
2807
  async lfsStatus(opts) {
2517
- const args = ["lfs", "status"];
2518
- if (opts?.json) {
2519
- args.push("--json");
2520
- }
2521
- if (opts?.porcelain) {
2522
- args.push("--porcelain");
2523
- }
2524
- const result = await this.runner.runOrThrow(this.context, args, {
2525
- signal: opts?.signal
2526
- });
2527
- const files = [];
2528
- if (opts?.json) {
2529
- try {
2530
- const json = JSON.parse(result.stdout);
2531
- if (json.files) {
2532
- for (const [name, info] of Object.entries(json.files)) {
2533
- files.push({
2534
- name,
2535
- size: info.size ?? 0,
2536
- status: "unknown"
2537
- });
2538
- }
2539
- }
2540
- } catch {
2541
- }
2542
- }
2543
- return { files };
2808
+ validateOptions("lfsStatus", opts);
2809
+ const result = await this.runner.runOrThrow(this.context, ["lfs", "status", "--json"], opts);
2810
+ return parseLfsStatusJson(result.stdout);
2544
2811
  }
2545
2812
  /**
2546
2813
  * Pre-upload LFS objects before commit/push (2-phase commit pattern)
@@ -2768,12 +3035,19 @@ var WorktreeRepoImpl = class _WorktreeRepoImpl {
2768
3035
  });
2769
3036
  }
2770
3037
  async lfsFetch(opts) {
3038
+ validateOptions("lfsFetch", opts);
2771
3039
  if (this._lfsMode === "disabled") {
2772
3040
  return;
2773
3041
  }
2774
3042
  const args = ["lfs", "fetch"];
2775
- if (opts?.onProgress || opts?.onLfsProgress) {
2776
- args.push("--progress");
3043
+ if (opts?.dryRun) {
3044
+ args.push("--dry-run");
3045
+ }
3046
+ if (opts?.refetch) {
3047
+ args.push("--refetch");
3048
+ }
3049
+ if (opts?.json) {
3050
+ args.push("--json");
2777
3051
  }
2778
3052
  if (opts?.all) {
2779
3053
  args.push("--all");
@@ -2786,18 +3060,14 @@ var WorktreeRepoImpl = class _WorktreeRepoImpl {
2786
3060
  }
2787
3061
  if (opts?.include) {
2788
3062
  const patterns = Array.isArray(opts.include) ? opts.include : [opts.include];
2789
- for (const pattern of patterns) {
2790
- args.push("--include", pattern);
2791
- }
3063
+ args.push("--include", patterns.join(","));
2792
3064
  }
2793
3065
  if (opts?.exclude) {
2794
3066
  const patterns = Array.isArray(opts.exclude) ? opts.exclude : [opts.exclude];
2795
- for (const pattern of patterns) {
2796
- args.push("--exclude", pattern);
2797
- }
3067
+ args.push("--exclude", patterns.join(","));
2798
3068
  }
2799
- if (opts?.remote) {
2800
- args.push(opts.remote);
3069
+ if (opts?.remote || opts?.refs) {
3070
+ args.push(opts.remote ?? "origin");
2801
3071
  }
2802
3072
  if (opts?.refs) {
2803
3073
  const refList = Array.isArray(opts.refs) ? opts.refs : [opts.refs];
@@ -2838,19 +3108,17 @@ var WorktreeRepoImpl = class _WorktreeRepoImpl {
2838
3108
  });
2839
3109
  }
2840
3110
  async lfsLsFiles(opts) {
3111
+ validateOptions("lfsLsFiles", opts);
2841
3112
  if (this._lfsMode === "disabled") {
2842
3113
  return [];
2843
3114
  }
2844
- const args = ["lfs", "ls-files"];
3115
+ const args = ["lfs", "ls-files", "--json"];
2845
3116
  if (opts?.long) {
2846
3117
  args.push("--long");
2847
3118
  }
2848
3119
  if (opts?.size) {
2849
3120
  args.push("--size");
2850
3121
  }
2851
- if (opts?.debug) {
2852
- args.push("--debug");
2853
- }
2854
3122
  if (opts?.all) {
2855
3123
  args.push("--all");
2856
3124
  }
@@ -2859,15 +3127,11 @@ var WorktreeRepoImpl = class _WorktreeRepoImpl {
2859
3127
  }
2860
3128
  if (opts?.include) {
2861
3129
  const patterns = Array.isArray(opts.include) ? opts.include : [opts.include];
2862
- for (const pattern of patterns) {
2863
- args.push("--include", pattern);
2864
- }
3130
+ args.push("--include", patterns.join(","));
2865
3131
  }
2866
3132
  if (opts?.exclude) {
2867
3133
  const patterns = Array.isArray(opts.exclude) ? opts.exclude : [opts.exclude];
2868
- for (const pattern of patterns) {
2869
- args.push("--exclude", pattern);
2870
- }
3134
+ args.push("--exclude", patterns.join(","));
2871
3135
  }
2872
3136
  if (opts?.ref) {
2873
3137
  args.push(opts.ref);
@@ -2875,19 +3139,7 @@ var WorktreeRepoImpl = class _WorktreeRepoImpl {
2875
3139
  const result = await this.runner.runOrThrow(this.context, args, {
2876
3140
  signal: opts?.signal
2877
3141
  });
2878
- const entries = [];
2879
- for (const line of parseLines(result.stdout)) {
2880
- const match = line.match(/^([0-9a-f]+)\s+([-*])\s+(.+?)(?:\s+\((\d+)\s*(?:B|bytes)?\))?$/);
2881
- if (match) {
2882
- entries.push({
2883
- oid: match[1],
2884
- path: match[3],
2885
- size: match[4] ? Number.parseInt(match[4], 10) : void 0,
2886
- status: match[2] === "*" ? "checked-out" : "not-checked-out"
2887
- });
2888
- }
2889
- }
2890
- return entries;
3142
+ return parseLfsFilesJson(result.stdout);
2891
3143
  }
2892
3144
  async lfsTrack(patterns, opts) {
2893
3145
  const args = ["lfs", "track"];
@@ -2952,12 +3204,12 @@ var WorktreeRepoImpl = class _WorktreeRepoImpl {
2952
3204
  const result = await this.runner.runOrThrow(this.context, args, {
2953
3205
  signal: opts?.signal
2954
3206
  });
2955
- const data = JSON.parse(result.stdout);
3207
+ const data2 = JSON.parse(result.stdout);
2956
3208
  return {
2957
- id: data.id,
2958
- path: data.path,
2959
- owner: { name: data.owner.name },
2960
- lockedAt: new Date(data.locked_at)
3209
+ id: data2.id,
3210
+ path: data2.path,
3211
+ owner: { name: data2.owner.name },
3212
+ lockedAt: new Date(data2.locked_at)
2961
3213
  };
2962
3214
  }
2963
3215
  async lfsUnlock(pathOrId, opts) {
@@ -3005,8 +3257,8 @@ var WorktreeRepoImpl = class _WorktreeRepoImpl {
3005
3257
  const result = await this.runner.runOrThrow(this.context, args, {
3006
3258
  signal: opts?.signal
3007
3259
  });
3008
- const data = JSON.parse(result.stdout);
3009
- return data.map((lock) => ({
3260
+ const data2 = JSON.parse(result.stdout);
3261
+ return data2.map((lock) => ({
3010
3262
  id: lock.id,
3011
3263
  path: lock.path,
3012
3264
  owner: { name: lock.owner.name },
@@ -3223,6 +3475,7 @@ var WorktreeRepoImpl = class _WorktreeRepoImpl {
3223
3475
  return parseWorktreeList(result.stdout);
3224
3476
  }
3225
3477
  async worktreeAdd(path, opts) {
3478
+ validateOptions("worktreeAdd", opts);
3226
3479
  const args = ["worktree", "add"];
3227
3480
  if (opts?.detach) {
3228
3481
  args.push("--detach");
@@ -3318,10 +3571,9 @@ var WorktreeRepoImpl = class _WorktreeRepoImpl {
3318
3571
  signal: opts?.signal
3319
3572
  });
3320
3573
  }
3321
- // ==========================================================================
3322
- // High-level API - add
3323
- // ==========================================================================
3324
3574
  async add(paths, opts) {
3575
+ validatePathInput("add", paths, opts);
3576
+ validateOptions("add", opts);
3325
3577
  const args = ["add"];
3326
3578
  if (opts?.verbose) {
3327
3579
  args.push("--verbose");
@@ -3437,12 +3689,12 @@ var WorktreeRepoImpl = class _WorktreeRepoImpl {
3437
3689
  return branches;
3438
3690
  }
3439
3691
  async branchCurrent(opts) {
3440
- const result = await this.runner.run(this.context, ["symbolic-ref", "--short", "HEAD"], {
3441
- signal: opts?.signal
3442
- });
3443
- if (result.exitCode !== 0) {
3692
+ const args = ["symbolic-ref", "--quiet", "--short", "HEAD"];
3693
+ const result = await this.runner.run(this.context, args, opts);
3694
+ if (result.exitCode === 1 && !result.aborted) {
3444
3695
  return null;
3445
3696
  }
3697
+ this.runner.checkResult(this.context, args, result);
3446
3698
  return result.stdout.trim();
3447
3699
  }
3448
3700
  async branchCreate(name, opts) {
@@ -3492,9 +3744,11 @@ var WorktreeRepoImpl = class _WorktreeRepoImpl {
3492
3744
  }
3493
3745
  // Implementation
3494
3746
  async checkout(targetOrPaths, opts) {
3747
+ validateOptions(Array.isArray(targetOrPaths) ? "checkoutPath" : "checkoutBranch", opts);
3495
3748
  const args = ["checkout"];
3496
3749
  const isPathMode = Array.isArray(targetOrPaths);
3497
3750
  if (isPathMode) {
3751
+ validatePathInput("checkout", targetOrPaths, opts);
3498
3752
  const pathOpts = opts;
3499
3753
  if (pathOpts?.force) {
3500
3754
  args.push("--force");
@@ -3576,6 +3830,7 @@ var WorktreeRepoImpl = class _WorktreeRepoImpl {
3576
3830
  // High-level API - commit
3577
3831
  // ==========================================================================
3578
3832
  async commit(opts) {
3833
+ validateOptions("commit", opts);
3579
3834
  const args = ["commit"];
3580
3835
  if (opts?.message) {
3581
3836
  args.push("-m", opts.message);
@@ -3596,9 +3851,6 @@ var WorktreeRepoImpl = class _WorktreeRepoImpl {
3596
3851
  const date = opts.date instanceof Date ? opts.date.toISOString() : opts.date;
3597
3852
  args.push("--date", date);
3598
3853
  }
3599
- if (opts?.dryRun) {
3600
- args.push("--dry-run");
3601
- }
3602
3854
  if (opts?.noVerify) {
3603
3855
  args.push("--no-verify");
3604
3856
  }
@@ -3616,9 +3868,6 @@ var WorktreeRepoImpl = class _WorktreeRepoImpl {
3616
3868
  if (opts?.file) {
3617
3869
  args.push("--file", opts.file);
3618
3870
  }
3619
- if (opts?.reeditMessage) {
3620
- args.push("--reedit-message", opts.reeditMessage);
3621
- }
3622
3871
  if (opts?.reuseMessage) {
3623
3872
  args.push("--reuse-message", opts.reuseMessage);
3624
3873
  }
@@ -3661,10 +3910,9 @@ var WorktreeRepoImpl = class _WorktreeRepoImpl {
3661
3910
  if (opts?.allowEmptyMessage) {
3662
3911
  args.push("--allow-empty-message");
3663
3912
  }
3664
- const result = await this.runner.runOrThrow(this.context, args, {
3913
+ await this.runner.runOrThrow(this.context, args, {
3665
3914
  signal: opts?.signal
3666
3915
  });
3667
- const output = result.stdout;
3668
3916
  let hash = "";
3669
3917
  let branch = "";
3670
3918
  let summary = "";
@@ -3675,17 +3923,29 @@ var WorktreeRepoImpl = class _WorktreeRepoImpl {
3675
3923
  signal: opts?.signal
3676
3924
  });
3677
3925
  hash = hashResult.stdout.trim();
3678
- const branchResult = await this.runner.run(this.context, ["symbolic-ref", "--short", "HEAD"], {
3679
- signal: opts?.signal
3680
- });
3681
- branch = branchResult.exitCode === 0 ? branchResult.stdout.trim() : "HEAD";
3682
- const statsMatch = output.match(
3683
- /(\d+) files? changed(?:, (\d+) insertions?\(\+\))?(?:, (\d+) deletions?\(-\))?/
3926
+ branch = await this.branchCurrent(opts) ?? "HEAD";
3927
+ const stats = await this.runner.runOrThrow(
3928
+ this.context,
3929
+ ["diff-tree", "--root", "--no-commit-id", "--numstat", "-r", "-z", "-M", hash],
3930
+ opts
3684
3931
  );
3685
- if (statsMatch) {
3686
- filesChanged = Number.parseInt(statsMatch[1] || "0", 10);
3687
- insertions = Number.parseInt(statsMatch[2] || "0", 10);
3688
- deletions = Number.parseInt(statsMatch[3] || "0", 10);
3932
+ const records = parseRecords(stats.stdout);
3933
+ for (let i = 0; i < records.length; i++) {
3934
+ const record2 = records[i];
3935
+ const match = record2.match(/^(\d+|-)\t(\d+|-)\t([\s\S]*)$/);
3936
+ if (!match) {
3937
+ throw new GitError("ParseError", "Invalid commit numstat record");
3938
+ }
3939
+ filesChanged++;
3940
+ if (match[1] !== "-") {
3941
+ insertions += Number(match[1]);
3942
+ }
3943
+ if (match[2] !== "-") {
3944
+ deletions += Number(match[2]);
3945
+ }
3946
+ if (match[3] === "") {
3947
+ i += 2;
3948
+ }
3689
3949
  }
3690
3950
  const logResult = await this.runner.runOrThrow(this.context, ["log", "-1", "--format=%s"], {
3691
3951
  signal: opts?.signal
@@ -3700,11 +3960,12 @@ var WorktreeRepoImpl = class _WorktreeRepoImpl {
3700
3960
  deletions
3701
3961
  };
3702
3962
  }
3703
- // ==========================================================================
3704
- // High-level API - diff
3705
- // ==========================================================================
3706
3963
  async diff(target, opts) {
3707
- const args = ["diff"];
3964
+ validateOptions("diff", opts);
3965
+ const args = ["diff", "--no-ext-diff", "--no-textconv", "--no-color"];
3966
+ if (opts?.nameOnly || opts?.nameStatus) {
3967
+ args.push("-z");
3968
+ }
3708
3969
  if (opts?.staged) {
3709
3970
  args.push("--staged");
3710
3971
  }
@@ -3782,10 +4043,7 @@ var WorktreeRepoImpl = class _WorktreeRepoImpl {
3782
4043
  args.push("--text");
3783
4044
  }
3784
4045
  if (opts?.mergeBase) {
3785
- args.push(`--merge-base=${opts.mergeBase}`);
3786
- }
3787
- if (opts?.noIndex) {
3788
- args.push("--no-index");
4046
+ args.push("--merge-base");
3789
4047
  }
3790
4048
  if (opts?.wordDiff) {
3791
4049
  args.push(`--word-diff=${opts.wordDiff}`);
@@ -3799,30 +4057,28 @@ var WorktreeRepoImpl = class _WorktreeRepoImpl {
3799
4057
  const result = await this.runner.runOrThrow(this.context, args, {
3800
4058
  signal: opts?.signal
3801
4059
  });
4060
+ if (opts?.nameOnly) {
4061
+ return parseRecords(result.stdout);
4062
+ }
3802
4063
  if (opts?.nameStatus) {
4064
+ const records = parseRecords(result.stdout);
3803
4065
  const files = [];
3804
- for (const line of parseLines(result.stdout)) {
3805
- const match = line.match(/^([AMDRTCUX])\t(.+?)(?:\t(.+))?$/);
3806
- const status = match?.[1];
3807
- const pathOrOld = match?.[2];
3808
- const newPath = match?.[3];
3809
- if (status !== void 0 && pathOrOld !== void 0) {
3810
- const entry = {
3811
- status,
3812
- path: newPath ?? pathOrOld
3813
- };
3814
- if (newPath !== void 0) {
3815
- entry.oldPath = pathOrOld;
3816
- }
3817
- files.push(entry);
4066
+ for (let i = 0; i < records.length; ) {
4067
+ const code = records[i++];
4068
+ if (!/^[AMDRTCUXB][0-9]*$/.test(code)) {
4069
+ throw new GitError("ParseError", "Invalid diff status");
3818
4070
  }
3819
- }
3820
- return { files };
3821
- }
3822
- if (opts?.nameOnly) {
3823
- const files = [];
3824
- for (const line of parseLines(result.stdout)) {
3825
- files.push({ status: "M", path: line });
4071
+ const oldPath = records[i++];
4072
+ const renamed = code[0] === "R" || code[0] === "C";
4073
+ const path = renamed ? records[i++] : oldPath;
4074
+ if (oldPath === void 0 || path === void 0) {
4075
+ throw new GitError("ParseError", "Missing diff path");
4076
+ }
4077
+ files.push({
4078
+ status: code[0],
4079
+ path,
4080
+ ...renamed ? { oldPath, similarity: Number(code.slice(1)) } : {}
4081
+ });
3826
4082
  }
3827
4083
  return { files };
3828
4084
  }
@@ -3832,6 +4088,7 @@ var WorktreeRepoImpl = class _WorktreeRepoImpl {
3832
4088
  // High-level API - merge
3833
4089
  // ==========================================================================
3834
4090
  async merge(branch, opts) {
4091
+ validateOptions("merge", opts);
3835
4092
  if (opts?.abort) {
3836
4093
  await this.runner.runOrThrow(this.context, ["merge", "--abort"], {
3837
4094
  signal: opts?.signal
@@ -3845,6 +4102,10 @@ var WorktreeRepoImpl = class _WorktreeRepoImpl {
3845
4102
  const hash = (await this.runner.runOrThrow(this.context, ["rev-parse", "HEAD"])).stdout.trim();
3846
4103
  return { success: true, hash };
3847
4104
  }
4105
+ if (opts?.quit) {
4106
+ await this.runner.runOrThrow(this.context, ["merge", "--quit"], opts);
4107
+ return { success: true };
4108
+ }
3848
4109
  const args = ["merge"];
3849
4110
  if (opts?.message) {
3850
4111
  args.push("-m", opts.message);
@@ -3929,17 +4190,20 @@ var WorktreeRepoImpl = class _WorktreeRepoImpl {
3929
4190
  signal: opts?.signal,
3930
4191
  env: this.lfsModeEnv()
3931
4192
  });
4193
+ if (result.aborted) {
4194
+ this.runner.checkResult(this.context, args, result);
4195
+ }
3932
4196
  if (result.exitCode !== 0) {
3933
- const statusResult = await this.runner.runOrThrow(this.context, ["status", "--porcelain"], {
3934
- signal: opts?.signal
3935
- });
3936
- const conflicts = parseLines(statusResult.stdout).filter(
3937
- (line) => line.startsWith("UU ") || line.startsWith("AA ") || line.startsWith("DD ")
3938
- ).map((line) => line.slice(3));
3939
- return {
3940
- success: false,
3941
- conflicts
3942
- };
4197
+ const statusResult = await this.runner.runOrThrow(
4198
+ this.context,
4199
+ ["status", "--porcelain=v2", "-z"],
4200
+ { signal: opts?.signal }
4201
+ );
4202
+ const conflicts = parsePorcelainV2(statusResult.stdout).filter((entry) => entry.type === "unmerged").map((entry) => entry.path);
4203
+ if (conflicts.length === 0) {
4204
+ this.runner.checkResult(this.context, args, result);
4205
+ }
4206
+ return { success: false, conflicts };
3943
4207
  }
3944
4208
  const hashResult = await this.runner.runOrThrow(this.context, ["rev-parse", "HEAD"], {
3945
4209
  signal: opts?.signal
@@ -3955,6 +4219,7 @@ var WorktreeRepoImpl = class _WorktreeRepoImpl {
3955
4219
  // High-level API - pull
3956
4220
  // ==========================================================================
3957
4221
  async pull(opts) {
4222
+ validateOptions("pull", opts);
3958
4223
  const args = ["pull"];
3959
4224
  if (opts?.onProgress || opts?.onLfsProgress) {
3960
4225
  args.push("--progress");
@@ -4140,10 +4405,8 @@ var WorktreeRepoImpl = class _WorktreeRepoImpl {
4140
4405
  env: this.lfsModeEnv()
4141
4406
  });
4142
4407
  }
4143
- // ==========================================================================
4144
- // High-level API - rm
4145
- // ==========================================================================
4146
4408
  async rm(paths, opts) {
4409
+ validatePathInput("rm", paths, opts);
4147
4410
  const args = ["rm"];
4148
4411
  if (opts?.force) {
4149
4412
  args.push("--force");
@@ -4179,38 +4442,29 @@ var WorktreeRepoImpl = class _WorktreeRepoImpl {
4179
4442
  // High-level API - Stash Operations
4180
4443
  // ==========================================================================
4181
4444
  async stashList(opts) {
4182
- const result = await this.runner.runOrThrow(this.context, ["stash", "list"], {
4183
- signal: opts?.signal
4184
- });
4185
- const entries = [];
4186
- for (const line of parseLines(result.stdout)) {
4187
- const match = line.match(/^stash@\{(\d+)\}:\s*(?:On\s+)?(.+?):\s*(.+)$/);
4188
- const indexStr = match?.[1];
4189
- const branchOrContext = match?.[2];
4190
- const message = match?.[3];
4191
- if (indexStr !== void 0 && message !== void 0) {
4192
- const wipMatch = branchOrContext?.match(/^WIP on (.+)$/);
4193
- entries.push({
4194
- index: Number.parseInt(indexStr, 10),
4195
- message,
4196
- branch: wipMatch?.[1] ?? branchOrContext,
4197
- commit: ""
4198
- // We'd need another command to get the commit hash
4199
- });
4200
- }
4445
+ const result = await this.runner.runOrThrow(
4446
+ this.context,
4447
+ ["stash", "list", "-z", "--format=%gd%x00%H%x00%gs"],
4448
+ opts
4449
+ );
4450
+ const fields = parseRecords(result.stdout);
4451
+ if (fields.length % 3 !== 0) {
4452
+ throw new GitError("ParseError", "Invalid stash record");
4201
4453
  }
4202
- if (entries.length > 0) {
4203
- for (const entry of entries) {
4204
- try {
4205
- const hashResult = await this.runner.runOrThrow(
4206
- this.context,
4207
- ["rev-parse", `stash@{${entry.index}}`],
4208
- { signal: opts?.signal }
4209
- );
4210
- entry.commit = hashResult.stdout.trim();
4211
- } catch {
4212
- }
4454
+ const entries = [];
4455
+ for (let i = 0; i < fields.length; i += 3) {
4456
+ const index = fields[i]?.match(/^stash@\{(\d+)\}$/)?.[1];
4457
+ if (index === void 0 || !fields[i + 1]) {
4458
+ throw new GitError("ParseError", "Invalid stash metadata");
4213
4459
  }
4460
+ const subject = fields[i + 2];
4461
+ const context = subject.match(/^(?:WIP on|On) (.*?): ([\s\S]*)$/);
4462
+ entries.push({
4463
+ index: Number(index),
4464
+ commit: fields[i + 1],
4465
+ message: context?.[2] ?? subject,
4466
+ ...context ? { branch: context[1] } : {}
4467
+ });
4214
4468
  }
4215
4469
  return entries;
4216
4470
  }
@@ -4286,6 +4540,7 @@ var WorktreeRepoImpl = class _WorktreeRepoImpl {
4286
4540
  // High-level API - switch
4287
4541
  // ==========================================================================
4288
4542
  async switch(branch, opts) {
4543
+ validateOptions("switch", opts);
4289
4544
  const args = ["switch"];
4290
4545
  if (opts?.create) {
4291
4546
  args.push("-c");
@@ -4485,6 +4740,7 @@ var WorktreeRepoImpl = class _WorktreeRepoImpl {
4485
4740
  // Medium Priority - cherry-pick
4486
4741
  // ==========================================================================
4487
4742
  async cherryPick(commits, opts) {
4743
+ validateOptions("cherryPick", opts);
4488
4744
  if (opts?.abort) {
4489
4745
  await this.runner.runOrThrow(this.context, ["cherry-pick", "--abort"], {
4490
4746
  signal: opts?.signal
@@ -4519,9 +4775,6 @@ var WorktreeRepoImpl = class _WorktreeRepoImpl {
4519
4775
  if (opts?.strategy) {
4520
4776
  args.push("-s", opts.strategy);
4521
4777
  }
4522
- if (opts?.noVerify) {
4523
- args.push("--no-verify");
4524
- }
4525
4778
  if (opts?.cleanup) {
4526
4779
  args.push("--cleanup", opts.cleanup);
4527
4780
  }
@@ -4566,6 +4819,7 @@ var WorktreeRepoImpl = class _WorktreeRepoImpl {
4566
4819
  // Medium Priority - clean
4567
4820
  // ==========================================================================
4568
4821
  async clean(opts) {
4822
+ validateOptions("clean", opts);
4569
4823
  const args = ["clean"];
4570
4824
  if (opts?.force) {
4571
4825
  args.push("-f");
@@ -4635,6 +4889,7 @@ var WorktreeRepoImpl = class _WorktreeRepoImpl {
4635
4889
  // Medium Priority - rebase
4636
4890
  // ==========================================================================
4637
4891
  async rebase(opts) {
4892
+ validateOptions("rebase", opts);
4638
4893
  if (opts?.abort) {
4639
4894
  await this.runner.runOrThrow(this.context, ["rebase", "--abort"], {
4640
4895
  signal: opts?.signal
@@ -4765,10 +5020,9 @@ var WorktreeRepoImpl = class _WorktreeRepoImpl {
4765
5020
  env: this.lfsModeEnv()
4766
5021
  });
4767
5022
  }
4768
- // ==========================================================================
4769
- // Medium Priority - restore
4770
- // ==========================================================================
4771
5023
  async restore(paths, opts) {
5024
+ validatePathInput("restore", paths, opts);
5025
+ validateOptions("restore", opts);
4772
5026
  const args = ["restore"];
4773
5027
  if (opts?.staged) {
4774
5028
  args.push("--staged");
@@ -4828,6 +5082,7 @@ var WorktreeRepoImpl = class _WorktreeRepoImpl {
4828
5082
  // Medium Priority - revert
4829
5083
  // ==========================================================================
4830
5084
  async revert(commits, opts) {
5085
+ validateOptions("revert", opts);
4831
5086
  if (opts?.abort) {
4832
5087
  await this.runner.runOrThrow(this.context, ["revert", "--abort"], {
4833
5088
  signal: opts?.signal
@@ -4856,9 +5111,6 @@ var WorktreeRepoImpl = class _WorktreeRepoImpl {
4856
5111
  if (opts?.mainline !== void 0) {
4857
5112
  args.push("-m", opts.mainline.toString());
4858
5113
  }
4859
- if (opts?.noVerify) {
4860
- args.push("--no-verify");
4861
- }
4862
5114
  if (opts?.cleanup) {
4863
5115
  args.push("--cleanup", opts.cleanup);
4864
5116
  }
@@ -4970,6 +5222,10 @@ var WorktreeRepoImpl = class _WorktreeRepoImpl {
4970
5222
  });
4971
5223
  return result2.stdout.trim();
4972
5224
  }
5225
+ validateRevParseQuery(refOrOpts);
5226
+ if ("pathFormat" in refOrOpts && refOrOpts.pathFormat) {
5227
+ args.push(`--path-format=${refOrOpts.pathFormat}`);
5228
+ }
4973
5229
  const queryOpts = refOrOpts;
4974
5230
  if ("gitDir" in queryOpts && queryOpts.gitDir) {
4975
5231
  args.push("--git-dir");
@@ -5064,9 +5320,6 @@ var WorktreeRepoImpl = class _WorktreeRepoImpl {
5064
5320
  } else if ("localEnvVars" in queryOpts && queryOpts.localEnvVars) {
5065
5321
  args.push("--local-env-vars");
5066
5322
  }
5067
- if ("pathFormat" in queryOpts && queryOpts.pathFormat) {
5068
- args.push(`--path-format=${queryOpts.pathFormat}`);
5069
- }
5070
5323
  const result = await this.runner.runOrThrow(this.context, args, {
5071
5324
  signal: queryOpts.signal
5072
5325
  });
@@ -5406,6 +5659,7 @@ var WorktreeRepoImpl = class _WorktreeRepoImpl {
5406
5659
  });
5407
5660
  }
5408
5661
  async remoteSetHead(remote, branch, opts) {
5662
+ validateOptions("remoteSetHead", opts);
5409
5663
  const args = ["remote", "set-head"];
5410
5664
  if (opts?.auto) {
5411
5665
  args.push("--auto");
@@ -5479,25 +5733,14 @@ var WorktreeRepoImpl = class _WorktreeRepoImpl {
5479
5733
  * Get a typed config value
5480
5734
  */
5481
5735
  async configGet(key, opts) {
5482
- const result = await this.runner.run(this.context, ["config", "--get", key], {
5483
- signal: opts?.signal
5484
- });
5485
- if (result.exitCode !== 0) {
5486
- return void 0;
5487
- }
5488
- return result.stdout.trim();
5489
- }
5490
- /**
5491
- * Get all values for a typed multi-valued config key
5492
- */
5493
- async configGetAll(key, opts) {
5494
- const result = await this.runner.run(this.context, ["config", "--get-all", key], {
5495
- signal: opts?.signal
5496
- });
5497
- if (result.exitCode !== 0) {
5498
- return [];
5499
- }
5500
- return parseLines(result.stdout);
5736
+ const values = await readTypedConfig(this.runner, this.context, key, opts);
5737
+ return values.at(-1);
5738
+ }
5739
+ /**
5740
+ * Get all values for a typed multi-valued config key
5741
+ */
5742
+ async configGetAll(key, opts) {
5743
+ return readTypedConfig(this.runner, this.context, key, opts, true);
5501
5744
  }
5502
5745
  /**
5503
5746
  * Set a typed config value
@@ -5523,33 +5766,8 @@ var WorktreeRepoImpl = class _WorktreeRepoImpl {
5523
5766
  signal: opts?.signal
5524
5767
  });
5525
5768
  }
5526
- /**
5527
- * Get a raw config value (for arbitrary keys)
5528
- */
5529
5769
  async configGetRaw(key, opts) {
5530
- const args = ["config"];
5531
- if (opts?.type) {
5532
- args.push(`--type=${opts.type}`);
5533
- }
5534
- if (opts?.default !== void 0) {
5535
- args.push("--default", opts.default);
5536
- }
5537
- if (opts?.all) {
5538
- args.push("--get-all");
5539
- } else {
5540
- args.push("--get");
5541
- }
5542
- args.push(key);
5543
- const result = await this.runner.run(this.context, args, {
5544
- signal: opts?.signal
5545
- });
5546
- if (result.exitCode !== 0) {
5547
- return void 0;
5548
- }
5549
- if (opts?.all) {
5550
- return parseLines(result.stdout);
5551
- }
5552
- return result.stdout.trim();
5770
+ return readConfig(this.runner, this.context, key, opts);
5553
5771
  }
5554
5772
  /**
5555
5773
  * Set a raw config value (for arbitrary keys)
@@ -5576,47 +5794,7 @@ var WorktreeRepoImpl = class _WorktreeRepoImpl {
5576
5794
  * List all config values
5577
5795
  */
5578
5796
  async configList(opts) {
5579
- const args = ["config", "--list"];
5580
- if (opts?.showOrigin) {
5581
- args.push("--show-origin");
5582
- }
5583
- if (opts?.showScope) {
5584
- args.push("--show-scope");
5585
- }
5586
- if (opts?.includes) {
5587
- args.push("--includes");
5588
- }
5589
- if (opts?.nameOnly) {
5590
- args.push("--name-only");
5591
- }
5592
- const result = await this.runner.runOrThrow(this.context, args, {
5593
- signal: opts?.signal
5594
- });
5595
- const entries = [];
5596
- for (const line of parseLines(result.stdout)) {
5597
- let keyValue = line;
5598
- if (opts?.showOrigin || opts?.showScope) {
5599
- const tabIndex = line.lastIndexOf(" ");
5600
- if (tabIndex !== -1) {
5601
- keyValue = line.slice(tabIndex + 1);
5602
- }
5603
- }
5604
- if (opts?.nameOnly) {
5605
- entries.push({
5606
- key: keyValue,
5607
- value: ""
5608
- });
5609
- } else {
5610
- const eqIndex = keyValue.indexOf("=");
5611
- if (eqIndex !== -1) {
5612
- entries.push({
5613
- key: keyValue.slice(0, eqIndex),
5614
- value: keyValue.slice(eqIndex + 1)
5615
- });
5616
- }
5617
- }
5618
- }
5619
- return entries;
5797
+ return listConfig(this.runner, this.context, opts);
5620
5798
  }
5621
5799
  async configRenameSection(oldName, newName, opts) {
5622
5800
  await this.runner.runOrThrow(this.context, ["config", "--rename-section", oldName, newName], {
@@ -5833,11 +6011,14 @@ var GitImpl = class {
5833
6011
  return new WorktreeRepoImpl(repoRunner, path, opts);
5834
6012
  }
5835
6013
  async clone(url, path, opts) {
6014
+ validateOptions("clone", opts);
5836
6015
  const args = buildCloneArgs(opts);
5837
6016
  if (opts?.onProgress || opts?.onLfsProgress) {
5838
6017
  args.push("--progress");
5839
6018
  }
5840
6019
  args.push(url, path);
6020
+ const destinationExisted = await this.adapters.fs.exists(path);
6021
+ const alreadyAborted = opts?.signal?.aborted;
5841
6022
  try {
5842
6023
  await this.runner.runOrThrow({ type: "global" }, args, {
5843
6024
  signal: opts?.signal,
@@ -5845,7 +6026,7 @@ var GitImpl = class {
5845
6026
  onLfsProgress: opts?.onLfsProgress
5846
6027
  });
5847
6028
  } catch (error) {
5848
- if (error instanceof GitError && error.kind === "Aborted" && opts?.cleanupOnAbort !== false) {
6029
+ if (error instanceof GitError && error.kind === "Aborted" && opts?.cleanupOnAbort !== false && !destinationExisted && !alreadyAborted) {
5849
6030
  await this.adapters.fs.deleteDirectory(path);
5850
6031
  }
5851
6032
  throw error;
@@ -5856,6 +6037,7 @@ var GitImpl = class {
5856
6037
  return new WorktreeRepoImpl(this.runner, path);
5857
6038
  }
5858
6039
  async init(path, opts) {
6040
+ validateOptions("init", opts);
5859
6041
  const args = ["init"];
5860
6042
  if (opts?.quiet) {
5861
6043
  args.push("--quiet");
@@ -5887,6 +6069,8 @@ var GitImpl = class {
5887
6069
  args.push("--separate-git-dir", opts.separateGitDir);
5888
6070
  }
5889
6071
  args.push(path);
6072
+ const destinationExisted = await this.adapters.fs.exists(path);
6073
+ const alreadyAborted = opts?.signal?.aborted;
5890
6074
  try {
5891
6075
  await this.runner.runOrThrow({ type: "global" }, args, {
5892
6076
  signal: opts?.signal,
@@ -5903,7 +6087,7 @@ var GitImpl = class {
5903
6087
  );
5904
6088
  }
5905
6089
  } catch (error) {
5906
- if (error instanceof GitError && error.kind === "Aborted" && opts?.cleanupOnAbort !== false) {
6090
+ if (error instanceof GitError && error.kind === "Aborted" && opts?.cleanupOnAbort !== false && !destinationExisted && !alreadyAborted) {
5907
6091
  await this.adapters.fs.deleteDirectory(path);
5908
6092
  }
5909
6093
  throw error;
@@ -5917,6 +6101,7 @@ var GitImpl = class {
5917
6101
  * List references in a remote repository
5918
6102
  */
5919
6103
  async lsRemote(url, opts) {
6104
+ validateOptions("lsRemote", opts);
5920
6105
  const args = ["ls-remote"];
5921
6106
  if (opts?.heads) {
5922
6107
  args.push("--heads");
@@ -5927,15 +6112,9 @@ var GitImpl = class {
5927
6112
  if (opts?.refs) {
5928
6113
  args.push("--refs");
5929
6114
  }
5930
- if (opts?.getUrl) {
5931
- args.push("--get-url");
5932
- }
5933
6115
  if (opts?.sort) {
5934
6116
  args.push("--sort", opts.sort);
5935
6117
  }
5936
- if (opts?.symref) {
5937
- args.push("--symref");
5938
- }
5939
6118
  args.push(url);
5940
6119
  const result = await this.runner.runOrThrow({ type: "global" }, args, {
5941
6120
  signal: opts?.signal,
@@ -5979,27 +6158,14 @@ var GitImpl = class {
5979
6158
  * Get a typed global config value
5980
6159
  */
5981
6160
  async configGet(key, opts) {
5982
- const result = await this.runner.run({ type: "global" }, ["config", "--global", "--get", key], {
5983
- signal: opts?.signal
5984
- });
5985
- if (result.exitCode !== 0) {
5986
- return void 0;
5987
- }
5988
- return result.stdout.trim();
6161
+ const values = await readTypedConfig(this.runner, { type: "global" }, key, opts);
6162
+ return values.at(-1);
5989
6163
  }
5990
6164
  /**
5991
6165
  * Get all values for a typed multi-valued global config key
5992
6166
  */
5993
6167
  async configGetAll(key, opts) {
5994
- const result = await this.runner.run(
5995
- { type: "global" },
5996
- ["config", "--global", "--get-all", key],
5997
- { signal: opts?.signal }
5998
- );
5999
- if (result.exitCode !== 0) {
6000
- return [];
6001
- }
6002
- return parseLines(result.stdout);
6168
+ return readTypedConfig(this.runner, { type: "global" }, key, opts, true);
6003
6169
  }
6004
6170
  /**
6005
6171
  * Set a typed global config value
@@ -6027,27 +6193,8 @@ var GitImpl = class {
6027
6193
  signal: opts?.signal
6028
6194
  });
6029
6195
  }
6030
- /**
6031
- * Get a raw global config value (for arbitrary keys)
6032
- */
6033
6196
  async configGetRaw(key, opts) {
6034
- const args = ["config", "--global"];
6035
- if (opts?.all) {
6036
- args.push("--get-all");
6037
- } else {
6038
- args.push("--get");
6039
- }
6040
- args.push(key);
6041
- const result = await this.runner.run({ type: "global" }, args, {
6042
- signal: opts?.signal
6043
- });
6044
- if (result.exitCode !== 0) {
6045
- return void 0;
6046
- }
6047
- if (opts?.all) {
6048
- return parseLines(result.stdout);
6049
- }
6050
- return result.stdout.trim();
6197
+ return readConfig(this.runner, { type: "global" }, key, opts);
6051
6198
  }
6052
6199
  /**
6053
6200
  * Set a raw global config value (for arbitrary keys)
@@ -6074,34 +6221,7 @@ var GitImpl = class {
6074
6221
  * List all global config values
6075
6222
  */
6076
6223
  async configList(opts) {
6077
- const args = ["config", "--global", "--list"];
6078
- if (opts?.showOrigin) {
6079
- args.push("--show-origin");
6080
- }
6081
- if (opts?.showScope) {
6082
- args.push("--show-scope");
6083
- }
6084
- const result = await this.runner.runOrThrow({ type: "global" }, args, {
6085
- signal: opts?.signal
6086
- });
6087
- const entries = [];
6088
- for (const line of parseLines(result.stdout)) {
6089
- let keyValue = line;
6090
- if (opts?.showOrigin || opts?.showScope) {
6091
- const tabIndex = line.lastIndexOf(" ");
6092
- if (tabIndex !== -1) {
6093
- keyValue = line.slice(tabIndex + 1);
6094
- }
6095
- }
6096
- const eqIndex = keyValue.indexOf("=");
6097
- if (eqIndex !== -1) {
6098
- entries.push({
6099
- key: keyValue.slice(0, eqIndex),
6100
- value: keyValue.slice(eqIndex + 1)
6101
- });
6102
- }
6103
- }
6104
- return entries;
6224
+ return listConfig(this.runner, { type: "global" }, opts);
6105
6225
  }
6106
6226
  // ==========================================================================
6107
6227
  // Global LFS Operations
@@ -6174,6 +6294,89 @@ async function createGit(options) {
6174
6294
  return git;
6175
6295
  }
6176
6296
 
6297
+ // src/internal/client.ts
6298
+ var GitClient = class {
6299
+ constructor(git) {
6300
+ this.git = git;
6301
+ }
6302
+ get open() {
6303
+ return this.git.open.bind(this.git);
6304
+ }
6305
+ /**
6306
+ * Open an existing bare repository
6307
+ *
6308
+ * Throws GitError if the repository is not bare.
6309
+ *
6310
+ * @throws GitError with kind 'NotBareRepo' if the repository is not bare
6311
+ */
6312
+ get openBare() {
6313
+ return this.git.openBare.bind(this.git);
6314
+ }
6315
+ /**
6316
+ * Open an existing repository without type guarantee
6317
+ *
6318
+ * Returns either WorktreeRepo or BareRepo depending on the repository type.
6319
+ * Use this when you don't know the repository type at compile time.
6320
+ */
6321
+ get openRaw() {
6322
+ return this.git.openRaw.bind(this.git);
6323
+ }
6324
+ clone(url, path, opts) {
6325
+ return this.git.clone(url, path, opts);
6326
+ }
6327
+ init(path, opts) {
6328
+ return this.git.init(path, opts);
6329
+ }
6330
+ /**
6331
+ * List references in a remote repository
6332
+ */
6333
+ get lsRemote() {
6334
+ return this.git.lsRemote.bind(this.git);
6335
+ }
6336
+ /**
6337
+ * Get git version
6338
+ */
6339
+ get version() {
6340
+ return this.git.version.bind(this.git);
6341
+ }
6342
+ /**
6343
+ * Execute a raw git command (repository-agnostic)
6344
+ */
6345
+ get raw() {
6346
+ return this.git.raw.bind(this.git);
6347
+ }
6348
+ /**
6349
+ * Global config operations
6350
+ *
6351
+ * Operates on ~/.gitconfig (user-level configuration).
6352
+ * For repository-level config, use repo.config instead.
6353
+ */
6354
+ get config() {
6355
+ return this.git.config;
6356
+ }
6357
+ /**
6358
+ * Global LFS operations
6359
+ *
6360
+ * Operates on ~/.gitconfig (user-level) or /etc/gitconfig (system-level).
6361
+ * For repository-level LFS operations, use repo.lfs instead.
6362
+ *
6363
+ * @example
6364
+ * ```typescript
6365
+ * // Install LFS globally
6366
+ * await git.lfs.install();
6367
+ *
6368
+ * // Install system-wide
6369
+ * await git.lfs.install({ system: true });
6370
+ *
6371
+ * // Get LFS version
6372
+ * const version = await git.lfs.version();
6373
+ * ```
6374
+ */
6375
+ get lfs() {
6376
+ return this.git.lfs;
6377
+ }
6378
+ };
6379
+
6177
6380
  // src/adapters/node/exec.ts
6178
6381
  import { spawn } from "child_process";
6179
6382
  function resolveChildEnv(env, inheritEnv) {
@@ -6185,7 +6388,7 @@ function resolveChildEnv(env, inheritEnv) {
6185
6388
  async function* streamToAsyncIterable(stream) {
6186
6389
  let buffer = "";
6187
6390
  for await (const chunk of stream) {
6188
- buffer += chunk.toString("utf8");
6391
+ buffer += chunk;
6189
6392
  const lines = buffer.split("\n");
6190
6393
  buffer = lines.pop() ?? "";
6191
6394
  for (const line of lines) {
@@ -6214,12 +6417,17 @@ var NodeExecAdapter = class {
6214
6417
  throw new Error("argv must not be empty");
6215
6418
  }
6216
6419
  const args = argv.slice(1);
6420
+ if (signal?.aborted) {
6421
+ return Promise.resolve({ stdout: "", stderr: "", exitCode: -1, aborted: true });
6422
+ }
6217
6423
  return new Promise((resolve, reject) => {
6218
6424
  const child = spawn(command, args, {
6219
6425
  cwd,
6220
6426
  env: resolveChildEnv(env, inheritEnv),
6221
6427
  stdio: [options.stdin === void 0 ? "ignore" : "pipe", "pipe", "pipe"]
6222
6428
  });
6429
+ child.stdout?.setEncoding("utf8");
6430
+ child.stderr?.setEncoding("utf8");
6223
6431
  let stdout = "";
6224
6432
  let stderr = "";
6225
6433
  let aborted = false;
@@ -6237,12 +6445,12 @@ var NodeExecAdapter = class {
6237
6445
  }
6238
6446
  }
6239
6447
  child.stdout?.on("data", (chunk) => {
6240
- const text = chunk.toString("utf8");
6448
+ const text = chunk;
6241
6449
  stdout += text;
6242
6450
  handlers?.onStdout?.(text);
6243
6451
  });
6244
6452
  child.stderr?.on("data", (chunk) => {
6245
- const text = chunk.toString("utf8");
6453
+ const text = chunk;
6246
6454
  stderr += text;
6247
6455
  handlers?.onStderr?.(text);
6248
6456
  });
@@ -6257,6 +6465,7 @@ var NodeExecAdapter = class {
6257
6465
  reject(error);
6258
6466
  });
6259
6467
  child.on("close", (code, sig) => {
6468
+ signal?.removeEventListener("abort", abortHandler);
6260
6469
  if (sig) {
6261
6470
  exitSignal = sig;
6262
6471
  }
@@ -6297,13 +6506,15 @@ var NodeExecAdapter = class {
6297
6506
  }
6298
6507
  }
6299
6508
  const waitPromise = new Promise((resolve, reject) => {
6509
+ child.stdout?.setEncoding("utf8");
6510
+ child.stderr?.setEncoding("utf8");
6300
6511
  let stdout = "";
6301
6512
  let stderr = "";
6302
6513
  child.stdout?.on("data", (chunk) => {
6303
- stdout += chunk.toString("utf8");
6514
+ stdout += chunk;
6304
6515
  });
6305
6516
  child.stderr?.on("data", (chunk) => {
6306
- stderr += chunk.toString("utf8");
6517
+ stderr += chunk;
6307
6518
  });
6308
6519
  child.stdin?.on("error", (error) => {
6309
6520
  if (error.code !== "EPIPE" && error.code !== "EOF") {
@@ -6570,114 +6781,14 @@ function createNodeAdapters() {
6570
6781
  fs: new NodeFsAdapter()
6571
6782
  };
6572
6783
  }
6573
- var TypeGit = class _TypeGit {
6574
- git;
6575
- /**
6576
- * Create a TypeGit instance with Git version check
6577
- *
6578
- * @param createOpts - Options including skipVersionCheck
6579
- * @returns TypeGit instance
6580
- * @throws GitError with kind 'UnsupportedGitVersion' if Git version is below minimum
6581
- */
6582
- static async create(createOpts) {
6583
- const gitInstance = await createGit({
6584
- ...createOpts,
6585
- adapters: createNodeAdapters()
6586
- });
6587
- return new _TypeGit(gitInstance);
6784
+ var TypeGit = class _TypeGit extends GitClient {
6785
+ static async create(options) {
6786
+ return new _TypeGit(await createGit({ ...options, adapters: createNodeAdapters() }));
6588
6787
  }
6589
6788
  constructor(optionsOrGit) {
6590
- if (optionsOrGit && "open" in optionsOrGit) {
6591
- this.git = optionsOrGit;
6592
- } else {
6593
- this.git = createGitSync({
6594
- ...optionsOrGit,
6595
- adapters: createNodeAdapters()
6596
- });
6597
- }
6598
- }
6599
- /**
6600
- * Open an existing worktree repository
6601
- *
6602
- * This is the most common use case. Throws GitError if the repository is bare.
6603
- *
6604
- * @throws GitError with kind 'NotWorktreeRepo' if the repository is bare
6605
- */
6606
- get open() {
6607
- return this.git.open.bind(this.git);
6608
- }
6609
- /**
6610
- * Open an existing bare repository
6611
- *
6612
- * Throws GitError if the repository is not bare.
6613
- *
6614
- * @throws GitError with kind 'NotBareRepo' if the repository is not bare
6615
- */
6616
- get openBare() {
6617
- return this.git.openBare.bind(this.git);
6618
- }
6619
- /**
6620
- * Open an existing repository without type guarantee
6621
- *
6622
- * Returns either WorktreeRepo or BareRepo depending on the repository type.
6623
- * Use this when you don't know the repository type at compile time.
6624
- */
6625
- get openRaw() {
6626
- return this.git.openRaw.bind(this.git);
6627
- }
6628
- clone(url, path, opts) {
6629
- return this.git.clone(url, path, opts);
6630
- }
6631
- init(path, opts) {
6632
- return this.git.init(path, opts);
6633
- }
6634
- /**
6635
- * List references in a remote repository
6636
- */
6637
- get lsRemote() {
6638
- return this.git.lsRemote.bind(this.git);
6639
- }
6640
- /**
6641
- * Get git version
6642
- */
6643
- get version() {
6644
- return this.git.version.bind(this.git);
6645
- }
6646
- /**
6647
- * Execute a raw git command (repository-agnostic)
6648
- */
6649
- get raw() {
6650
- return this.git.raw.bind(this.git);
6651
- }
6652
- /**
6653
- * Global config operations
6654
- *
6655
- * Operates on ~/.gitconfig (user-level configuration).
6656
- * For repository-level config, use repo.config instead.
6657
- */
6658
- get config() {
6659
- return this.git.config;
6660
- }
6661
- /**
6662
- * Global LFS operations
6663
- *
6664
- * Operates on ~/.gitconfig (user-level) or /etc/gitconfig (system-level).
6665
- * For repository-level LFS operations, use repo.lfs instead.
6666
- *
6667
- * @example
6668
- * ```typescript
6669
- * // Install LFS globally
6670
- * await git.lfs.install();
6671
- *
6672
- * // Install system-wide
6673
- * await git.lfs.install({ system: true });
6674
- *
6675
- * // Get LFS version
6676
- * const version = await git.lfs.version();
6677
- * ```
6678
- */
6679
- get lfs() {
6680
- return this.git.lfs;
6789
+ super(
6790
+ optionsOrGit && "open" in optionsOrGit ? optionsOrGit : createGitSync({ ...optionsOrGit, adapters: createNodeAdapters() })
6791
+ );
6681
6792
  }
6682
6793
  };
6683
6794
  export {