@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 393 lines 14.4 KB
Raw
1 import { SourceControlProviderKind } from "@t3tools/contracts";
2 import * as Schema from "effect/Schema";
3 import * as Effect from "effect/Effect";
4 import * as Option from "effect/Option";
5 import { SourceControlProviderError, type ChangeRequest } from "@t3tools/contracts";
6 import {
7 parseGitRemoteHost,
8 unknownRemoteProvider as unknownHostProvider,
9 } from "@t3tools/source-control-core/shared/definition";
10
11 import * as GitLabCli from "./GitLabCli.ts";
12 import * as GitLabChangeRequestTemplate from "./gitLabChangeRequestTemplate.ts";
13 import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
14 import * as SourceControlProvider from "@t3tools/source-control-core/server/SourceControlProvider";
15 import {
16 combinedAuthOutput,
17 firstSafeAuthLine,
18 matchFirst,
19 parseCliHost,
20 providerAuth,
21 type SourceControlAuthProbeInput,
22 type SourceControlCliDiscoverySpec,
23 type SourceControlUnknownRemoteRefinementInput,
24 } from "@t3tools/source-control-core/server/discovery";
25 import { findAuthenticatedGitLabHost, parseGitLabAuthStatusHosts } from "./gitLabAuthStatus.ts";
26
27 const decodeLinkSubject = Schema.decodeUnknownEffect(
28 Schema.fromJsonString(
29 Schema.Struct({ title: Schema.String, description: Schema.NullOr(Schema.String) }),
30 ),
31 );
32
33 function toChangeRequest(summary: GitLabCli.GitLabMergeRequestSummary): ChangeRequest {
34 return {
35 provider: SourceControlProviderKind.make("gitlab"),
36 number: summary.number,
37 title: summary.title,
38 url: summary.url,
39 baseRefName: summary.baseRefName,
40 headRefName: summary.headRefName,
41 ...(summary.headSha !== undefined ? { headSha: summary.headSha } : {}),
42 state: summary.state ?? "open",
43 ...(summary.isDraft === true ? { isDraft: true } : {}),
44 closedAt: summary.closedAt ?? null,
45 mergedAt: summary.mergedAt ?? null,
46 updatedAt: summary.updatedAt ?? Option.none(),
47 ...(summary.isCrossRepository !== undefined
48 ? { isCrossRepository: summary.isCrossRepository }
49 : {}),
50 ...(summary.headRepositoryNameWithOwner !== undefined
51 ? { headRepositoryNameWithOwner: summary.headRepositoryNameWithOwner }
52 : {}),
53 ...(summary.headRepositoryOwnerLogin !== undefined
54 ? { headRepositoryOwnerLogin: summary.headRepositoryOwnerLogin }
55 : {}),
56 };
57 }
58
59 function parseGitLabAuth(input: SourceControlAuthProbeInput) {
60 const output = combinedAuthOutput(input);
61 const authenticatedHost = findAuthenticatedGitLabHost(parseGitLabAuthStatusHosts(output));
62 const account =
63 authenticatedHost?.account ??
64 matchFirst(output, [
65 /Logged in to .* as\s+([^\s(]+)/iu,
66 /Logged in to .* account\s+([^\s(]+)/iu,
67 /account:\s*([^\s(]+)/iu,
68 ]);
69 const host = authenticatedHost?.host ?? parseCliHost(output);
70
71 if (account) {
72 return providerAuth({ status: "authenticated", account, host });
73 }
74
75 if (input.exitCode !== 0) {
76 return providerAuth({
77 status: "unauthenticated",
78 host,
79 detail: firstSafeAuthLine(output) ?? "Run `glab auth login` to authenticate GitLab CLI.",
80 });
81 }
82
83 return providerAuth({
84 status: "unknown",
85 host,
86 detail: firstSafeAuthLine(output) ?? "GitLab CLI auth status could not be parsed.",
87 });
88 }
89
90 const GITLAB_HOST_NOT_LOGGED_IN_PATTERN =
91 /\bnot (?:been )?authenticated with glab\b|\bno gitlab instances? ha(?:s|ve) been authenticated\b/iu;
92
93 function refineUnknownGitLabRemote(input: SourceControlUnknownRemoteRefinementInput) {
94 const host = input.context.provider.name.toLowerCase();
95 const output = combinedAuthOutput(input.auth);
96 const authenticated = parseGitLabAuthStatusHosts(output).some(
97 (entry) => entry.account !== null && entry.host === host,
98 );
99
100 if (!authenticated) {
101 return GITLAB_HOST_NOT_LOGGED_IN_PATTERN.test(output) ? null : undefined;
102 }
103
104 return {
105 kind: SourceControlProviderKind.make("gitlab"),
106 name: "GitLab Self-Hosted",
107 baseUrl: input.context.provider.baseUrl,
108 } as const;
109 }
110
111 /** The caller refines only an identity no host recognised, so its remote is on an unknown host. */
112 function unknownRemoteProvider(remoteUrl: string) {
113 const remote = parseGitRemoteHost(remoteUrl);
114 return remote === null ? null : unknownHostProvider(remote);
115 }
116
117 // A glab login confirms a self-hosted GitLab whose hostname does not identify its provider.
118 const refineRepositoryIdentity: NonNullable<
119 SourceControlProvider.SourceControlProvider["Service"]["refineRepositoryIdentity"]
120 > = Effect.fn("GitLabSourceControlProvider.refineRepositoryIdentity")(function* ({
121 identity,
122 resolveContext,
123 }) {
124 if (!identity.rootPath || (identity.provider !== undefined && identity.provider !== "unknown"))
125 return identity;
126 const provider = unknownRemoteProvider(identity.locator.remoteUrl);
127 if (!provider) return identity;
128 const context = yield* resolveContext({
129 cwd: identity.rootPath,
130 context: {
131 provider,
132 remoteName: identity.locator.remoteName,
133 remoteUrl: identity.locator.remoteUrl,
134 },
135 });
136 return context?.provider.kind === "gitlab"
137 ? { ...identity, provider: SourceControlProviderKind.make("gitlab") }
138 : identity;
139 });
140
141 export const discovery = {
142 type: "cli",
143 kind: SourceControlProviderKind.make("gitlab"),
144 label: "GitLab",
145 executable: "glab",
146 versionArgs: ["--version"],
147 // Without --all, glab 1.79+ checks only the current host unless that is gitlab.com; older
148 // glab lists every host and rejects --all. --all waits on every host, so ask it only after
149 // the current host reports signed out.
150 authArgs: ["auth", "status"],
151 authRetryArgs: ["auth", "status", "--all"],
152 // glab host matching requires the remote's exact spelling.
153 remoteRefinementArgs: ({ provider, remoteUrl }) => {
154 const authority = /^[a-z][a-z0-9+.-]*:\/\/([^/]+)/iu.exec(remoteUrl.trim())?.[1];
155 const remoteHost = authority
156 ? authority.slice(authority.lastIndexOf("@") + 1)
157 : remoteUrl.trim().replace(/^[^@:/]+@/u, "");
158 const host = remoteHost.toLowerCase().startsWith(provider.name.toLowerCase())
159 ? remoteHost.slice(0, provider.name.length)
160 : provider.name;
161 return ["auth", "status", "--hostname", host];
162 },
163 parseAuth: parseGitLabAuth,
164 refineUnknownRemote: refineUnknownGitLabRemote,
165 installHint:
166 "Install the GitLab command-line tool (`glab`) from https://gitlab.com/gitlab-org/cli or your package manager (for example `brew install glab`).",
167 } satisfies SourceControlCliDiscoverySpec;
168
169 export const make = Effect.gen(function* () {
170 const gitlab = yield* GitLabCli.GitLabCli;
171 const { git } = yield* SourceControlHost.SourceControlHost;
172
173 const readLinkSubject = Effect.fn("GitLabSourceControlProvider.readLinkSubject")(function* (
174 input: { readonly cwd: string; readonly url: URL },
175 endpoint: string,
176 ) {
177 const result = yield* gitlab
178 .execute({
179 cwd: input.cwd,
180 callerNamedHost: input.url.host,
181 args: ["api", "--hostname", input.url.host, endpoint],
182 timeoutMs: 3_000,
183 maxOutputBytes: 32_000,
184 })
185 .pipe(
186 Effect.mapError(
187 (cause) =>
188 new SourceControlProviderError({
189 provider: SourceControlProviderKind.make("gitlab"),
190 operation: "resolveLink",
191 cwd: input.cwd,
192 detail: "The linked subject could not be read.",
193 cause,
194 }),
195 ),
196 );
197 const subject = yield* decodeLinkSubject(result.stdout).pipe(
198 Effect.mapError(
199 (cause) =>
200 new SourceControlProviderError({
201 provider: SourceControlProviderKind.make("gitlab"),
202 operation: "resolveLink.decode",
203 cwd: input.cwd,
204 detail: "The linked subject could not be read.",
205 cause,
206 }),
207 ),
208 );
209 return { title: subject.title, body: subject.description };
210 });
211
212 return SourceControlProvider.SourceControlProvider.of({
213 kind: SourceControlProviderKind.make("gitlab"),
214 // GitLab lists fork merge requests by source branch with no owner filter, so read a full page.
215 headBranchProbe: ({ headSelectors }) => ({
216 headSelectors: headSelectors.filter((selector) => !selector.includes(":")),
217 limit: 100,
218 }),
219 readChangeRequestTemplate: Effect.fn("GitLabSourceControlProvider.readChangeRequestTemplate")(
220 function ({ cwd, treeish }) {
221 return GitLabChangeRequestTemplate.detect(cwd, treeish, git.execute);
222 },
223 ),
224 refineRepositoryIdentity,
225 resolveLink: (input) => {
226 // Automatic enrichment must not send ambient CLI credentials to a host from message text.
227 if (input.url.host !== "gitlab.com") return undefined;
228 const match = /^\/(.+)\/-\/(merge_requests|issues)\/([1-9]\d*)(?:\/.*)?$/.exec(
229 input.url.pathname,
230 );
231 if (!match) return undefined;
232 return readLinkSubject(
233 input,
234 `projects/${encodeURIComponent(match[1]!)}/${match[2]}/${match[3]}`,
235 );
236 },
237 listChangeRequests: Effect.fn("GitLabSourceControlProvider.listChangeRequests")(
238 function (input) {
239 const source = SourceControlProvider.sourceControlRefFromInput(input);
240 return gitlab
241 .listMergeRequests({
242 cwd: input.cwd,
243 headSelector: input.headSelector,
244 ...(source ? { source } : {}),
245 state: input.state,
246 ...(input.limit !== undefined ? { limit: input.limit } : {}),
247 })
248 .pipe(
249 Effect.map((items) => items.map(toChangeRequest)),
250 Effect.mapError(
251 (error) =>
252 new SourceControlProviderError({
253 provider: SourceControlProviderKind.make("gitlab"),
254 operation: "listChangeRequests",
255 command: error.command,
256 cwd: input.cwd,
257 reference: SourceControlProvider.transportSafeSourceControlErrorValue(
258 input.headSelector,
259 ),
260 detail: error.detail,
261 cause: error,
262 }),
263 ),
264 );
265 },
266 ),
267 getChangeRequest: Effect.fn("GitLabSourceControlProvider.getChangeRequest")(function (input) {
268 return gitlab.getMergeRequest(input).pipe(
269 Effect.map(toChangeRequest),
270 Effect.mapError(
271 (error) =>
272 new SourceControlProviderError({
273 provider: SourceControlProviderKind.make("gitlab"),
274 operation: "getChangeRequest",
275 command: error.command,
276 cwd: input.cwd,
277 reference: SourceControlProvider.transportSafeSourceControlErrorValue(
278 input.reference,
279 ),
280 detail: error.detail,
281 cause: error,
282 }),
283 ),
284 );
285 }),
286 createsDraftChangeRequests: true,
287 createChangeRequest: Effect.fn("GitLabSourceControlProvider.createChangeRequest")(
288 function (input) {
289 const source = SourceControlProvider.sourceControlRefFromInput(input);
290 return gitlab
291 .createMergeRequest({
292 cwd: input.cwd,
293 baseBranch: input.baseRefName,
294 headSelector: input.headSelector,
295 ...(source ? { source } : {}),
296 ...(input.target ? { target: input.target } : {}),
297 title: input.title,
298 bodyFile: input.bodyFile,
299 ...(input.draft === true ? { draft: true } : {}),
300 })
301 .pipe(
302 Effect.mapError(
303 (error) =>
304 new SourceControlProviderError({
305 provider: SourceControlProviderKind.make("gitlab"),
306 operation: "createChangeRequest",
307 command: error.command,
308 cwd: input.cwd,
309 reference: SourceControlProvider.transportSafeSourceControlErrorValue(
310 input.headSelector,
311 ),
312 detail: error.detail,
313 cause: error,
314 }),
315 ),
316 );
317 },
318 ),
319 getRepositoryCloneUrls: Effect.fn("GitLabSourceControlProvider.getRepositoryCloneUrls")(
320 function (input) {
321 return gitlab.getRepositoryCloneUrls(input).pipe(
322 Effect.mapError(
323 (error) =>
324 new SourceControlProviderError({
325 provider: SourceControlProviderKind.make("gitlab"),
326 operation: "getRepositoryCloneUrls",
327 command: error.command,
328 cwd: input.cwd,
329 repository: SourceControlProvider.transportSafeSourceControlErrorValue(
330 input.repository,
331 ),
332 detail: error.detail,
333 cause: error,
334 }),
335 ),
336 );
337 },
338 ),
339 createRepository: Effect.fn("GitLabSourceControlProvider.createRepository")(function (input) {
340 return gitlab.createRepository(input).pipe(
341 Effect.mapError(
342 (error) =>
343 new SourceControlProviderError({
344 provider: SourceControlProviderKind.make("gitlab"),
345 operation: "createRepository",
346 command: error.command,
347 cwd: input.cwd,
348 repository: SourceControlProvider.transportSafeSourceControlErrorValue(
349 input.repository,
350 ),
351 detail: error.detail,
352 cause: error,
353 }),
354 ),
355 );
356 }),
357 getDefaultBranch: Effect.fn("GitLabSourceControlProvider.getDefaultBranch")(function (input) {
358 return gitlab.getDefaultBranch(input).pipe(
359 Effect.mapError(
360 (error) =>
361 new SourceControlProviderError({
362 provider: SourceControlProviderKind.make("gitlab"),
363 operation: "getDefaultBranch",
364 command: error.command,
365 cwd: input.cwd,
366 detail: error.detail,
367 cause: error,
368 }),
369 ),
370 );
371 }),
372 checkoutChangeRequest: Effect.fn("GitLabSourceControlProvider.checkoutChangeRequest")(
373 function (input) {
374 return gitlab.checkoutMergeRequest(input).pipe(
375 Effect.mapError(
376 (error) =>
377 new SourceControlProviderError({
378 provider: SourceControlProviderKind.make("gitlab"),
379 operation: "checkoutChangeRequest",
380 command: error.command,
381 cwd: input.cwd,
382 reference: SourceControlProvider.transportSafeSourceControlErrorValue(
383 input.reference,
384 ),
385 detail: error.detail,
386 cause: error,
387 }),
388 ),
389 );
390 },
391 ),
392 });
393 });