@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 825 lines 26.8 KB
Raw
1 import * as Context from "effect/Context";
2 import * as Effect from "effect/Effect";
3 import * as Exit from "effect/Exit";
4 import * as FileSystem from "effect/FileSystem";
5 import * as Layer from "effect/Layer";
6 import * as Match from "effect/Match";
7 import * as Option from "effect/Option";
8 import * as Result from "effect/Result";
9 import * as Schema from "effect/Schema";
10 import type * as DateTime from "effect/DateTime";
11
12 import {
13 TrimmedNonEmptyString,
14 type SourceControlRepositoryVisibility,
15 type VcsError,
16 type VcsProcessExitFailureKind,
17 } from "@t3tools/contracts";
18
19 import * as HostProcess from "@t3tools/shared/HostProcess";
20 import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
21 import {
22 decodeGitLabMergeRequestJson,
23 decodeGitLabMergeRequestListJson,
24 } from "./gitLabMergeRequests.ts";
25 import type * as SourceControlProvider from "@t3tools/source-control-core/server/SourceControlProvider";
26
27 const DEFAULT_TIMEOUT_MS = 30_000;
28 // GitLab allows ~1M-character descriptions; glab's JSON escaping (`\u003c`) can grow one sixfold.
29 const MERGE_REQUEST_LIST_MAX_BYTES = 8_000_000;
30 const decodeJsonArray = Schema.decodeUnknownExit(
31 Schema.fromJsonString(Schema.Array(Schema.Unknown)),
32 );
33
34 const gitLabCliExecutionErrorContext = {
35 operation: Schema.Literal("execute"),
36 command: Schema.Literal("glab"),
37 cwd: Schema.String,
38 cause: Schema.Defect(),
39 };
40
41 const gitLabCliDecodeErrorContext = {
42 command: Schema.Literal("glab"),
43 cwd: Schema.String,
44 cause: Schema.Defect(),
45 };
46
47 export class GitLabCliUnavailableError extends Schema.TaggedError<GitLabCliUnavailableError>()(
48 "GitLabCliUnavailableError",
49 gitLabCliExecutionErrorContext,
50 ) {
51 get detail(): string {
52 return "GitLab CLI (`glab`) is required but not available on PATH.";
53 }
54
55 override get message(): string {
56 return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
57 }
58 }
59
60 export class GitLabCliAuthenticationError extends Schema.TaggedError<GitLabCliAuthenticationError>()(
61 "GitLabCliAuthenticationError",
62 gitLabCliExecutionErrorContext,
63 ) {
64 get detail(): string {
65 return "GitLab CLI is not authenticated. Run `glab auth login` and retry.";
66 }
67
68 override get message(): string {
69 return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
70 }
71 }
72
73 export class GitLabCliRateLimitError extends Schema.TaggedError<GitLabCliRateLimitError>()(
74 "GitLabCliRateLimitError",
75 gitLabCliExecutionErrorContext,
76 ) {
77 get detail(): string {
78 return "GitLab API rate limit exceeded.";
79 }
80
81 override get message(): string {
82 return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
83 }
84 }
85
86 export class GitLabMergeRequestNotFoundError extends Schema.TaggedError<GitLabMergeRequestNotFoundError>()(
87 "GitLabMergeRequestNotFoundError",
88 {
89 ...gitLabCliExecutionErrorContext,
90 reference: Schema.String,
91 },
92 ) {
93 get detail(): string {
94 return `Merge request ${this.reference} was not found. Check the MR number or URL and try again.`;
95 }
96
97 override get message(): string {
98 return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
99 }
100
101 static fromVcsError(
102 context: {
103 readonly operation: "execute";
104 readonly command: "glab";
105 readonly cwd: string;
106 readonly reference: string;
107 },
108 error: VcsError,
109 ): GitLabCliError {
110 if (error._tag === "VcsProcessExitError" && error.failureKind === "not-found") {
111 return new GitLabMergeRequestNotFoundError({ ...context, cause: error });
112 }
113
114 return GitLabCliCommandError.fromVcsError(
115 {
116 operation: context.operation,
117 command: context.command,
118 cwd: context.cwd,
119 },
120 error,
121 );
122 }
123 }
124
125 export class GitLabCliCommandError extends Schema.TaggedError<GitLabCliCommandError>()(
126 "GitLabCliCommandError",
127 gitLabCliExecutionErrorContext,
128 ) {
129 get detail(): string {
130 return "GitLab CLI command failed.";
131 }
132
133 override get message(): string {
134 return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
135 }
136
137 static fromVcsError(
138 context: {
139 readonly operation: "execute";
140 readonly command: "glab";
141 readonly cwd: string;
142 },
143 error: VcsError,
144 ): GitLabCliError {
145 return Match.valueTags(error, {
146 VcsProcessSpawnError: (cause) => new GitLabCliUnavailableError({ ...context, cause }),
147 VcsProcessExitError: (cause) => {
148 switch (cause.failureKind) {
149 case "authentication":
150 return new GitLabCliAuthenticationError({ ...context, cause });
151 case "rate-limited":
152 return new GitLabCliRateLimitError({ ...context, cause });
153 case "not-found":
154 case "command-failed":
155 case undefined:
156 return new GitLabCliCommandError({ ...context, cause });
157 }
158 },
159 VcsProcessTimeoutError: (cause) => new GitLabCliCommandError({ ...context, cause }),
160 VcsProcessStdinWriteError: (cause) => new GitLabCliCommandError({ ...context, cause }),
161 VcsProcessOutputReadError: (cause) => new GitLabCliCommandError({ ...context, cause }),
162 VcsProcessOutputLimitError: (cause) => new GitLabCliCommandError({ ...context, cause }),
163 VcsProcessMissingExitCodeError: (cause) => new GitLabCliCommandError({ ...context, cause }),
164 VcsRepositoryDetectionError: (cause) => new GitLabCliCommandError({ ...context, cause }),
165 VcsCheckpointStorageError: (cause) => new GitLabCliCommandError({ ...context, cause }),
166 VcsUnsupportedOperationError: (cause) => new GitLabCliCommandError({ ...context, cause }),
167 });
168 }
169 }
170
171 export class GitLabMergeRequestListDecodeError extends Schema.TaggedError<GitLabMergeRequestListDecodeError>()(
172 "GitLabMergeRequestListDecodeError",
173 {
174 ...gitLabCliDecodeErrorContext,
175 operation: Schema.Literal("listMergeRequests"),
176 },
177 ) {
178 get detail(): string {
179 return "GitLab CLI returned invalid MR list JSON.";
180 }
181
182 override get message(): string {
183 return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
184 }
185 }
186
187 export class GitLabMergeRequestDecodeError extends Schema.TaggedError<GitLabMergeRequestDecodeError>()(
188 "GitLabMergeRequestDecodeError",
189 {
190 ...gitLabCliDecodeErrorContext,
191 operation: Schema.Literal("getMergeRequest"),
192 reference: Schema.String,
193 },
194 ) {
195 get detail(): string {
196 return "GitLab CLI returned invalid merge request JSON.";
197 }
198
199 override get message(): string {
200 return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
201 }
202 }
203
204 export class GitLabRepositoryDecodeError extends Schema.TaggedError<GitLabRepositoryDecodeError>()(
205 "GitLabRepositoryDecodeError",
206 {
207 ...gitLabCliDecodeErrorContext,
208 operation: Schema.Literals([
209 "getRepositoryCloneUrls",
210 "createRepository",
211 "getDefaultBranch",
212 "createMergeRequest",
213 ]),
214 repository: Schema.optional(Schema.String),
215 },
216 ) {
217 get detail(): string {
218 return "GitLab CLI returned invalid repository JSON.";
219 }
220
221 override get message(): string {
222 return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
223 }
224 }
225
226 export class GitLabNamespaceDecodeError extends Schema.TaggedError<GitLabNamespaceDecodeError>()(
227 "GitLabNamespaceDecodeError",
228 {
229 ...gitLabCliDecodeErrorContext,
230 operation: Schema.Literal("createRepository"),
231 namespacePath: Schema.String,
232 },
233 ) {
234 get detail(): string {
235 return "GitLab CLI returned invalid namespace JSON.";
236 }
237
238 override get message(): string {
239 return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
240 }
241 }
242
243 export class GitLabMergeRequestBodyReadError extends Schema.TaggedError<GitLabMergeRequestBodyReadError>()(
244 "GitLabMergeRequestBodyReadError",
245 {
246 operation: Schema.Literal("createMergeRequest"),
247 command: Schema.Literal("glab"),
248 cwd: Schema.String,
249 cause: Schema.Defect(),
250 },
251 ) {
252 get detail(): string {
253 return "The merge request description could not be read.";
254 }
255
256 override get message(): string {
257 return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
258 }
259 }
260
261 export const GitLabCliError = Schema.Union([
262 GitLabCliUnavailableError,
263 GitLabCliAuthenticationError,
264 GitLabCliRateLimitError,
265 GitLabMergeRequestNotFoundError,
266 GitLabCliCommandError,
267 GitLabMergeRequestListDecodeError,
268 GitLabMergeRequestDecodeError,
269 GitLabRepositoryDecodeError,
270 GitLabNamespaceDecodeError,
271 GitLabMergeRequestBodyReadError,
272 ]);
273 export type GitLabCliError = typeof GitLabCliError.Type;
274
275 export interface GitLabMergeRequestSummary {
276 readonly number: number;
277 readonly title: string;
278 readonly url: string;
279 readonly baseRefName: string;
280 readonly headRefName: string;
281 readonly headSha?: string;
282 readonly state?: "open" | "closed" | "merged";
283 readonly isDraft?: boolean;
284 readonly closedAt?: string | null;
285 readonly mergedAt?: string | null;
286 readonly updatedAt?: Option.Option<DateTime.Utc>;
287 readonly isCrossRepository?: boolean;
288 readonly headRepositoryNameWithOwner?: string | null;
289 readonly headRepositoryOwnerLogin?: string | null;
290 }
291
292 export interface GitLabRepositoryCloneUrls {
293 readonly nameWithOwner: string;
294 readonly url: string;
295 readonly sshUrl: string;
296 }
297
298 export class GitLabCli extends Context.Service<
299 GitLabCli,
300 {
301 readonly execute: (input: {
302 readonly cwd: string;
303 readonly host?: string | undefined;
304 /** A host taken from caller input, not from a project remote. See `ENVIRONMENT_TOKEN_VARIABLES`. */
305 readonly callerNamedHost?: string | undefined;
306 readonly args: ReadonlyArray<string>;
307 readonly timeoutMs?: number;
308 /** Keeps sensitive payloads out of argv. */
309 readonly stdin?: string;
310 readonly maxOutputBytes?: number;
311 }) => Effect.Effect<SourceControlHost.SourceControlProcessOutput, GitLabCliError>;
312
313 readonly listMergeRequests: (input: {
314 readonly cwd: string;
315 readonly headSelector: string;
316 readonly source?: SourceControlProvider.SourceControlRefSelector;
317 readonly state: "open" | "closed" | "merged" | "all";
318 readonly limit?: number;
319 }) => Effect.Effect<ReadonlyArray<GitLabMergeRequestSummary>, GitLabCliError>;
320
321 readonly getMergeRequest: (input: {
322 readonly cwd: string;
323 readonly reference: string;
324 }) => Effect.Effect<GitLabMergeRequestSummary, GitLabCliError>;
325
326 readonly getRepositoryCloneUrls: (input: {
327 readonly cwd: string;
328 readonly repository: string;
329 }) => Effect.Effect<GitLabRepositoryCloneUrls, GitLabCliError>;
330
331 readonly createRepository: (input: {
332 readonly cwd: string;
333 readonly repository: string;
334 readonly visibility: SourceControlRepositoryVisibility;
335 }) => Effect.Effect<GitLabRepositoryCloneUrls, GitLabCliError>;
336
337 readonly createMergeRequest: (input: {
338 readonly cwd: string;
339 readonly baseBranch: string;
340 readonly headSelector: string;
341 readonly source?: SourceControlProvider.SourceControlRefSelector;
342 readonly target?: SourceControlProvider.SourceControlRefSelector;
343 readonly title: string;
344 readonly bodyFile: string;
345 readonly draft?: boolean;
346 }) => Effect.Effect<void, GitLabCliError>;
347
348 readonly getDefaultBranch: (input: {
349 readonly cwd: string;
350 }) => Effect.Effect<string | null, GitLabCliError>;
351
352 readonly checkoutMergeRequest: (input: {
353 readonly cwd: string;
354 readonly reference: string;
355 readonly force?: boolean;
356 }) => Effect.Effect<void, GitLabCliError>;
357 }
358 >()("@t3tools/source-control-gitlab/server/GitLabCli") {}
359
360 // The create-MR endpoint has no draft attribute; GitLab reads the draft marker from the title.
361 // Same markers and case rule as glab's `EnsureTitlePrefix`.
362 const draftTitle = (title: string) =>
363 /^\s*(?:\[draft\]|\(draft\)|draft:)/i.test(title) ? title : `Draft: ${title}`;
364
365 const RawGitLabRepositoryCloneUrlsSchema = Schema.Struct({
366 path_with_namespace: TrimmedNonEmptyString,
367 web_url: TrimmedNonEmptyString,
368 http_url_to_repo: TrimmedNonEmptyString,
369 ssh_url_to_repo: TrimmedNonEmptyString,
370 });
371
372 const RawGitLabDefaultBranchSchema = Schema.Struct({
373 default_branch: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
374 });
375
376 const decodeGitLabMergeRequestProject = Schema.decodeEffect(
377 Schema.fromJsonString(Schema.Struct({ id: Schema.Number, path: TrimmedNonEmptyString })),
378 );
379
380 const RawGitLabNamespaceSchema = Schema.Struct({
381 id: Schema.Number,
382 });
383
384 const decodeGitLabRepositoryCloneUrls = Schema.decodeEffect(
385 Schema.fromJsonString(RawGitLabRepositoryCloneUrlsSchema),
386 );
387 const decodeGitLabDefaultBranch = Schema.decodeEffect(
388 Schema.fromJsonString(RawGitLabDefaultBranchSchema),
389 );
390 const decodeGitLabNamespace = Schema.decodeEffect(Schema.fromJsonString(RawGitLabNamespaceSchema));
391
392 function normalizeRepositoryCloneUrls(
393 raw: Schema.Schema.Type<typeof RawGitLabRepositoryCloneUrlsSchema>,
394 ): GitLabRepositoryCloneUrls {
395 return {
396 nameWithOwner: raw.path_with_namespace,
397 url: raw.web_url,
398 sshUrl: raw.ssh_url_to_repo,
399 };
400 }
401
402 function stateArgs(state: "open" | "closed" | "merged" | "all"): ReadonlyArray<string> {
403 switch (state) {
404 case "open":
405 return [];
406 case "closed":
407 return ["--closed"];
408 case "merged":
409 return ["--merged"];
410 case "all":
411 return ["--all"];
412 }
413 }
414
415 function normalizeHeadSelector(headSelector: string): string {
416 const trimmed = headSelector.trim();
417 const ownerBranch = /^[^:]+:(.+)$/.exec(trimmed);
418 return ownerBranch?.[1]?.trim() || trimmed;
419 }
420
421 function sourceRefName(input: {
422 readonly headSelector: string;
423 readonly source?: SourceControlProvider.SourceControlRefSelector;
424 }): string {
425 return input.source?.refName ?? normalizeHeadSelector(input.headSelector);
426 }
427
428 function toSummaryWithOptionalUpdatedAt(
429 record: GitLabMergeRequestSummary & {
430 readonly updatedAt: Option.Option<DateTime.Utc>;
431 },
432 ): GitLabMergeRequestSummary {
433 const { updatedAt, ...summary } = record;
434 return Option.isSome(updatedAt) ? { ...summary, updatedAt } : summary;
435 }
436
437 function parseRepositoryPath(repository: string): {
438 readonly namespacePath: string | null;
439 readonly projectPath: string;
440 } {
441 const parts: Array<string> = [];
442 for (const part of repository.split("/")) {
443 const trimmed = part.trim();
444 if (trimmed.length > 0) {
445 parts.push(trimmed);
446 }
447 }
448 const projectPath = parts.at(-1) ?? repository.trim();
449 const namespacePath = parts.length > 1 ? parts.slice(0, -1).join("/") : null;
450 return { namespacePath, projectPath };
451 }
452
453 function parseRepositoryLookup(repository: string): {
454 readonly host: string | null;
455 readonly projectPath: string;
456 } {
457 const trimmed = repository.trim();
458 if (!/^https?:\/\//i.test(trimmed)) return { host: null, projectPath: repository };
459 try {
460 const url = new URL(trimmed);
461 const projectPath = decodeURIComponent(url.pathname)
462 .replace(/\/-(?:\/.*)?$/, "")
463 .replace(/^\/+|\/+$/g, "")
464 .replace(/\.git$/, "");
465 return projectPath.length === 0
466 ? { host: null, projectPath: repository }
467 : { host: url.host, projectPath };
468 } catch {
469 return { host: null, projectPath: repository };
470 }
471 }
472
473 // glab prints a missing project or merge request as a bare 404, and an expired
474 // OAuth login as an `invalid_grant` refresh failure without suggesting `glab auth login`.
475 const classifyGlabFailure = (stderr: string): VcsProcessExitFailureKind | null => {
476 const normalized = stderr.toLowerCase();
477 if (normalized.includes("glab auth login") || normalized.includes("invalid_grant")) {
478 return "authentication";
479 }
480
481 if (normalized.includes("not found") || normalized.includes("404")) {
482 return "not-found";
483 }
484
485 return null;
486 };
487
488 /**
489 * These are the login for glab's default host (GITLAB_HOST, else gitlab.com). glab before 1.131
490 * sends them to any host a command names, so a host a caller names runs without them and falls
491 * back to that host's own `glab auth login`.
492 */
493 const ENVIRONMENT_TOKEN_VARIABLES = ["GITLAB_TOKEN", "GITLAB_ACCESS_TOKEN", "OAUTH_TOKEN"] as const;
494 const WITHOUT_ENVIRONMENT_TOKEN = Object.fromEntries(
495 ENVIRONMENT_TOKEN_VARIABLES.map((name) => [name, ""]),
496 );
497
498 const hostOf = (value: string) =>
499 value
500 .trim()
501 .toLowerCase()
502 .replace(/^[a-z][a-z0-9+.-]*:\/\//, "")
503 .replace(/\/.*$/, "");
504
505 /** @public */
506 export const make = Effect.gen(function* () {
507 const { process } = yield* SourceControlHost.SourceControlHost;
508 const fileSystem = yield* FileSystem.FileSystem;
509 const environment = yield* HostProcess.Environment;
510 const defaultHost = hostOf(environment.GITLAB_HOST?.trim() || "gitlab.com");
511
512 const run = (
513 input: Parameters<GitLabCli["Service"]["execute"]>[0],
514 mapError: (error: VcsError) => GitLabCliError,
515 ) =>
516 process
517 .run({
518 operation: "GitLabCli.execute",
519 command: "glab",
520 args: input.args,
521 cwd: input.cwd,
522 env: {
523 // glab may otherwise prefer a different checkout remote.
524 ...(input.host === undefined ? {} : { GITLAB_HOST: input.host }),
525 ...(input.callerNamedHost !== undefined && hostOf(input.callerNamedHost) !== defaultHost
526 ? WITHOUT_ENVIRONMENT_TOKEN
527 : {}),
528 },
529 classifyFailure: classifyGlabFailure,
530 notFoundDetail: "Merge request not found.",
531 timeoutMs: input.timeoutMs ?? DEFAULT_TIMEOUT_MS,
532 ...(input.stdin === undefined ? {} : { stdin: input.stdin }),
533 ...(input.maxOutputBytes === undefined ? {} : { maxOutputBytes: input.maxOutputBytes }),
534 })
535 .pipe(Effect.mapError(mapError));
536
537 const execute: GitLabCli["Service"]["execute"] = (input) =>
538 run(input, (error) =>
539 GitLabCliCommandError.fromVcsError(
540 { operation: "execute", command: "glab", cwd: input.cwd },
541 error,
542 ),
543 );
544
545 const executeMergeRequest = (input: {
546 readonly cwd: string;
547 readonly reference: string;
548 readonly args: ReadonlyArray<string>;
549 }) =>
550 run(input, (error) =>
551 GitLabMergeRequestNotFoundError.fromVcsError(
552 {
553 operation: "execute",
554 command: "glab",
555 cwd: input.cwd,
556 reference: input.reference,
557 },
558 error,
559 ),
560 );
561
562 return GitLabCli.of({
563 execute,
564 listMergeRequests: Effect.fn("GitLabCli.listMergeRequests")(function* (input) {
565 const limit = input.limit ?? 20;
566 let pageSize = limit;
567 let page = 1;
568 const items: GitLabMergeRequestSummary[] = [];
569 while (items.length < limit) {
570 const result = yield* execute({
571 cwd: input.cwd,
572 args: [
573 "mr",
574 "list",
575 "--source-branch",
576 sourceRefName(input),
577 ...stateArgs(input.state),
578 "--per-page",
579 String(pageSize),
580 ...(page > 1 ? ["--page", String(page)] : []),
581 "--output",
582 "json",
583 ],
584 maxOutputBytes: MERGE_REQUEST_LIST_MAX_BYTES,
585 });
586 if (result.stdoutTruncated && pageSize > 1) {
587 pageSize = Math.max(1, Math.floor(pageSize / 2));
588 page = 1;
589 items.length = 0;
590 continue;
591 }
592 const raw = result.stdout.trim();
593 if (raw.length === 0) break;
594 const decoded = decodeGitLabMergeRequestListJson(raw);
595 if (result.stdoutTruncated || !Result.isSuccess(decoded)) {
596 return yield* new GitLabMergeRequestListDecodeError({
597 operation: "listMergeRequests",
598 command: "glab",
599 cwd: input.cwd,
600 cause: Result.isFailure(decoded) ? decoded.failure : "MR list output was truncated",
601 });
602 }
603 items.push(...decoded.success.map(toSummaryWithOptionalUpdatedAt));
604 // Count raw entries: the decoder drops invalid ones, which would end paging early.
605 const entries = decodeJsonArray(raw);
606 if (
607 page * pageSize >= limit ||
608 (Exit.isSuccess(entries) && entries.value.length < pageSize)
609 ) {
610 break;
611 }
612 page += 1;
613 }
614 return items.slice(0, limit);
615 }),
616 getMergeRequest: Effect.fn("GitLabCli.getMergeRequest")(function (input) {
617 return executeMergeRequest({
618 cwd: input.cwd,
619 reference: input.reference,
620 args: ["mr", "view", "--output", "json", "--", input.reference],
621 }).pipe(
622 Effect.map((result) => result.stdout.trim()),
623 Effect.flatMap((raw) =>
624 Effect.sync(() => decodeGitLabMergeRequestJson(raw)).pipe(
625 Effect.flatMap((decoded) => {
626 if (!Result.isSuccess(decoded)) {
627 return Effect.fail(
628 new GitLabMergeRequestDecodeError({
629 operation: "getMergeRequest",
630 command: "glab",
631 cwd: input.cwd,
632 reference: input.reference,
633 cause: decoded.failure,
634 }),
635 );
636 }
637
638 return Effect.succeed(toSummaryWithOptionalUpdatedAt(decoded.success));
639 }),
640 ),
641 ),
642 );
643 }),
644 getRepositoryCloneUrls: Effect.fn("GitLabCli.getRepositoryCloneUrls")(function (input) {
645 const { host, projectPath } = parseRepositoryLookup(input.repository);
646 return execute({
647 cwd: input.cwd,
648 ...(host === null ? {} : { callerNamedHost: host }),
649 args: [
650 "api",
651 ...(host === null ? [] : ["--hostname", host]),
652 `projects/${encodeURIComponent(projectPath)}`,
653 ],
654 }).pipe(
655 Effect.map((result) => result.stdout.trim()),
656 Effect.flatMap((raw) =>
657 decodeGitLabRepositoryCloneUrls(raw).pipe(
658 Effect.mapError(
659 (cause) =>
660 new GitLabRepositoryDecodeError({
661 operation: "getRepositoryCloneUrls",
662 command: "glab",
663 cwd: input.cwd,
664 repository: input.repository,
665 cause,
666 }),
667 ),
668 ),
669 ),
670 Effect.map(normalizeRepositoryCloneUrls),
671 );
672 }),
673 createRepository: Effect.fn("GitLabCli.createRepository")(function (input) {
674 const { namespacePath, projectPath } = parseRepositoryPath(input.repository);
675 const namespaceId: Effect.Effect<number | null, GitLabCliError> = namespacePath
676 ? execute({
677 cwd: input.cwd,
678 args: ["api", `namespaces/${encodeURIComponent(namespacePath)}`],
679 }).pipe(
680 Effect.map((result) => result.stdout.trim()),
681 Effect.flatMap((raw) =>
682 decodeGitLabNamespace(raw).pipe(
683 Effect.mapError(
684 (cause) =>
685 new GitLabNamespaceDecodeError({
686 operation: "createRepository",
687 command: "glab",
688 cwd: input.cwd,
689 namespacePath,
690 cause,
691 }),
692 ),
693 ),
694 ),
695 Effect.map((namespace) => namespace.id),
696 )
697 : Effect.succeed(null);
698
699 return namespaceId.pipe(
700 Effect.flatMap((resolvedNamespaceId) =>
701 execute({
702 cwd: input.cwd,
703 args: [
704 "api",
705 "--method",
706 "POST",
707 "projects",
708 "--raw-field",
709 `path=${projectPath}`,
710 "--raw-field",
711 `name=${projectPath}`,
712 "--raw-field",
713 `visibility=${input.visibility}`,
714 ...(resolvedNamespaceId === null
715 ? []
716 : ["--raw-field", `namespace_id=${resolvedNamespaceId}`]),
717 ],
718 }),
719 ),
720 Effect.map((result) => result.stdout.trim()),
721 Effect.flatMap((raw) =>
722 decodeGitLabRepositoryCloneUrls(raw).pipe(
723 Effect.mapError(
724 (cause) =>
725 new GitLabRepositoryDecodeError({
726 operation: "createRepository",
727 command: "glab",
728 cwd: input.cwd,
729 repository: input.repository,
730 cause,
731 }),
732 ),
733 ),
734 ),
735 Effect.map(normalizeRepositoryCloneUrls),
736 );
737 }),
738 createMergeRequest: Effect.fn("GitLabCli.createMergeRequest")(function* (input) {
739 // A confined glab (Snap) has a private /tmp, so it cannot open the server's body file.
740 const description = yield* fileSystem.readFileString(input.bodyFile).pipe(
741 Effect.mapError(
742 (cause) =>
743 new GitLabMergeRequestBodyReadError({
744 operation: "createMergeRequest",
745 command: "glab",
746 cwd: input.cwd,
747 cause,
748 }),
749 ),
750 );
751 let project = ":fullpath";
752 let targetProjectId: number | undefined;
753 if (input.source?.repository || input.source?.owner) {
754 const result = yield* execute({ cwd: input.cwd, args: ["api", "projects/:fullpath"] });
755 const targetProject = yield* decodeGitLabMergeRequestProject(result.stdout).pipe(
756 Effect.mapError(
757 (cause) =>
758 new GitLabRepositoryDecodeError({
759 operation: "createMergeRequest",
760 command: "glab",
761 cwd: input.cwd,
762 cause,
763 }),
764 ),
765 );
766 project = encodeURIComponent(
767 input.source.repository ?? `${input.source.owner}/${targetProject.path}`,
768 );
769 targetProjectId = targetProject.id;
770 }
771 yield* execute({
772 cwd: input.cwd,
773 args: [
774 "api",
775 "--method",
776 "POST",
777 `projects/${project}/merge_requests`,
778 "--raw-field",
779 `source_branch=${sourceRefName(input)}`,
780 "--raw-field",
781 `target_branch=${input.target?.refName ?? input.baseBranch}`,
782 ...(targetProjectId === undefined
783 ? []
784 : ["--raw-field", `target_project_id=${targetProjectId}`]),
785 "--raw-field",
786 `title=${input.draft === true ? draftTitle(input.title) : input.title}`,
787 "--field",
788 "description=@-",
789 ],
790 stdin: description,
791 });
792 }),
793 getDefaultBranch: Effect.fn("GitLabCli.getDefaultBranch")(function (input) {
794 return execute({
795 cwd: input.cwd,
796 args: ["api", "projects/:fullpath"],
797 }).pipe(
798 Effect.map((result) => result.stdout.trim()),
799 Effect.flatMap((raw) =>
800 decodeGitLabDefaultBranch(raw).pipe(
801 Effect.mapError(
802 (cause) =>
803 new GitLabRepositoryDecodeError({
804 operation: "getDefaultBranch",
805 command: "glab",
806 cwd: input.cwd,
807 cause,
808 }),
809 ),
810 ),
811 ),
812 Effect.map((value) => value.default_branch ?? null),
813 );
814 }),
815 checkoutMergeRequest: Effect.fn("GitLabCli.checkoutMergeRequest")(function (input) {
816 return executeMergeRequest({
817 cwd: input.cwd,
818 reference: input.reference,
819 args: ["mr", "checkout", "--", input.reference],
820 }).pipe(Effect.asVoid);
821 }),
822 });
823 });
824
825 export const layer = Layer.effect(GitLabCli, make);