feat(scm): Gitlab (#2462)
Co-authored-by: Julius Marminge <[email protected]>
This commit is contained in:
1 parent
350d76ee14
commit
0ce7e56e43
24 files changed
+1608
-187
No files matched your search
@@ -0,0 +1,266 @@
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { Effect, Layer } from "effect";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { afterEach, expect, vi } from "vitest";
|
||||
|
||||
import { VcsProcessExitError } from "@t3tools/contracts";
|
||||
|
||||
import { VcsProcess, type VcsProcessOutput, type VcsProcessShape } from "../vcs/VcsProcess.ts";
|
||||
import * as GitLabCli from "./GitLabCli.ts";
|
||||
|
||||
const mockedRun = vi.fn<VcsProcessShape["run"]>();
|
||||
const layer = it.layer(
|
||||
GitLabCli.layer.pipe(
|
||||
Layer.provide(
|
||||
Layer.mock(VcsProcess)({
|
||||
run: mockedRun,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
function processOutput(stdout: string): VcsProcessOutput {
|
||||
return {
|
||||
exitCode: ChildProcessSpawner.ExitCode(0),
|
||||
stdout,
|
||||
stderr: "",
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
};
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
mockedRun.mockReset();
|
||||
});
|
||||
|
||||
layer("GitLabCli.layer", (it) => {
|
||||
it.effect("parses merge request view output", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedRun.mockReturnValueOnce(
|
||||
Effect.succeed(
|
||||
processOutput(
|
||||
JSON.stringify({
|
||||
iid: 42,
|
||||
title: "Add MR thread creation",
|
||||
web_url: "https://gitlab.com/pingdotgg/t3code/-/merge_requests/42",
|
||||
target_branch: "main",
|
||||
source_branch: "feature/mr-threads",
|
||||
state: "opened",
|
||||
source_project_id: 101,
|
||||
target_project_id: 100,
|
||||
source_project: {
|
||||
path_with_namespace: "octocat/t3code",
|
||||
},
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const result = yield* Effect.gen(function* () {
|
||||
const glab = yield* GitLabCli.GitLabCli;
|
||||
return yield* glab.getMergeRequest({
|
||||
cwd: "/repo",
|
||||
reference: "42",
|
||||
});
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(result, {
|
||||
number: 42,
|
||||
title: "Add MR thread creation",
|
||||
url: "https://gitlab.com/pingdotgg/t3code/-/merge_requests/42",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/mr-threads",
|
||||
state: "open",
|
||||
isCrossRepository: true,
|
||||
headRepositoryNameWithOwner: "octocat/t3code",
|
||||
headRepositoryOwnerLogin: "octocat",
|
||||
});
|
||||
expect(mockedRun).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
command: "glab",
|
||||
cwd: "/repo",
|
||||
args: ["mr", "view", "42", "--output", "json"],
|
||||
}),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("skips invalid entries when parsing MR lists", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedRun.mockReturnValueOnce(
|
||||
Effect.succeed(
|
||||
processOutput(
|
||||
JSON.stringify([
|
||||
{
|
||||
iid: 0,
|
||||
title: "invalid",
|
||||
web_url: "https://gitlab.com/pingdotgg/t3code/-/merge_requests/0",
|
||||
target_branch: "main",
|
||||
source_branch: "feature/invalid",
|
||||
},
|
||||
{
|
||||
iid: 43,
|
||||
title: " Valid MR ",
|
||||
web_url: " https://gitlab.com/pingdotgg/t3code/-/merge_requests/43 ",
|
||||
target_branch: " main ",
|
||||
source_branch: " feature/mr-list ",
|
||||
state: "merged",
|
||||
},
|
||||
]),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const result = yield* Effect.gen(function* () {
|
||||
const glab = yield* GitLabCli.GitLabCli;
|
||||
return yield* glab.listMergeRequests({
|
||||
cwd: "/repo",
|
||||
headSelector: "feature/mr-list",
|
||||
state: "all",
|
||||
});
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(result, [
|
||||
{
|
||||
number: 43,
|
||||
title: "Valid MR",
|
||||
url: "https://gitlab.com/pingdotgg/t3code/-/merge_requests/43",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/mr-list",
|
||||
state: "merged",
|
||||
},
|
||||
]);
|
||||
expect(mockedRun).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
command: "glab",
|
||||
cwd: "/repo",
|
||||
args: [
|
||||
"mr",
|
||||
"list",
|
||||
"--source-branch",
|
||||
"feature/mr-list",
|
||||
"--all",
|
||||
"--per-page",
|
||||
"20",
|
||||
"--output",
|
||||
"json",
|
||||
],
|
||||
}),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reads repository clone URLs", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedRun.mockReturnValueOnce(
|
||||
Effect.succeed(
|
||||
processOutput(
|
||||
JSON.stringify({
|
||||
path_with_namespace: "octocat/t3code",
|
||||
web_url: "https://gitlab.com/octocat/t3code",
|
||||
http_url_to_repo: "https://gitlab.com/octocat/t3code.git",
|
||||
ssh_url_to_repo: "[email protected]:octocat/t3code.git",
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const result = yield* Effect.gen(function* () {
|
||||
const glab = yield* GitLabCli.GitLabCli;
|
||||
return yield* glab.getRepositoryCloneUrls({
|
||||
cwd: "/repo",
|
||||
repository: "octocat/t3code",
|
||||
});
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(result, {
|
||||
nameWithOwner: "octocat/t3code",
|
||||
url: "https://gitlab.com/octocat/t3code.git",
|
||||
sshUrl: "[email protected]:octocat/t3code.git",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("creates merge requests through the GitLab API without placing the body in argv", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedRun.mockReturnValueOnce(Effect.succeed(processOutput("{}")));
|
||||
|
||||
const glab = yield* GitLabCli.GitLabCli;
|
||||
yield* glab.createMergeRequest({
|
||||
cwd: "/repo",
|
||||
baseBranch: "main",
|
||||
headSelector: "owner:feature/provider",
|
||||
title: "Provider MR",
|
||||
bodyFile: "/tmp/t3-mr-body.md",
|
||||
});
|
||||
|
||||
expect(mockedRun).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
command: "glab",
|
||||
cwd: "/repo",
|
||||
args: [
|
||||
"api",
|
||||
"--method",
|
||||
"POST",
|
||||
"projects/:fullpath/merge_requests",
|
||||
"--raw-field",
|
||||
"source_branch=feature/provider",
|
||||
"--raw-field",
|
||||
"target_branch=main",
|
||||
"--raw-field",
|
||||
"title=Provider MR",
|
||||
"--field",
|
||||
"description=@/tmp/t3-mr-body.md",
|
||||
],
|
||||
}),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not pass unsupported force flags when checking out merge requests", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedRun.mockReturnValueOnce(Effect.succeed(processOutput("")));
|
||||
|
||||
const glab = yield* GitLabCli.GitLabCli;
|
||||
yield* glab.checkoutMergeRequest({
|
||||
cwd: "/repo",
|
||||
reference: "42",
|
||||
force: true,
|
||||
});
|
||||
|
||||
expect(mockedRun).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
command: "glab",
|
||||
cwd: "/repo",
|
||||
args: ["mr", "checkout", "42"],
|
||||
}),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("surfaces a friendly error when the merge request is not found", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedRun.mockReturnValueOnce(
|
||||
Effect.fail(
|
||||
new VcsProcessExitError({
|
||||
operation: "GitLabCli.execute",
|
||||
command: "glab mr view 4888",
|
||||
cwd: "/repo",
|
||||
exitCode: 1,
|
||||
detail: "GET 404 merge request not found",
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const error = yield* Effect.gen(function* () {
|
||||
const glab = yield* GitLabCli.GitLabCli;
|
||||
return yield* glab.getMergeRequest({
|
||||
cwd: "/repo",
|
||||
reference: "4888",
|
||||
});
|
||||
}).pipe(Effect.flip);
|
||||
|
||||
assert.equal(error.message.includes("Merge request not found"), true);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,368 @@
|
||||
import { Context, Effect, Layer, Option, Result, Schema, SchemaIssue, type DateTime } from "effect";
|
||||
|
||||
import { TrimmedNonEmptyString } from "@t3tools/contracts";
|
||||
|
||||
import {
|
||||
decodeGitLabMergeRequestJson,
|
||||
decodeGitLabMergeRequestListJson,
|
||||
formatGitLabJsonDecodeError,
|
||||
} from "./gitLabMergeRequests.ts";
|
||||
import { VcsProcess, type VcsProcessOutput } from "../vcs/VcsProcess.ts";
|
||||
import type { SourceControlRefSelector } from "./SourceControlProvider.ts";
|
||||
|
||||
const DEFAULT_TIMEOUT_MS = 30_000;
|
||||
|
||||
export class GitLabCliError extends Schema.TaggedErrorClass<GitLabCliError>()("GitLabCliError", {
|
||||
operation: Schema.String,
|
||||
detail: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
}) {
|
||||
override get message(): string {
|
||||
return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
export interface GitLabMergeRequestSummary {
|
||||
readonly number: number;
|
||||
readonly title: string;
|
||||
readonly url: string;
|
||||
readonly baseRefName: string;
|
||||
readonly headRefName: string;
|
||||
readonly state?: "open" | "closed" | "merged";
|
||||
readonly updatedAt?: Option.Option<DateTime.Utc>;
|
||||
readonly isCrossRepository?: boolean;
|
||||
readonly headRepositoryNameWithOwner?: string | null;
|
||||
readonly headRepositoryOwnerLogin?: string | null;
|
||||
}
|
||||
|
||||
export interface GitLabRepositoryCloneUrls {
|
||||
readonly nameWithOwner: string;
|
||||
readonly url: string;
|
||||
readonly sshUrl: string;
|
||||
}
|
||||
|
||||
export interface GitLabCliShape {
|
||||
readonly execute: (input: {
|
||||
readonly cwd: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
readonly timeoutMs?: number;
|
||||
}) => Effect.Effect<VcsProcessOutput, GitLabCliError>;
|
||||
|
||||
readonly listMergeRequests: (input: {
|
||||
readonly cwd: string;
|
||||
readonly headSelector: string;
|
||||
readonly source?: SourceControlRefSelector;
|
||||
readonly state: "open" | "closed" | "merged" | "all";
|
||||
readonly limit?: number;
|
||||
}) => Effect.Effect<ReadonlyArray<GitLabMergeRequestSummary>, GitLabCliError>;
|
||||
|
||||
readonly getMergeRequest: (input: {
|
||||
readonly cwd: string;
|
||||
readonly reference: string;
|
||||
}) => Effect.Effect<GitLabMergeRequestSummary, GitLabCliError>;
|
||||
|
||||
readonly getRepositoryCloneUrls: (input: {
|
||||
readonly cwd: string;
|
||||
readonly repository: string;
|
||||
}) => Effect.Effect<GitLabRepositoryCloneUrls, GitLabCliError>;
|
||||
|
||||
readonly createMergeRequest: (input: {
|
||||
readonly cwd: string;
|
||||
readonly baseBranch: string;
|
||||
readonly headSelector: string;
|
||||
readonly source?: SourceControlRefSelector;
|
||||
readonly target?: SourceControlRefSelector;
|
||||
readonly title: string;
|
||||
readonly bodyFile: string;
|
||||
}) => Effect.Effect<void, GitLabCliError>;
|
||||
|
||||
readonly getDefaultBranch: (input: {
|
||||
readonly cwd: string;
|
||||
}) => Effect.Effect<string | null, GitLabCliError>;
|
||||
|
||||
readonly checkoutMergeRequest: (input: {
|
||||
readonly cwd: string;
|
||||
readonly reference: string;
|
||||
readonly force?: boolean;
|
||||
}) => Effect.Effect<void, GitLabCliError>;
|
||||
}
|
||||
|
||||
export class GitLabCli extends Context.Service<GitLabCli, GitLabCliShape>()(
|
||||
"t3/source-control/GitLabCli",
|
||||
) {}
|
||||
|
||||
function isVcsProcessSpawnError(error: unknown): boolean {
|
||||
return (
|
||||
typeof error === "object" &&
|
||||
error !== null &&
|
||||
"_tag" in error &&
|
||||
error._tag === "VcsProcessSpawnError"
|
||||
);
|
||||
}
|
||||
|
||||
function normalizeGitLabCliError(operation: "execute" | "stdout", error: unknown): GitLabCliError {
|
||||
if (error instanceof Error) {
|
||||
if (error.message.includes("Command not found: glab") || isVcsProcessSpawnError(error)) {
|
||||
return new GitLabCliError({
|
||||
operation,
|
||||
detail: "GitLab CLI (`glab`) is required but not available on PATH.",
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
|
||||
const lower = error.message.toLowerCase();
|
||||
if (
|
||||
lower.includes("authentication failed") ||
|
||||
lower.includes("not logged in") ||
|
||||
lower.includes("glab auth login") ||
|
||||
lower.includes("token")
|
||||
) {
|
||||
return new GitLabCliError({
|
||||
operation,
|
||||
detail: "GitLab CLI is not authenticated. Run `glab auth login` and retry.",
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
|
||||
if (
|
||||
lower.includes("merge request not found") ||
|
||||
lower.includes("not found") ||
|
||||
lower.includes("404")
|
||||
) {
|
||||
return new GitLabCliError({
|
||||
operation,
|
||||
detail: "Merge request not found. Check the MR number or URL and try again.",
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
|
||||
return new GitLabCliError({
|
||||
operation,
|
||||
detail: `GitLab CLI command failed: ${error.message}`,
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
|
||||
return new GitLabCliError({
|
||||
operation,
|
||||
detail: "GitLab CLI command failed.",
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
|
||||
const RawGitLabRepositoryCloneUrlsSchema = Schema.Struct({
|
||||
path_with_namespace: TrimmedNonEmptyString,
|
||||
web_url: TrimmedNonEmptyString,
|
||||
http_url_to_repo: TrimmedNonEmptyString,
|
||||
ssh_url_to_repo: TrimmedNonEmptyString,
|
||||
});
|
||||
|
||||
const RawGitLabDefaultBranchSchema = Schema.Struct({
|
||||
default_branch: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
|
||||
});
|
||||
|
||||
function normalizeRepositoryCloneUrls(
|
||||
raw: Schema.Schema.Type<typeof RawGitLabRepositoryCloneUrlsSchema>,
|
||||
): GitLabRepositoryCloneUrls {
|
||||
return {
|
||||
nameWithOwner: raw.path_with_namespace,
|
||||
url: raw.http_url_to_repo || raw.web_url,
|
||||
sshUrl: raw.ssh_url_to_repo,
|
||||
};
|
||||
}
|
||||
|
||||
function decodeGitLabJson<S extends Schema.Top>(
|
||||
raw: string,
|
||||
schema: S,
|
||||
operation: "getRepositoryCloneUrls" | "getDefaultBranch",
|
||||
invalidDetail: string,
|
||||
): Effect.Effect<S["Type"], GitLabCliError, S["DecodingServices"]> {
|
||||
return Schema.decodeEffect(Schema.fromJsonString(schema))(raw).pipe(
|
||||
Effect.mapError(
|
||||
(error) =>
|
||||
new GitLabCliError({
|
||||
operation,
|
||||
detail: `${invalidDetail}: ${SchemaIssue.makeFormatterDefault()(error.issue)}`,
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
function stateArgs(state: "open" | "closed" | "merged" | "all"): ReadonlyArray<string> {
|
||||
switch (state) {
|
||||
case "open":
|
||||
return [];
|
||||
case "closed":
|
||||
return ["--closed"];
|
||||
case "merged":
|
||||
return ["--merged"];
|
||||
case "all":
|
||||
return ["--all"];
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeHeadSelector(headSelector: string): string {
|
||||
const trimmed = headSelector.trim();
|
||||
const ownerBranch = /^[^:]+:(.+)$/.exec(trimmed);
|
||||
return ownerBranch?.[1]?.trim() || trimmed;
|
||||
}
|
||||
|
||||
function sourceRefName(input: {
|
||||
readonly headSelector: string;
|
||||
readonly source?: SourceControlRefSelector;
|
||||
}): string {
|
||||
return input.source?.refName ?? normalizeHeadSelector(input.headSelector);
|
||||
}
|
||||
|
||||
function sourceProjectIdentifier(source: SourceControlRefSelector | undefined): string | null {
|
||||
return source?.repository ?? source?.owner ?? null;
|
||||
}
|
||||
|
||||
function toSummaryWithOptionalUpdatedAt(
|
||||
record: GitLabMergeRequestSummary & {
|
||||
readonly updatedAt: Option.Option<DateTime.Utc>;
|
||||
},
|
||||
): GitLabMergeRequestSummary {
|
||||
const { updatedAt, ...summary } = record;
|
||||
return Option.isSome(updatedAt) ? { ...summary, updatedAt } : summary;
|
||||
}
|
||||
|
||||
export const make = Effect.fn("makeGitLabCli")(function* () {
|
||||
const process = yield* VcsProcess;
|
||||
|
||||
const execute: GitLabCliShape["execute"] = (input) =>
|
||||
process
|
||||
.run({
|
||||
operation: "GitLabCli.execute",
|
||||
command: "glab",
|
||||
args: input.args,
|
||||
cwd: input.cwd,
|
||||
timeoutMs: input.timeoutMs ?? DEFAULT_TIMEOUT_MS,
|
||||
})
|
||||
.pipe(Effect.mapError((error) => normalizeGitLabCliError("execute", error)));
|
||||
|
||||
return GitLabCli.of({
|
||||
execute,
|
||||
listMergeRequests: (input) =>
|
||||
execute({
|
||||
cwd: input.cwd,
|
||||
args: [
|
||||
"mr",
|
||||
"list",
|
||||
"--source-branch",
|
||||
sourceRefName(input),
|
||||
...stateArgs(input.state),
|
||||
"--per-page",
|
||||
String(input.limit ?? 20),
|
||||
"--output",
|
||||
"json",
|
||||
],
|
||||
}).pipe(
|
||||
Effect.map((result) => result.stdout.trim()),
|
||||
Effect.flatMap((raw) =>
|
||||
raw.length === 0
|
||||
? Effect.succeed([])
|
||||
: Effect.sync(() => decodeGitLabMergeRequestListJson(raw)).pipe(
|
||||
Effect.flatMap((decoded) => {
|
||||
if (!Result.isSuccess(decoded)) {
|
||||
return Effect.fail(
|
||||
new GitLabCliError({
|
||||
operation: "listMergeRequests",
|
||||
detail: `GitLab CLI returned invalid MR list JSON: ${formatGitLabJsonDecodeError(decoded.failure)}`,
|
||||
cause: decoded.failure,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
return Effect.succeed(decoded.success.map(toSummaryWithOptionalUpdatedAt));
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
getMergeRequest: (input) =>
|
||||
execute({
|
||||
cwd: input.cwd,
|
||||
args: ["mr", "view", input.reference, "--output", "json"],
|
||||
}).pipe(
|
||||
Effect.map((result) => result.stdout.trim()),
|
||||
Effect.flatMap((raw) =>
|
||||
Effect.sync(() => decodeGitLabMergeRequestJson(raw)).pipe(
|
||||
Effect.flatMap((decoded) => {
|
||||
if (!Result.isSuccess(decoded)) {
|
||||
return Effect.fail(
|
||||
new GitLabCliError({
|
||||
operation: "getMergeRequest",
|
||||
detail: `GitLab CLI returned invalid merge request JSON: ${formatGitLabJsonDecodeError(decoded.failure)}`,
|
||||
cause: decoded.failure,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
return Effect.succeed(toSummaryWithOptionalUpdatedAt(decoded.success));
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
getRepositoryCloneUrls: (input) =>
|
||||
execute({
|
||||
cwd: input.cwd,
|
||||
args: ["api", `projects/${encodeURIComponent(input.repository)}`],
|
||||
}).pipe(
|
||||
Effect.map((result) => result.stdout.trim()),
|
||||
Effect.flatMap((raw) =>
|
||||
decodeGitLabJson(
|
||||
raw,
|
||||
RawGitLabRepositoryCloneUrlsSchema,
|
||||
"getRepositoryCloneUrls",
|
||||
"GitLab CLI returned invalid repository JSON.",
|
||||
),
|
||||
),
|
||||
Effect.map(normalizeRepositoryCloneUrls),
|
||||
),
|
||||
createMergeRequest: (input) => {
|
||||
const sourceProject = sourceProjectIdentifier(input.source);
|
||||
return execute({
|
||||
cwd: input.cwd,
|
||||
args: [
|
||||
"api",
|
||||
"--method",
|
||||
"POST",
|
||||
"projects/:fullpath/merge_requests",
|
||||
"--raw-field",
|
||||
`source_branch=${sourceRefName(input)}`,
|
||||
"--raw-field",
|
||||
`target_branch=${input.target?.refName ?? input.baseBranch}`,
|
||||
...(sourceProject ? ["--raw-field", `source_project_id=${sourceProject}`] : []),
|
||||
"--raw-field",
|
||||
`title=${input.title}`,
|
||||
"--field",
|
||||
`description=@${input.bodyFile}`,
|
||||
],
|
||||
}).pipe(Effect.asVoid);
|
||||
},
|
||||
getDefaultBranch: (input) =>
|
||||
execute({
|
||||
cwd: input.cwd,
|
||||
args: ["api", "projects/:fullpath"],
|
||||
}).pipe(
|
||||
Effect.map((result) => result.stdout.trim()),
|
||||
Effect.flatMap((raw) =>
|
||||
decodeGitLabJson(
|
||||
raw,
|
||||
RawGitLabDefaultBranchSchema,
|
||||
"getDefaultBranch",
|
||||
"GitLab CLI returned invalid repository JSON.",
|
||||
),
|
||||
),
|
||||
Effect.map((value) => value.default_branch ?? null),
|
||||
),
|
||||
checkoutMergeRequest: (input) =>
|
||||
execute({
|
||||
cwd: input.cwd,
|
||||
args: ["mr", "checkout", input.reference],
|
||||
}).pipe(Effect.asVoid),
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(GitLabCli, make());
|
||||
@@ -0,0 +1,105 @@
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { Effect, Layer, Option } from "effect";
|
||||
|
||||
import { GitLabCli, type GitLabCliShape } from "./GitLabCli.ts";
|
||||
import * as GitLabSourceControlProvider from "./GitLabSourceControlProvider.ts";
|
||||
|
||||
function makeProvider(gitlab: Partial<GitLabCliShape>) {
|
||||
return GitLabSourceControlProvider.make().pipe(Effect.provide(Layer.mock(GitLabCli)(gitlab)));
|
||||
}
|
||||
|
||||
it.effect("maps GitLab MR summaries into provider-neutral change requests", () =>
|
||||
Effect.gen(function* () {
|
||||
const provider = yield* makeProvider({
|
||||
getMergeRequest: () =>
|
||||
Effect.succeed({
|
||||
number: 42,
|
||||
title: "Add GitLab provider",
|
||||
url: "https://gitlab.com/pingdotgg/t3code/-/merge_requests/42",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/source-control",
|
||||
state: "open",
|
||||
isCrossRepository: true,
|
||||
headRepositoryNameWithOwner: "fork/t3code",
|
||||
headRepositoryOwnerLogin: "fork",
|
||||
}),
|
||||
});
|
||||
|
||||
const changeRequest = yield* provider.getChangeRequest({
|
||||
cwd: "/repo",
|
||||
reference: "42",
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(changeRequest, {
|
||||
provider: "gitlab",
|
||||
number: 42,
|
||||
title: "Add GitLab provider",
|
||||
url: "https://gitlab.com/pingdotgg/t3code/-/merge_requests/42",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/source-control",
|
||||
state: "open",
|
||||
updatedAt: Option.none(),
|
||||
isCrossRepository: true,
|
||||
headRepositoryNameWithOwner: "fork/t3code",
|
||||
headRepositoryOwnerLogin: "fork",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("lists GitLab MRs through provider-neutral input names", () =>
|
||||
Effect.gen(function* () {
|
||||
let listInput: Parameters<GitLabCliShape["listMergeRequests"]>[0] | null = null;
|
||||
const provider = yield* makeProvider({
|
||||
listMergeRequests: (input) => {
|
||||
listInput = input;
|
||||
return Effect.succeed([]);
|
||||
},
|
||||
});
|
||||
|
||||
yield* provider.listChangeRequests({
|
||||
cwd: "/repo",
|
||||
headSelector: "feature/provider",
|
||||
state: "all",
|
||||
limit: 10,
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(listInput, {
|
||||
cwd: "/repo",
|
||||
headSelector: "feature/provider",
|
||||
state: "all",
|
||||
limit: 10,
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("creates GitLab MRs through provider-neutral input names", () =>
|
||||
Effect.gen(function* () {
|
||||
let createInput: Parameters<GitLabCliShape["createMergeRequest"]>[0] | null = null;
|
||||
const provider = yield* makeProvider({
|
||||
createMergeRequest: (input) => {
|
||||
createInput = input;
|
||||
return Effect.void;
|
||||
},
|
||||
});
|
||||
|
||||
yield* provider.createChangeRequest({
|
||||
cwd: "/repo",
|
||||
baseRefName: "main",
|
||||
headSelector: "owner:feature/provider",
|
||||
title: "Provider MR",
|
||||
bodyFile: "/tmp/body.md",
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(createInput, {
|
||||
cwd: "/repo",
|
||||
baseBranch: "main",
|
||||
headSelector: "owner:feature/provider",
|
||||
source: {
|
||||
owner: "owner",
|
||||
refName: "feature/provider",
|
||||
},
|
||||
title: "Provider MR",
|
||||
bodyFile: "/tmp/body.md",
|
||||
});
|
||||
}),
|
||||
);
|
||||
@@ -0,0 +1,106 @@
|
||||
import { Effect, Layer, Option } from "effect";
|
||||
import { SourceControlProviderError, type ChangeRequest } from "@t3tools/contracts";
|
||||
|
||||
import { GitLabCli, type GitLabCliError, type GitLabMergeRequestSummary } from "./GitLabCli.ts";
|
||||
import { SourceControlProvider, type SourceControlRefSelector } from "./SourceControlProvider.ts";
|
||||
|
||||
function providerError(operation: string, cause: GitLabCliError): SourceControlProviderError {
|
||||
return new SourceControlProviderError({
|
||||
provider: "gitlab",
|
||||
operation,
|
||||
detail: cause.detail,
|
||||
cause,
|
||||
});
|
||||
}
|
||||
|
||||
function toChangeRequest(summary: GitLabMergeRequestSummary): ChangeRequest {
|
||||
return {
|
||||
provider: "gitlab",
|
||||
number: summary.number,
|
||||
title: summary.title,
|
||||
url: summary.url,
|
||||
baseRefName: summary.baseRefName,
|
||||
headRefName: summary.headRefName,
|
||||
state: summary.state ?? "open",
|
||||
updatedAt: summary.updatedAt ?? Option.none(),
|
||||
...(summary.isCrossRepository !== undefined
|
||||
? { isCrossRepository: summary.isCrossRepository }
|
||||
: {}),
|
||||
...(summary.headRepositoryNameWithOwner !== undefined
|
||||
? { headRepositoryNameWithOwner: summary.headRepositoryNameWithOwner }
|
||||
: {}),
|
||||
...(summary.headRepositoryOwnerLogin !== undefined
|
||||
? { headRepositoryOwnerLogin: summary.headRepositoryOwnerLogin }
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
|
||||
function sourceFromInput(input: {
|
||||
readonly headSelector: string;
|
||||
readonly source?: SourceControlRefSelector;
|
||||
}): SourceControlRefSelector | undefined {
|
||||
if (input.source) {
|
||||
return input.source;
|
||||
}
|
||||
|
||||
const match = /^([^:/\s]+):(.+)$/u.exec(input.headSelector.trim());
|
||||
const owner = match?.[1]?.trim();
|
||||
const refName = match?.[2]?.trim();
|
||||
return owner && refName ? { owner, refName } : undefined;
|
||||
}
|
||||
|
||||
export const make = Effect.fn("makeGitLabSourceControlProvider")(function* () {
|
||||
const gitlab = yield* GitLabCli;
|
||||
|
||||
return SourceControlProvider.of({
|
||||
kind: "gitlab",
|
||||
listChangeRequests: (input) => {
|
||||
const source = sourceFromInput(input);
|
||||
return gitlab
|
||||
.listMergeRequests({
|
||||
cwd: input.cwd,
|
||||
headSelector: input.headSelector,
|
||||
...(source ? { source } : {}),
|
||||
state: input.state,
|
||||
...(input.limit !== undefined ? { limit: input.limit } : {}),
|
||||
})
|
||||
.pipe(
|
||||
Effect.map((items) => items.map(toChangeRequest)),
|
||||
Effect.mapError((error) => providerError("listChangeRequests", error)),
|
||||
);
|
||||
},
|
||||
getChangeRequest: (input) =>
|
||||
gitlab.getMergeRequest(input).pipe(
|
||||
Effect.map(toChangeRequest),
|
||||
Effect.mapError((error) => providerError("getChangeRequest", error)),
|
||||
),
|
||||
createChangeRequest: (input) => {
|
||||
const source = sourceFromInput(input);
|
||||
return gitlab
|
||||
.createMergeRequest({
|
||||
cwd: input.cwd,
|
||||
baseBranch: input.baseRefName,
|
||||
headSelector: input.headSelector,
|
||||
...(source ? { source } : {}),
|
||||
...(input.target ? { target: input.target } : {}),
|
||||
title: input.title,
|
||||
bodyFile: input.bodyFile,
|
||||
})
|
||||
.pipe(Effect.mapError((error) => providerError("createChangeRequest", error)));
|
||||
},
|
||||
getRepositoryCloneUrls: (input) =>
|
||||
gitlab
|
||||
.getRepositoryCloneUrls(input)
|
||||
.pipe(Effect.mapError((error) => providerError("getRepositoryCloneUrls", error))),
|
||||
getDefaultBranch: (input) =>
|
||||
gitlab
|
||||
.getDefaultBranch(input)
|
||||
.pipe(Effect.mapError((error) => providerError("getDefaultBranch", error))),
|
||||
checkoutChangeRequest: (input) =>
|
||||
gitlab
|
||||
.checkoutMergeRequest(input)
|
||||
.pipe(Effect.mapError((error) => providerError("checkoutChangeRequest", error))),
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(SourceControlProvider, make());
|
||||
@@ -94,7 +94,7 @@ Logged in to github.com account juliusmarminge (keyring)
|
||||
},
|
||||
{
|
||||
kind: "gitlab",
|
||||
implemented: false,
|
||||
implemented: true,
|
||||
status: "missing",
|
||||
auth: "unknown",
|
||||
account: Option.none(),
|
||||
|
||||
@@ -83,7 +83,7 @@ const SOURCE_CONTROL_PROVIDER_PROBES: ReadonlyArray<ProviderProbe> = [
|
||||
versionArgs: ["--version"],
|
||||
authArgs: ["auth", "status"],
|
||||
parseAuth: parseGitLabAuth,
|
||||
implemented: false,
|
||||
implemented: true,
|
||||
installHint:
|
||||
"Install GitLab CLI with `brew install glab` or from https://gitlab.com/gitlab-org/cli.",
|
||||
},
|
||||
|
||||
@@ -2,6 +2,7 @@ import { assert, it } from "@effect/vitest";
|
||||
import { DateTime, Effect, Layer, Option } from "effect";
|
||||
|
||||
import { GitHubCli } from "./GitHubCli.ts";
|
||||
import { GitLabCli } from "./GitLabCli.ts";
|
||||
import * as SourceControlProviderRegistry from "./SourceControlProviderRegistry.ts";
|
||||
import { VcsDriverRegistry } from "../vcs/VcsDriverRegistry.ts";
|
||||
import type { VcsDriverShape } from "../vcs/VcsDriver.ts";
|
||||
@@ -50,7 +51,9 @@ function makeRegistry(input: {
|
||||
});
|
||||
|
||||
return SourceControlProviderRegistry.make().pipe(
|
||||
Effect.provide(Layer.mergeAll(registryLayer, Layer.mock(GitHubCli)({}))),
|
||||
Effect.provide(
|
||||
Layer.mergeAll(registryLayer, Layer.mock(GitHubCli)({}), Layer.mock(GitLabCli)({})),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -78,27 +81,16 @@ it.effect("routes directly by provider kind for remote-first workflows", () =>
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"detects GitLab remotes and returns an unsupported provider until one is registered",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const registry = yield* makeRegistry({
|
||||
remotes: [{ name: "origin", url: "[email protected]:group/project.git" }],
|
||||
});
|
||||
it.effect("routes GitLab remotes to the GitLab provider", () =>
|
||||
Effect.gen(function* () {
|
||||
const registry = yield* makeRegistry({
|
||||
remotes: [{ name: "origin", url: "[email protected]:group/project.git" }],
|
||||
});
|
||||
|
||||
const provider = yield* registry.resolve({ cwd: "/repo" });
|
||||
const provider = yield* registry.resolve({ cwd: "/repo" });
|
||||
|
||||
assert.strictEqual(provider.kind, "gitlab");
|
||||
const error = yield* Effect.flip(
|
||||
provider.listChangeRequests({
|
||||
cwd: "/repo",
|
||||
headSelector: "feature/source-control",
|
||||
state: "open",
|
||||
}),
|
||||
);
|
||||
|
||||
assert.strictEqual(error.provider, "gitlab");
|
||||
}),
|
||||
assert.strictEqual(provider.kind, "gitlab");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("falls back to a non-origin remote when origin is not configured", () =>
|
||||
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
type SourceControlProviderShape,
|
||||
} from "./SourceControlProvider.ts";
|
||||
import * as GitHubSourceControlProvider from "./GitHubSourceControlProvider.ts";
|
||||
import * as GitLabSourceControlProvider from "./GitLabSourceControlProvider.ts";
|
||||
import { VcsDriverRegistry } from "../vcs/VcsDriverRegistry.ts";
|
||||
|
||||
const PROVIDER_DETECTION_CACHE_CAPACITY = 2_048;
|
||||
@@ -151,11 +152,16 @@ export const makeWithProviders = Effect.fn("makeSourceControlProviderRegistryWit
|
||||
|
||||
export const make = Effect.fn("makeSourceControlProviderRegistry")(function* () {
|
||||
const github = yield* GitHubSourceControlProvider.make();
|
||||
const gitlab = yield* GitLabSourceControlProvider.make();
|
||||
return yield* makeWithProviders([
|
||||
{
|
||||
kind: "github",
|
||||
provider: github,
|
||||
},
|
||||
{
|
||||
kind: "gitlab",
|
||||
provider: gitlab,
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
import { Cause, DateTime, Exit, Option, Result, Schema } from "effect";
|
||||
import { PositiveInt, TrimmedNonEmptyString } from "@t3tools/contracts";
|
||||
import { decodeJsonResult, formatSchemaError } from "@t3tools/shared/schemaJson";
|
||||
|
||||
export interface NormalizedGitLabMergeRequestRecord {
|
||||
readonly number: number;
|
||||
readonly title: string;
|
||||
readonly url: string;
|
||||
readonly baseRefName: string;
|
||||
readonly headRefName: string;
|
||||
readonly state: "open" | "closed" | "merged";
|
||||
readonly updatedAt: Option.Option<DateTime.Utc>;
|
||||
readonly isCrossRepository?: boolean;
|
||||
readonly headRepositoryNameWithOwner?: string | null;
|
||||
readonly headRepositoryOwnerLogin?: string | null;
|
||||
}
|
||||
|
||||
const GitLabProjectReferenceSchema = Schema.Struct({
|
||||
path_with_namespace: Schema.optional(Schema.String),
|
||||
pathWithNamespace: Schema.optional(Schema.String),
|
||||
namespace: Schema.optional(
|
||||
Schema.NullOr(
|
||||
Schema.Struct({
|
||||
path: Schema.optional(Schema.String),
|
||||
full_path: Schema.optional(Schema.String),
|
||||
fullPath: Schema.optional(Schema.String),
|
||||
}),
|
||||
),
|
||||
),
|
||||
});
|
||||
|
||||
const GitLabMergeRequestSchema = Schema.Struct({
|
||||
iid: PositiveInt,
|
||||
title: TrimmedNonEmptyString,
|
||||
web_url: TrimmedNonEmptyString,
|
||||
source_branch: TrimmedNonEmptyString,
|
||||
target_branch: TrimmedNonEmptyString,
|
||||
state: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
updated_at: Schema.optional(Schema.OptionFromNullOr(Schema.DateTimeUtcFromString)),
|
||||
source_project_id: Schema.optional(Schema.NullOr(Schema.Number)),
|
||||
target_project_id: Schema.optional(Schema.NullOr(Schema.Number)),
|
||||
source_project: Schema.optional(Schema.NullOr(GitLabProjectReferenceSchema)),
|
||||
target_project: Schema.optional(Schema.NullOr(GitLabProjectReferenceSchema)),
|
||||
});
|
||||
|
||||
function trimOptionalString(value: string | null | undefined): string | null {
|
||||
const trimmed = value?.trim() ?? "";
|
||||
return trimmed.length > 0 ? trimmed : null;
|
||||
}
|
||||
|
||||
function normalizeGitLabMergeRequestState(
|
||||
state: string | null | undefined,
|
||||
): "open" | "closed" | "merged" {
|
||||
const normalized = state?.trim().toLowerCase();
|
||||
if (normalized === "merged") {
|
||||
return "merged";
|
||||
}
|
||||
if (normalized === "closed") {
|
||||
return "closed";
|
||||
}
|
||||
return "open";
|
||||
}
|
||||
|
||||
function projectPathWithNamespace(
|
||||
project: Schema.Schema.Type<typeof GitLabProjectReferenceSchema> | null | undefined,
|
||||
): string | null {
|
||||
const explicit =
|
||||
trimOptionalString(project?.path_with_namespace) ??
|
||||
trimOptionalString(project?.pathWithNamespace);
|
||||
if (explicit) {
|
||||
return explicit;
|
||||
}
|
||||
|
||||
const namespacePath =
|
||||
trimOptionalString(project?.namespace?.full_path) ??
|
||||
trimOptionalString(project?.namespace?.fullPath) ??
|
||||
trimOptionalString(project?.namespace?.path);
|
||||
return namespacePath;
|
||||
}
|
||||
|
||||
function ownerLoginFromPathWithNamespace(pathWithNamespace: string | null): string | null {
|
||||
const [owner] = pathWithNamespace?.split("/") ?? [];
|
||||
return trimOptionalString(owner);
|
||||
}
|
||||
|
||||
function normalizeGitLabMergeRequestRecord(
|
||||
raw: Schema.Schema.Type<typeof GitLabMergeRequestSchema>,
|
||||
): NormalizedGitLabMergeRequestRecord {
|
||||
const sourceProjectPath = projectPathWithNamespace(raw.source_project);
|
||||
const targetProjectPath = projectPathWithNamespace(raw.target_project);
|
||||
const isCrossRepository =
|
||||
typeof raw.source_project_id === "number" && typeof raw.target_project_id === "number"
|
||||
? raw.source_project_id !== raw.target_project_id
|
||||
: sourceProjectPath !== null && targetProjectPath !== null
|
||||
? sourceProjectPath.toLowerCase() !== targetProjectPath.toLowerCase()
|
||||
: undefined;
|
||||
const headRepositoryOwnerLogin = ownerLoginFromPathWithNamespace(sourceProjectPath);
|
||||
|
||||
return {
|
||||
number: raw.iid,
|
||||
title: raw.title,
|
||||
url: raw.web_url,
|
||||
baseRefName: raw.target_branch,
|
||||
headRefName: raw.source_branch,
|
||||
state: normalizeGitLabMergeRequestState(raw.state),
|
||||
updatedAt: raw.updated_at ?? Option.none(),
|
||||
...(typeof isCrossRepository === "boolean" ? { isCrossRepository } : {}),
|
||||
...(sourceProjectPath ? { headRepositoryNameWithOwner: sourceProjectPath } : {}),
|
||||
...(headRepositoryOwnerLogin ? { headRepositoryOwnerLogin } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
const decodeGitLabMergeRequestList = decodeJsonResult(Schema.Array(Schema.Unknown));
|
||||
const decodeGitLabMergeRequest = decodeJsonResult(GitLabMergeRequestSchema);
|
||||
const decodeGitLabMergeRequestEntry = Schema.decodeUnknownExit(GitLabMergeRequestSchema);
|
||||
|
||||
export const formatGitLabJsonDecodeError = formatSchemaError;
|
||||
|
||||
export function decodeGitLabMergeRequestListJson(
|
||||
raw: string,
|
||||
): Result.Result<
|
||||
ReadonlyArray<NormalizedGitLabMergeRequestRecord>,
|
||||
Cause.Cause<Schema.SchemaError>
|
||||
> {
|
||||
const result = decodeGitLabMergeRequestList(raw);
|
||||
if (Result.isSuccess(result)) {
|
||||
const mergeRequests: NormalizedGitLabMergeRequestRecord[] = [];
|
||||
for (const entry of result.success) {
|
||||
const decodedEntry = decodeGitLabMergeRequestEntry(entry);
|
||||
if (Exit.isFailure(decodedEntry)) {
|
||||
continue;
|
||||
}
|
||||
mergeRequests.push(normalizeGitLabMergeRequestRecord(decodedEntry.value));
|
||||
}
|
||||
return Result.succeed(mergeRequests);
|
||||
}
|
||||
return Result.fail(result.failure);
|
||||
}
|
||||
|
||||
export function decodeGitLabMergeRequestJson(
|
||||
raw: string,
|
||||
): Result.Result<NormalizedGitLabMergeRequestRecord, Cause.Cause<Schema.SchemaError>> {
|
||||
const result = decodeGitLabMergeRequest(raw);
|
||||
if (Result.isSuccess(result)) {
|
||||
return Result.succeed(normalizeGitLabMergeRequestRecord(result.success));
|
||||
}
|
||||
return Result.fail(result.failure);
|
||||
}
|
||||
Reference in new issue
Block a user