type-git 0.7.0 → 0.8.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.
@@ -3,6 +3,7 @@ import {
3
3
  GIT_LOG_FORMAT,
4
4
  GitArgumentError,
5
5
  GitError,
6
+ branchNameSyntax,
6
7
  commandHostOf,
7
8
  parseGitLog,
8
9
  parseLines,
@@ -12,12 +13,13 @@ import {
12
13
  parseRecords,
13
14
  parseWorktreeList,
14
15
  registerCommandHost,
16
+ validRefSortKey,
15
17
  validateInput,
16
18
  validateOptions,
17
19
  validatePathInput,
18
20
  validateRevParseQuery,
19
21
  validateRevParseRefOpts
20
- } from "./chunk-5NI3KM5Z.js";
22
+ } from "./chunk-UAKOSACD.js";
21
23
 
22
24
  // src/core/clone-config.ts
23
25
  var HTTP_VARIABLES = [
@@ -141,6 +143,208 @@ function checkedOperands(command, name, values) {
141
143
  }
142
144
  return [...values];
143
145
  }
146
+ function checkedNewBranchName(command, name, value) {
147
+ if (branchNameSyntax(value) === false) {
148
+ throw new GitArgumentError(
149
+ `${command}: ${name} is not a valid branch name (got ${JSON.stringify(value)}); see git check-ref-format --branch.`
150
+ );
151
+ }
152
+ return value;
153
+ }
154
+ function checkedRefSortKey(command, value) {
155
+ if (!validRefSortKey(value)) {
156
+ throw new GitArgumentError(
157
+ `${command}: sort is not a ref-filter sort key (got ${JSON.stringify(value)}); use an optional '-', an optional version: or v:, and a field name such as refname.`
158
+ );
159
+ }
160
+ return value;
161
+ }
162
+
163
+ // src/core/untrusted-repo.ts
164
+ var UNTRUSTED_REPO_MIN_GIT_VERSION = "2.38.0";
165
+ function untrustedRepoConfigOverrides(platform = process.platform, execPath = process.execPath) {
166
+ const hooksPath = platform === "win32" ? `${execPath}/no-hooks` : "/dev/null";
167
+ return [
168
+ `core.hooksPath=${hooksPath}`,
169
+ "core.fsmonitor=",
170
+ "protocol.ext.allow=never",
171
+ "safe.bareRepository=explicit"
172
+ ];
173
+ }
174
+ var PLAIN_KEYS2 = /* @__PURE__ */ new Set([
175
+ "core.repositoryformatversion",
176
+ "core.bare",
177
+ "core.logallrefupdates",
178
+ "core.filemode",
179
+ "core.ignorecase",
180
+ "core.precomposeunicode",
181
+ "core.symlinks",
182
+ "core.autocrlf",
183
+ "core.eol",
184
+ "core.safecrlf",
185
+ "core.longpaths",
186
+ "core.quotepath",
187
+ "core.sparsecheckout",
188
+ "core.sparsecheckoutcone",
189
+ "core.compression",
190
+ "core.bigfilethreshold",
191
+ "core.checkstat",
192
+ "core.trustctime",
193
+ "core.untrackedcache",
194
+ "core.commitgraph",
195
+ "core.multipackindex",
196
+ "core.abbrev",
197
+ "extensions.objectformat",
198
+ "extensions.compatobjectformat",
199
+ "extensions.refstorage",
200
+ "extensions.worktreeconfig",
201
+ "extensions.partialclone",
202
+ "extensions.preciousobjects",
203
+ "user.name",
204
+ "user.email",
205
+ "init.defaultbranch",
206
+ "index.version",
207
+ "index.sparse",
208
+ "maintenance.auto",
209
+ "maintenance.strategy",
210
+ "protocol.version",
211
+ "fetch.prune",
212
+ "fetch.prunetags",
213
+ "pull.rebase",
214
+ "pull.ff",
215
+ "push.default",
216
+ "push.autosetupremote",
217
+ "merge.ff",
218
+ "merge.conflictstyle",
219
+ "rebase.autostash",
220
+ "rebase.autosquash",
221
+ "rebase.updaterefs",
222
+ "diff.algorithm",
223
+ "color.ui",
224
+ "lfs.repositoryformatversion",
225
+ "lfs.fetchinclude",
226
+ "lfs.fetchexclude"
227
+ ]);
228
+ var SUBSECTION_VARIABLES = /* @__PURE__ */ new Map([
229
+ [
230
+ "remote",
231
+ /* @__PURE__ */ new Set([
232
+ "url",
233
+ "pushurl",
234
+ "fetch",
235
+ "push",
236
+ "tagopt",
237
+ "prune",
238
+ "prunetags",
239
+ "mirror",
240
+ "promisor",
241
+ "partialclonefilter",
242
+ "skipdefaultupdate",
243
+ "skipfetchall"
244
+ ])
245
+ ],
246
+ ["branch", /* @__PURE__ */ new Set(["remote", "merge", "rebase", "pushremote", "description"])],
247
+ ["submodule", /* @__PURE__ */ new Set(["url", "active", "branch", "ignore", "shallow"])]
248
+ ]);
249
+ var URL_VARIABLES = /* @__PURE__ */ new Map([
250
+ ["remote", /* @__PURE__ */ new Set(["url", "pushurl"])],
251
+ ["submodule", /* @__PURE__ */ new Set(["url"])]
252
+ ]);
253
+ var REMOTE_NAME_VARIABLES = /* @__PURE__ */ new Map([
254
+ ["branch", /* @__PURE__ */ new Set(["remote", "pushremote"])]
255
+ ]);
256
+ var REBASE_MODE_KEYS = /* @__PURE__ */ new Set(["pull.rebase", "branch.*.rebase"]);
257
+ function isNetworkRemoteUrl(value) {
258
+ if (/^(?:https?|ssh|git|git\+ssh|ssh\+git):\/\/[^/\\]/i.test(value)) {
259
+ return true;
260
+ }
261
+ if (value.includes("://") || value.includes("::")) {
262
+ return false;
263
+ }
264
+ const match = /^(?:[^@/\\:]+@)?([^/\\:]+):/.exec(value);
265
+ return match !== null && match[1].length > 1;
266
+ }
267
+ function isPlainRemoteName(value) {
268
+ return value.length > 0 && !value.startsWith(".") && !/[/\\:]/.test(value);
269
+ }
270
+ var LFS_FILTER_VALUES = /* @__PURE__ */ new Map([
271
+ ["clean", /* @__PURE__ */ new Set(["git-lfs clean -- %f"])],
272
+ ["smudge", /* @__PURE__ */ new Set(["git-lfs smudge -- %f", "git-lfs smudge --skip -- %f"])],
273
+ ["process", /* @__PURE__ */ new Set(["git-lfs filter-process", "git-lfs filter-process --skip"])],
274
+ ["required", /* @__PURE__ */ new Set(["true"])]
275
+ ]);
276
+ function asciiLower2(text) {
277
+ return text.replace(/[A-Z]/g, (letter) => String.fromCharCode(letter.charCodeAt(0) + 32));
278
+ }
279
+ function isDataOnlyRepoConfigEntry(key, value, configuredRemotes) {
280
+ const namesRemote = (name) => name !== void 0 && isPlainRemoteName(name) && (configuredRemotes === void 0 || configuredRemotes.has(name));
281
+ const first = key.indexOf(".");
282
+ const last = key.lastIndexOf(".");
283
+ if (first <= 0 || last === key.length - 1) {
284
+ return false;
285
+ }
286
+ const section = asciiLower2(key.slice(0, first));
287
+ const variable = asciiLower2(key.slice(last + 1));
288
+ if (first === last) {
289
+ const name = `${section}.${variable}`;
290
+ if (name === "extensions.partialclone") {
291
+ return namesRemote(value);
292
+ }
293
+ return PLAIN_KEYS2.has(name) && !(REBASE_MODE_KEYS.has(name) && isInteractive(value));
294
+ }
295
+ const subsection = key.slice(first + 1, last);
296
+ if (section === "filter" && subsection === "lfs") {
297
+ return value !== void 0 && LFS_FILTER_VALUES.get(variable)?.has(value) === true;
298
+ }
299
+ if (section === "lfs") {
300
+ return variable === "access";
301
+ }
302
+ if (URL_VARIABLES.get(section)?.has(variable) === true) {
303
+ return value !== void 0 && isNetworkRemoteUrl(value);
304
+ }
305
+ if (REMOTE_NAME_VARIABLES.get(section)?.has(variable) === true) {
306
+ return namesRemote(value);
307
+ }
308
+ if (REBASE_MODE_KEYS.has(`${section}.*.${variable}`) && isInteractive(value)) {
309
+ return false;
310
+ }
311
+ return SUBSECTION_VARIABLES.get(section)?.has(variable) === true;
312
+ }
313
+ function isInteractive(value) {
314
+ const mode = value === void 0 ? "" : asciiLower2(value);
315
+ return mode === "interactive" || mode === "i";
316
+ }
317
+ function parseScopedConfigList(stdout) {
318
+ const fields = stdout.split("\0");
319
+ const entries = [];
320
+ for (let i = 0; i + 1 < fields.length; i += 2) {
321
+ const scope = fields[i];
322
+ const pair = fields[i + 1];
323
+ const newline = pair.indexOf("\n");
324
+ entries.push(
325
+ newline === -1 ? { scope, key: pair, value: void 0 } : { scope, key: pair.slice(0, newline), value: pair.slice(newline + 1) }
326
+ );
327
+ }
328
+ return entries;
329
+ }
330
+ function unsafeRepoConfigKeys(entries) {
331
+ const own = entries.filter((entry) => entry.scope === "local" || entry.scope === "worktree");
332
+ const configuredRemotes = /* @__PURE__ */ new Set();
333
+ for (const { key } of own) {
334
+ const first = key.indexOf(".");
335
+ const last = key.lastIndexOf(".");
336
+ if (first > 0 && last > first && asciiLower2(key.slice(0, first)) === "remote" && asciiLower2(key.slice(last + 1)) === "url") {
337
+ configuredRemotes.add(key.slice(first + 1, last));
338
+ }
339
+ }
340
+ const unsafe = /* @__PURE__ */ new Set();
341
+ for (const entry of own) {
342
+ if (!isDataOnlyRepoConfigEntry(entry.key, entry.value, configuredRemotes)) {
343
+ unsafe.add(entry.key);
344
+ }
345
+ }
346
+ return [...unsafe];
347
+ }
144
348
 
145
349
  // src/internal/config.ts
146
350
  var CONFIG_ENUMS = {
@@ -1231,9 +1435,24 @@ async function runWithConcurrency(items, run, options) {
1231
1435
  }
1232
1436
 
1233
1437
  // src/impl/worktree-repo-impl.ts
1438
+ var RESET_MODES = [
1439
+ "soft",
1440
+ "mixed",
1441
+ "hard",
1442
+ "merge",
1443
+ "keep"
1444
+ ];
1234
1445
  var PRE_UPLOAD_DEFAULT_BATCH_SIZE = 200;
1235
1446
  var PRE_UPLOAD_DEFAULT_CONCURRENCY = 4;
1236
1447
  var PRE_UPLOAD_WARMUP_BATCH_COUNT = 1;
1448
+ function stashEntry(index, command) {
1449
+ if (!Number.isInteger(index) || index < 0 || index >= 1e8) {
1450
+ throw new GitArgumentError(
1451
+ `${command}: index must be an integer from 0 to 99999999 (got ${index})`
1452
+ );
1453
+ }
1454
+ return `stash@{${index}}`;
1455
+ }
1237
1456
  var WorktreeRepoImpl = class _WorktreeRepoImpl {
1238
1457
  kind = "worktree";
1239
1458
  workdir;
@@ -1504,7 +1723,7 @@ var WorktreeRepoImpl = class _WorktreeRepoImpl {
1504
1723
  if (opts.findRenames === true) {
1505
1724
  args.push("--find-renames");
1506
1725
  } else if (typeof opts.findRenames === "number") {
1507
- args.push(`--find-renames=${opts.findRenames}`);
1726
+ args.push(`--find-renames=${opts.findRenames}%`);
1508
1727
  }
1509
1728
  }
1510
1729
  const result = await this.runner.runOrThrow(this.context, args, {
@@ -2618,8 +2837,8 @@ var WorktreeRepoImpl = class _WorktreeRepoImpl {
2618
2837
  if (opts?.noMerged) {
2619
2838
  args.push(`--no-merged=${opts.noMerged}`);
2620
2839
  }
2621
- if (opts?.sort) {
2622
- args.push(`--sort=${opts.sort}`);
2840
+ if (opts?.sort !== void 0) {
2841
+ args.push(`--sort=${checkedRefSortKey("branch.list", opts.sort)}`);
2623
2842
  }
2624
2843
  if (opts?.pointsAt) {
2625
2844
  args.push(`--points-at=${opts.pointsAt}`);
@@ -2661,15 +2880,17 @@ var WorktreeRepoImpl = class _WorktreeRepoImpl {
2661
2880
  }
2662
2881
  async branchCreate(name, opts) {
2663
2882
  const args = ["branch"];
2883
+ if (opts?.setUpstreamTo && opts.recurseSubmodules) {
2884
+ throw new GitArgumentError(
2885
+ "branch.create: setUpstreamTo cannot be combined with recurseSubmodules"
2886
+ );
2887
+ }
2664
2888
  if (opts?.force) {
2665
2889
  args.push("--force");
2666
2890
  }
2667
2891
  if (opts?.track) {
2668
2892
  args.push("--track");
2669
2893
  }
2670
- if (opts?.setUpstreamTo) {
2671
- args.push(`--set-upstream-to=${opts.setUpstreamTo}`);
2672
- }
2673
2894
  if (opts?.createReflog) {
2674
2895
  args.push("--create-reflog");
2675
2896
  }
@@ -2677,12 +2898,24 @@ var WorktreeRepoImpl = class _WorktreeRepoImpl {
2677
2898
  args.push("--recurse-submodules");
2678
2899
  }
2679
2900
  args.push(checkedOperand("branch.create", "name", name));
2901
+ checkedNewBranchName("branch.create", "name", name);
2680
2902
  if (opts?.startPoint) {
2681
2903
  args.push(checkedOperand("branch.create", "startPoint", opts.startPoint));
2682
2904
  }
2683
2905
  await this.runner.runOrThrow(this.context, args, {
2684
2906
  signal: opts?.signal
2685
2907
  });
2908
+ if (opts?.setUpstreamTo) {
2909
+ await this.runner.runOrThrow(
2910
+ this.context,
2911
+ [
2912
+ "branch",
2913
+ `--set-upstream-to=${opts.setUpstreamTo}`,
2914
+ checkedOperand("branch.create", "name", name)
2915
+ ],
2916
+ { signal: opts?.signal }
2917
+ );
2918
+ }
2686
2919
  }
2687
2920
  async branchDelete(name, opts) {
2688
2921
  const args = ["branch"];
@@ -2706,7 +2939,11 @@ var WorktreeRepoImpl = class _WorktreeRepoImpl {
2706
2939
  "branch",
2707
2940
  "-m",
2708
2941
  checkedOperand("branch.rename", "oldName", oldName),
2709
- checkedOperand("branch.rename", "newName", newName)
2942
+ checkedNewBranchName(
2943
+ "branch.rename",
2944
+ "newName",
2945
+ checkedOperand("branch.rename", "newName", newName)
2946
+ )
2710
2947
  ],
2711
2948
  {
2712
2949
  signal: opts?.signal
@@ -3355,7 +3592,12 @@ var WorktreeRepoImpl = class _WorktreeRepoImpl {
3355
3592
  async reset(target, opts) {
3356
3593
  validateOptions("reset", opts);
3357
3594
  const args = ["reset"];
3358
- if (opts?.mode) {
3595
+ if (opts?.mode !== void 0) {
3596
+ if (!RESET_MODES.includes(opts.mode)) {
3597
+ throw new GitArgumentError(
3598
+ `reset: mode must be one of ${RESET_MODES.join(", ")} (got ${typeof opts.mode === "string" ? JSON.stringify(opts.mode) : typeof opts.mode})`
3599
+ );
3600
+ }
3359
3601
  args.push(`--${opts.mode}`);
3360
3602
  }
3361
3603
  if (opts?.quiet) {
@@ -3374,7 +3616,7 @@ var WorktreeRepoImpl = class _WorktreeRepoImpl {
3374
3616
  args.push(`--pathspec-from-file=${opts.pathspecFromFile}`);
3375
3617
  }
3376
3618
  if (target) {
3377
- args.push(checkedOperand("reset", "target", target));
3619
+ args.push(checkedOperand("reset", "target", target), "--");
3378
3620
  }
3379
3621
  await this.runner.runOrThrow(this.context, args, {
3380
3622
  signal: opts?.signal,
@@ -3469,6 +3711,7 @@ var WorktreeRepoImpl = class _WorktreeRepoImpl {
3469
3711
  args.push(`--pathspec-from-file=${opts.pathspecFromFile}`);
3470
3712
  }
3471
3713
  if (opts?.paths && opts.paths.length > 0) {
3714
+ validatePathInput("stash.push", opts.paths, opts);
3472
3715
  args.push("--", ...opts.paths);
3473
3716
  }
3474
3717
  await this.runner.runOrThrow(this.context, args, {
@@ -3481,7 +3724,7 @@ var WorktreeRepoImpl = class _WorktreeRepoImpl {
3481
3724
  args.push("--index");
3482
3725
  }
3483
3726
  if (opts?.index !== void 0) {
3484
- args.push(`stash@{${opts.index}}`);
3727
+ args.push(stashEntry(opts.index, "stash.pop"));
3485
3728
  }
3486
3729
  await this.runner.runOrThrow(this.context, args, {
3487
3730
  signal: opts?.signal
@@ -3493,7 +3736,7 @@ var WorktreeRepoImpl = class _WorktreeRepoImpl {
3493
3736
  args.push("--index");
3494
3737
  }
3495
3738
  if (opts?.index !== void 0) {
3496
- args.push(`stash@{${opts.index}}`);
3739
+ args.push(stashEntry(opts.index, "stash.apply"));
3497
3740
  }
3498
3741
  await this.runner.runOrThrow(this.context, args, {
3499
3742
  signal: opts?.signal
@@ -3502,7 +3745,7 @@ var WorktreeRepoImpl = class _WorktreeRepoImpl {
3502
3745
  async stashDrop(index, opts) {
3503
3746
  const args = ["stash", "drop"];
3504
3747
  if (index !== void 0) {
3505
- args.push(`stash@{${index}}`);
3748
+ args.push(stashEntry(index, "stash.drop"));
3506
3749
  }
3507
3750
  await this.runner.runOrThrow(this.context, args, {
3508
3751
  signal: opts?.signal
@@ -3517,14 +3760,19 @@ var WorktreeRepoImpl = class _WorktreeRepoImpl {
3517
3760
  // High-level API - switch
3518
3761
  // ==========================================================================
3519
3762
  async switch(branch, opts) {
3520
- validateInput("switchTarget", { branch }, "switch");
3763
+ validateInput(
3764
+ "switchTarget",
3765
+ {
3766
+ branch,
3767
+ track: opts?.track,
3768
+ create: opts?.create,
3769
+ forceCreate: opts?.forceCreate,
3770
+ orphan: opts?.orphan
3771
+ },
3772
+ "switch"
3773
+ );
3521
3774
  validateOptions("switch", opts);
3522
3775
  const args = ["switch"];
3523
- if (opts?.create) {
3524
- args.push("-c");
3525
- } else if (opts?.forceCreate) {
3526
- args.push("-C");
3527
- }
3528
3776
  if (opts?.discard) {
3529
3777
  args.push("--discard-changes");
3530
3778
  }
@@ -3552,16 +3800,25 @@ var WorktreeRepoImpl = class _WorktreeRepoImpl {
3552
3800
  if (opts?.force) {
3553
3801
  args.push("--force");
3554
3802
  }
3555
- if (opts?.orphan) {
3556
- args.push("--orphan");
3557
- }
3558
3803
  if (opts?.overwriteIgnore === false) {
3559
3804
  args.push("--no-overwrite-ignore");
3560
3805
  }
3561
3806
  if (opts?.ignoreOtherWorktrees) {
3562
3807
  args.push("--ignore-other-worktrees");
3563
3808
  }
3564
- args.push(checkedOperand("switch", "branch", branch));
3809
+ const target = checkedOperand("switch", "branch", branch);
3810
+ if (opts?.create || opts?.forceCreate || opts?.orphan) {
3811
+ checkedNewBranchName("switch", "branch", target);
3812
+ }
3813
+ if (opts?.create) {
3814
+ args.push("-c", target);
3815
+ } else if (opts?.forceCreate) {
3816
+ args.push("-C", target);
3817
+ } else if (opts?.orphan) {
3818
+ args.push("--orphan", target);
3819
+ } else {
3820
+ args.push(target);
3821
+ }
3565
3822
  if (opts?.startPoint) {
3566
3823
  args.push(checkedOperand("switch", "startPoint", opts.startPoint));
3567
3824
  }
@@ -3876,6 +4133,7 @@ var WorktreeRepoImpl = class _WorktreeRepoImpl {
3876
4133
  // ==========================================================================
3877
4134
  async rebase(opts) {
3878
4135
  validateOptions("rebase", opts);
4136
+ checkRebaseBackend(opts);
3879
4137
  const args = ["rebase"];
3880
4138
  if (opts?.abort) {
3881
4139
  args.push("--abort");
@@ -3956,9 +4214,14 @@ var WorktreeRepoImpl = class _WorktreeRepoImpl {
3956
4214
  } else if (opts?.autostash === false) {
3957
4215
  args.push("--no-autostash");
3958
4216
  }
3959
- if (opts?.exec) {
4217
+ if (opts?.exec !== void 0) {
3960
4218
  const execs = Array.isArray(opts.exec) ? opts.exec : [opts.exec];
3961
4219
  for (const cmd of execs) {
4220
+ if (typeof cmd !== "string" || /^[ \t\r\f\v]*$/.test(cmd) || cmd.includes("\n")) {
4221
+ throw new GitArgumentError(
4222
+ "rebase: exec must be a nonempty command without newlines [rebase.exec-command]"
4223
+ );
4224
+ }
3962
4225
  args.push("--exec", cmd);
3963
4226
  }
3964
4227
  }
@@ -3999,6 +4262,15 @@ var WorktreeRepoImpl = class _WorktreeRepoImpl {
3999
4262
  }
4000
4263
  async restore(paths, opts) {
4001
4264
  validatePathInput("restore", paths, opts);
4265
+ validateInput(
4266
+ "restorePaths",
4267
+ {
4268
+ paths: Array.isArray(paths) ? paths : [paths],
4269
+ pathspecFromFile: opts?.pathspecFromFile,
4270
+ source: opts?.source
4271
+ },
4272
+ "restore"
4273
+ );
4002
4274
  validateOptions("restore", opts);
4003
4275
  const args = ["restore"];
4004
4276
  if (opts?.staged) {
@@ -4853,6 +5125,17 @@ var WorktreeRepoImpl = class _WorktreeRepoImpl {
4853
5125
  );
4854
5126
  }
4855
5127
  };
5128
+ function checkRebaseBackend(opts) {
5129
+ if (!(opts?.apply || opts?.whitespace)) {
5130
+ return;
5131
+ }
5132
+ const implied = opts.root && !opts.onto ? "--root without --onto" : opts.reapplyCherryPicks !== void 0 && !opts.keepBase ? "--[no-]reapply-cherry-picks without --keep-base" : !opts.apply && opts.ignoreWhitespace ? "--ignore-whitespace without --apply" : void 0;
5133
+ if (implied) {
5134
+ throw new GitArgumentError(
5135
+ `rebase: ${implied} implies the merge backend, which apply options cannot use [rebase.apply-implied-merge]`
5136
+ );
5137
+ }
5138
+ }
4856
5139
 
4857
5140
  // src/impl/git-impl.ts
4858
5141
  var GIT_VERSION_REGEX = /git version (\S+)/;
@@ -4960,9 +5243,129 @@ function toCliRunnerOptions(opts) {
4960
5243
  credential: opts.credential ? {
4961
5244
  helper: opts.credential.helper,
4962
5245
  helperPath: opts.credential.helperPath
4963
- } : void 0
5246
+ } : void 0,
5247
+ configOverrides: opts.untrusted === true ? untrustedRepoConfigOverrides() : void 0
4964
5248
  };
4965
5249
  }
5250
+ async function listDirectory(fs, dirPath) {
5251
+ if (fs.readDirectory === void 0) {
5252
+ throw new GitError(
5253
+ "CapabilityMissing",
5254
+ "untrusted: true needs a file system adapter that implements readDirectory"
5255
+ );
5256
+ }
5257
+ return await fs.readDirectory(dirPath);
5258
+ }
5259
+ async function assertDataOnlyRepoConfig(runner, fs, context, label, allowWorktree = false) {
5260
+ const where = context.type === "bare" ? { gitDir: context.gitDir } : { workdir: context.workdir };
5261
+ const result = await runner.run(context, ["config", "--list", "--show-scope", "-z"]);
5262
+ if (result.exitCode !== 0) {
5263
+ throw new GitError(
5264
+ "UnsafeRepoConfig",
5265
+ `Could not read the configuration of untrusted repository ${label}`,
5266
+ { ...where, exitCode: result.exitCode, stderr: result.stderr }
5267
+ );
5268
+ }
5269
+ const unsafe = unsafeRepoConfigKeys(parseScopedConfigList(result.stdout)).filter(
5270
+ (key) => !(allowWorktree && key.toLowerCase() === "core.worktree")
5271
+ );
5272
+ if (unsafe.length > 0) {
5273
+ throw new GitError(
5274
+ "UnsafeRepoConfig",
5275
+ `Refusing untrusted repository ${label}: its configuration sets keys that are not data-only: ${unsafe.join(", ")}`,
5276
+ where
5277
+ );
5278
+ }
5279
+ for (const name of ["remotes", "branches"]) {
5280
+ const located = await revParsePath(runner, context, [
5281
+ "--path-format=absolute",
5282
+ "--git-path",
5283
+ name
5284
+ ]);
5285
+ if (located.exitCode !== 0) {
5286
+ throw new GitError(
5287
+ "UnsafeRepoConfig",
5288
+ `Could not locate the Git directory of untrusted repository ${label}`,
5289
+ { ...where, exitCode: located.exitCode, stderr: located.stderr }
5290
+ );
5291
+ }
5292
+ if ((await listDirectory(fs, located.path)).length > 0) {
5293
+ throw new GitError(
5294
+ "UnsafeRepoConfig",
5295
+ `Refusing untrusted repository ${label}: ${located.path} defines remotes outside its configuration`,
5296
+ where
5297
+ );
5298
+ }
5299
+ }
5300
+ }
5301
+ function stripLineBreak(output) {
5302
+ const line = output.endsWith("\n") ? output.slice(0, -1) : output;
5303
+ return process.platform === "win32" && line.endsWith("\r") ? line.slice(0, -1) : line;
5304
+ }
5305
+ async function revParsePath(runner, context, args) {
5306
+ const result = await runner.run(context, ["rev-parse", ...args]);
5307
+ return {
5308
+ exitCode: result.exitCode,
5309
+ stderr: result.stderr,
5310
+ path: stripLineBreak(result.stdout)
5311
+ };
5312
+ }
5313
+ async function assertDataOnlySubmoduleConfigs(runner, fs, workdir, label, expectedTop) {
5314
+ const context = { type: "worktree", workdir };
5315
+ const topResult = await revParsePath(runner, context, ["--show-toplevel"]);
5316
+ const gitDirResult = await revParsePath(runner, context, ["--absolute-git-dir"]);
5317
+ const index = await runner.run(context, ["ls-files", "--stage", "-z", "--full-name", "--", ":/"]);
5318
+ const failed = [topResult, gitDirResult, index].find((result) => result.exitCode !== 0);
5319
+ if (failed !== void 0) {
5320
+ throw new GitError(
5321
+ "UnsafeRepoConfig",
5322
+ `Could not list the submodules of untrusted repository ${label}`,
5323
+ { workdir, exitCode: failed.exitCode, stderr: failed.stderr }
5324
+ );
5325
+ }
5326
+ const top = topResult.path;
5327
+ const gitDir = gitDirResult.path;
5328
+ if (expectedTop !== void 0 && top !== expectedTop) {
5329
+ throw new GitError(
5330
+ "UnsafeRepoConfig",
5331
+ `Refusing untrusted repository ${label}: its core.worktree points at ${top}`,
5332
+ { workdir }
5333
+ );
5334
+ }
5335
+ for (const entry of index.stdout.split("\0")) {
5336
+ const tab = entry.indexOf(" ");
5337
+ if (tab === -1 || !entry.startsWith("160000 ")) {
5338
+ continue;
5339
+ }
5340
+ const subpath = entry.slice(tab + 1);
5341
+ const subdir = `${top}/${subpath}`;
5342
+ if ((await listDirectory(fs, subdir)).length === 0) {
5343
+ continue;
5344
+ }
5345
+ const sublabel = `${label} (submodule ${subpath})`;
5346
+ const subContext = { type: "worktree", workdir: subdir };
5347
+ const subGitDir = await revParsePath(runner, subContext, ["--absolute-git-dir"]);
5348
+ if (subGitDir.exitCode !== 0) {
5349
+ throw new GitError(
5350
+ "UnsafeRepoConfig",
5351
+ `Could not open submodule of untrusted repository ${sublabel}`,
5352
+ { workdir: subdir, exitCode: subGitDir.exitCode, stderr: subGitDir.stderr }
5353
+ );
5354
+ }
5355
+ if (subGitDir.path === gitDir) {
5356
+ continue;
5357
+ }
5358
+ await assertDataOnlyRepoConfig(runner, fs, subContext, sublabel, true);
5359
+ await assertDataOnlySubmoduleConfigs(runner, fs, subdir, sublabel, subdir);
5360
+ }
5361
+ }
5362
+ function gitDirRefusal(path, exitCode, stderr) {
5363
+ return new GitError(
5364
+ "NonZeroExit",
5365
+ `Not a worktree or bare repository: ${path}. In untrusted mode, open a worktree by its top-level directory, not its .git directory`,
5366
+ { exitCode, stderr }
5367
+ );
5368
+ }
4966
5369
  var GitImpl = class {
4967
5370
  runner;
4968
5371
  adapters;
@@ -5033,10 +5436,21 @@ var GitImpl = class {
5033
5436
  * Returns either WorktreeRepo or BareRepo depending on the repository type.
5034
5437
  */
5035
5438
  async openRaw(path, opts) {
5439
+ if (opts?.untrusted === true) {
5440
+ const version = await this.version();
5441
+ if (compareVersions(version, UNTRUSTED_REPO_MIN_GIT_VERSION) < 0) {
5442
+ throw new GitError(
5443
+ "UnsupportedGitVersion",
5444
+ `untrusted: true needs Git ${UNTRUSTED_REPO_MIN_GIT_VERSION} or later (found ${version})`
5445
+ );
5446
+ }
5447
+ }
5036
5448
  const repoRunner = opts ? this.runner.withOptions(toCliRunnerOptions(opts)) : this.runner;
5449
+ const untrusted = opts?.untrusted === true;
5037
5450
  const result = await repoRunner.run({ type: "worktree", workdir: path }, [
5038
5451
  "rev-parse",
5039
- "--is-bare-repository"
5452
+ "--is-bare-repository",
5453
+ ...untrusted ? ["--is-inside-git-dir"] : []
5040
5454
  ]);
5041
5455
  if (result.exitCode !== 0) {
5042
5456
  const bareResult = await repoRunner.run({ type: "bare", gitDir: path }, [
@@ -5050,10 +5464,36 @@ var GitImpl = class {
5050
5464
  });
5051
5465
  }
5052
5466
  if (bareResult.stdout.trim() === "true") {
5467
+ if (opts?.untrusted === true) {
5468
+ await assertDataOnlyRepoConfig(
5469
+ repoRunner,
5470
+ this.adapters.fs,
5471
+ { type: "bare", gitDir: path },
5472
+ path
5473
+ );
5474
+ }
5053
5475
  return new BareRepoImpl(repoRunner, path, opts);
5054
5476
  }
5477
+ if (untrusted) {
5478
+ throw gitDirRefusal(path, result.exitCode, result.stderr);
5479
+ }
5480
+ }
5481
+ const [bareLine, insideGitDirLine] = result.stdout.trim().split(/\r?\n/);
5482
+ const isBare = bareLine === "true";
5483
+ if (untrusted && !isBare && insideGitDirLine === "true") {
5484
+ throw gitDirRefusal(path, result.exitCode, result.stderr);
5485
+ }
5486
+ if (untrusted) {
5487
+ await assertDataOnlyRepoConfig(
5488
+ repoRunner,
5489
+ this.adapters.fs,
5490
+ isBare ? { type: "bare", gitDir: path } : { type: "worktree", workdir: path },
5491
+ path
5492
+ );
5493
+ if (!isBare) {
5494
+ await assertDataOnlySubmoduleConfigs(repoRunner, this.adapters.fs, path, path);
5495
+ }
5055
5496
  }
5056
- const isBare = result.stdout.trim() === "true";
5057
5497
  if (isBare) {
5058
5498
  return new BareRepoImpl(repoRunner, path, opts);
5059
5499
  }