@omercnet/paseo-pr-radar 3.2.3 → 3.3.0-next.529.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +13 -3
- package/client/agent-launch-options.tsx +416 -0
- package/client/directory-observation.ts +53 -9
- package/client/highlight.ts +24 -0
- package/client/highlighted-text.tsx +27 -0
- package/client/pr-radar.tsx +609 -167
- package/client/radar.ts +326 -5
- package/client/screen-state.ts +20 -0
- package/client/settings-screen.tsx +290 -0
- package/client/start-agent-modal.tsx +691 -0
- package/client/use-radar.ts +6 -2
- package/examples/pr-radar-route.py +55 -0
- package/index.client.tsx +13 -2
- package/index.server.ts +26 -1
- package/package.json +6 -5
- package/paseo-plugin.json +1 -1
- package/server/viewer-scope.ts +164 -6
- package/server/workspace-ops.ts +1464 -0
- package/shared/settings.ts +68 -0
- package/shared/viewer-scope.ts +87 -0
|
@@ -0,0 +1,1464 @@
|
|
|
1
|
+
import { type ChildProcessByStdio, execFile, spawn } from "node:child_process";
|
|
2
|
+
import { constants } from "node:fs";
|
|
3
|
+
import { access, mkdir, readdir, realpath, stat } from "node:fs/promises";
|
|
4
|
+
import { homedir } from "node:os";
|
|
5
|
+
import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path";
|
|
6
|
+
import type { Readable, Writable } from "node:stream";
|
|
7
|
+
import { promisify } from "node:util";
|
|
8
|
+
import type { z } from "zod";
|
|
9
|
+
import type { PrRadarSettings } from "../shared/settings";
|
|
10
|
+
import {
|
|
11
|
+
type LocalDirEntry,
|
|
12
|
+
type listLocalDirs,
|
|
13
|
+
type prepareWorkspaceCwd,
|
|
14
|
+
RoutingScriptResultSchema,
|
|
15
|
+
type runRoutingScript,
|
|
16
|
+
} from "../shared/viewer-scope";
|
|
17
|
+
|
|
18
|
+
const execFileAsync = promisify(execFile);
|
|
19
|
+
const COMMAND_TIMEOUT_MS = 30_000;
|
|
20
|
+
const CLONE_TIMEOUT_MS = 120_000;
|
|
21
|
+
const MAX_BUFFER_BYTES = 8 * 1024 * 1024;
|
|
22
|
+
|
|
23
|
+
/** The server-side settings the handlers trust; RPC input never supplies these paths. */
|
|
24
|
+
export type WorkspaceOpsSettings = Pick<PrRadarSettings, "sourceCodeDir" | "routingScriptPath">;
|
|
25
|
+
export type ReadWorkspaceSettings = () => Promise<WorkspaceOpsSettings>;
|
|
26
|
+
|
|
27
|
+
export interface RoutingScriptLimits {
|
|
28
|
+
timeoutMs: number;
|
|
29
|
+
outputBytes: number;
|
|
30
|
+
killGraceMs: number;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
const DEFAULT_ROUTING_LIMITS: RoutingScriptLimits = {
|
|
34
|
+
timeoutMs: COMMAND_TIMEOUT_MS,
|
|
35
|
+
outputBytes: 1024 * 1024,
|
|
36
|
+
killGraceMs: 2_000,
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
// Environment handed to child processes. Everything else in the daemon's environment (API keys,
|
|
40
|
+
// cloud credentials, tokens for other tools) stays behind. A routing script gets only what a
|
|
41
|
+
// script needs to find its interpreter and locale. gh additionally needs its own credentials and
|
|
42
|
+
// config location (GH_TOKEN, GITHUB_TOKEN, GH_HOST, GH_CONFIG_DIR, XDG_CONFIG_HOME), the agent
|
|
43
|
+
// socket for ssh remotes, and proxy settings.
|
|
44
|
+
const BASE_ENV_KEYS: ReadonlySet<string> = new Set([
|
|
45
|
+
"PATH",
|
|
46
|
+
"HOME",
|
|
47
|
+
"USER",
|
|
48
|
+
"LOGNAME",
|
|
49
|
+
"TMPDIR",
|
|
50
|
+
"TZ",
|
|
51
|
+
"LANG",
|
|
52
|
+
"LANGUAGE",
|
|
53
|
+
]);
|
|
54
|
+
const GH_ENV_KEYS: ReadonlySet<string> = new Set([
|
|
55
|
+
"GH_TOKEN",
|
|
56
|
+
"GITHUB_TOKEN",
|
|
57
|
+
"GH_ENTERPRISE_TOKEN",
|
|
58
|
+
"GITHUB_ENTERPRISE_TOKEN",
|
|
59
|
+
"GH_HOST",
|
|
60
|
+
"GH_CONFIG_DIR",
|
|
61
|
+
"XDG_CONFIG_HOME",
|
|
62
|
+
"XDG_DATA_HOME",
|
|
63
|
+
"XDG_STATE_HOME",
|
|
64
|
+
"SSH_AUTH_SOCK",
|
|
65
|
+
"DBUS_SESSION_BUS_ADDRESS",
|
|
66
|
+
"XDG_RUNTIME_DIR",
|
|
67
|
+
"SSL_CERT_FILE",
|
|
68
|
+
"SSL_CERT_DIR",
|
|
69
|
+
"GIT_SSL_CAINFO",
|
|
70
|
+
"HTTP_PROXY",
|
|
71
|
+
"HTTPS_PROXY",
|
|
72
|
+
"NO_PROXY",
|
|
73
|
+
"ALL_PROXY",
|
|
74
|
+
"http_proxy",
|
|
75
|
+
"https_proxy",
|
|
76
|
+
"no_proxy",
|
|
77
|
+
"all_proxy",
|
|
78
|
+
]);
|
|
79
|
+
|
|
80
|
+
// git gets only transport and configuration-location variables. GitHub tokens stay gh-only:
|
|
81
|
+
// repository config, credential helpers or transport helpers must not inherit them from the daemon.
|
|
82
|
+
// The gh credential helper (credential.https://github.com.helper) needs gh's config-location vars to
|
|
83
|
+
// find its auth, so those non-token vars are passed too.
|
|
84
|
+
const GIT_ENV_KEYS: ReadonlySet<string> = new Set([
|
|
85
|
+
"GIT_CONFIG_GLOBAL",
|
|
86
|
+
"GIT_CONFIG_SYSTEM",
|
|
87
|
+
"GIT_CONFIG_NOSYSTEM",
|
|
88
|
+
"SSH_AUTH_SOCK",
|
|
89
|
+
"GH_CONFIG_DIR",
|
|
90
|
+
"XDG_CONFIG_HOME",
|
|
91
|
+
"XDG_DATA_HOME",
|
|
92
|
+
"XDG_STATE_HOME",
|
|
93
|
+
"DBUS_SESSION_BUS_ADDRESS",
|
|
94
|
+
"XDG_RUNTIME_DIR",
|
|
95
|
+
"SSL_CERT_FILE",
|
|
96
|
+
"SSL_CERT_DIR",
|
|
97
|
+
"GIT_SSL_CAINFO",
|
|
98
|
+
"HTTP_PROXY",
|
|
99
|
+
"HTTPS_PROXY",
|
|
100
|
+
"NO_PROXY",
|
|
101
|
+
"ALL_PROXY",
|
|
102
|
+
"http_proxy",
|
|
103
|
+
"https_proxy",
|
|
104
|
+
"no_proxy",
|
|
105
|
+
"all_proxy",
|
|
106
|
+
]);
|
|
107
|
+
|
|
108
|
+
function allowListedEnv(extraKeys: ReadonlySet<string>): NodeJS.ProcessEnv {
|
|
109
|
+
const env: NodeJS.ProcessEnv = {};
|
|
110
|
+
for (const [key, value] of Object.entries(process.env)) {
|
|
111
|
+
if (value === undefined) continue;
|
|
112
|
+
if (BASE_ENV_KEYS.has(key) || key.startsWith("LC_") || extraKeys.has(key)) env[key] = value;
|
|
113
|
+
}
|
|
114
|
+
return env;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
export function expandUserPath(rawPath: string): string {
|
|
118
|
+
const trimmed = rawPath.trim();
|
|
119
|
+
if (trimmed === "~") return homedir();
|
|
120
|
+
if (trimmed.startsWith("~/")) return join(homedir(), trimmed.slice(2));
|
|
121
|
+
return resolve(trimmed);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
async function exists(target: string): Promise<boolean> {
|
|
125
|
+
try {
|
|
126
|
+
await access(target);
|
|
127
|
+
return true;
|
|
128
|
+
} catch {
|
|
129
|
+
return false;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
async function isGitRepo(dir: string): Promise<boolean> {
|
|
134
|
+
return exists(join(dir, ".git"));
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
// Hooks and transport helpers can come from repository config, and a checked-out PR is untrusted:
|
|
138
|
+
// every git call switches off hooks/fsmonitor and neutralizes command-running config that can spawn
|
|
139
|
+
// helper processes during fetch, checkout, diff/status or credential lookup.
|
|
140
|
+
const GIT_SAFETY_ARGS = [
|
|
141
|
+
"-c",
|
|
142
|
+
"core.hooksPath=/dev/null",
|
|
143
|
+
"-c",
|
|
144
|
+
"core.fsmonitor=false",
|
|
145
|
+
"-c",
|
|
146
|
+
"core.sshCommand=ssh -oBatchMode=yes",
|
|
147
|
+
"-c",
|
|
148
|
+
"core.askPass=/bin/false",
|
|
149
|
+
"-c",
|
|
150
|
+
"credential.helper=",
|
|
151
|
+
"-c",
|
|
152
|
+
"credential.https://github.com.helper=!gh auth git-credential",
|
|
153
|
+
"-c",
|
|
154
|
+
"credential.username=",
|
|
155
|
+
"-c",
|
|
156
|
+
"credential.https://github.com.username=",
|
|
157
|
+
"-c",
|
|
158
|
+
"core.gitProxy=",
|
|
159
|
+
"-c",
|
|
160
|
+
"protocol.ext.allow=never",
|
|
161
|
+
"-c",
|
|
162
|
+
"core.pager=cat",
|
|
163
|
+
"-c",
|
|
164
|
+
"diff.external=",
|
|
165
|
+
"-c",
|
|
166
|
+
"filter.lfs.clean=",
|
|
167
|
+
"-c",
|
|
168
|
+
"filter.lfs.smudge=",
|
|
169
|
+
"-c",
|
|
170
|
+
"filter.lfs.process=",
|
|
171
|
+
"-c",
|
|
172
|
+
"filter.lfs.required=false",
|
|
173
|
+
"-c",
|
|
174
|
+
"http.sslVerify=true",
|
|
175
|
+
"-c",
|
|
176
|
+
"core.alternaterefscommand=",
|
|
177
|
+
"-c",
|
|
178
|
+
"submodule.recurse=false",
|
|
179
|
+
"-c",
|
|
180
|
+
"fetch.recurseSubmodules=false",
|
|
181
|
+
"-c",
|
|
182
|
+
"fetch.bundleURI=",
|
|
183
|
+
"-c",
|
|
184
|
+
"hook.post-checkout.enabled=false",
|
|
185
|
+
"-c",
|
|
186
|
+
"hook.reference-transaction.enabled=false",
|
|
187
|
+
];
|
|
188
|
+
|
|
189
|
+
function withSanitizedPath(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv {
|
|
190
|
+
const path = env.PATH;
|
|
191
|
+
if (path === undefined) return env;
|
|
192
|
+
const sanitized = path
|
|
193
|
+
.split(":")
|
|
194
|
+
.filter((entry) => entry && isAbsolute(entry))
|
|
195
|
+
.join(":");
|
|
196
|
+
return { ...env, PATH: sanitized };
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
function gitEnv(): NodeJS.ProcessEnv {
|
|
200
|
+
return withSanitizedPath({
|
|
201
|
+
...allowListedEnv(GIT_ENV_KEYS),
|
|
202
|
+
GIT_CONFIG_GLOBAL: "/dev/null",
|
|
203
|
+
GIT_CONFIG_NOSYSTEM: "1",
|
|
204
|
+
GIT_ALLOW_PROTOCOL: "file:ssh:https:http",
|
|
205
|
+
GIT_ASKPASS: "/bin/false",
|
|
206
|
+
SSH_ASKPASS: "/bin/false",
|
|
207
|
+
GIT_SSH_COMMAND: "ssh -oBatchMode=yes",
|
|
208
|
+
GIT_TERMINAL_PROMPT: "0",
|
|
209
|
+
});
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
interface FilterOverride {
|
|
213
|
+
key: string;
|
|
214
|
+
value: string;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
async function configuredFilterSafetyArgs(cwd: string): Promise<FilterOverride[]> {
|
|
218
|
+
let raw: Buffer = Buffer.alloc(0);
|
|
219
|
+
try {
|
|
220
|
+
const result = await execFileAsync(
|
|
221
|
+
"git",
|
|
222
|
+
[
|
|
223
|
+
...GIT_SAFETY_ARGS,
|
|
224
|
+
"-C",
|
|
225
|
+
cwd,
|
|
226
|
+
"config",
|
|
227
|
+
"--null",
|
|
228
|
+
"--name-only",
|
|
229
|
+
"--get-regexp",
|
|
230
|
+
"^(filter|hook)\\.",
|
|
231
|
+
],
|
|
232
|
+
{ timeout: 3_000, maxBuffer: MAX_BUFFER_BYTES, env: gitEnv(), encoding: "buffer" },
|
|
233
|
+
);
|
|
234
|
+
raw = result.stdout as Buffer;
|
|
235
|
+
} catch (err) {
|
|
236
|
+
// `git config --get-regexp` exits 1 when nothing matches; only that counts as "no filters".
|
|
237
|
+
// A timeout, buffer overflow or other failure must fail closed, not let repo filters run.
|
|
238
|
+
const code =
|
|
239
|
+
err && typeof err === "object" && "code" in err
|
|
240
|
+
? (err as { code?: unknown }).code
|
|
241
|
+
: undefined;
|
|
242
|
+
if (code !== 1) {
|
|
243
|
+
throw new Error(
|
|
244
|
+
`Could not enumerate repository filter configuration in ${cwd}: ${errorMessage(err)}`,
|
|
245
|
+
);
|
|
246
|
+
}
|
|
247
|
+
raw = Buffer.alloc(0);
|
|
248
|
+
}
|
|
249
|
+
const stdout = raw.toString("utf8");
|
|
250
|
+
// Re-encoding must reproduce the raw bytes; a mismatch means invalid UTF-8 in a filter name,
|
|
251
|
+
// which a lossy decode would mangle into a different key and leave the real command active.
|
|
252
|
+
if (!Buffer.from(stdout, "utf8").equals(raw)) {
|
|
253
|
+
throw new Error(
|
|
254
|
+
`Could not enumerate repository filter configuration in ${cwd}: filter names contain invalid UTF-8.`,
|
|
255
|
+
);
|
|
256
|
+
}
|
|
257
|
+
const overrides: FilterOverride[] = [];
|
|
258
|
+
for (const key of stdout.split("\0")) {
|
|
259
|
+
let value: string | null = null;
|
|
260
|
+
if (/^filter\.[\s\S]*\.(clean|smudge|process|required)$/.test(key)) {
|
|
261
|
+
value = key.endsWith(".required") ? "false" : "";
|
|
262
|
+
} else if (/^hook\.[\s\S]*\.(command|event|enabled)$/.test(key)) {
|
|
263
|
+
value = key.endsWith(".enabled") ? "false" : "";
|
|
264
|
+
}
|
|
265
|
+
if (value !== null) overrides.push({ key, value });
|
|
266
|
+
}
|
|
267
|
+
return overrides;
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
async function runGit(cwd: string, args: string[], timeout = COMMAND_TIMEOUT_MS): Promise<string> {
|
|
271
|
+
const filterOverrides = await configuredFilterSafetyArgs(cwd);
|
|
272
|
+
const env = gitEnv();
|
|
273
|
+
// Filter keys are passed losslessly through GIT_CONFIG_KEY_n/GIT_CONFIG_VALUE_n rather than
|
|
274
|
+
// `-c key=value`, whose `=` parsing mis-parses subsection names that contain `=` (e.g.
|
|
275
|
+
// `filter.evil=x.clean`). Environment pairs override config files but not `-c`, which is fine.
|
|
276
|
+
if (filterOverrides.length > 0) {
|
|
277
|
+
env.GIT_CONFIG_COUNT = String(filterOverrides.length);
|
|
278
|
+
for (const [index, override] of filterOverrides.entries()) {
|
|
279
|
+
env[`GIT_CONFIG_KEY_${index}`] = override.key;
|
|
280
|
+
env[`GIT_CONFIG_VALUE_${index}`] = override.value;
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
const { stdout } = await execFileAsync("git", [...GIT_SAFETY_ARGS, "-C", cwd, ...args], {
|
|
284
|
+
timeout,
|
|
285
|
+
maxBuffer: MAX_BUFFER_BYTES,
|
|
286
|
+
env,
|
|
287
|
+
});
|
|
288
|
+
return stdout.trim();
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/** The environment gh runs with; the viewer queries use it too. */
|
|
292
|
+
export function ghEnv(): NodeJS.ProcessEnv {
|
|
293
|
+
return withSanitizedPath({ ...allowListedEnv(GH_ENV_KEYS), GIT_TERMINAL_PROMPT: "0" });
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
async function cloneGitHubRepo(repository: string, targetDir: string): Promise<void> {
|
|
297
|
+
const cloneUrl = `https://github.com/${repository}.git`;
|
|
298
|
+
await runGit(
|
|
299
|
+
dirname(targetDir),
|
|
300
|
+
["clone", "--no-checkout", "--", cloneUrl, targetDir],
|
|
301
|
+
CLONE_TIMEOUT_MS,
|
|
302
|
+
);
|
|
303
|
+
await runGit(targetDir, ["checkout", "--force"], CLONE_TIMEOUT_MS);
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
function isInside(base: string, target: string): boolean {
|
|
307
|
+
const rel = relative(base, target);
|
|
308
|
+
return rel !== "" && !rel.startsWith("..") && !isAbsolute(rel);
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
/** realpath of the nearest existing ancestor plus the not-yet-existing remainder. */
|
|
312
|
+
async function realpathLoose(target: string): Promise<string> {
|
|
313
|
+
const missing: string[] = [];
|
|
314
|
+
let current = resolve(target);
|
|
315
|
+
for (;;) {
|
|
316
|
+
try {
|
|
317
|
+
return join(await realpath(current), ...missing.reverse());
|
|
318
|
+
} catch {
|
|
319
|
+
const parent = dirname(current);
|
|
320
|
+
if (parent === current) return resolve(target);
|
|
321
|
+
missing.push(basename(current));
|
|
322
|
+
current = parent;
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
async function assertInsideSourceDir(
|
|
328
|
+
realSourceDir: string,
|
|
329
|
+
target: string,
|
|
330
|
+
label: string,
|
|
331
|
+
): Promise<void> {
|
|
332
|
+
if (!isInside(realSourceDir, await realpathLoose(target))) {
|
|
333
|
+
throw new Error(`${label} ${target} is outside the configured source directory.`);
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
function repoParts(repository: string): { owner: string; name: string } {
|
|
338
|
+
const [owner = "", name = ""] = repository.split("/");
|
|
339
|
+
return { owner, name };
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
export function slugifyBranch(branch: string): string {
|
|
343
|
+
return branch
|
|
344
|
+
.toLowerCase()
|
|
345
|
+
.replace(/[^a-z0-9]+/g, "-")
|
|
346
|
+
.replace(/^-+|-+$/g, "")
|
|
347
|
+
.slice(0, 32);
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
export function defaultWorktreeName(
|
|
351
|
+
repository: string,
|
|
352
|
+
prNumber: number,
|
|
353
|
+
headRefName: string,
|
|
354
|
+
itemKind: "pr" | "issue" = "pr",
|
|
355
|
+
): string {
|
|
356
|
+
const { name } = repoParts(repository);
|
|
357
|
+
const slug = slugifyBranch(headRefName);
|
|
358
|
+
const base = name || "repo";
|
|
359
|
+
const kindPrefix = itemKind === "issue" ? "issue" : "pr";
|
|
360
|
+
return slug ? `${base}-${kindPrefix}-${prNumber}-${slug}` : `${base}-${kindPrefix}-${prNumber}`;
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
export function isAbsoluteOrHomePath(rawPath: string): boolean {
|
|
364
|
+
const trimmed = rawPath.trim();
|
|
365
|
+
return trimmed === "~" || trimmed.startsWith("~/") || trimmed.startsWith("/");
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
export function isValidRepositorySlug(repository: string): boolean {
|
|
369
|
+
const trimmed = repository.trim();
|
|
370
|
+
if (!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(trimmed)) return false;
|
|
371
|
+
const [owner, name] = trimmed.split("/");
|
|
372
|
+
return [owner, name].every((part) => part !== "." && part !== ".." && !part.startsWith("-"));
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
export function isValidWorktreeName(name: string): boolean {
|
|
376
|
+
const trimmed = name.trim();
|
|
377
|
+
if (!trimmed || trimmed === "." || trimmed === "..") return false;
|
|
378
|
+
if (trimmed.startsWith(".") || trimmed.startsWith("-")) return false;
|
|
379
|
+
return !/[\\/\0]/.test(trimmed);
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
export function parseGitHubRepoFromRemote(remoteUrl: string): string | null {
|
|
383
|
+
const trimmed = remoteUrl
|
|
384
|
+
.trim()
|
|
385
|
+
.replace(/\/+$/, "")
|
|
386
|
+
.replace(/\.git$/i, "");
|
|
387
|
+
if (!trimmed) return null;
|
|
388
|
+
const scpMatch = trimmed.match(/^[^@/\s]+@([^:/\s]+):([^/\s]+\/[^/\s]+)$/);
|
|
389
|
+
if (scpMatch) {
|
|
390
|
+
if (scpMatch[1].toLowerCase() !== "github.com") return null;
|
|
391
|
+
return scpMatch[2].toLowerCase();
|
|
392
|
+
}
|
|
393
|
+
try {
|
|
394
|
+
const parsed = new URL(trimmed);
|
|
395
|
+
if (parsed.hostname.toLowerCase() !== "github.com") return null;
|
|
396
|
+
const parts = parsed.pathname.replace(/^\/+/, "").split("/").filter(Boolean);
|
|
397
|
+
if (parts.length === 2) {
|
|
398
|
+
return `${parts[0]}/${parts[1]}`.toLowerCase();
|
|
399
|
+
}
|
|
400
|
+
} catch {
|
|
401
|
+
return null;
|
|
402
|
+
}
|
|
403
|
+
return null;
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
async function findMatchingRemote(dir: string, repository: string): Promise<string | null> {
|
|
407
|
+
if (!repository) return null;
|
|
408
|
+
const target = repository.trim().toLowerCase();
|
|
409
|
+
try {
|
|
410
|
+
const remotesOut = await runGit(dir, ["remote"], 3_000);
|
|
411
|
+
const remotes = remotesOut
|
|
412
|
+
.split(/\r?\n/)
|
|
413
|
+
.map((line) => line.trim())
|
|
414
|
+
.filter(Boolean);
|
|
415
|
+
const ordered = [
|
|
416
|
+
...remotes.filter((name) => name === "upstream"),
|
|
417
|
+
...remotes.filter((name) => name === "origin"),
|
|
418
|
+
...remotes.filter((name) => name !== "upstream" && name !== "origin"),
|
|
419
|
+
];
|
|
420
|
+
for (const remoteName of ordered) {
|
|
421
|
+
const remoteUrl = await runGit(dir, ["remote", "get-url", remoteName], 3_000).catch(() => "");
|
|
422
|
+
if (parseGitHubRepoFromRemote(remoteUrl) === target) {
|
|
423
|
+
return remoteName;
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
return null;
|
|
427
|
+
} catch {
|
|
428
|
+
return null;
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
async function gitRemoteMatches(dir: string, repository: string): Promise<boolean> {
|
|
433
|
+
return Boolean(await findMatchingRemote(dir, repository));
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
async function resolveGitCommonDir(dir: string): Promise<string | null> {
|
|
437
|
+
try {
|
|
438
|
+
return await runGit(dir, ["rev-parse", "--path-format=absolute", "--git-common-dir"], 3_000);
|
|
439
|
+
} catch {
|
|
440
|
+
return null;
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
async function listWorktrees(
|
|
445
|
+
repoDir: string,
|
|
446
|
+
): Promise<Array<{ path: string; branch: string | null }>> {
|
|
447
|
+
try {
|
|
448
|
+
const output = await runGit(repoDir, ["worktree", "list", "--porcelain"], 5_000);
|
|
449
|
+
const items: Array<{ path: string; branch: string | null }> = [];
|
|
450
|
+
let currentPath: string | null = null;
|
|
451
|
+
let currentBranch: string | null = null;
|
|
452
|
+
for (const line of output.split(/\r?\n/)) {
|
|
453
|
+
if (line.startsWith("worktree ")) {
|
|
454
|
+
if (currentPath) items.push({ path: currentPath, branch: currentBranch });
|
|
455
|
+
currentPath = line.slice("worktree ".length).trim();
|
|
456
|
+
currentBranch = null;
|
|
457
|
+
} else if (line.startsWith("branch ")) {
|
|
458
|
+
currentBranch = line
|
|
459
|
+
.slice("branch ".length)
|
|
460
|
+
.replace(/^refs\/heads\//, "")
|
|
461
|
+
.trim();
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
if (currentPath) items.push({ path: currentPath, branch: currentBranch });
|
|
465
|
+
return items;
|
|
466
|
+
} catch {
|
|
467
|
+
return [];
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
async function resolveSuggestedClonePath(sourceDir: string, repository: string): Promise<string> {
|
|
472
|
+
const { owner, name } = repoParts(repository);
|
|
473
|
+
if (!name) return join(sourceDir, "repo");
|
|
474
|
+
const flatPath = join(sourceDir, name);
|
|
475
|
+
if (!(await exists(flatPath)) || (await gitRemoteMatches(flatPath, repository))) {
|
|
476
|
+
return flatPath;
|
|
477
|
+
}
|
|
478
|
+
return owner ? join(sourceDir, owner, name) : flatPath;
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
export async function listLocalDirsHandler(
|
|
482
|
+
input: z.output<typeof listLocalDirs.input>,
|
|
483
|
+
readSettings: ReadWorkspaceSettings,
|
|
484
|
+
): Promise<z.output<typeof listLocalDirs.output>> {
|
|
485
|
+
const settings = await readSettings();
|
|
486
|
+
const expandedSourceDir = expandUserPath(settings.sourceCodeDir);
|
|
487
|
+
const realSourceDir = await realpathLoose(expandedSourceDir);
|
|
488
|
+
const query = input.query.trim().toLowerCase();
|
|
489
|
+
const { name: repoName } = repoParts(input.repository);
|
|
490
|
+
const entries: LocalDirEntry[] = [];
|
|
491
|
+
const seen = new Set<string>();
|
|
492
|
+
|
|
493
|
+
if (await exists(expandedSourceDir)) {
|
|
494
|
+
const topItems = await readdir(expandedSourceDir, { withFileTypes: true }).catch(() => []);
|
|
495
|
+
for (const item of topItems) {
|
|
496
|
+
if (!item.isDirectory() || item.name.startsWith(".")) continue;
|
|
497
|
+
const fullPath = join(expandedSourceDir, item.name);
|
|
498
|
+
const isRepo = await isGitRepo(fullPath);
|
|
499
|
+
const isMatch =
|
|
500
|
+
Boolean(input.repository) &&
|
|
501
|
+
(item.name.toLowerCase() === repoName.toLowerCase() ||
|
|
502
|
+
(isRepo && (await gitRemoteMatches(fullPath, input.repository))));
|
|
503
|
+
|
|
504
|
+
if (!seen.has(fullPath)) {
|
|
505
|
+
seen.add(fullPath);
|
|
506
|
+
entries.push({
|
|
507
|
+
path: fullPath,
|
|
508
|
+
label: item.name,
|
|
509
|
+
kind: isRepo ? "repo" : "dir",
|
|
510
|
+
branch: null,
|
|
511
|
+
isMatch,
|
|
512
|
+
});
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
if (isRepo && (isMatch || !query || item.name.toLowerCase().includes(query))) {
|
|
516
|
+
const worktrees = await listWorktrees(fullPath);
|
|
517
|
+
for (const wt of worktrees) {
|
|
518
|
+
if (seen.has(wt.path)) continue;
|
|
519
|
+
if (!isInside(realSourceDir, await realpathLoose(wt.path))) continue;
|
|
520
|
+
seen.add(wt.path);
|
|
521
|
+
entries.push({
|
|
522
|
+
path: wt.path,
|
|
523
|
+
label: `${item.name} · ${basename(wt.path)}`,
|
|
524
|
+
kind: "worktree",
|
|
525
|
+
branch: wt.branch,
|
|
526
|
+
isMatch,
|
|
527
|
+
});
|
|
528
|
+
}
|
|
529
|
+
} else if (!isRepo) {
|
|
530
|
+
// Scan one level deeper for <owner>/<repo> layouts.
|
|
531
|
+
const subItems = await readdir(fullPath, { withFileTypes: true }).catch(() => []);
|
|
532
|
+
for (const sub of subItems) {
|
|
533
|
+
if (!sub.isDirectory() || sub.name.startsWith(".")) continue;
|
|
534
|
+
const subPath = join(fullPath, sub.name);
|
|
535
|
+
const subIsRepo = await isGitRepo(subPath);
|
|
536
|
+
const subMatch =
|
|
537
|
+
Boolean(input.repository) &&
|
|
538
|
+
(sub.name.toLowerCase() === repoName.toLowerCase() ||
|
|
539
|
+
(subIsRepo && (await gitRemoteMatches(subPath, input.repository))));
|
|
540
|
+
if (!seen.has(subPath)) {
|
|
541
|
+
seen.add(subPath);
|
|
542
|
+
entries.push({
|
|
543
|
+
path: subPath,
|
|
544
|
+
label: `${item.name}/${sub.name}`,
|
|
545
|
+
kind: subIsRepo ? "repo" : "dir",
|
|
546
|
+
branch: null,
|
|
547
|
+
isMatch: subMatch,
|
|
548
|
+
});
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
const filtered = entries
|
|
556
|
+
.filter((entry) => {
|
|
557
|
+
if (!query) return true;
|
|
558
|
+
return (
|
|
559
|
+
entry.path.toLowerCase().includes(query) ||
|
|
560
|
+
entry.label.toLowerCase().includes(query) ||
|
|
561
|
+
(entry.branch?.toLowerCase().includes(query) ?? false)
|
|
562
|
+
);
|
|
563
|
+
})
|
|
564
|
+
.sort((a, b) => {
|
|
565
|
+
if (a.isMatch !== b.isMatch) return a.isMatch ? -1 : 1;
|
|
566
|
+
const rank = { worktree: 0, repo: 1, dir: 2 };
|
|
567
|
+
if (rank[a.kind] !== rank[b.kind]) return rank[a.kind] - rank[b.kind];
|
|
568
|
+
return a.label.localeCompare(b.label);
|
|
569
|
+
})
|
|
570
|
+
.slice(0, 40);
|
|
571
|
+
|
|
572
|
+
const suggestedClonePath = await resolveSuggestedClonePath(expandedSourceDir, input.repository);
|
|
573
|
+
return { expandedSourceDir, entries: filtered, suggestedClonePath };
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
function prRef(prNumber: number): string {
|
|
577
|
+
return `refs/pr-radar/pull/${prNumber}`;
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
/**
|
|
581
|
+
* Fetches the PR head into a dedicated ref and resolves that ref, never FETCH_HEAD, which a
|
|
582
|
+
* concurrent fetch in the same checkout can overwrite between the fetch and the lookup.
|
|
583
|
+
*/
|
|
584
|
+
async function fetchPrHead(baseRoot: string, remote: string, prNumber: number): Promise<string> {
|
|
585
|
+
await assertNoUnsafeTransportConfig(baseRoot);
|
|
586
|
+
const ref = prRef(prNumber);
|
|
587
|
+
await runGit(baseRoot, ["fetch", "--end-of-options", remote, `+pull/${prNumber}/head:${ref}`]);
|
|
588
|
+
return runGit(baseRoot, ["rev-parse", "--verify", `${ref}^{commit}`]);
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
async function effectiveConfigKeys(repoDir: string, pattern: string): Promise<string[]> {
|
|
592
|
+
let raw: Buffer = Buffer.alloc(0);
|
|
593
|
+
try {
|
|
594
|
+
// No `-c` here: `git config --get-regexp` also lists command-scope values, and the baseline
|
|
595
|
+
// `-c http.sslVerify=true` would otherwise self-trigger the transport guard.
|
|
596
|
+
const result = await execFileAsync(
|
|
597
|
+
"git",
|
|
598
|
+
["-C", repoDir, "config", "--null", "--name-only", "--get-regexp", pattern],
|
|
599
|
+
{
|
|
600
|
+
timeout: 3_000,
|
|
601
|
+
maxBuffer: MAX_BUFFER_BYTES,
|
|
602
|
+
env: { ...gitEnv(), LC_ALL: "C" },
|
|
603
|
+
encoding: "buffer",
|
|
604
|
+
},
|
|
605
|
+
);
|
|
606
|
+
raw = result.stdout as Buffer;
|
|
607
|
+
} catch (err) {
|
|
608
|
+
const code =
|
|
609
|
+
err && typeof err === "object" && "code" in err
|
|
610
|
+
? (err as { code?: unknown }).code
|
|
611
|
+
: undefined;
|
|
612
|
+
if (code !== 1) throw err;
|
|
613
|
+
raw = Buffer.alloc(0);
|
|
614
|
+
}
|
|
615
|
+
const stdout = raw.toString("utf8");
|
|
616
|
+
if (!Buffer.from(stdout, "utf8").equals(raw)) {
|
|
617
|
+
throw new Error(
|
|
618
|
+
`Could not enumerate repository git config in ${repoDir}: keys contain invalid UTF-8.`,
|
|
619
|
+
);
|
|
620
|
+
}
|
|
621
|
+
return stdout.split("\0").filter(Boolean);
|
|
622
|
+
}
|
|
623
|
+
|
|
624
|
+
const UNSAFE_TRANSPORT_CONFIG =
|
|
625
|
+
"^(http\\.|remote\\..*\\.(proxy|uploadpack|vcs)$|core\\.alternaterefscommand$|fetch\\.bundleuri$|url\\.)";
|
|
626
|
+
|
|
627
|
+
async function assertNoUnsafeTransportConfig(repoDir: string): Promise<void> {
|
|
628
|
+
const keys = await effectiveConfigKeys(repoDir, UNSAFE_TRANSPORT_CONFIG);
|
|
629
|
+
if (keys.length > 0) {
|
|
630
|
+
throw new Error(
|
|
631
|
+
`Repository ${repoDir} configures transport keys that could redirect or exfiltrate the fetch (${keys[0]}); remove them from its git config before starting the agent.`,
|
|
632
|
+
);
|
|
633
|
+
}
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
async function branchExists(repoDir: string, branch: string): Promise<boolean> {
|
|
637
|
+
try {
|
|
638
|
+
await runGit(
|
|
639
|
+
repoDir,
|
|
640
|
+
["rev-parse", "--verify", "--quiet", `refs/heads/${branch}^{commit}`],
|
|
641
|
+
3_000,
|
|
642
|
+
);
|
|
643
|
+
return true;
|
|
644
|
+
} catch {
|
|
645
|
+
return false;
|
|
646
|
+
}
|
|
647
|
+
}
|
|
648
|
+
|
|
649
|
+
/**
|
|
650
|
+
* Resetting an existing branch to `target` is only safe when it moves forward: commits that are
|
|
651
|
+
* not contained in the target would otherwise fall off the branch.
|
|
652
|
+
*/
|
|
653
|
+
async function assertBranchFastForwards(
|
|
654
|
+
repoDir: string,
|
|
655
|
+
branch: string,
|
|
656
|
+
target: string,
|
|
657
|
+
targetLabel: string,
|
|
658
|
+
): Promise<void> {
|
|
659
|
+
if (!(await branchExists(repoDir, branch))) return;
|
|
660
|
+
try {
|
|
661
|
+
await runGit(repoDir, ["merge-base", "--is-ancestor", `refs/heads/${branch}`, target], 3_000);
|
|
662
|
+
} catch {
|
|
663
|
+
throw new Error(
|
|
664
|
+
`Branch ${branch} has local commits that are not in ${targetLabel}, so it was left unchanged. Push or rename the branch, or delete it, then try again.`,
|
|
665
|
+
);
|
|
666
|
+
}
|
|
667
|
+
}
|
|
668
|
+
|
|
669
|
+
/**
|
|
670
|
+
* `checkout -B` replaces a git-ignored local file (a `.env`, say) without a word when the PR tracks
|
|
671
|
+
* the same path, and the dirty check does not see ignored files. Refuse before that happens.
|
|
672
|
+
*/
|
|
673
|
+
async function assertNoIgnoredFileOverwrite(
|
|
674
|
+
dir: string,
|
|
675
|
+
target: string,
|
|
676
|
+
prNumber: number,
|
|
677
|
+
): Promise<void> {
|
|
678
|
+
const ignored = (
|
|
679
|
+
await runGit(dir, [
|
|
680
|
+
"ls-files",
|
|
681
|
+
"-z",
|
|
682
|
+
"--others",
|
|
683
|
+
"--ignored",
|
|
684
|
+
"--exclude-standard",
|
|
685
|
+
"--directory",
|
|
686
|
+
])
|
|
687
|
+
)
|
|
688
|
+
.split("\0")
|
|
689
|
+
.filter(Boolean);
|
|
690
|
+
if (ignored.length === 0) return;
|
|
691
|
+
// `--directory` emits an ignored directory as `private/`; stripping the slash makes the pathspec
|
|
692
|
+
// also match a tracked *file* named `private` (which the incoming tree replaces the directory
|
|
693
|
+
// with), not just tracked files underneath it.
|
|
694
|
+
const pathspecs = [...new Set(ignored.map((path) => `:(literal)${path.replace(/\/$/, "")}`))];
|
|
695
|
+
const incoming = (
|
|
696
|
+
await runGit(dir, ["ls-tree", "-r", "-z", "--name-only", target, "--", ...pathspecs])
|
|
697
|
+
)
|
|
698
|
+
.split("\0")
|
|
699
|
+
.filter(Boolean);
|
|
700
|
+
if (incoming.length > 0) {
|
|
701
|
+
throw new Error(
|
|
702
|
+
`PR #${prNumber} tracks ${incoming[0]}, which would overwrite an ignored local file in ${dir}; move that file aside, or use CWD-WORKTREE.`,
|
|
703
|
+
);
|
|
704
|
+
}
|
|
705
|
+
}
|
|
706
|
+
|
|
707
|
+
const NUL_BYTE = 0x00;
|
|
708
|
+
const TAB_BYTE = 0x09;
|
|
709
|
+
const SPACE_BYTE = 0x20;
|
|
710
|
+
const GITLINK_ENTRY_PREFIX = Buffer.from("160000 ");
|
|
711
|
+
|
|
712
|
+
/** Runs git and returns its stdout undecoded, so a caller can inspect names that are not UTF-8. */
|
|
713
|
+
async function runGitBytes(
|
|
714
|
+
cwd: string,
|
|
715
|
+
args: string[],
|
|
716
|
+
timeout = COMMAND_TIMEOUT_MS,
|
|
717
|
+
): Promise<Buffer> {
|
|
718
|
+
const { stdout } = await execFileAsync("git", [...GIT_SAFETY_ARGS, "-C", cwd, ...args], {
|
|
719
|
+
timeout,
|
|
720
|
+
maxBuffer: MAX_BUFFER_BYTES,
|
|
721
|
+
env: gitEnv(),
|
|
722
|
+
encoding: "buffer",
|
|
723
|
+
});
|
|
724
|
+
return stdout as Buffer;
|
|
725
|
+
}
|
|
726
|
+
|
|
727
|
+
/** Splits `-z` output on NUL into its non-empty records, byte for byte. */
|
|
728
|
+
function nulSeparatedEntries(raw: Buffer): Buffer[] {
|
|
729
|
+
const entries: Buffer[] = [];
|
|
730
|
+
let start = 0;
|
|
731
|
+
for (let end = raw.indexOf(NUL_BYTE); end !== -1; end = raw.indexOf(NUL_BYTE, start)) {
|
|
732
|
+
if (end > start) entries.push(raw.subarray(start, end));
|
|
733
|
+
start = end + 1;
|
|
734
|
+
}
|
|
735
|
+
if (start < raw.length) entries.push(raw.subarray(start));
|
|
736
|
+
return entries;
|
|
737
|
+
}
|
|
738
|
+
|
|
739
|
+
function hasPrefix(bytes: Buffer, prefix: Buffer): boolean {
|
|
740
|
+
return bytes.subarray(0, prefix.length).equals(prefix);
|
|
741
|
+
}
|
|
742
|
+
|
|
743
|
+
/** The path of an `ls-files -s -z` or `ls-tree -z` record: everything after its first tab. */
|
|
744
|
+
function entryPathBytes(entry: Buffer): Buffer {
|
|
745
|
+
return entry.subarray(entry.indexOf(TAB_BYTE) + 1);
|
|
746
|
+
}
|
|
747
|
+
|
|
748
|
+
/**
|
|
749
|
+
* The paths of the submodule (mode 160000) entries in `ls-files -s -z` output. Only these paths are
|
|
750
|
+
* decoded, and strictly: a lossy decode would mangle a non-UTF-8 submodule path and let the
|
|
751
|
+
* comparison against the incoming tree miss it, so that one case fails closed. Every other tracked
|
|
752
|
+
* name, whatever its bytes, is skipped undecoded.
|
|
753
|
+
*/
|
|
754
|
+
function submodulePaths(dir: string, lsFilesOutput: Buffer): string[] {
|
|
755
|
+
const paths: string[] = [];
|
|
756
|
+
for (const entry of nulSeparatedEntries(lsFilesOutput)) {
|
|
757
|
+
if (!hasPrefix(entry, GITLINK_ENTRY_PREFIX)) continue;
|
|
758
|
+
const pathBytes = entryPathBytes(entry);
|
|
759
|
+
const path = pathBytes.toString("utf8");
|
|
760
|
+
if (!Buffer.from(path, "utf8").equals(pathBytes)) {
|
|
761
|
+
throw new Error(
|
|
762
|
+
`A submodule path in ${dir} is not valid UTF-8, so it cannot be checked against the incoming tree; refusing to proceed.`,
|
|
763
|
+
);
|
|
764
|
+
}
|
|
765
|
+
paths.push(path);
|
|
766
|
+
}
|
|
767
|
+
return paths;
|
|
768
|
+
}
|
|
769
|
+
|
|
770
|
+
/**
|
|
771
|
+
* `checkout -B` also silently discards a submodule's uncommitted edits and untracked files when the
|
|
772
|
+
* incoming tree replaces the gitlink (or an ancestor directory holding it) with a file, symlink or
|
|
773
|
+
* directory. The dirty check passes because submodules are ignored, so refuse before the switch.
|
|
774
|
+
*/
|
|
775
|
+
async function assertNoGitlinkToFileOverwrite(
|
|
776
|
+
dir: string,
|
|
777
|
+
target: string,
|
|
778
|
+
prNumber: number,
|
|
779
|
+
): Promise<void> {
|
|
780
|
+
const gitlinkPaths = submodulePaths(dir, await runGitBytes(dir, ["ls-files", "-s", "-z"]));
|
|
781
|
+
if (gitlinkPaths.length === 0) return;
|
|
782
|
+
|
|
783
|
+
// Returns the mode of the exact entry at `path` in the target tree (or null when absent). A leaf
|
|
784
|
+
// produces exactly the entry at `path`; a directory produces only its children (`path/…`).
|
|
785
|
+
// Compared as bytes, so a sibling with a non-UTF-8 name can neither match nor break it.
|
|
786
|
+
const targetEntryMode = async (path: string): Promise<string | null> => {
|
|
787
|
+
const wanted = Buffer.from(path, "utf8");
|
|
788
|
+
const childPrefix = Buffer.from(`${path}/`, "utf8");
|
|
789
|
+
const entries = nulSeparatedEntries(
|
|
790
|
+
await runGitBytes(dir, ["ls-tree", "-z", target, "--", `:(literal)${path}`]),
|
|
791
|
+
);
|
|
792
|
+
let hasChildren = false;
|
|
793
|
+
for (const entry of entries) {
|
|
794
|
+
const entryPath = entryPathBytes(entry);
|
|
795
|
+
if (entryPath.equals(wanted)) return entry.subarray(0, entry.indexOf(SPACE_BYTE)).toString();
|
|
796
|
+
if (hasPrefix(entryPath, childPrefix)) hasChildren = true;
|
|
797
|
+
}
|
|
798
|
+
return hasChildren ? "040000" : null;
|
|
799
|
+
};
|
|
800
|
+
|
|
801
|
+
// A gitlink that becomes anything but another gitlink (file, symlink, directory, or removed)
|
|
802
|
+
// discards the submodule's working tree.
|
|
803
|
+
for (const path of gitlinkPaths) {
|
|
804
|
+
if ((await targetEntryMode(path)) !== "160000") {
|
|
805
|
+
throw new Error(
|
|
806
|
+
`PR #${prNumber} replaces the submodule under ${path} with a regular file, symlink or directory, which would discard uncommitted changes inside it; move those changes aside, or use CWD-WORKTREE.`,
|
|
807
|
+
);
|
|
808
|
+
}
|
|
809
|
+
}
|
|
810
|
+
// An ancestor directory that becomes a leaf (file or symlink) also discards the subtree.
|
|
811
|
+
for (const path of gitlinkPaths) {
|
|
812
|
+
let parent = path.includes("/") ? path.slice(0, path.lastIndexOf("/")) : "";
|
|
813
|
+
while (parent) {
|
|
814
|
+
const mode = await targetEntryMode(parent);
|
|
815
|
+
if (mode !== null && mode !== "040000") {
|
|
816
|
+
throw new Error(
|
|
817
|
+
`PR #${prNumber} replaces the submodule under ${parent} with a regular file or symlink, which would discard uncommitted changes inside it; move those changes aside, or use CWD-WORKTREE.`,
|
|
818
|
+
);
|
|
819
|
+
}
|
|
820
|
+
parent = parent.includes("/") ? parent.slice(0, parent.lastIndexOf("/")) : "";
|
|
821
|
+
}
|
|
822
|
+
}
|
|
823
|
+
}
|
|
824
|
+
|
|
825
|
+
/** The checked-out branch, or null on a detached HEAD. A git failure is an error, not "detached". */
|
|
826
|
+
async function currentBranch(repoDir: string): Promise<string | null> {
|
|
827
|
+
const name = await runGit(repoDir, ["branch", "--show-current"], 3_000);
|
|
828
|
+
return name || null;
|
|
829
|
+
}
|
|
830
|
+
|
|
831
|
+
/** Remote branch names that stand in for a default branch the remote has not recorded. */
|
|
832
|
+
const CONVENTIONAL_DEFAULT_BRANCHES = ["main", "master"];
|
|
833
|
+
|
|
834
|
+
/**
|
|
835
|
+
* New issue branches start from the remote default branch. Without a recorded remote default the
|
|
836
|
+
* current HEAD is used, but only when it is already on the conventional default branch (`main` or
|
|
837
|
+
* `master`) of the remote: a PR branch, a detached PR checkout or a local-only commit would carry
|
|
838
|
+
* unmerged, possibly untrusted code. Being on some other remote branch, such as a pushed PR branch,
|
|
839
|
+
* does not count.
|
|
840
|
+
*/
|
|
841
|
+
async function resolveIssueStartPoint(baseRoot: string, remote: string): Promise<string> {
|
|
842
|
+
const remoteHead = await runGit(
|
|
843
|
+
baseRoot,
|
|
844
|
+
["symbolic-ref", "--quiet", "--short", `refs/remotes/${remote}/HEAD`],
|
|
845
|
+
3_000,
|
|
846
|
+
).catch(() => "");
|
|
847
|
+
if (remoteHead) {
|
|
848
|
+
const resolved = await runGit(
|
|
849
|
+
baseRoot,
|
|
850
|
+
["rev-parse", "--verify", "--quiet", `${remoteHead}^{commit}`],
|
|
851
|
+
3_000,
|
|
852
|
+
).catch(() => "");
|
|
853
|
+
if (resolved) return resolved;
|
|
854
|
+
}
|
|
855
|
+
// One commit is checked and one is returned: another launch can move HEAD in between.
|
|
856
|
+
const head = await runGit(baseRoot, ["rev-parse", "--verify", "HEAD^{commit}"], 3_000);
|
|
857
|
+
const branch = await currentBranch(baseRoot);
|
|
858
|
+
if (branch?.startsWith("pr-radar/")) {
|
|
859
|
+
throw new Error(
|
|
860
|
+
`Base checkout ${baseRoot} is on ${branch} and has no recorded default branch for ${remote}; check out the default branch there, or use another directory.`,
|
|
861
|
+
);
|
|
862
|
+
}
|
|
863
|
+
for (const name of CONVENTIONAL_DEFAULT_BRANCHES) {
|
|
864
|
+
// `show-ref --verify` takes only the exact full ref name. `for-each-ref` would also match a
|
|
865
|
+
// branch named `main/x` by prefix, and `rev-parse` falls back to a tag literally named
|
|
866
|
+
// `refs/remotes/origin/main`; a pushed branch or tag could be named either way.
|
|
867
|
+
const ref = await runGit(
|
|
868
|
+
baseRoot,
|
|
869
|
+
["show-ref", "--verify", "--hash", `refs/remotes/${remote}/${name}`],
|
|
870
|
+
3_000,
|
|
871
|
+
).catch(() => "");
|
|
872
|
+
if (!ref) continue;
|
|
873
|
+
const tip = await runGit(baseRoot, ["rev-parse", "--verify", `${ref}^{commit}`], 3_000);
|
|
874
|
+
const published = await runGit(
|
|
875
|
+
baseRoot,
|
|
876
|
+
["merge-base", "--is-ancestor", head, tip],
|
|
877
|
+
3_000,
|
|
878
|
+
).then(
|
|
879
|
+
() => true,
|
|
880
|
+
() => false,
|
|
881
|
+
);
|
|
882
|
+
if (published) return head;
|
|
883
|
+
}
|
|
884
|
+
throw new Error(
|
|
885
|
+
`Base checkout ${baseRoot} has no recorded default branch for ${remote} and its HEAD is not on ${remote}/main or ${remote}/master, so it may carry unmerged code; run git remote set-head ${remote} --auto there, or check out the default branch.`,
|
|
886
|
+
);
|
|
887
|
+
}
|
|
888
|
+
|
|
889
|
+
async function refreshPrWorktree(
|
|
890
|
+
baseRoot: string,
|
|
891
|
+
worktreePath: string,
|
|
892
|
+
matchingRemote: string,
|
|
893
|
+
prNumber: number,
|
|
894
|
+
localBranchName: string,
|
|
895
|
+
): Promise<void> {
|
|
896
|
+
const dirty = await runGit(worktreePath, [
|
|
897
|
+
"status",
|
|
898
|
+
"--porcelain",
|
|
899
|
+
"--untracked-files=no",
|
|
900
|
+
"--ignore-submodules=all",
|
|
901
|
+
]);
|
|
902
|
+
if (dirty) {
|
|
903
|
+
throw new Error(
|
|
904
|
+
`Existing worktree ${worktreePath} has uncommitted changes; commit or stash them before updating PR #${prNumber}.`,
|
|
905
|
+
);
|
|
906
|
+
}
|
|
907
|
+
const prHead = await fetchPrHead(baseRoot, matchingRemote, prNumber);
|
|
908
|
+
await assertBranchFastForwards(baseRoot, localBranchName, prHead, `the head of PR #${prNumber}`);
|
|
909
|
+
await assertNoIgnoredFileOverwrite(worktreePath, prHead, prNumber);
|
|
910
|
+
await assertNoGitlinkToFileOverwrite(worktreePath, prHead, prNumber);
|
|
911
|
+
await runGit(worktreePath, ["checkout", "--no-overwrite-ignore", "-B", localBranchName, prHead]);
|
|
912
|
+
const wtHead = await runGit(worktreePath, ["rev-parse", "HEAD"]);
|
|
913
|
+
if (wtHead !== prHead) {
|
|
914
|
+
throw new Error(`Worktree verification failed for PR #${prNumber}.`);
|
|
915
|
+
}
|
|
916
|
+
}
|
|
917
|
+
|
|
918
|
+
/**
|
|
919
|
+
* A reused issue worktree may be a half-created one (a `worktree add --no-checkout` whose checkout
|
|
920
|
+
* failed and left every tracked file missing). Re-materialize the branch in that case; otherwise
|
|
921
|
+
* the user's work is present and left alone.
|
|
922
|
+
*/
|
|
923
|
+
async function refreshIssueWorktree(worktreePath: string, localBranchName: string): Promise<void> {
|
|
924
|
+
// A reused issue worktree must already be materialized. `ls-files` is empty only for a
|
|
925
|
+
// `worktree add --no-checkout` whose checkout never ran (or a fully staged deletion). Recover
|
|
926
|
+
// only when the directory holds nothing but `.git`; otherwise refuse rather than overwrite data
|
|
927
|
+
// that `git status` alone would miss (ignored files, hidden untracked files).
|
|
928
|
+
void localBranchName;
|
|
929
|
+
const tracked = await runGit(worktreePath, ["ls-files"], 3_000);
|
|
930
|
+
if (tracked) return;
|
|
931
|
+
const localData = (await readdir(worktreePath)).filter((name) => name !== ".git");
|
|
932
|
+
if (localData.length > 0) {
|
|
933
|
+
throw new Error(
|
|
934
|
+
`Existing worktree ${worktreePath} has no tracked files but contains local data; move that data aside or remove the worktree before reusing it.`,
|
|
935
|
+
);
|
|
936
|
+
}
|
|
937
|
+
await runGit(worktreePath, ["checkout", "--force"], CLONE_TIMEOUT_MS);
|
|
938
|
+
}
|
|
939
|
+
|
|
940
|
+
function errorMessage(err: unknown): string {
|
|
941
|
+
return err instanceof Error ? err.message : String(err);
|
|
942
|
+
}
|
|
943
|
+
|
|
944
|
+
/**
|
|
945
|
+
* Materializes a worktree that `worktree add --no-checkout` just registered. When the checkout
|
|
946
|
+
* fails, the half-created worktree is removed, so the next request does not find it by branch and
|
|
947
|
+
* hand back an unpopulated directory. If that removal fails too, both errors are reported: the
|
|
948
|
+
* original cause must not be lost, and the leftover worktree needs to be named.
|
|
949
|
+
*/
|
|
950
|
+
async function populateNewWorktree(baseRoot: string, worktreePath: string): Promise<void> {
|
|
951
|
+
try {
|
|
952
|
+
await runGit(worktreePath, ["checkout", "--force"], CLONE_TIMEOUT_MS);
|
|
953
|
+
} catch (checkoutError) {
|
|
954
|
+
try {
|
|
955
|
+
// No short timeout: the cleanup must be allowed to finish.
|
|
956
|
+
await runGit(baseRoot, ["worktree", "remove", "--force", worktreePath]);
|
|
957
|
+
} catch (removalError) {
|
|
958
|
+
throw new AggregateError(
|
|
959
|
+
[checkoutError, removalError],
|
|
960
|
+
`Checking out the new worktree ${worktreePath} failed (${errorMessage(checkoutError)}), and removing the half-created worktree failed too (${errorMessage(removalError)}); remove it with git worktree remove --force.`,
|
|
961
|
+
);
|
|
962
|
+
}
|
|
963
|
+
throw checkoutError;
|
|
964
|
+
}
|
|
965
|
+
}
|
|
966
|
+
|
|
967
|
+
/**
|
|
968
|
+
* Launches whose workspace is being prepared right now, one entry per repository and item. Two
|
|
969
|
+
* launches for the same item would race into the same clone, branch and worktree (a double click,
|
|
970
|
+
* or two devices), so a second one is refused instead of queued: the queue stays empty, and the
|
|
971
|
+
* first launch's result is what the user sees.
|
|
972
|
+
*/
|
|
973
|
+
const launchesInFlight = new Set<string>();
|
|
974
|
+
|
|
975
|
+
export async function prepareWorkspaceCwdHandler(
|
|
976
|
+
input: z.output<typeof prepareWorkspaceCwd.input>,
|
|
977
|
+
readSettings: ReadWorkspaceSettings,
|
|
978
|
+
): Promise<z.output<typeof prepareWorkspaceCwd.output>> {
|
|
979
|
+
const launchKey = `${input.repository.toLowerCase()}#${input.itemKind}-${input.prNumber}`;
|
|
980
|
+
if (launchesInFlight.has(launchKey)) {
|
|
981
|
+
throw new Error(
|
|
982
|
+
`A launch for ${input.itemKind} #${input.prNumber} of ${input.repository} is already preparing its workspace; wait for it to finish, then try again.`,
|
|
983
|
+
);
|
|
984
|
+
}
|
|
985
|
+
launchesInFlight.add(launchKey);
|
|
986
|
+
try {
|
|
987
|
+
return await prepareLockedWorkspaceCwd(input, readSettings);
|
|
988
|
+
} finally {
|
|
989
|
+
launchesInFlight.delete(launchKey);
|
|
990
|
+
}
|
|
991
|
+
}
|
|
992
|
+
|
|
993
|
+
async function prepareLockedWorkspaceCwd(
|
|
994
|
+
input: z.output<typeof prepareWorkspaceCwd.input>,
|
|
995
|
+
readSettings: ReadWorkspaceSettings,
|
|
996
|
+
): Promise<z.output<typeof prepareWorkspaceCwd.output>> {
|
|
997
|
+
if (!isValidRepositorySlug(input.repository)) {
|
|
998
|
+
throw new Error(`Invalid repository name: ${input.repository}`);
|
|
999
|
+
}
|
|
1000
|
+
if (input.targetDir && !isAbsoluteOrHomePath(input.targetDir)) {
|
|
1001
|
+
throw new Error(`Target directory must be an absolute or ~/ path: ${input.targetDir}`);
|
|
1002
|
+
}
|
|
1003
|
+
|
|
1004
|
+
const settings = await readSettings();
|
|
1005
|
+
const expandedSourceDir = expandUserPath(settings.sourceCodeDir);
|
|
1006
|
+
const realSourceDir = await realpathLoose(expandedSourceDir);
|
|
1007
|
+
let baseRoot = input.targetDir ? expandUserPath(input.targetDir) : "";
|
|
1008
|
+
if (input.targetDir) {
|
|
1009
|
+
await assertInsideSourceDir(realSourceDir, baseRoot, "Target directory");
|
|
1010
|
+
}
|
|
1011
|
+
let cloned = false;
|
|
1012
|
+
|
|
1013
|
+
if (!baseRoot) {
|
|
1014
|
+
baseRoot = await resolveSuggestedClonePath(expandedSourceDir, input.repository);
|
|
1015
|
+
// A symlink in the source directory can point at a checkout elsewhere.
|
|
1016
|
+
await assertInsideSourceDir(realSourceDir, baseRoot, "Base checkout");
|
|
1017
|
+
}
|
|
1018
|
+
|
|
1019
|
+
let matchingRemote = "origin";
|
|
1020
|
+
if (!(await exists(baseRoot))) {
|
|
1021
|
+
if (!input.allowClone) {
|
|
1022
|
+
throw new Error(
|
|
1023
|
+
`Directory does not exist: ${baseRoot}. Select "Clone ${input.repository}" to clone it.`,
|
|
1024
|
+
);
|
|
1025
|
+
}
|
|
1026
|
+
await mkdir(dirname(baseRoot), { recursive: true });
|
|
1027
|
+
await cloneGitHubRepo(input.repository, baseRoot);
|
|
1028
|
+
cloned = true;
|
|
1029
|
+
} else {
|
|
1030
|
+
const info = await stat(baseRoot);
|
|
1031
|
+
if (!info.isDirectory()) {
|
|
1032
|
+
throw new Error(`Target path is not a directory: ${baseRoot}`);
|
|
1033
|
+
}
|
|
1034
|
+
if (!(await isGitRepo(baseRoot))) {
|
|
1035
|
+
// If a worktree subdirectory was picked, let git discovery find it, otherwise require a git repo.
|
|
1036
|
+
const commonDir = await runGit(baseRoot, ["rev-parse", "--git-common-dir"]).catch(() => "");
|
|
1037
|
+
if (!commonDir) {
|
|
1038
|
+
throw new Error(`Target directory is not a git repository: ${baseRoot}`);
|
|
1039
|
+
}
|
|
1040
|
+
}
|
|
1041
|
+
const worktreeRoot = await runGit(baseRoot, [
|
|
1042
|
+
"rev-parse",
|
|
1043
|
+
"--path-format=absolute",
|
|
1044
|
+
"--show-toplevel",
|
|
1045
|
+
]).catch(() => "");
|
|
1046
|
+
if (!worktreeRoot) {
|
|
1047
|
+
throw new Error(`Target directory is not a git worktree: ${baseRoot}`);
|
|
1048
|
+
}
|
|
1049
|
+
baseRoot = worktreeRoot;
|
|
1050
|
+
await assertInsideSourceDir(realSourceDir, baseRoot, "Git worktree root");
|
|
1051
|
+
const matched = await findMatchingRemote(baseRoot, input.repository);
|
|
1052
|
+
if (!matched) {
|
|
1053
|
+
throw new Error(
|
|
1054
|
+
`Target directory ${baseRoot} does not match repository ${input.repository}.`,
|
|
1055
|
+
);
|
|
1056
|
+
}
|
|
1057
|
+
matchingRemote = matched;
|
|
1058
|
+
}
|
|
1059
|
+
|
|
1060
|
+
const localBranchName =
|
|
1061
|
+
input.itemKind === "issue"
|
|
1062
|
+
? `pr-radar/issue-${input.prNumber}`
|
|
1063
|
+
: `pr-radar/pr-${input.prNumber}`;
|
|
1064
|
+
|
|
1065
|
+
if (input.cwdMode === "CWD-BASE") {
|
|
1066
|
+
const branchBeforeSwitch = await currentBranch(baseRoot);
|
|
1067
|
+
if (!branchBeforeSwitch) {
|
|
1068
|
+
throw new Error(
|
|
1069
|
+
`Base checkout ${baseRoot} is in detached HEAD; check out a branch or use CWD-WORKTREE.`,
|
|
1070
|
+
);
|
|
1071
|
+
}
|
|
1072
|
+
const dirty = await runGit(baseRoot, [
|
|
1073
|
+
"status",
|
|
1074
|
+
"--porcelain",
|
|
1075
|
+
"--untracked-files=all",
|
|
1076
|
+
"--ignore-submodules=all",
|
|
1077
|
+
]);
|
|
1078
|
+
if (dirty) {
|
|
1079
|
+
throw new Error(
|
|
1080
|
+
`Base checkout ${baseRoot} has uncommitted or untracked changes; commit, stash or remove them, or use CWD-WORKTREE.`,
|
|
1081
|
+
);
|
|
1082
|
+
}
|
|
1083
|
+
const warning = `CWD-BASE will switch ${baseRoot} from ${branchBeforeSwitch} to ${localBranchName}.`;
|
|
1084
|
+
if (input.itemKind === "pr") {
|
|
1085
|
+
const prHead = await fetchPrHead(baseRoot, matchingRemote, input.prNumber);
|
|
1086
|
+
await assertBranchFastForwards(
|
|
1087
|
+
baseRoot,
|
|
1088
|
+
localBranchName,
|
|
1089
|
+
prHead,
|
|
1090
|
+
`the head of PR #${input.prNumber}`,
|
|
1091
|
+
);
|
|
1092
|
+
await assertNoIgnoredFileOverwrite(baseRoot, prHead, input.prNumber);
|
|
1093
|
+
await assertNoGitlinkToFileOverwrite(baseRoot, prHead, input.prNumber);
|
|
1094
|
+
await runGit(baseRoot, ["checkout", "--no-overwrite-ignore", "-B", localBranchName, prHead]);
|
|
1095
|
+
const headSha = await runGit(baseRoot, ["rev-parse", "HEAD"]);
|
|
1096
|
+
if (headSha !== prHead) {
|
|
1097
|
+
throw new Error(`Checkout verification failed for PR #${input.prNumber}.`);
|
|
1098
|
+
}
|
|
1099
|
+
} else if (await branchExists(baseRoot, localBranchName)) {
|
|
1100
|
+
await assertNoIgnoredFileOverwrite(baseRoot, localBranchName, input.prNumber);
|
|
1101
|
+
await assertNoGitlinkToFileOverwrite(baseRoot, localBranchName, input.prNumber);
|
|
1102
|
+
await runGit(baseRoot, ["checkout", "--no-overwrite-ignore", localBranchName]);
|
|
1103
|
+
} else {
|
|
1104
|
+
const startPoint = await resolveIssueStartPoint(baseRoot, matchingRemote);
|
|
1105
|
+
await assertNoIgnoredFileOverwrite(baseRoot, startPoint, input.prNumber);
|
|
1106
|
+
await assertNoGitlinkToFileOverwrite(baseRoot, startPoint, input.prNumber);
|
|
1107
|
+
await runGit(baseRoot, [
|
|
1108
|
+
"checkout",
|
|
1109
|
+
"--no-overwrite-ignore",
|
|
1110
|
+
"-b",
|
|
1111
|
+
localBranchName,
|
|
1112
|
+
startPoint,
|
|
1113
|
+
]);
|
|
1114
|
+
}
|
|
1115
|
+
return {
|
|
1116
|
+
cwd: baseRoot,
|
|
1117
|
+
baseRoot,
|
|
1118
|
+
cwdTag: "CWD-BASE",
|
|
1119
|
+
cloned,
|
|
1120
|
+
worktreeCreated: false,
|
|
1121
|
+
warning,
|
|
1122
|
+
};
|
|
1123
|
+
}
|
|
1124
|
+
|
|
1125
|
+
// CWD-WORKTREE: reuse existing worktree for this PR/issue branch if present (never reuse baseRoot).
|
|
1126
|
+
const resolvedBaseRoot = resolve(baseRoot);
|
|
1127
|
+
const existingWorktrees = await listWorktrees(baseRoot);
|
|
1128
|
+
// A CWD-BASE launch leaves the branch checked out in the base checkout, where `worktree add`
|
|
1129
|
+
// cannot also use it. Refuse, naming it, rather than fail inside git or quietly work in the base.
|
|
1130
|
+
const heldByBase = existingWorktrees.some(
|
|
1131
|
+
(wt) => wt.branch === localBranchName && resolve(wt.path) === resolvedBaseRoot,
|
|
1132
|
+
);
|
|
1133
|
+
if (heldByBase) {
|
|
1134
|
+
throw new Error(
|
|
1135
|
+
`Branch ${localBranchName} is checked out in the base checkout ${baseRoot} (an earlier CWD-BASE launch), so a worktree cannot use it too; switch that checkout to another branch, or launch with CWD-BASE.`,
|
|
1136
|
+
);
|
|
1137
|
+
}
|
|
1138
|
+
const existing = existingWorktrees.find(
|
|
1139
|
+
(wt) => wt.branch === localBranchName && resolve(wt.path) !== resolvedBaseRoot,
|
|
1140
|
+
);
|
|
1141
|
+
if (existing) {
|
|
1142
|
+
// `git worktree list` can name a worktree anywhere on disk.
|
|
1143
|
+
await assertInsideSourceDir(realSourceDir, existing.path, "Existing worktree");
|
|
1144
|
+
if (input.itemKind === "pr") {
|
|
1145
|
+
await refreshPrWorktree(
|
|
1146
|
+
baseRoot,
|
|
1147
|
+
existing.path,
|
|
1148
|
+
matchingRemote,
|
|
1149
|
+
input.prNumber,
|
|
1150
|
+
localBranchName,
|
|
1151
|
+
);
|
|
1152
|
+
} else {
|
|
1153
|
+
await refreshIssueWorktree(existing.path, localBranchName);
|
|
1154
|
+
}
|
|
1155
|
+
return {
|
|
1156
|
+
cwd: existing.path,
|
|
1157
|
+
baseRoot,
|
|
1158
|
+
cwdTag: "CWD-WORKTREE",
|
|
1159
|
+
cloned,
|
|
1160
|
+
worktreeCreated: false,
|
|
1161
|
+
};
|
|
1162
|
+
}
|
|
1163
|
+
|
|
1164
|
+
const worktreeFolder =
|
|
1165
|
+
input.worktreeName?.trim() ||
|
|
1166
|
+
defaultWorktreeName(input.repository, input.prNumber, input.headRefName, input.itemKind);
|
|
1167
|
+
if (!isValidWorktreeName(worktreeFolder)) {
|
|
1168
|
+
throw new Error(`Invalid worktree folder name: ${worktreeFolder}`);
|
|
1169
|
+
}
|
|
1170
|
+
const worktreePath = join(dirname(baseRoot), worktreeFolder);
|
|
1171
|
+
await assertInsideSourceDir(realSourceDir, worktreePath, "Worktree folder");
|
|
1172
|
+
|
|
1173
|
+
if (await exists(worktreePath)) {
|
|
1174
|
+
const [baseCommonDir, wtCommonDir, wtBranch] = await Promise.all([
|
|
1175
|
+
resolveGitCommonDir(baseRoot),
|
|
1176
|
+
resolveGitCommonDir(worktreePath),
|
|
1177
|
+
runGit(worktreePath, ["rev-parse", "--abbrev-ref", "HEAD"], 3_000).catch(() => ""),
|
|
1178
|
+
]);
|
|
1179
|
+
if (!baseCommonDir || wtCommonDir !== baseCommonDir || wtBranch !== localBranchName) {
|
|
1180
|
+
throw new Error(
|
|
1181
|
+
`Existing folder ${worktreePath} is not a worktree of ${input.repository} on branch ${localBranchName}. Choose a different worktree name.`,
|
|
1182
|
+
);
|
|
1183
|
+
}
|
|
1184
|
+
if (input.itemKind === "pr") {
|
|
1185
|
+
await refreshPrWorktree(
|
|
1186
|
+
baseRoot,
|
|
1187
|
+
worktreePath,
|
|
1188
|
+
matchingRemote,
|
|
1189
|
+
input.prNumber,
|
|
1190
|
+
localBranchName,
|
|
1191
|
+
);
|
|
1192
|
+
} else {
|
|
1193
|
+
await refreshIssueWorktree(worktreePath, localBranchName);
|
|
1194
|
+
}
|
|
1195
|
+
return {
|
|
1196
|
+
cwd: worktreePath,
|
|
1197
|
+
baseRoot,
|
|
1198
|
+
cwdTag: "CWD-WORKTREE",
|
|
1199
|
+
cloned,
|
|
1200
|
+
worktreeCreated: false,
|
|
1201
|
+
};
|
|
1202
|
+
}
|
|
1203
|
+
|
|
1204
|
+
if (input.itemKind === "issue") {
|
|
1205
|
+
if (await branchExists(baseRoot, localBranchName)) {
|
|
1206
|
+
await runGit(baseRoot, [
|
|
1207
|
+
"worktree",
|
|
1208
|
+
"add",
|
|
1209
|
+
"--no-checkout",
|
|
1210
|
+
"--",
|
|
1211
|
+
worktreePath,
|
|
1212
|
+
localBranchName,
|
|
1213
|
+
]);
|
|
1214
|
+
} else {
|
|
1215
|
+
const startPoint = await resolveIssueStartPoint(baseRoot, matchingRemote);
|
|
1216
|
+
await runGit(baseRoot, [
|
|
1217
|
+
"worktree",
|
|
1218
|
+
"add",
|
|
1219
|
+
"--no-checkout",
|
|
1220
|
+
"-b",
|
|
1221
|
+
localBranchName,
|
|
1222
|
+
"--",
|
|
1223
|
+
worktreePath,
|
|
1224
|
+
startPoint,
|
|
1225
|
+
]);
|
|
1226
|
+
}
|
|
1227
|
+
await populateNewWorktree(baseRoot, worktreePath);
|
|
1228
|
+
} else {
|
|
1229
|
+
const prHead = await fetchPrHead(baseRoot, matchingRemote, input.prNumber);
|
|
1230
|
+
await assertBranchFastForwards(
|
|
1231
|
+
baseRoot,
|
|
1232
|
+
localBranchName,
|
|
1233
|
+
prHead,
|
|
1234
|
+
`the head of PR #${input.prNumber}`,
|
|
1235
|
+
);
|
|
1236
|
+
await runGit(baseRoot, [
|
|
1237
|
+
"worktree",
|
|
1238
|
+
"add",
|
|
1239
|
+
"--no-checkout",
|
|
1240
|
+
"-B",
|
|
1241
|
+
localBranchName,
|
|
1242
|
+
"--",
|
|
1243
|
+
worktreePath,
|
|
1244
|
+
prHead,
|
|
1245
|
+
]);
|
|
1246
|
+
await populateNewWorktree(baseRoot, worktreePath);
|
|
1247
|
+
}
|
|
1248
|
+
|
|
1249
|
+
return {
|
|
1250
|
+
cwd: worktreePath,
|
|
1251
|
+
baseRoot,
|
|
1252
|
+
cwdTag: "CWD-WORKTREE",
|
|
1253
|
+
cloned,
|
|
1254
|
+
worktreeCreated: true,
|
|
1255
|
+
};
|
|
1256
|
+
}
|
|
1257
|
+
|
|
1258
|
+
const STICKY_BIT = 0o1000;
|
|
1259
|
+
|
|
1260
|
+
/**
|
|
1261
|
+
* Resolves the configured script to a real path and refuses anything but a regular, executable
|
|
1262
|
+
* file that only this user (or root) can modify: the file must be owned by the user or root, and so
|
|
1263
|
+
* must every directory above it, none of them writable by group or others unless sticky (like
|
|
1264
|
+
* /tmp). Otherwise another local user could create the script or swap a path component for their
|
|
1265
|
+
* own, and it would run as this user. `uid` is a parameter so tests can stand in for another user.
|
|
1266
|
+
*/
|
|
1267
|
+
export async function resolveRoutingScript(
|
|
1268
|
+
rawPath: string,
|
|
1269
|
+
uid: number | undefined = process.getuid?.(),
|
|
1270
|
+
): Promise<string> {
|
|
1271
|
+
const trimmed = rawPath.trim();
|
|
1272
|
+
if (!trimmed) {
|
|
1273
|
+
throw new Error("No routing script is configured in the PR Radar settings.");
|
|
1274
|
+
}
|
|
1275
|
+
if (!isAbsoluteOrHomePath(trimmed)) {
|
|
1276
|
+
throw new Error(`Routing script path must be an absolute or ~/ path: ${trimmed}`);
|
|
1277
|
+
}
|
|
1278
|
+
const expanded = expandUserPath(trimmed);
|
|
1279
|
+
if (!(await exists(expanded))) {
|
|
1280
|
+
throw new Error(`Routing script not found: ${expanded}`);
|
|
1281
|
+
}
|
|
1282
|
+
const scriptPath = await realpath(expanded);
|
|
1283
|
+
const info = await stat(scriptPath);
|
|
1284
|
+
if (!info.isFile()) {
|
|
1285
|
+
throw new Error(`Routing script is not a regular file: ${scriptPath}`);
|
|
1286
|
+
}
|
|
1287
|
+
const trustedOwner = (owner: number) => uid === undefined || owner === uid || owner === 0;
|
|
1288
|
+
if (!trustedOwner(info.uid)) {
|
|
1289
|
+
throw new Error(
|
|
1290
|
+
`Routing script ${scriptPath} is owned by another user; run chown on it, or use a script you own.`,
|
|
1291
|
+
);
|
|
1292
|
+
}
|
|
1293
|
+
if ((info.mode & 0o022) !== 0) {
|
|
1294
|
+
throw new Error(
|
|
1295
|
+
`Routing script ${scriptPath} must not be writable by group or others; run chmod go-w on it.`,
|
|
1296
|
+
);
|
|
1297
|
+
}
|
|
1298
|
+
for (let dir = dirname(scriptPath); ; dir = dirname(dir)) {
|
|
1299
|
+
const dirInfo = await stat(dir);
|
|
1300
|
+
if (!trustedOwner(dirInfo.uid)) {
|
|
1301
|
+
throw new Error(
|
|
1302
|
+
`Routing script directory ${dir} is owned by another user; move the script somewhere you own, or run chown on it.`,
|
|
1303
|
+
);
|
|
1304
|
+
}
|
|
1305
|
+
if ((dirInfo.mode & 0o022) !== 0 && (dirInfo.mode & STICKY_BIT) === 0) {
|
|
1306
|
+
throw new Error(
|
|
1307
|
+
`Routing script directory ${dir} must not be writable by group or others; run chmod go-w on it.`,
|
|
1308
|
+
);
|
|
1309
|
+
}
|
|
1310
|
+
if (dirname(dir) === dir) break;
|
|
1311
|
+
}
|
|
1312
|
+
try {
|
|
1313
|
+
await access(scriptPath, constants.X_OK);
|
|
1314
|
+
} catch {
|
|
1315
|
+
throw new Error(`Routing script is not executable: ${scriptPath}`);
|
|
1316
|
+
}
|
|
1317
|
+
return scriptPath;
|
|
1318
|
+
}
|
|
1319
|
+
|
|
1320
|
+
interface ScriptRun {
|
|
1321
|
+
/** Settles with the script's stdout, or rejects on failure, timeout or the output cap. */
|
|
1322
|
+
result: Promise<string>;
|
|
1323
|
+
/** Resolves once the script's process group has exited or has been sent SIGKILL. */
|
|
1324
|
+
finished: Promise<void>;
|
|
1325
|
+
}
|
|
1326
|
+
|
|
1327
|
+
function startScriptCapped(
|
|
1328
|
+
scriptPath: string,
|
|
1329
|
+
payload: unknown,
|
|
1330
|
+
limits: RoutingScriptLimits,
|
|
1331
|
+
): ScriptRun {
|
|
1332
|
+
const finishedGate = Promise.withResolvers<void>();
|
|
1333
|
+
const result = new Promise<string>((resolvePromise, rejectPromise) => {
|
|
1334
|
+
// Its own process group, so a timeout reaches the script's descendants too.
|
|
1335
|
+
let child: ChildProcessByStdio<Writable, Readable, Readable>;
|
|
1336
|
+
try {
|
|
1337
|
+
child = spawn(scriptPath, [], {
|
|
1338
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
1339
|
+
env: allowListedEnv(new Set()),
|
|
1340
|
+
detached: true,
|
|
1341
|
+
});
|
|
1342
|
+
} catch (spawnError) {
|
|
1343
|
+
finishedGate.resolve();
|
|
1344
|
+
rejectPromise(spawnError);
|
|
1345
|
+
return;
|
|
1346
|
+
}
|
|
1347
|
+
const out: Buffer[] = [];
|
|
1348
|
+
const err: Buffer[] = [];
|
|
1349
|
+
let outBytes = 0;
|
|
1350
|
+
let errBytes = 0;
|
|
1351
|
+
let settled = false;
|
|
1352
|
+
let terminating = false;
|
|
1353
|
+
let killTimer: NodeJS.Timeout | undefined;
|
|
1354
|
+
|
|
1355
|
+
function signalGroup(signal: NodeJS.Signals): void {
|
|
1356
|
+
try {
|
|
1357
|
+
if (child.pid !== undefined) process.kill(-child.pid, signal);
|
|
1358
|
+
} catch {
|
|
1359
|
+
// The group is already gone.
|
|
1360
|
+
}
|
|
1361
|
+
}
|
|
1362
|
+
function settle(finish: () => void): void {
|
|
1363
|
+
if (settled) return;
|
|
1364
|
+
settled = true;
|
|
1365
|
+
clearTimeout(timer);
|
|
1366
|
+
// A surviving descendant could otherwise keep feeding buffers nobody reads any more.
|
|
1367
|
+
child.stdout.destroy();
|
|
1368
|
+
child.stderr.destroy();
|
|
1369
|
+
finish();
|
|
1370
|
+
}
|
|
1371
|
+
function terminate(): void {
|
|
1372
|
+
if (terminating) return;
|
|
1373
|
+
terminating = true;
|
|
1374
|
+
signalGroup("SIGTERM");
|
|
1375
|
+
killTimer = setTimeout(() => {
|
|
1376
|
+
signalGroup("SIGKILL");
|
|
1377
|
+
finishedGate.resolve();
|
|
1378
|
+
}, limits.killGraceMs);
|
|
1379
|
+
}
|
|
1380
|
+
function overCap(): void {
|
|
1381
|
+
terminate();
|
|
1382
|
+
settle(() =>
|
|
1383
|
+
rejectPromise(new Error(`Routing script output exceeded ${limits.outputBytes} bytes.`)),
|
|
1384
|
+
);
|
|
1385
|
+
}
|
|
1386
|
+
|
|
1387
|
+
const timer = setTimeout(() => {
|
|
1388
|
+
terminate();
|
|
1389
|
+
settle(() =>
|
|
1390
|
+
rejectPromise(new Error(`Routing script timed out after ${limits.timeoutMs}ms.`)),
|
|
1391
|
+
);
|
|
1392
|
+
}, limits.timeoutMs);
|
|
1393
|
+
|
|
1394
|
+
child.stdout.on("data", (chunk: Buffer) => {
|
|
1395
|
+
if (settled) return;
|
|
1396
|
+
outBytes += chunk.length;
|
|
1397
|
+
if (outBytes > limits.outputBytes) return overCap();
|
|
1398
|
+
out.push(chunk);
|
|
1399
|
+
});
|
|
1400
|
+
child.stderr.on("data", (chunk: Buffer) => {
|
|
1401
|
+
if (settled) return;
|
|
1402
|
+
errBytes += chunk.length;
|
|
1403
|
+
if (errBytes > limits.outputBytes) return overCap();
|
|
1404
|
+
err.push(chunk);
|
|
1405
|
+
});
|
|
1406
|
+
child.on("error", (spawnError) => {
|
|
1407
|
+
settle(() => rejectPromise(spawnError));
|
|
1408
|
+
finishedGate.resolve();
|
|
1409
|
+
});
|
|
1410
|
+
child.on("close", (code) => {
|
|
1411
|
+
// Having asked it to stop, make sure no descendant outlives the script.
|
|
1412
|
+
if (terminating) signalGroup("SIGKILL");
|
|
1413
|
+
clearTimeout(killTimer);
|
|
1414
|
+
finishedGate.resolve();
|
|
1415
|
+
settle(() => {
|
|
1416
|
+
if (code !== 0) {
|
|
1417
|
+
const message = Buffer.concat(err).toString("utf8").trim();
|
|
1418
|
+
rejectPromise(new Error(message || `Routing script exited with code ${code}.`));
|
|
1419
|
+
return;
|
|
1420
|
+
}
|
|
1421
|
+
resolvePromise(Buffer.concat(out).toString("utf8").trim());
|
|
1422
|
+
});
|
|
1423
|
+
});
|
|
1424
|
+
child.stdin.on("error", () => {});
|
|
1425
|
+
child.stdin.end(`${JSON.stringify(payload)}\n`);
|
|
1426
|
+
});
|
|
1427
|
+
return { result, finished: finishedGate.promise };
|
|
1428
|
+
}
|
|
1429
|
+
|
|
1430
|
+
let routingScriptRunning = false;
|
|
1431
|
+
let routingScriptFinished: Promise<void> | null = null;
|
|
1432
|
+
|
|
1433
|
+
export async function waitForRoutingScriptIdleForTests(): Promise<void> {
|
|
1434
|
+
await routingScriptFinished;
|
|
1435
|
+
}
|
|
1436
|
+
|
|
1437
|
+
export async function runRoutingScriptHandler(
|
|
1438
|
+
input: z.output<typeof runRoutingScript.input>,
|
|
1439
|
+
readSettings: ReadWorkspaceSettings,
|
|
1440
|
+
limits: RoutingScriptLimits = DEFAULT_ROUTING_LIMITS,
|
|
1441
|
+
): Promise<z.output<typeof runRoutingScript.output>> {
|
|
1442
|
+
if (process.platform === "win32") {
|
|
1443
|
+
throw new Error("Routing scripts are not supported on Windows.");
|
|
1444
|
+
}
|
|
1445
|
+
const settings = await readSettings();
|
|
1446
|
+
const scriptPath = await resolveRoutingScript(settings.routingScriptPath);
|
|
1447
|
+
if (routingScriptRunning) {
|
|
1448
|
+
throw new Error("A routing script is already running; try again when it has finished.");
|
|
1449
|
+
}
|
|
1450
|
+
routingScriptRunning = true;
|
|
1451
|
+
// The guard is held until the script's process group is gone or has been sent SIGKILL, which can
|
|
1452
|
+
// be after the call itself has failed on a timeout.
|
|
1453
|
+
const run = startScriptCapped(scriptPath, input.payload, limits);
|
|
1454
|
+
routingScriptFinished = run.finished.then(() => {
|
|
1455
|
+
routingScriptRunning = false;
|
|
1456
|
+
routingScriptFinished = null;
|
|
1457
|
+
});
|
|
1458
|
+
void routingScriptFinished;
|
|
1459
|
+
const stdout = await run.result;
|
|
1460
|
+
|
|
1461
|
+
if (!stdout) return {};
|
|
1462
|
+
const parsed = JSON.parse(stdout) as unknown;
|
|
1463
|
+
return RoutingScriptResultSchema.parse(parsed);
|
|
1464
|
+
}
|