Open History to see the last commit
1import {
2 type SourceControlProviderAuth,
3 type SourceControlDiscoveryResult,
4 type SourceControlProviderDiscoveryItem,
5 type SourceControlProviderKind,
6 type VcsDiscoveryItem,
7 type VcsDriverKind,
8} from "@t3tools/contracts";
9import { Context, Effect, Layer, Option } from "effect";
10
11import { ServerConfig } from "../config.ts";
12import * as VcsProcess from "../vcs/VcsProcess.ts";
13
14interface DiscoveryProbe {
15 readonly label: string;
16 readonly executable?: string;
17 readonly versionArgs?: ReadonlyArray<string>;
18 readonly implemented: boolean;
19 readonly installHint: string;
20}
21
22type VcsProbe = DiscoveryProbe & {
23 readonly kind: VcsDriverKind;
24 readonly executable: string;
25 readonly versionArgs: ReadonlyArray<string>;
26};
27
28type ProviderProbe = DiscoveryProbe & {
29 readonly kind: SourceControlProviderKind;
30 readonly authArgs?: ReadonlyArray<string>;
31 readonly parseAuth?: (input: AuthProbeInput) => SourceControlProviderAuth;
32};
33
34interface AuthProbeInput {
35 readonly stdout: string;
36 readonly stderr: string;
37 readonly exitCode: VcsProcess.VcsProcessOutput["exitCode"];
38}
39
40interface DiscoveryProbeResult<Kind extends string> {
41 readonly kind: Kind;
42 readonly label: string;
43 readonly executable?: string;
44 readonly implemented: boolean;
45 readonly status: "available" | "missing";
46 readonly version: Option.Option<string>;
47 readonly installHint: string;
48 readonly detail: Option.Option<string>;
49}
50
51const VCS_PROBES: ReadonlyArray<VcsProbe> = [
52 {
53 kind: "git",
54 label: "Git",
55 executable: "git",
56 versionArgs: ["--version"],
57 implemented: true,
58 installHint: "Install Git from https://git-scm.com/downloads or with your package manager.",
59 },
60 {
61 kind: "jj",
62 label: "Jujutsu",
63 executable: "jj",
64 versionArgs: ["--version"],
65 implemented: false,
66 installHint: "Install Jujutsu with `brew install jj` or from https://github.com/jj-vcs/jj.",
67 },
68];
69
70const SOURCE_CONTROL_PROVIDER_PROBES: ReadonlyArray<ProviderProbe> = [
71 {
72 kind: "github",
73 label: "GitHub",
74 executable: "gh",
75 versionArgs: ["--version"],
76 authArgs: ["auth", "status"],
77 parseAuth: parseGitHubAuth,
78 implemented: true,
79 installHint: "Install GitHub CLI with `brew install gh` or from https://cli.github.com/.",
80 },
81 {
82 kind: "gitlab",
83 label: "GitLab",
84 executable: "glab",
85 versionArgs: ["--version"],
86 authArgs: ["auth", "status"],
87 parseAuth: parseGitLabAuth,
88 implemented: true,
89 installHint:
90 "Install GitLab CLI with `brew install glab` or from https://gitlab.com/gitlab-org/cli.",
91 },
92 {
93 kind: "azure-devops",
94 label: "Azure DevOps",
95 executable: "az",
96 versionArgs: ["--version"],
97 authArgs: ["account", "show", "--query", "user.name", "-o", "tsv"],
98 parseAuth: parseAzureAuth,
99 implemented: false,
100 installHint:
101 "Install Azure CLI with `brew install azure-cli`, then add Azure DevOps support with `az extension add --name azure-devops`.",
102 },
103 {
104 kind: "bitbucket",
105 label: "Bitbucket",
106 implemented: false,
107 installHint: "Bitbucket provider support is not available yet.",
108 },
109];
110
111function firstNonEmptyLine(text: string): Option.Option<string> {
112 const line = text
113 .split(/\r?\n/)
114 .map((entry) => entry.trim())
115 .find((entry) => entry.length > 0);
116 return line === undefined ? Option.none() : Option.some(line);
117}
118
119function detailFromCause(cause: unknown): Option.Option<string> {
120 if (cause instanceof Error && cause.message.trim().length > 0) {
121 return Option.some(cause.message.trim());
122 }
123 return Option.none();
124}
125
126function authAccount(account: string | undefined): Option.Option<string> {
127 const trimmed = account?.trim();
128 return trimmed === undefined || trimmed.length === 0 ? Option.none() : Option.some(trimmed);
129}
130
131function authHost(host: string | undefined): Option.Option<string> {
132 const trimmed = host?.trim();
133 return trimmed === undefined || trimmed.length === 0 ? Option.none() : Option.some(trimmed);
134}
135
136function authDetail(detail: string | undefined): Option.Option<string> {
137 const trimmed = detail?.trim();
138 return trimmed === undefined || trimmed.length === 0 ? Option.none() : Option.some(trimmed);
139}
140
141function providerAuth(input: {
142 readonly status: SourceControlProviderAuth["status"];
143 readonly account?: string | undefined;
144 readonly host?: string | undefined;
145 readonly detail?: string | undefined;
146}): SourceControlProviderAuth {
147 return {
148 status: input.status,
149 account: authAccount(input.account),
150 host: authHost(input.host),
151 detail: authDetail(input.detail),
152 };
153}
154
155function unknownAuth(detail?: string): SourceControlProviderAuth {
156 return providerAuth({ status: "unknown", detail });
157}
158
159function combinedAuthOutput(input: AuthProbeInput): string {
160 return [input.stdout, input.stderr].filter((entry) => entry.trim().length > 0).join("\n");
161}
162
163function sanitizedAuthLines(text: string): ReadonlyArray<string> {
164 return text
165 .split(/\r?\n/)
166 .map((entry) => entry.trim())
167 .filter((entry) => entry.length > 0)
168 .filter((entry) => !/^[-\s]*token(?:\s+scopes?)?:/iu.test(entry));
169}
170
171function firstSafeAuthLine(text: string): string | undefined {
172 return sanitizedAuthLines(text)[0];
173}
174
175function parseCliHost(text: string): string | undefined {
176 return sanitizedAuthLines(text)
177 .map((line) => line.replace(/^[^a-z0-9]+/iu, ""))
178 .find((line) => /^[a-z0-9][a-z0-9.-]*(?::\d+)?$/iu.test(line));
179}
180
181function matchFirst(text: string, patterns: ReadonlyArray<RegExp>): string | undefined {
182 for (const pattern of patterns) {
183 const match = pattern.exec(text);
184 const value = match?.[1]?.trim();
185 if (value && value.length > 0) return value;
186 }
187 return undefined;
188}
189
190function parseGitHubAuth(input: AuthProbeInput): SourceControlProviderAuth {
191 const output = combinedAuthOutput(input);
192 const account = matchFirst(output, [
193 /Logged in to .* account\s+([^\s(]+)/iu,
194 /Logged in to .* as\s+([^\s(]+)/iu,
195 ]);
196 const host = parseCliHost(output);
197
198 if (input.exitCode !== 0) {
199 return providerAuth({
200 status: "unauthenticated",
201 host,
202 detail: firstSafeAuthLine(output) ?? "Run `gh auth login` to authenticate GitHub CLI.",
203 });
204 }
205
206 if (account) {
207 return providerAuth({ status: "authenticated", account, host });
208 }
209
210 return providerAuth({
211 status: "unknown",
212 host,
213 detail: firstSafeAuthLine(output) ?? "GitHub CLI auth status could not be parsed.",
214 });
215}
216
217function parseGitLabAuth(input: AuthProbeInput): SourceControlProviderAuth {
218 const output = combinedAuthOutput(input);
219 const account = matchFirst(output, [
220 /Logged in to .* as\s+([^\s(]+)/iu,
221 /Logged in to .* account\s+([^\s(]+)/iu,
222 /account:\s*([^\s(]+)/iu,
223 ]);
224 const host = parseCliHost(output);
225
226 if (input.exitCode !== 0) {
227 return providerAuth({
228 status: "unauthenticated",
229 host,
230 detail: firstSafeAuthLine(output) ?? "Run `glab auth login` to authenticate GitLab CLI.",
231 });
232 }
233
234 if (account) {
235 return providerAuth({ status: "authenticated", account, host });
236 }
237
238 return providerAuth({
239 status: "unknown",
240 host,
241 detail: firstSafeAuthLine(output) ?? "GitLab CLI auth status could not be parsed.",
242 });
243}
244
245function parseAzureAuth(input: AuthProbeInput): SourceControlProviderAuth {
246 const account = input.stdout.trim().split(/\r?\n/)[0]?.trim();
247
248 if (input.exitCode !== 0) {
249 return providerAuth({
250 status: "unauthenticated",
251 detail:
252 firstSafeAuthLine(combinedAuthOutput(input)) ?? "Run `az login` to authenticate Azure CLI.",
253 });
254 }
255
256 if (account && account.length > 0) {
257 return providerAuth({ status: "authenticated", account, host: "dev.azure.com" });
258 }
259
260 return providerAuth({
261 status: "unknown",
262 host: "dev.azure.com",
263 detail: "Azure CLI account status could not be parsed.",
264 });
265}
266
267export interface SourceControlDiscoveryShape {
268 readonly discover: Effect.Effect<SourceControlDiscoveryResult>;
269}
270
271export class SourceControlDiscovery extends Context.Service<
272 SourceControlDiscovery,
273 SourceControlDiscoveryShape
274>()("t3/source-control/SourceControlDiscovery") {}
275
276export const layer = Layer.effect(
277 SourceControlDiscovery,
278 Effect.gen(function* () {
279 const config = yield* ServerConfig;
280 const process = yield* VcsProcess.VcsProcess;
281
282 const probe = <Kind extends VcsDriverKind | SourceControlProviderKind>(
283 input: DiscoveryProbe & { readonly kind: Kind },
284 ): Effect.Effect<DiscoveryProbeResult<Kind>> => {
285 const executable = input.executable;
286 const versionArgs = input.versionArgs;
287
288 if (!executable || !versionArgs) {
289 return Effect.succeed({
290 kind: input.kind,
291 label: input.label,
292 implemented: input.implemented,
293 status: "missing" as const,
294 version: Option.none<string>(),
295 installHint: input.installHint,
296 detail: Option.some(input.installHint),
297 } satisfies DiscoveryProbeResult<Kind>);
298 }
299
300 return process
301 .run({
302 operation: "source-control.discovery.probe",
303 command: executable,
304 args: versionArgs,
305 cwd: config.cwd,
306 timeoutMs: 5_000,
307 maxOutputBytes: 8_000,
308 truncateOutputAtMaxBytes: true,
309 })
310 .pipe(
311 Effect.map(
312 (result) =>
313 ({
314 kind: input.kind,
315 label: input.label,
316 executable,
317 implemented: input.implemented,
318 status: "available" as const,
319 version: Option.orElse(firstNonEmptyLine(result.stdout), () =>
320 firstNonEmptyLine(result.stderr),
321 ),
322 installHint: input.installHint,
323 detail: Option.none<string>(),
324 }) satisfies DiscoveryProbeResult<Kind>,
325 ),
326 Effect.catch((cause) =>
327 Effect.succeed({
328 kind: input.kind,
329 label: input.label,
330 executable,
331 implemented: input.implemented,
332 status: "missing" as const,
333 version: Option.none<string>(),
334 installHint: input.installHint,
335 detail: detailFromCause(cause),
336 } satisfies DiscoveryProbeResult<Kind>),
337 ),
338 );
339 };
340
341 const probeProvider = (input: ProviderProbe) =>
342 probe(input).pipe(
343 Effect.flatMap((item) => {
344 const executable = input.executable;
345 const authArgs = input.authArgs;
346 const parseAuth = input.parseAuth;
347
348 if (!executable || !authArgs || !parseAuth) {
349 return Effect.succeed({
350 ...item,
351 auth: unknownAuth(input.installHint),
352 } satisfies SourceControlProviderDiscoveryItem);
353 }
354
355 if (item.status !== "available") {
356 return Effect.succeed({
357 ...item,
358 auth: unknownAuth("CLI is not installed."),
359 } satisfies SourceControlProviderDiscoveryItem);
360 }
361
362 return process
363 .run({
364 operation: "source-control.discovery.auth",
365 command: executable,
366 args: authArgs,
367 cwd: config.cwd,
368 allowNonZeroExit: true,
369 timeoutMs: 5_000,
370 maxOutputBytes: 8_000,
371 truncateOutputAtMaxBytes: true,
372 })
373 .pipe(
374 Effect.map(
375 (result) =>
376 ({
377 ...item,
378 auth: parseAuth(result),
379 }) satisfies SourceControlProviderDiscoveryItem,
380 ),
381 Effect.catch((cause) =>
382 Effect.succeed({
383 ...item,
384 auth: unknownAuth(Option.getOrUndefined(detailFromCause(cause))),
385 } satisfies SourceControlProviderDiscoveryItem),
386 ),
387 );
388 }),
389 );
390
391 return SourceControlDiscovery.of({
392 discover: Effect.all({
393 versionControlSystems: Effect.all(
394 VCS_PROBES.map((entry) => probe(entry)) as ReadonlyArray<Effect.Effect<VcsDiscoveryItem>>,
395 { concurrency: "unbounded" },
396 ),
397 sourceControlProviders: Effect.all(
398 SOURCE_CONTROL_PROVIDER_PROBES.map((entry) => probeProvider(entry)) as ReadonlyArray<
399 Effect.Effect<SourceControlProviderDiscoveryItem>
400 >,
401 { concurrency: "unbounded" },
402 ),
403 }),
404 });
405 }),
406);