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