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