plugin-git-manager 1.4.0 → 1.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/dist/client/317.e7b1d59371812c30.js +10 -0
  2. package/dist/client/434.05d0ba2b821105dc.js +10 -0
  3. package/dist/client/453.cdcba6d2d0c9522b.js +10 -0
  4. package/dist/client/454.625da741a7e1161f.js +10 -0
  5. package/dist/client/index.js +1 -1
  6. package/dist/client-v2/317.4e116f84ed9081b6.js +10 -0
  7. package/dist/client-v2/434.764113d20743a45b.js +10 -0
  8. package/dist/client-v2/453.5ab80c06d8e61a7e.js +10 -0
  9. package/dist/client-v2/454.b885b1d35ef7ff72.js +10 -0
  10. package/dist/client-v2/index.js +1 -1
  11. package/dist/locale/en-US.json +12 -1
  12. package/dist/locale/vi-VN.json +12 -1
  13. package/dist/locale/zh-CN.json +12 -1
  14. package/dist/node_modules/simple-git/package.json +1 -1
  15. package/dist/node_modules/zod/package.json +1 -1
  16. package/dist/server/actions/git-actions.js +299 -87
  17. package/dist/server/actions/gitlab-api.js +19 -12
  18. package/dist/server/actions/subtree.js +20 -10
  19. package/dist/server/plugin.js +134 -10
  20. package/dist/server/repository-access.js +2 -2
  21. package/dist/server/request-method-policy.js +2 -1
  22. package/dist/server/services/review-source.js +2 -1
  23. package/dist/server/utils/cluster-git.js +181 -0
  24. package/package.json +2 -2
  25. package/src/client/__tests__/FileExplorerAndManage.test.tsx +236 -0
  26. package/src/client/__tests__/workflowRoutes.test.ts +3 -1
  27. package/src/client/components/CommitHistory.tsx +19 -7
  28. package/src/client/components/FileExplorer.tsx +80 -34
  29. package/src/client/components/GitManagerSettings.tsx +21 -5
  30. package/src/client/components/GitOperations.tsx +25 -4
  31. package/src/client/components/GitRuntimeBanner.tsx +97 -0
  32. package/src/client/components/RepositoryConfig.tsx +28 -6
  33. package/src/client/context/GitManagerContext.tsx +156 -13
  34. package/src/client/workflowRoutes.ts +11 -0
  35. package/src/locale/en-US.json +12 -1
  36. package/src/locale/vi-VN.json +12 -1
  37. package/src/locale/zh-CN.json +12 -1
  38. package/src/server/__tests__/git-actions.test.ts +329 -4
  39. package/src/server/__tests__/smoke.test.ts +32 -1
  40. package/src/server/actions/git-actions.ts +322 -96
  41. package/src/server/actions/gitlab-api.ts +20 -14
  42. package/src/server/actions/subtree.ts +23 -6
  43. package/src/server/plugin.ts +152 -3
  44. package/src/server/repository-access.ts +2 -2
  45. package/src/server/request-method-policy.ts +1 -0
  46. package/src/server/services/review-source.ts +3 -2
  47. package/src/server/utils/cluster-git.ts +209 -0
  48. package/dist/client/317.2d0d33871e24ee24.js +0 -10
  49. package/dist/client/434.2401f7257495b66e.js +0 -10
  50. package/dist/client/453.58657b9ba0904477.js +0 -10
  51. package/dist/client-v2/317.d2466574d00f94d0.js +0 -10
  52. package/dist/client-v2/434.32b0a07b821b9329.js +0 -10
  53. package/dist/client-v2/453.f9a0ec6d8e1bd1cc.js +0 -10
@@ -37,6 +37,8 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
37
37
  var git_actions_exports = {};
38
38
  __export(git_actions_exports, {
39
39
  acquireLock: () => acquireLock,
40
+ assertGitAvailable: () => assertGitAvailable,
41
+ assertLocalGitReady: () => assertLocalGitReady,
40
42
  branches: () => branches,
41
43
  checkout: () => checkout,
42
44
  clone: () => clone,
@@ -47,21 +49,31 @@ __export(git_actions_exports, {
47
49
  fetch: () => fetch,
48
50
  fileContent: () => fileContent,
49
51
  fileTree: () => fileTree,
52
+ getGit: () => getGit,
50
53
  getGitBinaryPath: () => getGitBinaryPath,
54
+ getGitMissingMessage: () => getGitMissingMessage,
51
55
  getRepo: () => getRepo,
56
+ installGit: () => installGit,
57
+ isGitAvailable: () => isGitAvailable,
52
58
  log: () => log,
53
59
  pull: () => pull,
54
60
  push: () => push,
55
61
  readChatCommit: () => readChatCommit,
62
+ resetGitBinaryCacheForTests: () => resetGitBinaryCacheForTests,
63
+ resolveGitBinary: () => resolveGitBinary,
64
+ runtimeStatus: () => runtimeStatus,
56
65
  status: () => status,
57
66
  validateBranch: () => validateBranch,
58
67
  validateLocalPath: () => validateLocalPath,
59
68
  validateRef: () => validateRef,
69
+ validateRepoRelativePath: () => validateRepoRelativePath,
60
70
  validateRepoUrl: () => validateRepoUrl,
61
- withAuth: () => withAuth
71
+ withAuth: () => withAuth,
72
+ withRepoLock: () => withRepoLock
62
73
  });
63
74
  module.exports = __toCommonJS(git_actions_exports);
64
75
  var import_simple_git = __toESM(require("simple-git"));
76
+ var import_crypto = require("crypto");
65
77
  var path = __toESM(require("path"));
66
78
  var fs = __toESM(require("fs"));
67
79
  var import_child_process = require("child_process");
@@ -69,10 +81,12 @@ var import_repository_access = require("../repository-access");
69
81
  var import_redact = require("../utils/redact");
70
82
  var import_get_repo_account = require("../utils/get-repo-account");
71
83
  var import_url_security = require("../utils/url-security");
84
+ var import_cluster_git = require("../utils/cluster-git");
72
85
  const REF_PATTERN = /^(?!-)[a-zA-Z0-9._/-]+$/;
86
+ const FALLBACK_GIT_PATHS = ["git", "/usr/bin/git", "/usr/local/bin/git", "/bin/git"];
87
+ const REPO_LOCK_TTL_MS = 5 * 60 * 1e3;
73
88
  const repoLocks = /* @__PURE__ */ new Map();
74
- const GIT_BINARY = process.env.GIT_BINARY_PATH || process.env.GIT_EXECUTABLE || "git";
75
- let gitAvailabilityChecked = false;
89
+ let cachedGitBinary = null;
76
90
  function getGitActionParams(ctx) {
77
91
  return (0, import_repository_access.getEffectiveActionParams)(ctx);
78
92
  }
@@ -119,24 +133,57 @@ function validateRepoUrl(repoUrl) {
119
133
  throw new Error("Only HTTPS repository URLs are allowed");
120
134
  }
121
135
  }
122
- async function withAuth(git, localPath, repoUrl, pat, fn, username, remoteName = "origin") {
123
- validateRepoUrl(repoUrl);
124
- const lock = acquireLock(localPath);
125
- await lock.promise;
136
+ async function withRepoLock(localPath, fn, lockManager) {
137
+ const runLocal = async () => {
138
+ const lock = acquireLock(localPath);
139
+ await lock.promise;
140
+ try {
141
+ return await fn();
142
+ } finally {
143
+ lock.release();
144
+ }
145
+ };
146
+ if (lockManager == null ? void 0 : lockManager.runExclusive) {
147
+ const lockKey = `git-repo:${(0, import_crypto.createHash)("sha256").update(localPath).digest("hex")}`;
148
+ return lockManager.runExclusive(lockKey, runLocal, REPO_LOCK_TTL_MS);
149
+ }
150
+ return runLocal();
151
+ }
152
+ function validateRepoRelativePath(rawPath, label = "file path") {
153
+ if (rawPath.includes("\0")) {
154
+ throw new Error(`Invalid ${label}`);
155
+ }
156
+ const normalized = rawPath.replace(/\\/g, "/").replace(/^\/+|\/+$/g, "");
157
+ if (!normalized || /^[a-zA-Z]:\//.test(normalized)) {
158
+ throw new Error(`Invalid ${label}`);
159
+ }
160
+ if (normalized.split("/").some((segment) => !segment || segment === "." || segment === "..")) {
161
+ throw new Error(`Invalid ${label}`);
162
+ }
163
+ return normalized;
164
+ }
165
+ async function runAuthenticatedGitUnlocked(git, repoUrl, pat, fn, username, remoteName = "origin") {
126
166
  try {
127
167
  git.env(credentialEnvironment(repoUrl, pat, username));
128
- await git.remote(["set-url", remoteName, repoUrl]);
168
+ const currentUrl = typeof git.raw === "function" ? (await git.raw(["config", "--get", `remote.${remoteName}.url`]).catch(() => "")).trim() : "";
169
+ if (currentUrl !== repoUrl) {
170
+ await git.remote(["set-url", remoteName, repoUrl]);
171
+ }
129
172
  return await fn();
130
173
  } catch (error) {
131
174
  throw redactGitCredentialError(error, pat, username);
132
175
  } finally {
133
- try {
134
- git.env(gitProcessEnvironment());
135
- } finally {
136
- lock.release();
137
- }
176
+ git.env(gitProcessEnvironment());
138
177
  }
139
178
  }
179
+ async function withAuth(git, localPath, repoUrl, pat, fn, username, remoteName = "origin", lockManager) {
180
+ validateRepoUrl(repoUrl);
181
+ return withRepoLock(
182
+ localPath,
183
+ () => runAuthenticatedGitUnlocked(git, repoUrl, pat, fn, username, remoteName),
184
+ lockManager
185
+ );
186
+ }
140
187
  function gitProcessEnvironment() {
141
188
  const env = { ...process.env };
142
189
  for (const key of Object.keys(env)) {
@@ -175,16 +222,82 @@ function redactGitCredentialError(error, pat, username) {
175
222
  }
176
223
  return (0, import_redact.redactError)(new Error(safeMessage));
177
224
  }
178
- function getGitMissingMessage() {
179
- return `Git executable "${GIT_BINARY}" was not found on the server. Install git in the app/worker container, or set GIT_BINARY_PATH to the absolute git binary path.`;
225
+ function configuredGitBinary() {
226
+ return (process.env.GIT_BINARY_PATH || process.env.GIT_EXECUTABLE || "").trim();
180
227
  }
181
- function assertGitAvailable(ctx) {
182
- if (gitAvailabilityChecked) return;
183
- const check = (0, import_child_process.spawnSync)(GIT_BINARY, ["--version"], { stdio: "ignore" });
184
- if (check.error || check.status !== 0) {
185
- ctx.throw(503, getGitMissingMessage());
228
+ function canExecuteGit(binary) {
229
+ if (path.isAbsolute(binary) && !fs.existsSync(binary)) {
230
+ return false;
186
231
  }
187
- gitAvailabilityChecked = true;
232
+ const check = (0, import_child_process.spawnSync)(binary, ["--version"], { stdio: "ignore" });
233
+ return !check.error && check.status === 0;
234
+ }
235
+ function resolveGitBinary() {
236
+ const configured = configuredGitBinary();
237
+ if (cachedGitBinary && cachedGitBinary.envValue === configured && (!path.isAbsolute(cachedGitBinary.binary) || fs.existsSync(cachedGitBinary.binary)) && canExecuteGit(cachedGitBinary.binary)) {
238
+ return cachedGitBinary.binary;
239
+ }
240
+ cachedGitBinary = null;
241
+ const candidates = configured ? [configured] : FALLBACK_GIT_PATHS;
242
+ for (const candidate of candidates) {
243
+ if (canExecuteGit(candidate)) {
244
+ cachedGitBinary = { envValue: configured, binary: candidate };
245
+ return candidate;
246
+ }
247
+ }
248
+ return null;
249
+ }
250
+ function resetGitBinaryCacheForTests() {
251
+ cachedGitBinary = null;
252
+ }
253
+ function isGitAvailable() {
254
+ return resolveGitBinary() !== null;
255
+ }
256
+ function getGitMissingMessage(clusterStatus) {
257
+ const binary = configuredGitBinary() || "git";
258
+ if ((clusterStatus == null ? void 0 : clusterStatus.available) && clusterStatus.status === "running") {
259
+ return `Git executable "${binary}" is currently being installed via Cluster Manager. Please wait a moment and retry.`;
260
+ }
261
+ if (clusterStatus == null ? void 0 : clusterStatus.available) {
262
+ return `Git executable "${binary}" was not found on the server. Install git via Cluster Manager (Package Installer), or set GIT_BINARY_PATH to the absolute git binary path.`;
263
+ }
264
+ return `Git executable "${binary}" was not found on the server. Install git in the app/worker container, or set GIT_BINARY_PATH to the absolute git binary path.`;
265
+ }
266
+ async function assertGitAvailable(ctx) {
267
+ const binary = resolveGitBinary();
268
+ if (binary) return binary;
269
+ const app = ctx.app;
270
+ const clusterStatus = await (0, import_cluster_git.readClusterGitStatus)(app).catch(() => void 0);
271
+ if ((clusterStatus == null ? void 0 : clusterStatus.available) && clusterStatus.gitConfigured && clusterStatus.previouslyInitialized) {
272
+ (0, import_cluster_git.dispatchClusterGitInstall)(app).catch((err) => {
273
+ var _a, _b;
274
+ (_b = (_a = app == null ? void 0 : app.log) == null ? void 0 : _a.warn) == null ? void 0 : _b.call(_a, "plugin-git-manager: background git restore via Cluster Manager failed", err);
275
+ });
276
+ const refreshedStatus = { ...clusterStatus, status: "running" };
277
+ return ctx.throw(503, getGitMissingMessage(refreshedStatus));
278
+ }
279
+ return ctx.throw(503, getGitMissingMessage(clusterStatus));
280
+ }
281
+ async function assertLocalGitReady(localPath, app) {
282
+ if (!fs.existsSync(localPath)) {
283
+ const missingDirError = Object.assign(
284
+ new Error("Repository directory does not exist. Please clone the repository first."),
285
+ { status: 400 }
286
+ );
287
+ throw missingDirError;
288
+ }
289
+ const binary = resolveGitBinary();
290
+ if (!binary) {
291
+ const clusterStatus = await (0, import_cluster_git.readClusterGitStatus)(app).catch(() => void 0);
292
+ if ((clusterStatus == null ? void 0 : clusterStatus.available) && clusterStatus.gitConfigured && clusterStatus.previouslyInitialized) {
293
+ (0, import_cluster_git.dispatchClusterGitInstall)(app).catch((err) => {
294
+ var _a, _b;
295
+ (_b = (_a = app == null ? void 0 : app.log) == null ? void 0 : _a.warn) == null ? void 0 : _b.call(_a, "plugin-git-manager: background git restore via Cluster Manager failed", err);
296
+ });
297
+ }
298
+ throw Object.assign(new Error(getGitMissingMessage(clusterStatus)), { status: 503 });
299
+ }
300
+ return createGit(localPath);
188
301
  }
189
302
  function isMissingGitError(error) {
190
303
  const message = error instanceof Error ? error.message : String(error);
@@ -193,20 +306,60 @@ function isMissingGitError(error) {
193
306
  function createGit(baseDir) {
194
307
  return (0, import_simple_git.default)({
195
308
  baseDir,
196
- binary: GIT_BINARY,
309
+ binary: getGitBinaryPath(),
197
310
  unsafe: { allowUnsafeConfigEnvCount: true, allowUnsafeCredentialHelper: true }
198
311
  }).env(gitProcessEnvironment());
199
312
  }
200
313
  function getGitBinaryPath() {
201
- return GIT_BINARY;
314
+ return resolveGitBinary() || configuredGitBinary() || "git";
202
315
  }
203
- function getGit(ctx, localPath) {
316
+ async function getGit(ctx, localPath) {
204
317
  if (!fs.existsSync(localPath)) {
205
318
  ctx.throw(400, "Repository directory does not exist. Please clone the repository first.");
206
319
  }
207
- assertGitAvailable(ctx);
320
+ await assertGitAvailable(ctx);
208
321
  return createGit(localPath);
209
322
  }
323
+ async function runtimeStatus(ctx, next) {
324
+ const binary = resolveGitBinary();
325
+ const app = ctx.app;
326
+ const clusterStatus = await (0, import_cluster_git.readClusterGitStatus)(app);
327
+ if (!binary && clusterStatus.available && clusterStatus.gitConfigured && clusterStatus.previouslyInitialized) {
328
+ const restore = await (0, import_cluster_git.dispatchClusterGitInstall)(app).catch(() => ({ dispatched: false }));
329
+ if (restore.dispatched) {
330
+ clusterStatus.status = "running";
331
+ }
332
+ }
333
+ ctx.body = {
334
+ success: true,
335
+ data: {
336
+ gitAvailable: binary !== null,
337
+ gitBinary: binary || configuredGitBinary() || "git",
338
+ clusterManager: {
339
+ available: clusterStatus.available,
340
+ gitConfigured: clusterStatus.gitConfigured,
341
+ status: clusterStatus.status,
342
+ progressPercent: clusterStatus.progressPercent
343
+ }
344
+ }
345
+ };
346
+ await next();
347
+ }
348
+ async function installGit(ctx, next) {
349
+ const binary = resolveGitBinary();
350
+ if (binary) {
351
+ ctx.body = { success: true, data: { alreadyInstalled: true, gitBinary: binary } };
352
+ await next();
353
+ return;
354
+ }
355
+ const app = ctx.app;
356
+ const result = await (0, import_cluster_git.dispatchClusterGitInstall)(app, { ensureGitInConfig: true });
357
+ if (!result.dispatched && result.reason !== "Cluster package installation is already running") {
358
+ ctx.throw(400, result.reason || "Unable to dispatch git installation via Cluster Manager");
359
+ }
360
+ ctx.body = { success: true, data: { dispatched: true } };
361
+ await next();
362
+ }
210
363
  async function getRepo(ctx, requestedRepositoryId) {
211
364
  const repositoryId = requestedRepositoryId ?? getGitActionParams(ctx).repositoryId;
212
365
  const repo = await ctx.db.getRepository("gitRepositories").findOne({
@@ -258,65 +411,94 @@ async function clone(ctx, next) {
258
411
  const { pat, username } = account;
259
412
  validateRepoUrl(repoUrl);
260
413
  validateBranch(defaultBranch);
261
- if (fs.existsSync(localPath)) {
262
- ctx.throw(400, "Directory already exists. Remove it before cloning again.");
263
- }
264
- if (!fs.existsSync(path.dirname(localPath))) {
265
- fs.mkdirSync(path.dirname(localPath), { recursive: true });
266
- }
267
- assertGitAvailable(ctx);
268
- try {
269
- await createGit().env(credentialEnvironment(repoUrl, pat, username)).clone(repoUrl, localPath, ["--branch", defaultBranch]);
270
- await ctx.db.getRepository("gitRepositories").update({
271
- filterByTk: repo.get("id"),
272
- values: { status: "connected" }
273
- });
274
- ctx.body = { success: true, message: "Repository cloned successfully" };
275
- } catch (err) {
276
- await ctx.db.getRepository("gitRepositories").update({
277
- filterByTk: repo.get("id"),
278
- values: { status: "error" }
279
- });
280
- if (isMissingGitError(err)) {
281
- ctx.throw(503, getGitMissingMessage());
282
- }
283
- throw redactGitCredentialError(err, pat, username);
284
- }
414
+ await assertGitAvailable(ctx);
415
+ const app = ctx.app;
416
+ await withRepoLock(
417
+ localPath,
418
+ async () => {
419
+ if (fs.existsSync(localPath)) {
420
+ const entries = fs.readdirSync(localPath);
421
+ if (entries.length > 0) {
422
+ if (fs.existsSync(path.join(localPath, ".git"))) {
423
+ const existingGit = createGit(localPath);
424
+ const existingOrigin = (await existingGit.raw(["config", "--get", "remote.origin.url"]).catch(() => "")).trim();
425
+ if (existingOrigin === repoUrl) {
426
+ await runAuthenticatedGitUnlocked(existingGit, repoUrl, pat, () => existingGit.fetch(), username);
427
+ await ctx.db.getRepository("gitRepositories").update({
428
+ filterByTk: repo.get("id"),
429
+ values: { status: "connected" }
430
+ });
431
+ ctx.body = { success: true, message: "Repository reconnected successfully" };
432
+ return;
433
+ }
434
+ }
435
+ ctx.throw(400, "Directory already exists. Remove it before cloning again.");
436
+ }
437
+ } else if (!fs.existsSync(path.dirname(localPath))) {
438
+ fs.mkdirSync(path.dirname(localPath), { recursive: true });
439
+ }
440
+ try {
441
+ await createGit().env(credentialEnvironment(repoUrl, pat, username)).clone(repoUrl, localPath, ["--branch", defaultBranch]);
442
+ await ctx.db.getRepository("gitRepositories").update({
443
+ filterByTk: repo.get("id"),
444
+ values: { status: "connected" }
445
+ });
446
+ ctx.body = { success: true, message: "Repository cloned successfully" };
447
+ } catch (err) {
448
+ await ctx.db.getRepository("gitRepositories").update({
449
+ filterByTk: repo.get("id"),
450
+ values: { status: "error" }
451
+ });
452
+ if (isMissingGitError(err) && !isGitAvailable()) {
453
+ const clusterStatus = await (0, import_cluster_git.readClusterGitStatus)(app).catch(() => void 0);
454
+ ctx.throw(503, getGitMissingMessage(clusterStatus));
455
+ }
456
+ throw redactGitCredentialError(err, pat, username);
457
+ }
458
+ },
459
+ app == null ? void 0 : app.lockManager
460
+ );
285
461
  await next();
286
462
  }
287
463
  async function pull(ctx, next) {
464
+ var _a;
288
465
  const repo = await getRepo(ctx);
289
466
  const localPath = validateLocalPath(repo.get("localPath"));
290
467
  const repoUrl = (repo.get("repoUrl") || "").trim();
291
468
  const account = await (0, import_get_repo_account.getRepoAccount)(ctx.db, repo);
292
469
  if (!account) return ctx.throw(400, "Repository has no Git account configured. Please assign a Git account first.");
293
470
  const { pat, username } = account;
294
- const git = getGit(ctx, localPath);
295
- const result = await withAuth(git, localPath, repoUrl, pat, () => git.pull(), username);
471
+ const git = await getGit(ctx, localPath);
472
+ const lockManager = (_a = ctx.app) == null ? void 0 : _a.lockManager;
473
+ const result = await withAuth(git, localPath, repoUrl, pat, () => git.pull(), username, "origin", lockManager);
296
474
  ctx.body = { success: true, data: result };
297
475
  await next();
298
476
  }
299
477
  async function push(ctx, next) {
478
+ var _a;
300
479
  const repo = await getRepo(ctx);
301
480
  const localPath = validateLocalPath(repo.get("localPath"));
302
481
  const repoUrl = (repo.get("repoUrl") || "").trim();
303
482
  const account = await (0, import_get_repo_account.getRepoAccount)(ctx.db, repo);
304
483
  if (!account) return ctx.throw(400, "Repository has no Git account configured. Please assign a Git account first.");
305
484
  const { pat, username } = account;
306
- const git = getGit(ctx, localPath);
307
- const result = await withAuth(git, localPath, repoUrl, pat, () => git.push(), username);
485
+ const git = await getGit(ctx, localPath);
486
+ const lockManager = (_a = ctx.app) == null ? void 0 : _a.lockManager;
487
+ const result = await withAuth(git, localPath, repoUrl, pat, () => git.push(), username, "origin", lockManager);
308
488
  ctx.body = { success: true, data: result };
309
489
  await next();
310
490
  }
311
491
  async function fetch(ctx, next) {
492
+ var _a;
312
493
  const repo = await getRepo(ctx);
313
494
  const localPath = validateLocalPath(repo.get("localPath"));
314
495
  const repoUrl = (repo.get("repoUrl") || "").trim();
315
496
  const account = await (0, import_get_repo_account.getRepoAccount)(ctx.db, repo);
316
497
  if (!account) return ctx.throw(400, "Repository has no Git account configured. Please assign a Git account first.");
317
498
  const { pat, username } = account;
318
- const git = getGit(ctx, localPath);
319
- const result = await withAuth(git, localPath, repoUrl, pat, () => git.fetch(), username);
499
+ const git = await getGit(ctx, localPath);
500
+ const lockManager = (_a = ctx.app) == null ? void 0 : _a.lockManager;
501
+ const result = await withAuth(git, localPath, repoUrl, pat, () => git.fetch(), username, "origin", lockManager);
320
502
  ctx.body = { success: true, data: result };
321
503
  await next();
322
504
  }
@@ -324,7 +506,7 @@ async function diff(ctx, next) {
324
506
  const repo = await getRepo(ctx);
325
507
  const localPath = validateLocalPath(repo.get("localPath"));
326
508
  const { file, commitHash, compareHash } = getGitActionParams(ctx);
327
- const git = getGit(ctx, localPath);
509
+ const git = await getGit(ctx, localPath);
328
510
  const args = [];
329
511
  if (commitHash && compareHash) {
330
512
  args.push(validateRef(commitHash), validateRef(compareHash));
@@ -332,8 +514,13 @@ async function diff(ctx, next) {
332
514
  args.push(validateRef(commitHash) + "^", validateRef(commitHash));
333
515
  }
334
516
  if (file) {
335
- if (file.includes("..")) ctx.throw(400, "Invalid file path");
336
- args.push("--", file);
517
+ let safeFile = "";
518
+ try {
519
+ safeFile = validateRepoRelativePath(file, "file path");
520
+ } catch {
521
+ ctx.throw(400, "Invalid file path");
522
+ }
523
+ args.push("--", safeFile);
337
524
  }
338
525
  const result = await git.diff(args);
339
526
  ctx.body = { success: true, data: result };
@@ -342,7 +529,8 @@ async function diff(ctx, next) {
342
529
  async function status(ctx, next) {
343
530
  const repo = await getRepo(ctx);
344
531
  const localPath = validateLocalPath(repo.get("localPath"));
345
- const result = await getGit(ctx, localPath).status();
532
+ const git = await getGit(ctx, localPath);
533
+ const result = await git.status();
346
534
  ctx.body = { success: true, data: result };
347
535
  await next();
348
536
  }
@@ -351,10 +539,14 @@ async function log(ctx, next) {
351
539
  const localPath = validateLocalPath(repo.get("localPath"));
352
540
  const { maxCount = 50, file, branch, skip } = getGitActionParams(ctx);
353
541
  const parsed = Number.parseInt(String(maxCount), 10);
354
- const options = { maxCount: Math.min(Math.max(parsed || 50, 1), 500) };
542
+ const boundedMaxCount = Math.min(Math.max(parsed || 50, 1), 500);
543
+ let safeFile;
355
544
  if (file) {
356
- if (file.includes("..")) ctx.throw(400, "Invalid file path");
357
- options.file = file;
545
+ try {
546
+ safeFile = validateRepoRelativePath(file, "file path");
547
+ } catch {
548
+ ctx.throw(400, "Invalid file path");
549
+ }
358
550
  }
359
551
  const args = [];
360
552
  if (branch) args.push(validateBranch(branch));
@@ -365,28 +557,29 @@ async function log(ctx, next) {
365
557
  }
366
558
  args.push(`--skip=${parsedSkip}`);
367
559
  }
368
- const result = args.length ? await getGit(ctx, localPath).log([
369
- ...args,
370
- `--max-count=${options.maxCount}`,
371
- ...file ? ["--follow", "--", file] : []
372
- ]) : await getGit(ctx, localPath).log(options);
560
+ const git = await getGit(ctx, localPath);
561
+ const result = args.length || safeFile ? await git.log([...args, `--max-count=${boundedMaxCount}`, ...safeFile ? ["--follow", "--", safeFile] : []]) : await git.log({ maxCount: boundedMaxCount });
373
562
  ctx.body = { success: true, data: result };
374
563
  await next();
375
564
  }
376
565
  async function branches(ctx, next) {
377
566
  const repo = await getRepo(ctx);
378
567
  const localPath = validateLocalPath(repo.get("localPath"));
379
- const result = await getGit(ctx, localPath).branch();
568
+ const git = await getGit(ctx, localPath);
569
+ const result = await git.branch();
380
570
  ctx.body = { success: true, data: result };
381
571
  await next();
382
572
  }
383
573
  async function checkout(ctx, next) {
574
+ var _a;
384
575
  const repo = await getRepo(ctx);
385
576
  const localPath = validateLocalPath(repo.get("localPath"));
386
577
  const { branch } = getGitActionParams(ctx);
387
578
  if (!branch) ctx.throw(400, "branch is required");
388
579
  validateBranch(branch);
389
- await getGit(ctx, localPath).checkout(branch);
580
+ const git = await getGit(ctx, localPath);
581
+ const lockManager = (_a = ctx.app) == null ? void 0 : _a.lockManager;
582
+ await withRepoLock(localPath, () => git.checkout(branch), lockManager);
390
583
  ctx.body = { success: true, message: `Switched to branch ${branch}` };
391
584
  await next();
392
585
  }
@@ -394,15 +587,20 @@ async function fileTree(ctx, next) {
394
587
  const repo = await getRepo(ctx);
395
588
  const localPath = validateLocalPath(repo.get("localPath"));
396
589
  const { ref = "HEAD", treePath = "", recursive } = getGitActionParams(ctx);
397
- const git = getGit(ctx, localPath);
590
+ const git = await getGit(ctx, localPath);
398
591
  validateRef(ref);
399
- if (treePath && treePath.includes("..")) {
400
- ctx.throw(400, "Invalid tree path");
592
+ let safeTreePath = "";
593
+ if (treePath) {
594
+ try {
595
+ safeTreePath = validateRepoRelativePath(treePath, "tree path");
596
+ } catch {
597
+ ctx.throw(400, "Invalid tree path");
598
+ }
401
599
  }
402
- const detailArgs = ["ls-tree", "-l"];
600
+ const detailArgs = ["-c", "core.quotePath=false", "ls-tree", "-l"];
403
601
  if (recursive === true || recursive === "true") detailArgs.push("-r");
404
- detailArgs.push(ref);
405
- if (treePath) detailArgs.push(treePath + "/");
602
+ detailArgs.push(ref, "--");
603
+ if (safeTreePath) detailArgs.push(`${safeTreePath}/`);
406
604
  const detailedResult = await git.raw(detailArgs);
407
605
  const items = detailedResult.trim().split("\n").filter(Boolean).map((line) => {
408
606
  const match = line.match(/^(\d+)\s+(blob|tree)\s+([a-f0-9]+)\s+(-|\d+)\t(.+)$/);
@@ -433,13 +631,16 @@ async function fileContent(ctx, next) {
433
631
  if (!filePath) {
434
632
  ctx.throw(400, "filePath is required");
435
633
  }
436
- if (filePath.includes("..")) {
634
+ let safeFilePath = "";
635
+ try {
636
+ safeFilePath = validateRepoRelativePath(filePath, "file path");
637
+ } catch {
437
638
  ctx.throw(400, "Invalid file path");
438
639
  }
439
640
  validateRef(ref);
440
- const git = getGit(ctx, localPath);
441
- const content = await git.show([`${ref}:${filePath}`]);
442
- ctx.body = { success: true, data: { content, filePath, ref } };
641
+ const git = await getGit(ctx, localPath);
642
+ const content = await git.raw(["-c", "core.quotePath=false", "show", `${ref}:${safeFilePath}`]);
643
+ ctx.body = { success: true, data: { content, filePath: safeFilePath, ref } };
443
644
  await next();
444
645
  }
445
646
  async function commitDetail(ctx, next) {
@@ -449,7 +650,7 @@ async function commitDetail(ctx, next) {
449
650
  if (!commitHash) {
450
651
  ctx.throw(400, "commitHash is required");
451
652
  }
452
- const git = getGit(ctx, localPath);
653
+ const git = await getGit(ctx, localPath);
453
654
  validateRef(commitHash);
454
655
  const DELIM_ARG = "%x00";
455
656
  const DELIM_OUT = "\0";
@@ -486,7 +687,7 @@ async function commitDetail(ctx, next) {
486
687
  }
487
688
  async function readLimitedGitOutput(localPath, args, maxBytes) {
488
689
  return new Promise((resolve, reject) => {
489
- const process2 = (0, import_child_process.spawn)(GIT_BINARY, args, {
690
+ const child = (0, import_child_process.spawn)(getGitBinaryPath(), args, {
490
691
  cwd: localPath,
491
692
  env: gitProcessEnvironment(),
492
693
  windowsHide: true,
@@ -495,7 +696,7 @@ async function readLimitedGitOutput(localPath, args, maxBytes) {
495
696
  const chunks = [];
496
697
  let size = 0;
497
698
  let truncated = false;
498
- process2.stdout.on("data", (chunk) => {
699
+ child.stdout.on("data", (chunk) => {
499
700
  const remaining = maxBytes - size;
500
701
  if (remaining > 0) {
501
702
  const data = chunk.subarray(0, remaining);
@@ -504,11 +705,11 @@ async function readLimitedGitOutput(localPath, args, maxBytes) {
504
705
  }
505
706
  if (chunk.length > remaining) {
506
707
  truncated = true;
507
- process2.kill();
708
+ child.kill();
508
709
  }
509
710
  });
510
- process2.on("error", reject);
511
- process2.on("close", (code) => {
711
+ child.on("error", reject);
712
+ child.on("close", (code) => {
512
713
  if (code !== 0 && !truncated) {
513
714
  reject(new Error("Unable to read commit diff"));
514
715
  return;
@@ -522,7 +723,7 @@ async function readChatCommit(ctx, commitHash, maxFiles, maxBytes, repositoryId)
522
723
  if (!/^[a-f\d]{4,64}$/i.test(commitHash)) ctx.throw(400, "Invalid commit hash");
523
724
  const repo = await getRepo(ctx, repositoryId);
524
725
  const localPath = validateLocalPath(repo.get("localPath"));
525
- const git = getGit(ctx, localPath);
726
+ const git = await getGit(ctx, localPath);
526
727
  const hash = (await git.raw(["rev-parse", "--verify", `${commitHash}^{commit}`])).trim();
527
728
  const [metadata, parentLine] = await Promise.all([
528
729
  git.raw(["show", "-s", "--format=%H%x00%an%x00%aI%x00%s%x00%b", hash]),
@@ -567,6 +768,8 @@ async function readChatCommit(ctx, commitHash, maxFiles, maxBytes, repositoryId)
567
768
  // Annotate the CommonJS export names for ESM import in node:
568
769
  0 && (module.exports = {
569
770
  acquireLock,
771
+ assertGitAvailable,
772
+ assertLocalGitReady,
570
773
  branches,
571
774
  checkout,
572
775
  clone,
@@ -577,16 +780,25 @@ async function readChatCommit(ctx, commitHash, maxFiles, maxBytes, repositoryId)
577
780
  fetch,
578
781
  fileContent,
579
782
  fileTree,
783
+ getGit,
580
784
  getGitBinaryPath,
785
+ getGitMissingMessage,
581
786
  getRepo,
787
+ installGit,
788
+ isGitAvailable,
582
789
  log,
583
790
  pull,
584
791
  push,
585
792
  readChatCommit,
793
+ resetGitBinaryCacheForTests,
794
+ resolveGitBinary,
795
+ runtimeStatus,
586
796
  status,
587
797
  validateBranch,
588
798
  validateLocalPath,
589
799
  validateRef,
800
+ validateRepoRelativePath,
590
801
  validateRepoUrl,
591
- withAuth
802
+ withAuth,
803
+ withRepoLock
592
804
  });