refactor(source-control): GitLab lives in @t3tools/source-control-gitlab (#17594)
Co-authored-by: Claude Opus 5.5 <[email protected]>
This commit is contained in:
1 parent
d01febb509
commit
eb459b5afa
30 files changed
+159
-52
No files matched your search
@@ -1,384 +0,0 @@
|
||||
import { assert, it, afterEach, expect, vi } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import { ChildProcessSpawner } from "effect/process";
|
||||
|
||||
import { VcsProcessExitError } from "@t3tools/contracts";
|
||||
|
||||
import * as VcsProcess from "../vcs/VcsProcess.ts";
|
||||
import * as GitLabCli from "./GitLabCli.ts";
|
||||
|
||||
const mockedRun = vi.fn<VcsProcess.VcsProcess["Service"]["run"]>();
|
||||
const layer = it.layer(
|
||||
GitLabCli.layer.pipe(
|
||||
Layer.provide(
|
||||
Layer.mock(VcsProcess.VcsProcess)({
|
||||
run: mockedRun,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
function processOutput(stdout: string): VcsProcess.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: "closed",
|
||||
closed_at: "2026-08-23T10:00:00Z",
|
||||
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: "closed",
|
||||
closedAt: "2026-08-23T10:00:00Z",
|
||||
mergedAt: null,
|
||||
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",
|
||||
merged_at: "2026-08-23T11:00:00Z",
|
||||
},
|
||||
]),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
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",
|
||||
closedAt: null,
|
||||
mergedAt: "2026-08-23T11:00:00Z",
|
||||
},
|
||||
]);
|
||||
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",
|
||||
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("creates repositories under an explicit namespace", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedRun
|
||||
|
||||
.mockReturnValueOnce(Effect.succeed(processOutput(JSON.stringify({ id: 1234 }))))
|
||||
.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 glab = yield* GitLabCli.GitLabCli;
|
||||
const result = yield* glab.createRepository({
|
||||
cwd: "/repo",
|
||||
repository: "octocat/t3code",
|
||||
visibility: "public",
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(result, {
|
||||
nameWithOwner: "octocat/t3code",
|
||||
url: "https://gitlab.com/octocat/t3code",
|
||||
sshUrl: "[email protected]:octocat/t3code.git",
|
||||
});
|
||||
expect(mockedRun).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
expect.objectContaining({
|
||||
command: "glab",
|
||||
cwd: "/repo",
|
||||
args: ["api", "namespaces/octocat"],
|
||||
}),
|
||||
);
|
||||
expect(mockedRun).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
expect.objectContaining({
|
||||
command: "glab",
|
||||
cwd: "/repo",
|
||||
args: [
|
||||
"api",
|
||||
"--method",
|
||||
"POST",
|
||||
"projects",
|
||||
"--raw-field",
|
||||
"path=t3code",
|
||||
"--raw-field",
|
||||
"name=t3code",
|
||||
"--raw-field",
|
||||
"visibility=public",
|
||||
"--raw-field",
|
||||
"namespace_id=1234",
|
||||
],
|
||||
}),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
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* () {
|
||||
const cause = new VcsProcessExitError({
|
||||
operation: "GitLabCli.execute",
|
||||
command: "glab",
|
||||
cwd: "/repo",
|
||||
exitCode: 1,
|
||||
detail: "GET 404 merge request not found",
|
||||
failureKind: "not-found",
|
||||
});
|
||||
mockedRun.mockReturnValueOnce(Effect.fail(cause));
|
||||
|
||||
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 4888 was not found"), true);
|
||||
assert.strictEqual(error._tag, "GitLabMergeRequestNotFoundError");
|
||||
assert.strictEqual(error.command, "glab");
|
||||
assert.strictEqual(error.cwd, "/repo");
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.equal(error.message.includes(cause.detail), false);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps non-merge-request not-found failures generic", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new VcsProcessExitError({
|
||||
operation: "GitLabCli.execute",
|
||||
command: "glab",
|
||||
cwd: "/repo",
|
||||
exitCode: 1,
|
||||
detail: "GET 404 project not found",
|
||||
failureKind: "not-found",
|
||||
});
|
||||
mockedRun.mockReturnValueOnce(Effect.fail(cause));
|
||||
|
||||
const error = yield* Effect.gen(function* () {
|
||||
const glab = yield* GitLabCli.GitLabCli;
|
||||
return yield* glab.getRepositoryCloneUrls({
|
||||
cwd: "/repo",
|
||||
repository: "missing/project",
|
||||
});
|
||||
}).pipe(Effect.flip);
|
||||
|
||||
assert.strictEqual(error._tag, "GitLabCliCommandError");
|
||||
assert.strictEqual(error.cause, cause);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("preserves rate-limit failures as a distinct error", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new VcsProcessExitError({
|
||||
operation: "GitLabCli.execute",
|
||||
command: "glab",
|
||||
cwd: "/repo",
|
||||
exitCode: 1,
|
||||
detail: "API rate limit exceeded.",
|
||||
failureKind: "rate-limited",
|
||||
});
|
||||
mockedRun.mockReturnValueOnce(Effect.fail(cause));
|
||||
|
||||
const glab = yield* GitLabCli.GitLabCli;
|
||||
const error = yield* glab
|
||||
.execute({ cwd: "/repo", args: ["api", "projects"] })
|
||||
.pipe(Effect.flip);
|
||||
|
||||
assert.strictEqual(error._tag, "GitLabCliRateLimitError");
|
||||
assert.strictEqual(error.cause, cause);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1,660 +0,0 @@
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Match from "effect/Match";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Result from "effect/Result";
|
||||
import * as Schema from "effect/Schema";
|
||||
import type * as DateTime from "effect/DateTime";
|
||||
|
||||
import {
|
||||
TrimmedNonEmptyString,
|
||||
type SourceControlRepositoryVisibility,
|
||||
type VcsError,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import * as VcsProcess from "../vcs/VcsProcess.ts";
|
||||
import {
|
||||
decodeGitLabMergeRequestJson,
|
||||
decodeGitLabMergeRequestListJson,
|
||||
} from "./gitLabMergeRequests.ts";
|
||||
import type * as SourceControlProvider from "@t3tools/source-control-core/server/SourceControlProvider";
|
||||
|
||||
const DEFAULT_TIMEOUT_MS = 30_000;
|
||||
|
||||
const gitLabCliExecutionErrorContext = {
|
||||
operation: Schema.Literal("execute"),
|
||||
command: Schema.Literal("glab"),
|
||||
cwd: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
};
|
||||
|
||||
const gitLabCliDecodeErrorContext = {
|
||||
command: Schema.Literal("glab"),
|
||||
cwd: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
};
|
||||
|
||||
export class GitLabCliUnavailableError extends Schema.TaggedError<GitLabCliUnavailableError>()(
|
||||
"GitLabCliUnavailableError",
|
||||
gitLabCliExecutionErrorContext,
|
||||
) {
|
||||
get detail(): string {
|
||||
return "GitLab CLI (`glab`) is required but not available on PATH.";
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class GitLabCliAuthenticationError extends Schema.TaggedError<GitLabCliAuthenticationError>()(
|
||||
"GitLabCliAuthenticationError",
|
||||
gitLabCliExecutionErrorContext,
|
||||
) {
|
||||
get detail(): string {
|
||||
return "GitLab CLI is not authenticated. Run `glab auth login` and retry.";
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class GitLabCliRateLimitError extends Schema.TaggedError<GitLabCliRateLimitError>()(
|
||||
"GitLabCliRateLimitError",
|
||||
gitLabCliExecutionErrorContext,
|
||||
) {
|
||||
get detail(): string {
|
||||
return "GitLab API rate limit exceeded.";
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class GitLabMergeRequestNotFoundError extends Schema.TaggedError<GitLabMergeRequestNotFoundError>()(
|
||||
"GitLabMergeRequestNotFoundError",
|
||||
{
|
||||
...gitLabCliExecutionErrorContext,
|
||||
reference: Schema.String,
|
||||
},
|
||||
) {
|
||||
get detail(): string {
|
||||
return `Merge request ${this.reference} was not found. Check the MR number or URL and try again.`;
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
|
||||
}
|
||||
|
||||
static fromVcsError(
|
||||
context: {
|
||||
readonly operation: "execute";
|
||||
readonly command: "glab";
|
||||
readonly cwd: string;
|
||||
readonly reference: string;
|
||||
},
|
||||
error: VcsError,
|
||||
): GitLabCliError {
|
||||
if (error._tag === "VcsProcessExitError" && error.failureKind === "not-found") {
|
||||
return new GitLabMergeRequestNotFoundError({ ...context, cause: error });
|
||||
}
|
||||
|
||||
return GitLabCliCommandError.fromVcsError(
|
||||
{
|
||||
operation: context.operation,
|
||||
command: context.command,
|
||||
cwd: context.cwd,
|
||||
},
|
||||
error,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export class GitLabCliCommandError extends Schema.TaggedError<GitLabCliCommandError>()(
|
||||
"GitLabCliCommandError",
|
||||
gitLabCliExecutionErrorContext,
|
||||
) {
|
||||
get detail(): string {
|
||||
return "GitLab CLI command failed.";
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
|
||||
}
|
||||
|
||||
static fromVcsError(
|
||||
context: {
|
||||
readonly operation: "execute";
|
||||
readonly command: "glab";
|
||||
readonly cwd: string;
|
||||
},
|
||||
error: VcsError,
|
||||
): GitLabCliError {
|
||||
return Match.valueTags(error, {
|
||||
VcsProcessSpawnError: (cause) => new GitLabCliUnavailableError({ ...context, cause }),
|
||||
VcsProcessExitError: (cause) => {
|
||||
switch (cause.failureKind) {
|
||||
case "authentication":
|
||||
return new GitLabCliAuthenticationError({ ...context, cause });
|
||||
case "rate-limited":
|
||||
return new GitLabCliRateLimitError({ ...context, cause });
|
||||
case "not-found":
|
||||
case "command-failed":
|
||||
case undefined:
|
||||
return new GitLabCliCommandError({ ...context, cause });
|
||||
}
|
||||
},
|
||||
VcsProcessTimeoutError: (cause) => new GitLabCliCommandError({ ...context, cause }),
|
||||
VcsProcessStdinWriteError: (cause) => new GitLabCliCommandError({ ...context, cause }),
|
||||
VcsProcessOutputReadError: (cause) => new GitLabCliCommandError({ ...context, cause }),
|
||||
VcsProcessOutputLimitError: (cause) => new GitLabCliCommandError({ ...context, cause }),
|
||||
VcsProcessMissingExitCodeError: (cause) => new GitLabCliCommandError({ ...context, cause }),
|
||||
VcsRepositoryDetectionError: (cause) => new GitLabCliCommandError({ ...context, cause }),
|
||||
VcsUnsupportedOperationError: (cause) => new GitLabCliCommandError({ ...context, cause }),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export class GitLabMergeRequestListDecodeError extends Schema.TaggedError<GitLabMergeRequestListDecodeError>()(
|
||||
"GitLabMergeRequestListDecodeError",
|
||||
{
|
||||
...gitLabCliDecodeErrorContext,
|
||||
operation: Schema.Literal("listMergeRequests"),
|
||||
},
|
||||
) {
|
||||
get detail(): string {
|
||||
return "GitLab CLI returned invalid MR list JSON.";
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class GitLabMergeRequestDecodeError extends Schema.TaggedError<GitLabMergeRequestDecodeError>()(
|
||||
"GitLabMergeRequestDecodeError",
|
||||
{
|
||||
...gitLabCliDecodeErrorContext,
|
||||
operation: Schema.Literal("getMergeRequest"),
|
||||
reference: Schema.String,
|
||||
},
|
||||
) {
|
||||
get detail(): string {
|
||||
return "GitLab CLI returned invalid merge request JSON.";
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class GitLabRepositoryDecodeError extends Schema.TaggedError<GitLabRepositoryDecodeError>()(
|
||||
"GitLabRepositoryDecodeError",
|
||||
{
|
||||
...gitLabCliDecodeErrorContext,
|
||||
operation: Schema.Literals(["getRepositoryCloneUrls", "createRepository", "getDefaultBranch"]),
|
||||
repository: Schema.optional(Schema.String),
|
||||
},
|
||||
) {
|
||||
get detail(): string {
|
||||
return "GitLab CLI returned invalid repository JSON.";
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class GitLabNamespaceDecodeError extends Schema.TaggedError<GitLabNamespaceDecodeError>()(
|
||||
"GitLabNamespaceDecodeError",
|
||||
{
|
||||
...gitLabCliDecodeErrorContext,
|
||||
operation: Schema.Literal("createRepository"),
|
||||
namespacePath: Schema.String,
|
||||
},
|
||||
) {
|
||||
get detail(): string {
|
||||
return "GitLab CLI returned invalid namespace JSON.";
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
export const GitLabCliError = Schema.Union([
|
||||
GitLabCliUnavailableError,
|
||||
GitLabCliAuthenticationError,
|
||||
GitLabCliRateLimitError,
|
||||
GitLabMergeRequestNotFoundError,
|
||||
GitLabCliCommandError,
|
||||
GitLabMergeRequestListDecodeError,
|
||||
GitLabMergeRequestDecodeError,
|
||||
GitLabRepositoryDecodeError,
|
||||
GitLabNamespaceDecodeError,
|
||||
]);
|
||||
export type GitLabCliError = typeof GitLabCliError.Type;
|
||||
|
||||
export interface GitLabMergeRequestSummary {
|
||||
readonly number: number;
|
||||
readonly title: string;
|
||||
readonly url: string;
|
||||
readonly baseRefName: string;
|
||||
readonly headRefName: string;
|
||||
readonly state?: "open" | "closed" | "merged";
|
||||
readonly isDraft?: boolean;
|
||||
readonly closedAt?: string | null;
|
||||
readonly mergedAt?: string | null;
|
||||
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 class GitLabCli extends Context.Service<
|
||||
GitLabCli,
|
||||
{
|
||||
readonly execute: (input: {
|
||||
readonly cwd: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
readonly timeoutMs?: number;
|
||||
/** Piped to the child's stdin, for payloads that must never appear in argv. */
|
||||
readonly stdin?: string;
|
||||
readonly maxOutputBytes?: number;
|
||||
}) => Effect.Effect<VcsProcess.VcsProcessOutput, GitLabCliError>;
|
||||
|
||||
readonly listMergeRequests: (input: {
|
||||
readonly cwd: string;
|
||||
readonly headSelector: string;
|
||||
readonly source?: SourceControlProvider.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 createRepository: (input: {
|
||||
readonly cwd: string;
|
||||
readonly repository: string;
|
||||
readonly visibility: SourceControlRepositoryVisibility;
|
||||
}) => Effect.Effect<GitLabRepositoryCloneUrls, GitLabCliError>;
|
||||
|
||||
readonly createMergeRequest: (input: {
|
||||
readonly cwd: string;
|
||||
readonly baseBranch: string;
|
||||
readonly headSelector: string;
|
||||
readonly source?: SourceControlProvider.SourceControlRefSelector;
|
||||
readonly target?: SourceControlProvider.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>;
|
||||
}
|
||||
>()("t3/sourceControl/GitLabCli") {}
|
||||
|
||||
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)),
|
||||
});
|
||||
|
||||
const RawGitLabNamespaceSchema = Schema.Struct({
|
||||
id: Schema.Number,
|
||||
});
|
||||
|
||||
const decodeGitLabRepositoryCloneUrls = Schema.decodeEffect(
|
||||
Schema.fromJsonString(RawGitLabRepositoryCloneUrlsSchema),
|
||||
);
|
||||
const decodeGitLabDefaultBranch = Schema.decodeEffect(
|
||||
Schema.fromJsonString(RawGitLabDefaultBranchSchema),
|
||||
);
|
||||
const decodeGitLabNamespace = Schema.decodeEffect(Schema.fromJsonString(RawGitLabNamespaceSchema));
|
||||
|
||||
function normalizeRepositoryCloneUrls(
|
||||
raw: Schema.Schema.Type<typeof RawGitLabRepositoryCloneUrlsSchema>,
|
||||
): GitLabRepositoryCloneUrls {
|
||||
return {
|
||||
nameWithOwner: raw.path_with_namespace,
|
||||
url: raw.web_url,
|
||||
sshUrl: raw.ssh_url_to_repo,
|
||||
};
|
||||
}
|
||||
|
||||
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?: SourceControlProvider.SourceControlRefSelector;
|
||||
}): string {
|
||||
return input.source?.refName ?? normalizeHeadSelector(input.headSelector);
|
||||
}
|
||||
|
||||
function sourceProjectIdentifier(
|
||||
source: SourceControlProvider.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;
|
||||
}
|
||||
|
||||
function parseRepositoryPath(repository: string): {
|
||||
readonly namespacePath: string | null;
|
||||
readonly projectPath: string;
|
||||
} {
|
||||
const parts: Array<string> = [];
|
||||
for (const part of repository.split("/")) {
|
||||
const trimmed = part.trim();
|
||||
if (trimmed.length > 0) {
|
||||
parts.push(trimmed);
|
||||
}
|
||||
}
|
||||
const projectPath = parts.at(-1) ?? repository.trim();
|
||||
const namespacePath = parts.length > 1 ? parts.slice(0, -1).join("/") : null;
|
||||
return { namespacePath, projectPath };
|
||||
}
|
||||
|
||||
/** @public Service construction is part of the canonical Effect module API. */
|
||||
export const make = Effect.gen(function* () {
|
||||
const process = yield* VcsProcess.VcsProcess;
|
||||
|
||||
const run = (
|
||||
input: Parameters<GitLabCli["Service"]["execute"]>[0],
|
||||
mapError: (error: VcsError) => GitLabCliError,
|
||||
) =>
|
||||
process
|
||||
.run({
|
||||
operation: "GitLabCli.execute",
|
||||
command: "glab",
|
||||
args: input.args,
|
||||
cwd: input.cwd,
|
||||
timeoutMs: input.timeoutMs ?? DEFAULT_TIMEOUT_MS,
|
||||
...(input.stdin === undefined ? {} : { stdin: input.stdin }),
|
||||
...(input.maxOutputBytes === undefined ? {} : { maxOutputBytes: input.maxOutputBytes }),
|
||||
})
|
||||
.pipe(Effect.mapError(mapError));
|
||||
|
||||
const execute: GitLabCli["Service"]["execute"] = (input) =>
|
||||
run(input, (error) =>
|
||||
GitLabCliCommandError.fromVcsError(
|
||||
{ operation: "execute", command: "glab", cwd: input.cwd },
|
||||
error,
|
||||
),
|
||||
);
|
||||
|
||||
const executeMergeRequest = (input: {
|
||||
readonly cwd: string;
|
||||
readonly reference: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
}) =>
|
||||
run(input, (error) =>
|
||||
GitLabMergeRequestNotFoundError.fromVcsError(
|
||||
{
|
||||
operation: "execute",
|
||||
command: "glab",
|
||||
cwd: input.cwd,
|
||||
reference: input.reference,
|
||||
},
|
||||
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 GitLabMergeRequestListDecodeError({
|
||||
operation: "listMergeRequests",
|
||||
command: "glab",
|
||||
cwd: input.cwd,
|
||||
cause: decoded.failure,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
return Effect.succeed(decoded.success.map(toSummaryWithOptionalUpdatedAt));
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
getMergeRequest: (input) =>
|
||||
executeMergeRequest({
|
||||
cwd: input.cwd,
|
||||
reference: input.reference,
|
||||
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 GitLabMergeRequestDecodeError({
|
||||
operation: "getMergeRequest",
|
||||
command: "glab",
|
||||
cwd: input.cwd,
|
||||
reference: input.reference,
|
||||
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) =>
|
||||
decodeGitLabRepositoryCloneUrls(raw).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new GitLabRepositoryDecodeError({
|
||||
operation: "getRepositoryCloneUrls",
|
||||
command: "glab",
|
||||
cwd: input.cwd,
|
||||
repository: input.repository,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
Effect.map(normalizeRepositoryCloneUrls),
|
||||
),
|
||||
createRepository: (input) => {
|
||||
const { namespacePath, projectPath } = parseRepositoryPath(input.repository);
|
||||
const namespaceId: Effect.Effect<number | null, GitLabCliError> = namespacePath
|
||||
? execute({
|
||||
cwd: input.cwd,
|
||||
args: ["api", `namespaces/${encodeURIComponent(namespacePath)}`],
|
||||
}).pipe(
|
||||
Effect.map((result) => result.stdout.trim()),
|
||||
Effect.flatMap((raw) =>
|
||||
decodeGitLabNamespace(raw).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new GitLabNamespaceDecodeError({
|
||||
operation: "createRepository",
|
||||
command: "glab",
|
||||
cwd: input.cwd,
|
||||
namespacePath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
Effect.map((namespace) => namespace.id),
|
||||
)
|
||||
: Effect.succeed(null);
|
||||
|
||||
return namespaceId.pipe(
|
||||
Effect.flatMap((resolvedNamespaceId) =>
|
||||
execute({
|
||||
cwd: input.cwd,
|
||||
args: [
|
||||
"api",
|
||||
"--method",
|
||||
"POST",
|
||||
"projects",
|
||||
"--raw-field",
|
||||
`path=${projectPath}`,
|
||||
"--raw-field",
|
||||
`name=${projectPath}`,
|
||||
"--raw-field",
|
||||
`visibility=${input.visibility}`,
|
||||
...(resolvedNamespaceId === null
|
||||
? []
|
||||
: ["--raw-field", `namespace_id=${resolvedNamespaceId}`]),
|
||||
],
|
||||
}),
|
||||
),
|
||||
Effect.map((result) => result.stdout.trim()),
|
||||
Effect.flatMap((raw) =>
|
||||
decodeGitLabRepositoryCloneUrls(raw).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new GitLabRepositoryDecodeError({
|
||||
operation: "createRepository",
|
||||
command: "glab",
|
||||
cwd: input.cwd,
|
||||
repository: input.repository,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
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) =>
|
||||
decodeGitLabDefaultBranch(raw).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new GitLabRepositoryDecodeError({
|
||||
operation: "getDefaultBranch",
|
||||
command: "glab",
|
||||
cwd: input.cwd,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
Effect.map((value) => value.default_branch ?? null),
|
||||
),
|
||||
checkoutMergeRequest: (input) =>
|
||||
executeMergeRequest({
|
||||
cwd: input.cwd,
|
||||
reference: input.reference,
|
||||
args: ["mr", "checkout", input.reference],
|
||||
}).pipe(Effect.asVoid),
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(GitLabCli, make);
|
||||
@@ -1,309 +0,0 @@
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import { ChildProcessSpawner } from "effect/process";
|
||||
|
||||
import * as GitLabCli from "./GitLabCli.ts";
|
||||
import { parseGitLabAuthStatusHosts } from "./gitLabAuthStatus.ts";
|
||||
import * as GitLabSourceControlProvider from "./GitLabSourceControlProvider.ts";
|
||||
|
||||
function makeProvider(gitlab: Partial<GitLabCli.GitLabCli["Service"]>) {
|
||||
return GitLabSourceControlProvider.make.pipe(
|
||||
Effect.provide(Layer.mock(GitLabCli.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: "closed",
|
||||
closedAt: "2026-08-23T10:00:00Z",
|
||||
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: "closed",
|
||||
closedAt: "2026-08-23T10:00:00Z",
|
||||
mergedAt: null,
|
||||
updatedAt: Option.none(),
|
||||
isCrossRepository: true,
|
||||
headRepositoryNameWithOwner: "fork/t3code",
|
||||
headRepositoryOwnerLogin: "fork",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("adds repository context while retaining GitLab CLI causes", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new GitLabCli.GitLabCliCommandError({
|
||||
operation: "execute",
|
||||
command: "glab",
|
||||
cwd: "/repo",
|
||||
cause: new Error("raw upstream detail that should remain in the cause"),
|
||||
});
|
||||
const provider = yield* makeProvider({
|
||||
createRepository: () => Effect.fail(cause),
|
||||
});
|
||||
|
||||
const error = yield* provider
|
||||
.createRepository({
|
||||
cwd: "/repo",
|
||||
repository: "owner/repo",
|
||||
visibility: "private",
|
||||
})
|
||||
.pipe(Effect.flip);
|
||||
|
||||
assert.deepStrictEqual(
|
||||
{
|
||||
provider: error.provider,
|
||||
operation: error.operation,
|
||||
command: error.command,
|
||||
cwd: error.cwd,
|
||||
repository: error.repository,
|
||||
detail: error.detail,
|
||||
},
|
||||
{
|
||||
provider: "gitlab",
|
||||
operation: "createRepository",
|
||||
command: "glab",
|
||||
cwd: "/repo",
|
||||
repository: "owner/repo",
|
||||
detail: "GitLab CLI command failed.",
|
||||
},
|
||||
);
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.equal(error.message.includes("raw upstream detail"), false);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("lists GitLab MRs through provider-neutral input names", () =>
|
||||
Effect.gen(function* () {
|
||||
let listInput: Parameters<GitLabCli.GitLabCli["Service"]["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<GitLabCli.GitLabCli["Service"]["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",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it("accepts authenticated GitLab hosts when another configured host fails", () => {
|
||||
const auth = GitLabSourceControlProvider.discovery.parseAuth({
|
||||
exitCode: ChildProcessSpawner.ExitCode(1),
|
||||
stdout: `gitlab.com
|
||||
x gitlab.com: API call failed: 401 Unauthorized
|
||||
! No token found
|
||||
self-hosted.example.test
|
||||
✓ Logged in to self-hosted.example.test as gitlab-user
|
||||
✓ Token found: ******
|
||||
`,
|
||||
stderr: "",
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(
|
||||
{
|
||||
status: auth.status,
|
||||
account: auth.account,
|
||||
host: auth.host,
|
||||
},
|
||||
{
|
||||
status: "authenticated",
|
||||
account: Option.some("gitlab-user"),
|
||||
host: Option.some("self-hosted.example.test"),
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
it("refines unknown GitLab remotes with mixed-case provider hosts", () => {
|
||||
const provider = GitLabSourceControlProvider.discovery.refineUnknownRemote?.({
|
||||
cwd: "/repo",
|
||||
context: {
|
||||
provider: {
|
||||
kind: "unknown",
|
||||
name: "Self-Hosted.Example.Test",
|
||||
baseUrl: "https://Self-Hosted.Example.Test",
|
||||
},
|
||||
remoteName: "origin",
|
||||
remoteUrl: "https://Self-Hosted.Example.Test/group/project.git",
|
||||
},
|
||||
auth: {
|
||||
exitCode: ChildProcessSpawner.ExitCode(0),
|
||||
stdout: `self-hosted.example.test
|
||||
✓ Logged in to self-hosted.example.test as gitlab-user
|
||||
✓ Token found: ******
|
||||
`,
|
||||
stderr: "",
|
||||
},
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(provider, {
|
||||
kind: "gitlab",
|
||||
name: "GitLab Self-Hosted",
|
||||
baseUrl: "https://Self-Hosted.Example.Test",
|
||||
});
|
||||
});
|
||||
|
||||
it("parses authenticated GitLab auth status hosts with ports and single-label names", () => {
|
||||
assert.deepStrictEqual(
|
||||
parseGitLabAuthStatusHosts(`localhost:8080
|
||||
✓ Logged in to localhost:8080 as local-user
|
||||
selfhosted
|
||||
✓ Logged in to selfhosted as single-label-user
|
||||
`),
|
||||
[
|
||||
{ host: "localhost:8080", account: "local-user" },
|
||||
{ host: "selfhosted", account: "single-label-user" },
|
||||
],
|
||||
);
|
||||
});
|
||||
|
||||
it.effect.each(["merge_requests", "issues"])(
|
||||
"resolves %s subjects on the linked host without using the checkout",
|
||||
(kind) =>
|
||||
Effect.gen(function* () {
|
||||
const provider = yield* makeProvider({
|
||||
execute: (input) => {
|
||||
assert.deepStrictEqual(input.args, [
|
||||
"api",
|
||||
"--hostname",
|
||||
"gitlab.com",
|
||||
`projects/group%2Fsubgroup%2Fproject/${kind}/42`,
|
||||
]);
|
||||
assert.strictEqual(input.maxOutputBytes, 32_000);
|
||||
assert.strictEqual(input.timeoutMs, 3_000);
|
||||
return Effect.succeed({
|
||||
exitCode: ChildProcessSpawner.ExitCode(0),
|
||||
stdout: JSON.stringify({
|
||||
title: "Pairing expiry",
|
||||
description: "Preserve remote access",
|
||||
}),
|
||||
stderr: "",
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
});
|
||||
},
|
||||
});
|
||||
const lookup = provider.resolveLink?.({
|
||||
cwd: "/unrelated",
|
||||
url: new URL(`https://gitlab.com/group/subgroup/project/-/${kind}/42`),
|
||||
});
|
||||
assert.ok(lookup);
|
||||
assert.deepStrictEqual(yield* lookup, {
|
||||
title: "Pairing expiry",
|
||||
body: "Preserve remote access",
|
||||
});
|
||||
assert.strictEqual(
|
||||
provider.resolveLink?.({
|
||||
cwd: "/unrelated",
|
||||
url: new URL("https://gitlab.com/owner/repo"),
|
||||
}),
|
||||
undefined,
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect.each(["read", "decode"] as const)(
|
||||
"retains the %s failure without exposing its raw contents",
|
||||
(stage) =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new GitLabCli.GitLabCliCommandError({
|
||||
command: "glab",
|
||||
cwd: "/repo",
|
||||
operation: "execute",
|
||||
cause: new Error("private response text"),
|
||||
});
|
||||
const provider = yield* makeProvider({
|
||||
execute: () =>
|
||||
stage === "read"
|
||||
? Effect.fail(cause)
|
||||
: Effect.succeed({
|
||||
exitCode: ChildProcessSpawner.ExitCode(0),
|
||||
stdout: "private response text",
|
||||
stderr: "",
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
}),
|
||||
});
|
||||
const lookup = provider.resolveLink?.({
|
||||
cwd: "/repo",
|
||||
url: new URL("https://gitlab.com/owner/repo/-/issues/42"),
|
||||
});
|
||||
assert.ok(lookup);
|
||||
const error = yield* Effect.flip(lookup);
|
||||
assert.strictEqual(error.operation, stage === "read" ? "resolveLink" : "resolveLink.decode");
|
||||
assert.strictEqual(error.detail, "The linked subject could not be read.");
|
||||
assert.notInclude(error.message, "private response text");
|
||||
if (stage === "read") assert.strictEqual(error.cause, cause);
|
||||
else assert.propertyVal(error.cause, "_tag", "SchemaError");
|
||||
}),
|
||||
);
|
||||
@@ -1,308 +0,0 @@
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Option from "effect/Option";
|
||||
import { SourceControlProviderError, type ChangeRequest } from "@t3tools/contracts";
|
||||
|
||||
import * as GitLabCli from "./GitLabCli.ts";
|
||||
import * as SourceControlProvider from "@t3tools/source-control-core/server/SourceControlProvider";
|
||||
import {
|
||||
combinedAuthOutput,
|
||||
firstSafeAuthLine,
|
||||
matchFirst,
|
||||
parseCliHost,
|
||||
providerAuth,
|
||||
type SourceControlAuthProbeInput,
|
||||
type SourceControlCliDiscoverySpec,
|
||||
type SourceControlUnknownRemoteRefinementInput,
|
||||
} from "@t3tools/source-control-core/server/discovery";
|
||||
import { findAuthenticatedGitLabHost, parseGitLabAuthStatusHosts } from "./gitLabAuthStatus.ts";
|
||||
|
||||
const decodeLinkSubject = Schema.decodeUnknownEffect(
|
||||
Schema.fromJsonString(
|
||||
Schema.Struct({ title: Schema.String, description: Schema.NullOr(Schema.String) }),
|
||||
),
|
||||
);
|
||||
|
||||
function toChangeRequest(summary: GitLabCli.GitLabMergeRequestSummary): ChangeRequest {
|
||||
return {
|
||||
provider: "gitlab",
|
||||
number: summary.number,
|
||||
title: summary.title,
|
||||
url: summary.url,
|
||||
baseRefName: summary.baseRefName,
|
||||
headRefName: summary.headRefName,
|
||||
state: summary.state ?? "open",
|
||||
...(summary.isDraft === true ? { isDraft: true } : {}),
|
||||
closedAt: summary.closedAt ?? null,
|
||||
mergedAt: summary.mergedAt ?? null,
|
||||
updatedAt: summary.updatedAt ?? Option.none(),
|
||||
...(summary.isCrossRepository !== undefined
|
||||
? { isCrossRepository: summary.isCrossRepository }
|
||||
: {}),
|
||||
...(summary.headRepositoryNameWithOwner !== undefined
|
||||
? { headRepositoryNameWithOwner: summary.headRepositoryNameWithOwner }
|
||||
: {}),
|
||||
...(summary.headRepositoryOwnerLogin !== undefined
|
||||
? { headRepositoryOwnerLogin: summary.headRepositoryOwnerLogin }
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
|
||||
function parseGitLabAuth(input: SourceControlAuthProbeInput) {
|
||||
const output = combinedAuthOutput(input);
|
||||
const authenticatedHost = findAuthenticatedGitLabHost(parseGitLabAuthStatusHosts(output));
|
||||
const account =
|
||||
authenticatedHost?.account ??
|
||||
matchFirst(output, [
|
||||
/Logged in to .* as\s+([^\s(]+)/iu,
|
||||
/Logged in to .* account\s+([^\s(]+)/iu,
|
||||
/account:\s*([^\s(]+)/iu,
|
||||
]);
|
||||
const host = authenticatedHost?.host ?? parseCliHost(output);
|
||||
|
||||
if (account) {
|
||||
return providerAuth({ status: "authenticated", account, host });
|
||||
}
|
||||
|
||||
if (input.exitCode !== 0) {
|
||||
return providerAuth({
|
||||
status: "unauthenticated",
|
||||
host,
|
||||
detail: firstSafeAuthLine(output) ?? "Run `glab auth login` to authenticate GitLab CLI.",
|
||||
});
|
||||
}
|
||||
|
||||
return providerAuth({
|
||||
status: "unknown",
|
||||
host,
|
||||
detail: firstSafeAuthLine(output) ?? "GitLab CLI auth status could not be parsed.",
|
||||
});
|
||||
}
|
||||
|
||||
function refineUnknownGitLabRemote(input: SourceControlUnknownRemoteRefinementInput) {
|
||||
const host = input.context.provider.name.toLowerCase();
|
||||
const authenticated = parseGitLabAuthStatusHosts(combinedAuthOutput(input.auth)).some(
|
||||
(entry) => entry.account !== null && entry.host === host,
|
||||
);
|
||||
|
||||
if (!authenticated) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
kind: "gitlab",
|
||||
name: "GitLab Self-Hosted",
|
||||
baseUrl: input.context.provider.baseUrl,
|
||||
} as const;
|
||||
}
|
||||
|
||||
export const discovery = {
|
||||
type: "cli",
|
||||
kind: "gitlab",
|
||||
label: "GitLab",
|
||||
executable: "glab",
|
||||
versionArgs: ["--version"],
|
||||
authArgs: ["auth", "status"],
|
||||
parseAuth: parseGitLabAuth,
|
||||
refineUnknownRemote: refineUnknownGitLabRemote,
|
||||
installHint:
|
||||
"Install the GitLab command-line tool (`glab`) from https://gitlab.com/gitlab-org/cli or your package manager (for example `brew install glab`).",
|
||||
} satisfies SourceControlCliDiscoverySpec;
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const gitlab = yield* GitLabCli.GitLabCli;
|
||||
|
||||
const readLinkSubject = Effect.fn("GitLabSourceControlProvider.readLinkSubject")(function* (
|
||||
input: { readonly cwd: string; readonly url: URL },
|
||||
endpoint: string,
|
||||
) {
|
||||
const result = yield* gitlab
|
||||
.execute({
|
||||
cwd: input.cwd,
|
||||
args: ["api", "--hostname", input.url.host, endpoint],
|
||||
timeoutMs: 3_000,
|
||||
maxOutputBytes: 32_000,
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new SourceControlProviderError({
|
||||
provider: "gitlab",
|
||||
operation: "resolveLink",
|
||||
cwd: input.cwd,
|
||||
detail: "The linked subject could not be read.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const subject = yield* decodeLinkSubject(result.stdout).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new SourceControlProviderError({
|
||||
provider: "gitlab",
|
||||
operation: "resolveLink.decode",
|
||||
cwd: input.cwd,
|
||||
detail: "The linked subject could not be read.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
return { title: subject.title, body: subject.description };
|
||||
});
|
||||
|
||||
return SourceControlProvider.SourceControlProvider.of({
|
||||
kind: "gitlab",
|
||||
resolveLink: (input) => {
|
||||
// Automatic enrichment must not send ambient CLI credentials to a host from message text.
|
||||
if (input.url.host !== "gitlab.com") return undefined;
|
||||
const match = /^\/(.+)\/-\/(merge_requests|issues)\/([1-9]\d*)(?:\/.*)?$/.exec(
|
||||
input.url.pathname,
|
||||
);
|
||||
if (!match) return undefined;
|
||||
return readLinkSubject(
|
||||
input,
|
||||
`projects/${encodeURIComponent(match[1]!)}/${match[2]}/${match[3]}`,
|
||||
);
|
||||
},
|
||||
listChangeRequests: (input) => {
|
||||
const source = SourceControlProvider.sourceControlRefFromInput(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) =>
|
||||
new SourceControlProviderError({
|
||||
provider: "gitlab",
|
||||
operation: "listChangeRequests",
|
||||
command: error.command,
|
||||
cwd: input.cwd,
|
||||
reference: SourceControlProvider.transportSafeSourceControlErrorValue(
|
||||
input.headSelector,
|
||||
),
|
||||
detail: error.detail,
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
);
|
||||
},
|
||||
getChangeRequest: (input) =>
|
||||
gitlab.getMergeRequest(input).pipe(
|
||||
Effect.map(toChangeRequest),
|
||||
Effect.mapError(
|
||||
(error) =>
|
||||
new SourceControlProviderError({
|
||||
provider: "gitlab",
|
||||
operation: "getChangeRequest",
|
||||
command: error.command,
|
||||
cwd: input.cwd,
|
||||
reference: SourceControlProvider.transportSafeSourceControlErrorValue(
|
||||
input.reference,
|
||||
),
|
||||
detail: error.detail,
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
),
|
||||
createChangeRequest: (input) => {
|
||||
const source = SourceControlProvider.sourceControlRefFromInput(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) =>
|
||||
new SourceControlProviderError({
|
||||
provider: "gitlab",
|
||||
operation: "createChangeRequest",
|
||||
command: error.command,
|
||||
cwd: input.cwd,
|
||||
reference: SourceControlProvider.transportSafeSourceControlErrorValue(
|
||||
input.headSelector,
|
||||
),
|
||||
detail: error.detail,
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
);
|
||||
},
|
||||
getRepositoryCloneUrls: (input) =>
|
||||
gitlab.getRepositoryCloneUrls(input).pipe(
|
||||
Effect.mapError(
|
||||
(error) =>
|
||||
new SourceControlProviderError({
|
||||
provider: "gitlab",
|
||||
operation: "getRepositoryCloneUrls",
|
||||
command: error.command,
|
||||
cwd: input.cwd,
|
||||
repository: SourceControlProvider.transportSafeSourceControlErrorValue(
|
||||
input.repository,
|
||||
),
|
||||
detail: error.detail,
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
),
|
||||
createRepository: (input) =>
|
||||
gitlab.createRepository(input).pipe(
|
||||
Effect.mapError(
|
||||
(error) =>
|
||||
new SourceControlProviderError({
|
||||
provider: "gitlab",
|
||||
operation: "createRepository",
|
||||
command: error.command,
|
||||
cwd: input.cwd,
|
||||
repository: SourceControlProvider.transportSafeSourceControlErrorValue(
|
||||
input.repository,
|
||||
),
|
||||
detail: error.detail,
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
),
|
||||
getDefaultBranch: (input) =>
|
||||
gitlab.getDefaultBranch(input).pipe(
|
||||
Effect.mapError(
|
||||
(error) =>
|
||||
new SourceControlProviderError({
|
||||
provider: "gitlab",
|
||||
operation: "getDefaultBranch",
|
||||
command: error.command,
|
||||
cwd: input.cwd,
|
||||
detail: error.detail,
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
),
|
||||
checkoutChangeRequest: (input) =>
|
||||
gitlab.checkoutMergeRequest(input).pipe(
|
||||
Effect.mapError(
|
||||
(error) =>
|
||||
new SourceControlProviderError({
|
||||
provider: "gitlab",
|
||||
operation: "checkoutChangeRequest",
|
||||
command: error.command,
|
||||
cwd: input.cwd,
|
||||
reference: SourceControlProvider.transportSafeSourceControlErrorValue(
|
||||
input.reference,
|
||||
),
|
||||
detail: error.detail,
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
),
|
||||
});
|
||||
});
|
||||
@@ -20,7 +20,8 @@ import * as AzureDevOpsCli from "@t3tools/source-control-azure-devops/server/Azu
|
||||
import * as AzureDevOpsPullRequestCli from "@t3tools/source-control-azure-devops/server/AzureDevOpsPullRequestCli";
|
||||
import * as BitbucketApi from "./BitbucketApi.ts";
|
||||
import * as GitHubApi from "./GitHubApi.ts";
|
||||
import * as GitLabCli from "./GitLabCli.ts";
|
||||
import * as GitLabCli from "@t3tools/source-control-gitlab/server/GitLabCli";
|
||||
import * as GitLabPullRequestCli from "@t3tools/source-control-gitlab/server/GitLabPullRequestCli";
|
||||
import * as ForgejoCli from "@t3tools/source-control-forgejo/server/ForgejoCli";
|
||||
import * as ForgejoSourceControlProvider from "@t3tools/source-control-forgejo/server/ForgejoSourceControlProvider";
|
||||
import * as ForgejoPullRequestProvider from "@t3tools/source-control-forgejo/server/ForgejoPullRequestProvider";
|
||||
@@ -46,6 +47,7 @@ const layerSourceControlProviderRegistryTest = (input: {
|
||||
Layer.mock(GitHubApi.GitHubApi)({}),
|
||||
Layer.mock(GitVcsDriver.GitVcsDriver)({}),
|
||||
Layer.mock(GitLabCli.GitLabCli)({}),
|
||||
Layer.mock(GitLabPullRequestCli.GitLabPullRequestCli)({}),
|
||||
Layer.mock(ForgejoCli.ForgejoCli)({ listLogins: () => Effect.succeed([]) }),
|
||||
Layer.mock(VcsDriverRegistry.VcsDriverRegistry)({}),
|
||||
Layer.mock(VcsProcess.VcsProcess)(input.process),
|
||||
|
||||
@@ -19,7 +19,8 @@ import * as BitbucketApi from "./BitbucketApi.ts";
|
||||
import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
|
||||
import * as GitHubApi from "./GitHubApi.ts";
|
||||
import * as GitHubCredentials from "./GitHubCredentials.ts";
|
||||
import * as GitLabCli from "./GitLabCli.ts";
|
||||
import * as GitLabCli from "@t3tools/source-control-gitlab/server/GitLabCli";
|
||||
import * as GitLabPullRequestCli from "@t3tools/source-control-gitlab/server/GitLabPullRequestCli";
|
||||
import * as ForgejoCli from "@t3tools/source-control-forgejo/server/ForgejoCli";
|
||||
import * as SourceControlProviderRegistry from "./SourceControlProviderRegistry.ts";
|
||||
import * as ServerSourceControlHost from "./ServerSourceControlHost.ts";
|
||||
@@ -114,6 +115,7 @@ function makeRegistry(input: {
|
||||
}),
|
||||
Layer.mock(GitVcsDriver.GitVcsDriver)({}),
|
||||
Layer.mock(GitLabCli.GitLabCli)(input.gitlab ?? {}),
|
||||
Layer.mock(GitLabPullRequestCli.GitLabPullRequestCli)({}),
|
||||
Layer.mock(ForgejoCli.ForgejoCli)({ listLogins: () => Effect.succeed([]) }),
|
||||
ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3-source-control-registry-test-",
|
||||
|
||||
@@ -13,7 +13,6 @@ import { detectSourceControlProviderFromRemoteUrl } from "@t3tools/shared/source
|
||||
|
||||
import * as BitbucketSourceControlProvider from "./BitbucketSourceControlProvider.ts";
|
||||
import * as GitHubSourceControlProvider from "./GitHubSourceControlProvider.ts";
|
||||
import * as GitLabSourceControlProvider from "./GitLabSourceControlProvider.ts";
|
||||
import * as BuiltInDrivers from "./builtInDrivers.ts";
|
||||
import * as SourceControlProvider from "@t3tools/source-control-core/server/SourceControlProvider";
|
||||
import {
|
||||
@@ -306,7 +305,6 @@ export const makeWithProviders = Effect.fn("makeSourceControlProviderRegistryWit
|
||||
export const make = Effect.gen(function* () {
|
||||
const github = yield* GitHubSourceControlProvider.make;
|
||||
const githubDiscovery = yield* GitHubSourceControlProvider.makeDiscovery;
|
||||
const gitlab = yield* GitLabSourceControlProvider.make;
|
||||
const bitbucket = yield* BitbucketSourceControlProvider.make;
|
||||
const bitbucketDiscovery = yield* BitbucketSourceControlProvider.makeDiscovery;
|
||||
const drivers = yield* Effect.forEach(BuiltInDrivers.BUILT_IN_SOURCE_CONTROL_DRIVERS, (driver) =>
|
||||
@@ -326,11 +324,6 @@ export const make = Effect.gen(function* () {
|
||||
provider: github,
|
||||
discovery: githubDiscovery,
|
||||
},
|
||||
{
|
||||
kind: "gitlab",
|
||||
provider: gitlab,
|
||||
discovery: GitLabSourceControlProvider.discovery,
|
||||
},
|
||||
{
|
||||
kind: "bitbucket",
|
||||
provider: bitbucket,
|
||||
|
||||
@@ -12,12 +12,15 @@ import * as AzureDevOpsPullRequestCli from "@t3tools/source-control-azure-devops
|
||||
import * as AzureDevOpsDriver from "@t3tools/source-control-azure-devops/server/driver";
|
||||
import * as ForgejoCli from "@t3tools/source-control-forgejo/server/ForgejoCli";
|
||||
import * as ForgejoDriver from "@t3tools/source-control-forgejo/server/driver";
|
||||
import * as GitLabCli from "@t3tools/source-control-gitlab/server/GitLabCli";
|
||||
import * as GitLabPullRequestCli from "@t3tools/source-control-gitlab/server/GitLabPullRequestCli";
|
||||
import * as GitLabDriver from "@t3tools/source-control-gitlab/server/driver";
|
||||
import type { SourceControlDriver } from "@t3tools/source-control-core/server/driver";
|
||||
import * as Layer from "effect/Layer";
|
||||
|
||||
import * as ServerSourceControlHost from "./ServerSourceControlHost.ts";
|
||||
|
||||
const drivers = [AzureDevOpsDriver.driver, ForgejoDriver.driver];
|
||||
const drivers = [GitLabDriver.driver, AzureDevOpsDriver.driver, ForgejoDriver.driver];
|
||||
|
||||
/** Every service a built-in driver's `make` needs; the server's layers must provide them all. */
|
||||
export type BuiltInSourceControlDriversEnv =
|
||||
@@ -31,4 +34,5 @@ export const BUILT_IN_SOURCE_CONTROL_DRIVERS: ReadonlyArray<
|
||||
export const layer = Layer.mergeAll(
|
||||
AzureDevOpsPullRequestCli.layer.pipe(Layer.provideMerge(AzureDevOpsCli.layer)),
|
||||
ForgejoCli.layer,
|
||||
GitLabPullRequestCli.layer.pipe(Layer.provideMerge(GitLabCli.layer)),
|
||||
).pipe(Layer.provideMerge(ServerSourceControlHost.layer));
|
||||
@@ -1,48 +0,0 @@
|
||||
const HOST_LINE_PATTERN = /^(?:[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?|\[[a-f0-9:.]+\])(?::\d+)?$/iu;
|
||||
const LOGGED_IN_PATTERN = /Logged in to .+? as\s+([^\s(]+)/iu;
|
||||
|
||||
export interface GitLabAuthStatusHost {
|
||||
readonly host: string;
|
||||
readonly account: string | null;
|
||||
}
|
||||
|
||||
export function parseGitLabAuthStatusHosts(text: string): ReadonlyArray<GitLabAuthStatusHost> {
|
||||
const hosts: GitLabAuthStatusHost[] = [];
|
||||
let currentHost: string | null = null;
|
||||
let currentLines: string[] = [];
|
||||
|
||||
const flush = () => {
|
||||
if (currentHost === null) return;
|
||||
|
||||
const account = LOGGED_IN_PATTERN.exec(currentLines.join("\n"))?.[1]?.trim() || null;
|
||||
hosts.push({ host: currentHost, account });
|
||||
currentHost = null;
|
||||
currentLines = [];
|
||||
};
|
||||
|
||||
for (const rawLine of text.split(/\r?\n/)) {
|
||||
const line = rawLine.trim();
|
||||
if (line.length === 0) continue;
|
||||
|
||||
const isHostLine =
|
||||
rawLine.length === rawLine.trimStart().length && HOST_LINE_PATTERN.test(line);
|
||||
if (isHostLine) {
|
||||
flush();
|
||||
currentHost = line.toLowerCase();
|
||||
continue;
|
||||
}
|
||||
|
||||
if (currentHost !== null) {
|
||||
currentLines.push(line);
|
||||
}
|
||||
}
|
||||
|
||||
flush();
|
||||
return hosts;
|
||||
}
|
||||
|
||||
export function findAuthenticatedGitLabHost(
|
||||
hosts: ReadonlyArray<GitLabAuthStatusHost>,
|
||||
): GitLabAuthStatusHost | undefined {
|
||||
return hosts.find((host) => host.account !== null);
|
||||
}
|
||||
@@ -1,161 +0,0 @@
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Result from "effect/Result";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { PositiveInt, TrimmedNonEmptyString } from "@t3tools/contracts";
|
||||
import { decodeJsonResult } 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 isDraft?: boolean;
|
||||
readonly closedAt?: string | null;
|
||||
readonly mergedAt?: string | null;
|
||||
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)),
|
||||
draft: Schema.optional(Schema.Boolean),
|
||||
work_in_progress: Schema.optional(Schema.Boolean),
|
||||
closed_at: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
merged_at: 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),
|
||||
...(raw.draft === true || raw.work_in_progress === true ? { isDraft: true } : {}),
|
||||
closedAt: raw.closed_at ?? null,
|
||||
mergedAt: raw.merged_at ?? null,
|
||||
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 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