Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

SourceControlProviderDiscovery.ts

349 lines11.5 KB

1import * as NodeUtil from "node:util";
2import type {
3 SourceControlProviderAuth,
4 SourceControlProviderDiscoveryItem,
5 SourceControlProviderInfo,
6 SourceControlProviderKind,
7} from "@t3tools/contracts";
8import * as Effect from "effect/Effect";
9import * as Option from "effect/Option";
10import * as PlatformError from "effect/PlatformError";
11​
12import type * as SourceControlProvider from "./SourceControlProvider.ts";
13import type * as VcsProcess from "../vcs/VcsProcess.ts";
14​
15export interface SourceControlAuthProbeInput {
16 readonly stdout: string;
17 readonly stderr: string;
18 readonly exitCode: VcsProcess.VcsProcessOutput["exitCode"];
20​
21export interface SourceControlUnknownRemoteRefinementInput {
22 readonly cwd: string;
23 readonly context: SourceControlProvider.SourceControlProviderContext;
24 readonly auth: SourceControlAuthProbeInput;
26​
27interface SourceControlDiscoverySpecBase {
28 readonly kind: SourceControlProviderKind;
29 readonly label: string;
30 readonly installHint: string;
32​
33export type SourceControlCliDiscoverySpec = SourceControlDiscoverySpecBase & {
34 readonly type: "cli";
35 readonly executable: string;
36 readonly versionArgs: ReadonlyArray<string>;
37 readonly authArgs: ReadonlyArray<string>;
38 readonly remoteRefinementArgs?: ReadonlyArray<string>;
39 readonly probeTimeoutMs?: number;
40 readonly parseAuth: (input: SourceControlAuthProbeInput) => SourceControlProviderAuth;
41 readonly refineUnknownRemote?: (
42 input: SourceControlUnknownRemoteRefinementInput,
43 ) => SourceControlProviderInfo | null;
44};
45​
46export type SourceControlApiDiscoverySpec = SourceControlDiscoverySpecBase & {
47 readonly type: "api";
48 readonly probeAuth: Effect.Effect<SourceControlProviderAuth, never>;
49};
50​
51export type SourceControlManagedCliDiscoverySpec = SourceControlDiscoverySpecBase & {
52 readonly type: "managed-cli";
53 readonly probe: (cwd: string) => Effect.Effect<SourceControlProviderDiscoveryItem>;
54 readonly refineUnknownRemote: (input: {
55 readonly cwd: string;
56 readonly context: SourceControlProvider.SourceControlProviderContext;
57 }) => Effect.Effect<SourceControlProviderInfo | null>;
58};
59​
60export type SourceControlProviderDiscoverySpec =
61 | SourceControlCliDiscoverySpec
62 | SourceControlManagedCliDiscoverySpec
63 | SourceControlApiDiscoverySpec;
64​
65type SourceControlCliRemoteRefinementSpec = SourceControlCliDiscoverySpec & {
66 readonly refineUnknownRemote: NonNullable<SourceControlCliDiscoverySpec["refineUnknownRemote"]>;
67};
68​
69// Most provider CLIs answer `--version` in well under a second, so a short budget keeps
70// discovery snappy. Specs whose CLI is known to be slower can raise it via probeTimeoutMs.
71const DEFAULT_PROBE_TIMEOUT_MS = 5_000;
72​
73function probeTimeoutMs(spec: SourceControlCliDiscoverySpec): number {
74 return spec.probeTimeoutMs ?? DEFAULT_PROBE_TIMEOUT_MS;
76​
77interface DiscoveryProbeResult {
78 readonly kind: SourceControlProviderKind;
79 readonly label: string;
80 readonly executable: string;
81 readonly status: "available" | "missing";
82 readonly version: Option.Option<string>;
83 readonly installHint: string;
84 readonly detail: Option.Option<string>;
86​
87export function firstNonEmptyLine(text: string): Option.Option<string> {
88 const line = NodeUtil.stripVTControlCharacters(text)
89 .split(/\r?\n/)
90 .map((entry) => entry.trim())
91 .find((entry) => entry.length > 0);
92 return line === undefined ? Option.none() : Option.some(line);
94​
95export function detailFromCause(cause: unknown): Option.Option<string> {
96 if (cause instanceof Error && cause.message.trim().length > 0) {
97 return Option.some(cause.message.trim());
98 }
99 return Option.none();
101​
102function authAccount(account: string | undefined): Option.Option<string> {
103 const trimmed = account?.trim();
104 return trimmed === undefined || trimmed.length === 0 ? Option.none() : Option.some(trimmed);
106​
107function authHost(host: string | undefined): Option.Option<string> {
108 const trimmed = host?.trim();
109 return trimmed === undefined || trimmed.length === 0 ? Option.none() : Option.some(trimmed);
111​
112function authDetail(detail: string | undefined): Option.Option<string> {
113 const trimmed = detail?.trim();
114 return trimmed === undefined || trimmed.length === 0 ? Option.none() : Option.some(trimmed);
116​
117export function providerAuth(input: {
118 readonly status: SourceControlProviderAuth["status"];
119 readonly account?: string | undefined;
120 readonly host?: string | undefined;
121 readonly detail?: string | undefined;
122}): SourceControlProviderAuth {
123 return {
124 status: input.status,
125 account: authAccount(input.account),
126 host: authHost(input.host),
127 detail: authDetail(input.detail),
128 };
130​
131function unknownAuth(detail?: string): SourceControlProviderAuth {
132 return providerAuth({ status: "unknown", detail });
134​
135export function combinedAuthOutput(input: SourceControlAuthProbeInput): string {
136 const parts: string[] = [];
137 for (const entry of [input.stdout, input.stderr]) {
138 if (entry.trim().length > 0) {
139 parts.push(entry);
140 }
141 }
142 return parts.join("\n");
144​
145function sanitizedAuthLines(text: string): ReadonlyArray<string> {
146 const lines: string[] = [];
147 for (const entry of text.split(/\r?\n/)) {
148 const line = entry.trim();
149 if (line.length === 0) continue;
150 if (/^[-\s]*token(?:\s+scopes?)?:/iu.test(line)) continue;
151 lines.push(line);
152 }
153 return lines;
155​
156export function firstSafeAuthLine(text: string): string | undefined {
157 return sanitizedAuthLines(text)[0];
159​
160export function parseCliHost(text: string): string | undefined {
161 return sanitizedAuthLines(text)
162 .map((line) => line.replace(/^[^a-z0-9]+/iu, ""))
163 .find((line) => /^[a-z0-9][a-z0-9.-]*(?::\d+)?$/iu.test(line));
165​
166export function matchFirst(text: string, patterns: ReadonlyArray<RegExp>): string | undefined {
167 for (const pattern of patterns) {
168 const match = pattern.exec(text);
169 const value = match?.[1]?.trim();
170 if (value && value.length > 0) return value;
171 }
172 return undefined;
174​
175function isCliRemoteRefinementSpec(
176 spec: SourceControlProviderDiscoverySpec,
177): spec is SourceControlCliRemoteRefinementSpec {
178 return spec.type === "cli" && spec.refineUnknownRemote !== undefined;
180​
181function probeCli(input: {
182 readonly spec: SourceControlCliDiscoverySpec;
183 readonly process: VcsProcess.VcsProcess["Service"];
184 readonly cwd: string;
185}): Effect.Effect<DiscoveryProbeResult> {
186 return input.process
187 .run({
188 operation: "source-control.discovery.probe",
189 command: input.spec.executable,
190 args: input.spec.versionArgs,
191 cwd: input.cwd,
192 timeoutMs: probeTimeoutMs(input.spec),
193 maxOutputBytes: 8_000,
194 appendTruncationMarker: true,
195 })
196 .pipe(
197 Effect.map(
198 (result) =>
199 ({
200 kind: input.spec.kind,
201 label: input.spec.label,
202 executable: input.spec.executable,
203 status: "available" as const,
204 version: Option.orElse(firstNonEmptyLine(result.stdout), () =>
205 firstNonEmptyLine(result.stderr),
206 ),
207 installHint: input.spec.installHint,
208 detail: Option.none<string>(),
209 }) satisfies DiscoveryProbeResult,
210 ),
211 Effect.catch((cause) =>
212 Effect.succeed({
213 kind: input.spec.kind,
214 label: input.spec.label,
215 executable: input.spec.executable,
216 // Only an executable lookup failure establishes that the CLI is missing.
217 status:
218 cause._tag === "VcsProcessSpawnError" &&
219 cause.cause instanceof PlatformError.PlatformError &&
220 cause.cause.reason._tag === "NotFound" &&
221 cause.cause.reason.module === "ChildProcess" &&
222 cause.cause.reason.method === "spawn"
223 ? ("missing" as const)
224 : ("available" as const),
225 version: Option.none<string>(),
226 installHint: input.spec.installHint,
227 detail: detailFromCause(cause),
228 } satisfies DiscoveryProbeResult),
229 ),
230 );
232​
233export function probeSourceControlProvider(input: {
234 readonly spec: SourceControlProviderDiscoverySpec;
235 readonly process: VcsProcess.VcsProcess["Service"];
236 readonly cwd: string;
237}): Effect.Effect<SourceControlProviderDiscoveryItem> {
238 if (input.spec.type === "managed-cli") return input.spec.probe(input.cwd);
239 if (input.spec.type === "api") {
240 return input.spec.probeAuth.pipe(
241 Effect.map(
242 (auth) =>
243 ({
244 kind: input.spec.kind,
245 label: input.spec.label,
246 status: "available" as const,
247 version: Option.none<string>(),
248 installHint: input.spec.installHint,
249 detail: Option.none<string>(),
250 auth,
251 }) satisfies SourceControlProviderDiscoveryItem,
252 ),
253 );
254 }
255​
256 const spec = input.spec;
257​
258 return probeCli({
259 spec,
260 process: input.process,
261 cwd: input.cwd,
262 }).pipe(
263 Effect.flatMap((item) => {
264 if (item.status !== "available" || Option.isSome(item.detail)) {
265 return Effect.succeed({
266 ...item,
267 auth: unknownAuth(
268 Option.getOrElse(
269 item.detail,
270 () => "Hosting integration command was not found on the server PATH.",
271 ),
272 ),
273 } satisfies SourceControlProviderDiscoveryItem);
274 }
275​
276 return input.process
277 .run({
278 operation: "source-control.discovery.auth",
279 command: spec.executable,
280 args: spec.authArgs,
281 cwd: input.cwd,
282 allowNonZeroExit: true,
283 timeoutMs: probeTimeoutMs(spec),
284 maxOutputBytes: 8_000,
285 appendTruncationMarker: true,
286 })
287 .pipe(
288 Effect.map(
289 (result) =>
290 ({
291 ...item,
292 auth: spec.parseAuth(result),
293 }) satisfies SourceControlProviderDiscoveryItem,
294 ),
295 Effect.catch((cause) =>
296 Effect.succeed({
297 ...item,
298 auth: unknownAuth(Option.getOrUndefined(detailFromCause(cause))),
299 } satisfies SourceControlProviderDiscoveryItem),
300 ),
301 );
302 }),
303 );
305​
306export const refineUnknownRemoteProvider = Effect.fn("refineUnknownRemoteProvider")(
307 function* (input: {
308 readonly specs: ReadonlyArray<SourceControlProviderDiscoverySpec>;
309 readonly process: VcsProcess.VcsProcess["Service"];
310 readonly cwd: string;
311 readonly context: SourceControlProvider.SourceControlProviderContext | null;
312 }): Effect.fn.Return<SourceControlProvider.SourceControlProviderContext | null> {
313 if (input.context === null || input.context.provider.kind !== "unknown") {
314 return input.context;
315 }
316 const context = input.context;
317​
318 const providers = yield* Effect.forEach(input.specs, (spec) => {
319 if (spec.type === "managed-cli") {
320 return spec.refineUnknownRemote({ cwd: input.cwd, context });
321 }
322 if (!isCliRemoteRefinementSpec(spec)) return Effect.succeed(null);
323 return input.process
324 .run({
325 operation: "source-control.discovery.refine-unknown-remote",
326 command: spec.executable,
327 args: spec.remoteRefinementArgs ?? spec.authArgs,
328 cwd: input.cwd,
329 allowNonZeroExit: true,
330 timeoutMs: probeTimeoutMs(spec),
331 maxOutputBytes: 8_000,
332 appendTruncationMarker: true,
333 })
334 .pipe(
335 Effect.map((auth) =>
336 spec.refineUnknownRemote({
337 cwd: input.cwd,
338 context,
339 auth,
340 }),
341 ),
342 Effect.orElseSucceed(() => null),
343 );
344 });
345 const provider = providers.find((candidate) => candidate !== null);
346​
347 return provider ? { ...context, provider } : context;
348 },
349);