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

SourceControlProviderDiscovery.ts

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