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

SourceControlProviderDiscovery.ts

318 lines10.1 KB

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