feat(source-control): add Bitbucket & Azure Devops providers (#2473)

Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: cursor[bot] <206951365+cursor[bot]@users.noreply.github.com>
This commit is contained in:
authored and GitHub committed 2026-05-04 00:59:58 -07:00
1 parent d501ebe877
commit 91a03e0747
59 files changed
+5852 -2345

No files matched your search

@@ -0,0 +1,288 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it, afterEach, describe, expect, vi } from "@effect/vitest";
import { Effect, FileSystem, Layer, Option } from "effect";
import { ChildProcessSpawner } from "effect/unstable/process";
import type { VcsError } from "@t3tools/contracts";
import * as VcsProcess from "../vcs/VcsProcess.ts";
import * as AzureDevOpsCli from "./AzureDevOpsCli.ts";
const processOutput = (stdout: string): VcsProcess.VcsProcessOutput => ({
exitCode: ChildProcessSpawner.ExitCode(0),
stdout,
stderr: "",
stdoutTruncated: false,
stderrTruncated: false,
});
const mockRun = vi.fn<VcsProcess.VcsProcessShape["run"]>();
const supportLayer = Layer.mergeAll(
Layer.mock(VcsProcess.VcsProcess)({
run: mockRun,
}),
NodeServices.layer,
);
const layer = Layer.mergeAll(AzureDevOpsCli.layer.pipe(Layer.provide(supportLayer)), supportLayer);
afterEach(() => {
mockRun.mockReset();
});
describe("AzureDevOpsCli.layer", () => {
it.effect("parses pull request view output", () =>
Effect.gen(function* () {
mockRun.mockReturnValueOnce(
Effect.succeed(
processOutput(
JSON.stringify({
pullRequestId: 42,
title: "Add Azure provider",
sourceRefName: "refs/heads/feature/source-control",
targetRefName: "refs/heads/main",
status: "active",
creationDate: "2026-01-02T00:00:00.000Z",
closedDate: null,
_links: {
web: {
href: "https://dev.azure.com/acme/project/_git/repo/pullrequest/42",
},
},
}),
),
),
);
const az = yield* AzureDevOpsCli.AzureDevOpsCli;
const result = yield* az.getPullRequest({
cwd: "/repo",
reference: "#42",
});
assert.strictEqual(result.number, 42);
assert.strictEqual(result.title, "Add Azure provider");
assert.strictEqual(result.baseRefName, "main");
assert.strictEqual(result.headRefName, "feature/source-control");
assert.strictEqual(result.state, "open");
assert.deepStrictEqual(result.updatedAt._tag, Option.some(1)._tag);
assert.deepStrictEqual(mockRun.mock.calls.at(-1)?.[0], {
operation: "AzureDevOpsCli.execute",
command: "az",
args: [
"repos",
"pr",
"show",
"--detect",
"true",
"--id",
"42",
"--only-show-errors",
"--output",
"json",
],
cwd: "/repo",
timeoutMs: 30_000,
});
}).pipe(Effect.provide(layer)),
);
it.effect("lists pull requests with Azure status and source branch arguments", () =>
Effect.gen(function* () {
mockRun.mockReturnValueOnce(
Effect.succeed(
processOutput(
JSON.stringify([
{
pullRequestId: 7,
title: "Merged work",
sourceRefName: "refs/heads/feature/merged",
targetRefName: "refs/heads/main",
status: "completed",
closedDate: "2026-01-03T00:00:00.000Z",
_links: {
web: {
href: "https://dev.azure.com/acme/project/_git/repo/pullrequest/7",
},
},
},
]),
),
),
);
const az = yield* AzureDevOpsCli.AzureDevOpsCli;
const result = yield* az.listPullRequests({
cwd: "/repo",
headSelector: "origin:feature/merged",
state: "merged",
limit: 10,
});
assert.strictEqual(result[0]?.state, "merged");
expect(mockRun).toHaveBeenCalledWith({
operation: "AzureDevOpsCli.execute",
command: "az",
args: [
"repos",
"pr",
"list",
"--detect",
"true",
"--source-branch",
"feature/merged",
"--status",
"completed",
"--top",
"10",
"--only-show-errors",
"--output",
"json",
],
cwd: "/repo",
timeoutMs: 30_000,
});
}).pipe(Effect.provide(layer)),
);
it.effect("reads repository clone URLs", () =>
Effect.gen(function* () {
mockRun.mockReturnValueOnce(
Effect.succeed(
processOutput(
JSON.stringify({
name: "repo",
webUrl: "https://dev.azure.com/acme/project/_git/repo",
remoteUrl: "https://dev.azure.com/acme/project/_git/repo",
sshUrl: "[email protected]:v3/acme/project/repo",
project: {
name: "project",
},
}),
),
),
);
const az = yield* AzureDevOpsCli.AzureDevOpsCli;
const result = yield* az.getRepositoryCloneUrls({
cwd: "/repo",
repository: "repo",
});
assert.deepStrictEqual(result, {
nameWithOwner: "project/repo",
url: "https://dev.azure.com/acme/project/_git/repo",
sshUrl: "[email protected]:v3/acme/project/repo",
});
}).pipe(Effect.provide(layer)),
);
it.effect("creates repositories through Azure Repos", () =>
Effect.gen(function* () {
mockRun.mockReturnValueOnce(
Effect.succeed(
processOutput(
JSON.stringify({
name: "repo",
webUrl: "https://dev.azure.com/acme/project/_git/repo",
remoteUrl: "https://dev.azure.com/acme/project/_git/repo",
sshUrl: "[email protected]:v3/acme/project/repo",
project: {
name: "project",
},
}),
),
),
);
const az = yield* AzureDevOpsCli.AzureDevOpsCli;
const result = yield* az.createRepository({
cwd: "/repo",
repository: "project/repo",
visibility: "private",
});
assert.deepStrictEqual(result, {
nameWithOwner: "project/repo",
url: "https://dev.azure.com/acme/project/_git/repo",
sshUrl: "[email protected]:v3/acme/project/repo",
});
expect(mockRun).toHaveBeenCalledWith({
operation: "AzureDevOpsCli.execute",
command: "az",
args: [
"repos",
"create",
"--detect",
"true",
"--name",
"repo",
"--project",
"project",
"--only-show-errors",
"--output",
"json",
],
cwd: "/repo",
timeoutMs: 30_000,
});
}).pipe(Effect.provide(layer)),
);
it.effect("creates pull requests using the body file as the Azure description", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const bodyFile = `/tmp/t3code-azure-devops-cli-${Date.now()}.md`;
yield* fileSystem.writeFileString(bodyFile, "Generated body");
mockRun.mockReturnValueOnce(Effect.succeed(processOutput("{}")));
const az = yield* AzureDevOpsCli.AzureDevOpsCli;
yield* az.createPullRequest({
cwd: "/repo",
baseBranch: "main",
headSelector: "feature/provider",
title: "Provider PR",
bodyFile,
});
expect(mockRun).toHaveBeenCalledWith(
expect.objectContaining({
command: "az",
cwd: "/repo",
args: expect.arrayContaining(["--description", `@${bodyFile}`]),
}),
);
expect(mockRun.mock.calls[0]?.[0].args).not.toContain("--output");
}).pipe(Effect.provide(layer)),
);
it.effect("does not force JSON output on checkout side-effect commands", () =>
Effect.gen(function* () {
mockRun.mockReturnValueOnce(Effect.succeed(processOutput("")));
const az = yield* AzureDevOpsCli.AzureDevOpsCli;
yield* az.checkoutPullRequest({
cwd: "/repo",
reference: "42",
});
expect(mockRun).toHaveBeenCalledWith({
operation: "AzureDevOpsCli.execute",
command: "az",
args: [
"repos",
"pr",
"checkout",
"--only-show-errors",
"--detect",
"true",
"--id",
"42",
"--remote-name",
"origin",
],
cwd: "/repo",
timeoutMs: 30_000,
});
}).pipe(Effect.provide(layer)),
);
});
@@ -0,0 +1,429 @@
import { Context, Effect, Layer, Result, Schema, SchemaIssue } from "effect";
import {
TrimmedNonEmptyString,
type SourceControlRepositoryVisibility,
type VcsError,
} from "@t3tools/contracts";
import * as VcsProcess from "../vcs/VcsProcess.ts";
import * as AzureDevOpsPullRequests from "./azureDevOpsPullRequests.ts";
import * as SourceControlProvider from "./SourceControlProvider.ts";
const DEFAULT_TIMEOUT_MS = 30_000;
export class AzureDevOpsCliError extends Schema.TaggedErrorClass<AzureDevOpsCliError>()(
"AzureDevOpsCliError",
{
operation: Schema.String,
detail: Schema.String,
cause: Schema.optional(Schema.Defect),
},
) {
override get message(): string {
return `Azure DevOps CLI failed in ${this.operation}: ${this.detail}`;
}
}
export interface AzureDevOpsRepositoryCloneUrls {
readonly nameWithOwner: string;
readonly url: string;
readonly sshUrl: string;
}
export interface AzureDevOpsCliShape {
readonly execute: (input: {
readonly cwd: string;
readonly args: ReadonlyArray<string>;
readonly timeoutMs?: number;
}) => Effect.Effect<VcsProcess.VcsProcessOutput, AzureDevOpsCliError>;
readonly listPullRequests: (input: {
readonly cwd: string;
readonly headSelector: string;
readonly source?: SourceControlProvider.SourceControlRefSelector;
readonly state: "open" | "closed" | "merged" | "all";
readonly limit?: number;
}) => Effect.Effect<
ReadonlyArray<AzureDevOpsPullRequests.NormalizedAzureDevOpsPullRequestRecord>,
AzureDevOpsCliError
>;
readonly getPullRequest: (input: {
readonly cwd: string;
readonly reference: string;
}) => Effect.Effect<
AzureDevOpsPullRequests.NormalizedAzureDevOpsPullRequestRecord,
AzureDevOpsCliError
>;
readonly getRepositoryCloneUrls: (input: {
readonly cwd: string;
readonly repository: string;
}) => Effect.Effect<AzureDevOpsRepositoryCloneUrls, AzureDevOpsCliError>;
readonly createRepository: (input: {
readonly cwd: string;
readonly repository: string;
readonly visibility: SourceControlRepositoryVisibility;
}) => Effect.Effect<AzureDevOpsRepositoryCloneUrls, AzureDevOpsCliError>;
readonly createPullRequest: (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, AzureDevOpsCliError>;
readonly getDefaultBranch: (input: {
readonly cwd: string;
}) => Effect.Effect<string | null, AzureDevOpsCliError>;
readonly checkoutPullRequest: (input: {
readonly cwd: string;
readonly reference: string;
readonly remoteName?: string;
}) => Effect.Effect<void, AzureDevOpsCliError>;
}
export class AzureDevOpsCli extends Context.Service<AzureDevOpsCli, AzureDevOpsCliShape>()(
"t3/source-control/AzureDevOpsCli",
) {}
function errorText(error: VcsError | unknown): string {
if (typeof error === "object" && error !== null) {
const tag = "_tag" in error && typeof error._tag === "string" ? error._tag : "";
const detail = "detail" in error && typeof error.detail === "string" ? error.detail : "";
const message = "message" in error && typeof error.message === "string" ? error.message : "";
return [tag, detail, message].filter(Boolean).join("\n");
}
return String(error);
}
function normalizeAzureDevOpsCliError(
operation: "execute",
error: VcsError | unknown,
): AzureDevOpsCliError {
const text = errorText(error);
const lower = text.toLowerCase();
if (lower.includes("command not found: az") || lower.includes("enoent")) {
return new AzureDevOpsCliError({
operation,
detail:
"Azure CLI (`az`) with the Azure DevOps extension is required but not available on PATH.",
cause: error,
});
}
if (
lower.includes("az devops login") ||
lower.includes("please run az login") ||
lower.includes("not logged in") ||
lower.includes("authentication failed") ||
lower.includes("unauthorized")
) {
return new AzureDevOpsCliError({
operation,
detail: "Azure DevOps CLI is not authenticated. Run `az devops login` and retry.",
cause: error,
});
}
if (
lower.includes("pull request") &&
(lower.includes("not found") || lower.includes("does not exist"))
) {
return new AzureDevOpsCliError({
operation,
detail: "Pull request not found. Check the PR number or URL and try again.",
cause: error,
});
}
return new AzureDevOpsCliError({
operation,
detail: text,
cause: error,
});
}
function normalizeChangeRequestId(reference: string): string {
const trimmed = reference.trim().replace(/^#/, "");
const urlMatch = /(?:pullrequest|pull-request|pull|_pulls?)\/(\d+)(?:\D.*)?$/i.exec(trimmed);
return urlMatch?.[1] ?? trimmed;
}
function toAzureStatus(state: "open" | "closed" | "merged" | "all"): string {
switch (state) {
case "open":
return "active";
case "closed":
return "abandoned";
case "merged":
return "completed";
case "all":
return "all";
}
}
const RawAzureDevOpsRepositorySchema = Schema.Struct({
name: TrimmedNonEmptyString,
webUrl: TrimmedNonEmptyString,
remoteUrl: TrimmedNonEmptyString,
sshUrl: TrimmedNonEmptyString,
project: Schema.optional(
Schema.Struct({
name: TrimmedNonEmptyString,
}),
),
defaultBranch: Schema.optional(Schema.NullOr(Schema.String)),
});
function normalizeDefaultBranch(value: string | null | undefined): string | null {
const trimmed = value?.trim().replace(/^refs\/heads\//, "") ?? "";
return trimmed.length > 0 ? trimmed : null;
}
function normalizeRepositoryCloneUrls(
raw: Schema.Schema.Type<typeof RawAzureDevOpsRepositorySchema>,
): AzureDevOpsRepositoryCloneUrls {
const projectName = raw.project?.name.trim();
return {
nameWithOwner: projectName ? `${projectName}/${raw.name}` : raw.name,
url: raw.remoteUrl,
sshUrl: raw.sshUrl,
};
}
function parseRepositorySpecifier(repository: string): {
readonly project: string | null;
readonly name: string;
} {
const parts = repository
.split("/")
.map((part) => part.trim())
.filter((part) => part.length > 0);
return {
project: parts.length > 1 ? (parts.at(-2) ?? null) : null,
name: parts.at(-1) ?? repository.trim(),
};
}
function decodeAzureDevOpsJson<S extends Schema.Top>(
raw: string,
schema: S,
operation: "getRepositoryCloneUrls" | "getDefaultBranch" | "createRepository",
invalidDetail: string,
): Effect.Effect<S["Type"], AzureDevOpsCliError, S["DecodingServices"]> {
return Schema.decodeEffect(Schema.fromJsonString(schema))(raw).pipe(
Effect.mapError(
(error) =>
new AzureDevOpsCliError({
operation,
detail: `${invalidDetail}: ${SchemaIssue.makeFormatterDefault()(error.issue)}`,
cause: error,
}),
),
);
}
export const make = Effect.fn("makeAzureDevOpsCli")(function* () {
const process = yield* VcsProcess.VcsProcess;
const execute: AzureDevOpsCliShape["execute"] = (input) =>
process
.run({
operation: "AzureDevOpsCli.execute",
command: "az",
args: input.args,
cwd: input.cwd,
timeoutMs: input.timeoutMs ?? DEFAULT_TIMEOUT_MS,
})
.pipe(Effect.mapError((error) => normalizeAzureDevOpsCliError("execute", error)));
const executeJson = (input: Parameters<AzureDevOpsCliShape["execute"]>[0]) =>
execute({
...input,
args: [...input.args, "--only-show-errors", "--output", "json"],
});
return AzureDevOpsCli.of({
execute,
listPullRequests: (input) =>
executeJson({
cwd: input.cwd,
args: [
"repos",
"pr",
"list",
"--detect",
"true",
"--source-branch",
SourceControlProvider.sourceBranch(input),
"--status",
toAzureStatus(input.state),
"--top",
String(input.limit ?? 20),
],
}).pipe(
Effect.map((result) => result.stdout.trim()),
Effect.flatMap((raw) =>
raw.length === 0
? Effect.succeed([])
: Effect.sync(() =>
AzureDevOpsPullRequests.decodeAzureDevOpsPullRequestListJson(raw),
).pipe(
Effect.flatMap((decoded) => {
if (!Result.isSuccess(decoded)) {
return Effect.fail(
new AzureDevOpsCliError({
operation: "listPullRequests",
detail: `Azure DevOps CLI returned invalid PR list JSON: ${AzureDevOpsPullRequests.formatAzureDevOpsJsonDecodeError(decoded.failure)}`,
cause: decoded.failure,
}),
);
}
return Effect.succeed(decoded.success);
}),
),
),
),
getPullRequest: (input) =>
executeJson({
cwd: input.cwd,
args: [
"repos",
"pr",
"show",
"--detect",
"true",
"--id",
normalizeChangeRequestId(input.reference),
],
}).pipe(
Effect.map((result) => result.stdout.trim()),
Effect.flatMap((raw) =>
Effect.sync(() => AzureDevOpsPullRequests.decodeAzureDevOpsPullRequestJson(raw)).pipe(
Effect.flatMap((decoded) => {
if (!Result.isSuccess(decoded)) {
return Effect.fail(
new AzureDevOpsCliError({
operation: "getPullRequest",
detail: `Azure DevOps CLI returned invalid pull request JSON: ${AzureDevOpsPullRequests.formatAzureDevOpsJsonDecodeError(decoded.failure)}`,
cause: decoded.failure,
}),
);
}
return Effect.succeed(decoded.success);
}),
),
),
),
getRepositoryCloneUrls: (input) =>
executeJson({
cwd: input.cwd,
args: ["repos", "show", "--detect", "true", "--repository", input.repository],
}).pipe(
Effect.map((result) => result.stdout.trim()),
Effect.flatMap((raw) =>
decodeAzureDevOpsJson(
raw,
RawAzureDevOpsRepositorySchema,
"getRepositoryCloneUrls",
"Azure DevOps CLI returned invalid repository JSON.",
),
),
Effect.map(normalizeRepositoryCloneUrls),
),
createRepository: (input) => {
const repository = parseRepositorySpecifier(input.repository);
// Azure Repos access is governed by project/organization permissions.
// `az repos create` does not expose a per-repository visibility flag, so
// the generic source-control visibility input is intentionally not
// translated into CLI args for this provider.
return executeJson({
cwd: input.cwd,
args: [
"repos",
"create",
"--detect",
"true",
"--name",
repository.name,
...(repository.project ? ["--project", repository.project] : []),
],
}).pipe(
Effect.map((result) => result.stdout.trim()),
Effect.flatMap((raw) =>
decodeAzureDevOpsJson(
raw,
RawAzureDevOpsRepositorySchema,
"createRepository",
"Azure DevOps CLI returned invalid repository JSON.",
),
),
Effect.map(normalizeRepositoryCloneUrls),
);
},
createPullRequest: (input) =>
execute({
cwd: input.cwd,
args: [
"repos",
"pr",
"create",
"--only-show-errors",
"--detect",
"true",
"--target-branch",
input.target?.refName ?? input.baseBranch,
"--source-branch",
SourceControlProvider.sourceBranch(input),
"--title",
input.title,
"--description",
`@${input.bodyFile}`,
],
}).pipe(Effect.asVoid),
getDefaultBranch: (input) =>
executeJson({
cwd: input.cwd,
args: ["repos", "show", "--detect", "true"],
}).pipe(
Effect.map((result) => result.stdout.trim()),
Effect.flatMap((raw) =>
decodeAzureDevOpsJson(
raw,
RawAzureDevOpsRepositorySchema,
"getDefaultBranch",
"Azure DevOps CLI returned invalid repository JSON.",
),
),
Effect.map((repo) => normalizeDefaultBranch(repo.defaultBranch)),
),
checkoutPullRequest: (input) =>
execute({
cwd: input.cwd,
args: [
"repos",
"pr",
"checkout",
"--only-show-errors",
"--detect",
"true",
"--id",
normalizeChangeRequestId(input.reference),
"--remote-name",
input.remoteName ?? "origin",
],
}).pipe(Effect.asVoid),
});
});
export const layer = Layer.effect(AzureDevOpsCli, make());
@@ -0,0 +1,91 @@
import { assert, it } from "@effect/vitest";
import { Effect, Layer, Option } from "effect";
import * as AzureDevOpsCli from "./AzureDevOpsCli.ts";
import * as AzureDevOpsSourceControlProvider from "./AzureDevOpsSourceControlProvider.ts";
function makeProvider(azure: Partial<AzureDevOpsCli.AzureDevOpsCliShape>) {
return AzureDevOpsSourceControlProvider.make().pipe(
Effect.provide(Layer.mock(AzureDevOpsCli.AzureDevOpsCli)(azure)),
);
}
it.effect("maps Azure DevOps PR summaries into provider-neutral change requests", () =>
Effect.gen(function* () {
const provider = yield* makeProvider({
getPullRequest: () =>
Effect.succeed({
number: 42,
title: "Add Azure provider",
url: "https://dev.azure.com/acme/project/_git/repo/pullrequest/42",
baseRefName: "main",
headRefName: "feature/source-control",
state: "open",
updatedAt: Option.none(),
}),
});
const changeRequest = yield* provider.getChangeRequest({
cwd: "/repo",
reference: "42",
});
assert.deepStrictEqual(changeRequest, {
provider: "azure-devops",
number: 42,
title: "Add Azure provider",
url: "https://dev.azure.com/acme/project/_git/repo/pullrequest/42",
baseRefName: "main",
headRefName: "feature/source-control",
state: "open",
updatedAt: Option.none(),
isCrossRepository: false,
});
}),
);
it.effect("creates Azure DevOps PRs through provider-neutral input names", () =>
Effect.gen(function* () {
let createInput: Parameters<AzureDevOpsCli.AzureDevOpsCliShape["createPullRequest"]>[0] | null =
null;
const provider = yield* makeProvider({
createPullRequest: (input) => {
createInput = input;
return Effect.void;
},
});
yield* provider.createChangeRequest({
cwd: "/repo",
baseRefName: "main",
headSelector: "feature/provider",
title: "Provider PR",
bodyFile: "/tmp/body.md",
});
assert.deepStrictEqual(createInput, {
cwd: "/repo",
baseBranch: "main",
headSelector: "feature/provider",
title: "Provider PR",
bodyFile: "/tmp/body.md",
});
}),
);
it.effect("uses Azure CLI repository detection for default branch lookup", () =>
Effect.gen(function* () {
let cwdInput: string | null = null;
const provider = yield* makeProvider({
getDefaultBranch: (input) => {
cwdInput = input.cwd;
return Effect.succeed("main");
},
});
const defaultBranch = yield* provider.getDefaultBranch({ cwd: "/repo" });
assert.strictEqual(defaultBranch, "main");
assert.strictEqual(cwdInput, "/repo");
}),
);
@@ -0,0 +1,144 @@
import { Effect, Layer } from "effect";
import { SourceControlProviderError, type ChangeRequest } from "@t3tools/contracts";
import * as AzureDevOpsCli from "./AzureDevOpsCli.ts";
import * as SourceControlProvider from "./SourceControlProvider.ts";
import * as SourceControlProviderDiscovery from "./SourceControlProviderDiscovery.ts";
function providerError(
operation: string,
cause: AzureDevOpsCli.AzureDevOpsCliError,
): SourceControlProviderError {
return new SourceControlProviderError({
provider: "azure-devops",
operation,
detail: cause.detail,
cause,
});
}
function parseAzureAuth(input: SourceControlProviderDiscovery.SourceControlAuthProbeInput) {
const account = input.stdout.trim().split(/\r?\n/)[0]?.trim();
if (input.exitCode !== 0) {
return SourceControlProviderDiscovery.providerAuth({
status: "unauthenticated",
detail:
SourceControlProviderDiscovery.firstSafeAuthLine(
SourceControlProviderDiscovery.combinedAuthOutput(input),
) ?? "Run `az login` to authenticate Azure CLI.",
});
}
if (account && account.length > 0) {
return SourceControlProviderDiscovery.providerAuth({
status: "authenticated",
account,
host: "dev.azure.com",
});
}
return SourceControlProviderDiscovery.providerAuth({
status: "unknown",
host: "dev.azure.com",
detail: "Azure CLI account status could not be parsed.",
});
}
export const discovery = {
type: "cli",
kind: "azure-devops",
label: "Azure DevOps",
executable: "az",
versionArgs: ["--version"],
authArgs: ["account", "show", "--query", "user.name", "-o", "tsv"],
parseAuth: parseAzureAuth,
installHint:
"Install the Azure command-line tools (`az`), then enable Azure DevOps support with `az extension add --name azure-devops`.",
} satisfies SourceControlProviderDiscovery.SourceControlCliDiscoverySpec;
function toChangeRequest(summary: {
readonly number: number;
readonly title: string;
readonly url: string;
readonly baseRefName: string;
readonly headRefName: string;
readonly state: "open" | "closed" | "merged";
readonly updatedAt: ChangeRequest["updatedAt"];
}): ChangeRequest {
return {
provider: "azure-devops",
number: summary.number,
title: summary.title,
url: summary.url,
baseRefName: summary.baseRefName,
headRefName: summary.headRefName,
state: summary.state,
updatedAt: summary.updatedAt,
isCrossRepository: false,
};
}
export const make = Effect.fn("makeAzureDevOpsSourceControlProvider")(function* () {
const azure = yield* AzureDevOpsCli.AzureDevOpsCli;
return SourceControlProvider.SourceControlProvider.of({
kind: "azure-devops",
listChangeRequests: (input) => {
const source = SourceControlProvider.sourceControlRefFromInput(input);
return azure
.listPullRequests({
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) =>
azure.getPullRequest(input).pipe(
Effect.map(toChangeRequest),
Effect.mapError((error) => providerError("getChangeRequest", error)),
),
createChangeRequest: (input) => {
const source = SourceControlProvider.sourceControlRefFromInput(input);
return azure
.createPullRequest({
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) =>
azure
.getRepositoryCloneUrls(input)
.pipe(Effect.mapError((error) => providerError("getRepositoryCloneUrls", error))),
createRepository: (input) =>
azure
.createRepository(input)
.pipe(Effect.mapError((error) => providerError("createRepository", error))),
getDefaultBranch: (input) =>
azure
.getDefaultBranch({ cwd: input.cwd })
.pipe(Effect.mapError((error) => providerError("getDefaultBranch", error))),
checkoutChangeRequest: (input) =>
azure
.checkoutPullRequest({
cwd: input.cwd,
reference: input.reference,
...(input.context ? { remoteName: input.context.remoteName } : {}),
})
.pipe(Effect.mapError((error) => providerError("checkoutChangeRequest", error))),
});
});
export const layer = Layer.effect(SourceControlProvider.SourceControlProvider, make());
@@ -0,0 +1,513 @@
import { assert, it, vi } from "@effect/vitest";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { ConfigProvider, DateTime, Effect, FileSystem, Layer, Option } from "effect";
import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http";
import * as BitbucketApi from "./BitbucketApi.ts";
import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
import type * as VcsDriver from "../vcs/VcsDriver.ts";
const bitbucketPullRequest = {
id: 42,
title: "Add Bitbucket provider",
state: "OPEN",
updated_on: "2026-01-02T00:00:00.000Z",
links: {
html: {
href: "https://bitbucket.org/pingdotgg/t3code/pull-requests/42",
},
},
source: {
branch: { name: "feature/source-control" },
repository: {
full_name: "octocat/t3code",
workspace: { slug: "octocat" },
},
},
destination: {
branch: { name: "main" },
repository: {
full_name: "pingdotgg/t3code",
workspace: { slug: "pingdotgg" },
},
},
};
const repositoryJson = {
full_name: "pingdotgg/t3code",
links: {
html: { href: "https://bitbucket.org/pingdotgg/t3code" },
clone: [
{ name: "https", href: "https://bitbucket.org/pingdotgg/t3code.git" },
{ name: "ssh", href: "[email protected]:pingdotgg/t3code.git" },
],
},
mainbranch: { name: "main" },
};
function makeLayer(input: {
readonly response: (request: HttpClientRequest.HttpClientRequest) => Response;
readonly git?: Partial<GitVcsDriver.GitVcsDriverShape>;
}) {
const execute = vi.fn((request: HttpClientRequest.HttpClientRequest) =>
Effect.succeed(HttpClientResponse.fromWeb(request, input.response(request))),
);
const gitMock = {
readConfigValue: vi.fn<GitVcsDriver.GitVcsDriverShape["readConfigValue"]>(() =>
Effect.succeed<string | null>("[email protected]:pingdotgg/t3code.git"),
),
resolvePrimaryRemoteName: vi.fn<GitVcsDriver.GitVcsDriverShape["resolvePrimaryRemoteName"]>(
() => Effect.succeed("origin"),
),
ensureRemote: vi.fn<GitVcsDriver.GitVcsDriverShape["ensureRemote"]>(() =>
Effect.succeed("octocat"),
),
fetchRemoteBranch: vi.fn<GitVcsDriver.GitVcsDriverShape["fetchRemoteBranch"]>(
() => Effect.void,
),
fetchRemoteTrackingBranch: vi.fn<GitVcsDriver.GitVcsDriverShape["fetchRemoteTrackingBranch"]>(
() => Effect.void,
),
setBranchUpstream: vi.fn<GitVcsDriver.GitVcsDriverShape["setBranchUpstream"]>(
() => Effect.void,
),
switchRef: vi.fn<GitVcsDriver.GitVcsDriverShape["switchRef"]>((request) =>
Effect.succeed({ refName: request.refName }),
),
listLocalBranchNames: vi.fn<GitVcsDriver.GitVcsDriverShape["listLocalBranchNames"]>(() =>
Effect.succeed([]),
),
};
const git = {
...gitMock,
...input.git,
} satisfies Partial<GitVcsDriver.GitVcsDriverShape>;
const driver = {
listRemotes: () =>
Effect.succeed({
remotes: [
{
name: "origin",
url: "[email protected]:pingdotgg/t3code.git",
pushUrl: Option.none(),
isPrimary: true,
},
],
freshness: {
source: "live-local" as const,
observedAt: DateTime.makeUnsafe("1970-01-01T00:00:00.000Z"),
expiresAt: Option.none(),
},
}),
} satisfies Partial<VcsDriver.VcsDriverShape>;
const layer = BitbucketApi.layer.pipe(
Layer.provide(
Layer.succeed(
HttpClient.HttpClient,
HttpClient.make((request) => execute(request)),
),
),
Layer.provide(
Layer.mock(VcsDriverRegistry.VcsDriverRegistry)({
resolve: () =>
Effect.succeed({
kind: "git",
repository: {
kind: "git",
rootPath: "/repo",
metadataPath: null,
freshness: {
source: "live-local" as const,
observedAt: DateTime.makeUnsafe("1970-01-01T00:00:00.000Z"),
expiresAt: Option.none(),
},
},
driver: driver as unknown as VcsDriver.VcsDriverShape,
}),
}),
),
Layer.provide(Layer.mock(GitVcsDriver.GitVcsDriver)(git)),
Layer.provide(
ConfigProvider.layer(
ConfigProvider.fromEnv({
env: {
T3CODE_BITBUCKET_API_BASE_URL: "https://api.test.local/2.0",
T3CODE_BITBUCKET_EMAIL: "[email protected]",
T3CODE_BITBUCKET_API_TOKEN: "token",
},
}),
),
),
Layer.provideMerge(NodeServices.layer),
);
return { execute, git: gitMock, layer };
}
it.effect("parses pull request responses from the Bitbucket REST API", () => {
const { execute, layer } = makeLayer({
response: () =>
Response.json({
...bitbucketPullRequest,
}),
});
return Effect.gen(function* () {
const bitbucket = yield* BitbucketApi.BitbucketApi;
const result = yield* bitbucket.getPullRequest({
cwd: "/repo",
reference: "#42",
});
assert.deepStrictEqual(result, {
number: 42,
title: "Add Bitbucket provider",
url: "https://bitbucket.org/pingdotgg/t3code/pull-requests/42",
baseRefName: "main",
headRefName: "feature/source-control",
state: "open",
updatedAt: Option.some(DateTime.makeUnsafe("2026-01-02T00:00:00.000Z")),
isCrossRepository: true,
headRepositoryNameWithOwner: "octocat/t3code",
headRepositoryOwnerLogin: "octocat",
});
assert.strictEqual(
execute.mock.calls[0]?.[0].url,
"https://api.test.local/2.0/repositories/pingdotgg/t3code/pullrequests/42",
);
}).pipe(Effect.provide(layer));
});
it.effect("lists pull requests with Bitbucket state and source branch query params", () => {
const { execute, layer } = makeLayer({
response: () =>
Response.json({
values: [
{
...bitbucketPullRequest,
id: 7,
state: "MERGED",
source: {
branch: { name: "feature/merged" },
repository: { full_name: "pingdotgg/t3code" },
},
},
],
}),
});
return Effect.gen(function* () {
const bitbucket = yield* BitbucketApi.BitbucketApi;
const result = yield* bitbucket.listPullRequests({
cwd: "/repo",
headSelector: "origin:feature/merged",
state: "merged",
limit: 10,
});
assert.strictEqual(result[0]?.state, "merged");
const request = execute.mock.calls[0]?.[0];
assert.strictEqual(
request?.url,
"https://api.test.local/2.0/repositories/pingdotgg/t3code/pullrequests",
);
assert.deepStrictEqual(request?.urlParams.params, [
["pagelen", "10"],
["sort", "-updated_on"],
["q", 'source.branch.name = "feature/merged" AND state = "MERGED"'],
["state", "MERGED"],
]);
}).pipe(Effect.provide(layer));
});
it.effect("lists closed pull requests with both closed Bitbucket states", () => {
const { execute, layer } = makeLayer({
response: () =>
Response.json({
values: [],
}),
});
return Effect.gen(function* () {
const bitbucket = yield* BitbucketApi.BitbucketApi;
yield* bitbucket.listPullRequests({
cwd: "/repo",
headSelector: "feature/closed",
state: "closed",
limit: 10,
});
assert.deepStrictEqual(execute.mock.calls[0]?.[0].urlParams.params, [
["pagelen", "10"],
["sort", "-updated_on"],
[
"q",
'source.branch.name = "feature/closed" AND (state = "DECLINED" OR state = "SUPERSEDED")',
],
["state", "DECLINED"],
["state", "SUPERSEDED"],
]);
}).pipe(Effect.provide(layer));
});
it.effect("expands all-state pull request listing instead of relying on Bitbucket defaults", () => {
const { execute, layer } = makeLayer({
response: () =>
Response.json({
values: [],
}),
});
return Effect.gen(function* () {
const bitbucket = yield* BitbucketApi.BitbucketApi;
yield* bitbucket.listPullRequests({
cwd: "/repo",
headSelector: "feature/all",
state: "all",
limit: 10,
});
assert.deepStrictEqual(execute.mock.calls[0]?.[0].urlParams.params, [
["pagelen", "10"],
["sort", "-updated_on"],
[
"q",
'source.branch.name = "feature/all" AND (state = "OPEN" OR state = "MERGED" OR state = "DECLINED" OR state = "SUPERSEDED")',
],
["state", "OPEN"],
["state", "MERGED"],
["state", "DECLINED"],
["state", "SUPERSEDED"],
]);
}).pipe(Effect.provide(layer));
});
it.effect("reads repository clone URLs and default branch", () => {
const { layer } = makeLayer({
response: () => Response.json(repositoryJson),
});
return Effect.gen(function* () {
const bitbucket = yield* BitbucketApi.BitbucketApi;
const cloneUrls = yield* bitbucket.getRepositoryCloneUrls({
cwd: "/repo",
repository: "pingdotgg/t3code",
});
const defaultBranch = yield* bitbucket.getDefaultBranch({ cwd: "/repo" });
assert.deepStrictEqual(cloneUrls, {
nameWithOwner: "pingdotgg/t3code",
url: "https://bitbucket.org/pingdotgg/t3code.git",
sshUrl: "[email protected]:pingdotgg/t3code.git",
});
assert.strictEqual(defaultBranch, "main");
}).pipe(Effect.provide(layer));
});
it.effect("creates repositories through the Bitbucket REST API", () => {
const { execute, layer } = makeLayer({
response: () => Response.json(repositoryJson),
});
return Effect.gen(function* () {
const bitbucket = yield* BitbucketApi.BitbucketApi;
const cloneUrls = yield* bitbucket.createRepository({
cwd: "/repo",
repository: "pingdotgg/t3code",
visibility: "private",
});
assert.deepStrictEqual(cloneUrls, {
nameWithOwner: "pingdotgg/t3code",
url: "https://bitbucket.org/pingdotgg/t3code.git",
sshUrl: "[email protected]:pingdotgg/t3code.git",
});
const request = execute.mock.calls[0]?.[0];
assert.strictEqual(request?.url, "https://api.test.local/2.0/repositories/pingdotgg/t3code");
assert.strictEqual(request?.method, "POST");
assert.ok(request);
const rawBody = (request.body as { readonly body?: Uint8Array }).body;
assert.ok(rawBody);
assert.deepStrictEqual(JSON.parse(new TextDecoder().decode(rawBody)), {
scm: "git",
is_private: true,
});
}).pipe(Effect.provide(layer));
});
it.effect("creates pull requests using the official REST payload shape", () => {
const { execute, layer } = makeLayer({
response: () => Response.json(bitbucketPullRequest),
});
return Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const bodyFile = yield* fileSystem.makeTempFileScoped({ prefix: "bitbucket-pr-body-" });
yield* fileSystem.writeFileString(bodyFile, "PR body");
const bitbucket = yield* BitbucketApi.BitbucketApi;
yield* bitbucket.createPullRequest({
cwd: "/repo",
baseBranch: "main",
headSelector: "owner:feature/provider",
title: "Provider PR",
bodyFile,
});
const request = execute.mock.calls[0]?.[0];
assert.strictEqual(
request?.url,
"https://api.test.local/2.0/repositories/pingdotgg/t3code/pullrequests",
);
assert.strictEqual(request?.method, "POST");
assert.ok(request);
const rawBody = (request.body as { readonly body?: Uint8Array }).body;
assert.ok(rawBody);
assert.deepStrictEqual(JSON.parse(new TextDecoder().decode(rawBody)), {
title: "Provider PR",
description: "PR body",
source: {
branch: { name: "feature/provider" },
repository: { full_name: "owner/t3code" },
},
destination: {
branch: { name: "main" },
},
});
}).pipe(Effect.provide(layer), Effect.scoped);
});
it.effect("reports auth status through the Bitbucket REST /user endpoint", () => {
const { layer } = makeLayer({
response: () => Response.json({ username: "bitbucket-user" }),
});
return Effect.gen(function* () {
const bitbucket = yield* BitbucketApi.BitbucketApi;
const auth = yield* bitbucket.probeAuth;
assert.deepStrictEqual(auth, {
status: "authenticated",
account: Option.some("bitbucket-user"),
host: Option.some("bitbucket.org"),
detail: Option.none(),
});
}).pipe(Effect.provide(layer));
});
it.effect("checks out same-repository pull requests with the existing Bitbucket remote", () => {
const { git, layer } = makeLayer({
response: () =>
Response.json({
...bitbucketPullRequest,
source: {
branch: { name: "feature/source-control" },
repository: {
full_name: "pingdotgg/t3code",
workspace: { slug: "pingdotgg" },
},
},
}),
});
return Effect.gen(function* () {
const bitbucket = yield* BitbucketApi.BitbucketApi;
yield* bitbucket.checkoutPullRequest({
cwd: "/repo",
context: {
provider: {
kind: "bitbucket",
name: "Bitbucket",
baseUrl: "https://bitbucket.org",
},
remoteName: "origin",
remoteUrl: "[email protected]:pingdotgg/t3code.git",
},
reference: "42",
force: true,
});
assert.strictEqual(git.ensureRemote.mock.calls.length, 0);
assert.deepStrictEqual(git.fetchRemoteBranch.mock.calls[0]?.[0], {
cwd: "/repo",
remoteName: "origin",
remoteBranch: "feature/source-control",
localBranch: "feature/source-control",
});
assert.deepStrictEqual(git.setBranchUpstream.mock.calls[0]?.[0], {
cwd: "/repo",
branch: "feature/source-control",
remoteName: "origin",
remoteBranch: "feature/source-control",
});
assert.deepStrictEqual(git.switchRef.mock.calls[0]?.[0], {
cwd: "/repo",
refName: "feature/source-control",
});
}).pipe(Effect.provide(layer));
});
it.effect("checks out fork pull requests through an ensured fork remote", () => {
const { git, layer } = makeLayer({
response: (request) => {
if (request.url.endsWith("/repositories/octocat/t3code")) {
return Response.json({
...repositoryJson,
full_name: "octocat/t3code",
links: {
html: { href: "https://bitbucket.org/octocat/t3code" },
clone: [
{ name: "https", href: "https://bitbucket.org/octocat/t3code.git" },
{ name: "ssh", href: "[email protected]:octocat/t3code.git" },
],
},
});
}
return Response.json({
...bitbucketPullRequest,
source: {
branch: { name: "main" },
repository: {
full_name: "octocat/t3code",
workspace: { slug: "octocat" },
},
},
});
},
});
return Effect.gen(function* () {
const bitbucket = yield* BitbucketApi.BitbucketApi;
yield* bitbucket.checkoutPullRequest({
cwd: "/repo",
reference: "42",
force: true,
});
assert.deepStrictEqual(git.ensureRemote.mock.calls[0]?.[0], {
cwd: "/repo",
preferredName: "octocat",
url: "[email protected]:octocat/t3code.git",
});
assert.deepStrictEqual(git.fetchRemoteBranch.mock.calls[0]?.[0], {
cwd: "/repo",
remoteName: "octocat",
remoteBranch: "main",
localBranch: "t3code/pr-42/main",
});
assert.deepStrictEqual(git.setBranchUpstream.mock.calls[0]?.[0], {
cwd: "/repo",
branch: "t3code/pr-42/main",
remoteName: "octocat",
remoteBranch: "main",
});
assert.deepStrictEqual(git.switchRef.mock.calls[0]?.[0], {
cwd: "/repo",
refName: "t3code/pr-42/main",
});
}).pipe(Effect.provide(layer));
});
@@ -0,0 +1,703 @@
import { Config, Context, Effect, FileSystem, Layer, Option, Schema } from "effect";
import {
TrimmedNonEmptyString,
type SourceControlProviderAuth,
type SourceControlRepositoryCloneUrls,
type SourceControlRepositoryVisibility,
} from "@t3tools/contracts";
import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http";
import { sanitizeBranchFragment } from "@t3tools/shared/git";
import { detectSourceControlProviderFromRemoteUrl } from "@t3tools/shared/sourceControl";
import * as BitbucketPullRequests from "./bitbucketPullRequests.ts";
import * as SourceControlProvider from "./SourceControlProvider.ts";
import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
const DEFAULT_API_BASE_URL = "https://api.bitbucket.org/2.0";
const BitbucketApiEnvConfig = Config.all({
baseUrl: Config.string("T3CODE_BITBUCKET_API_BASE_URL").pipe(
Config.withDefault(DEFAULT_API_BASE_URL),
),
accessToken: Config.string("T3CODE_BITBUCKET_ACCESS_TOKEN").pipe(Config.option),
email: Config.string("T3CODE_BITBUCKET_EMAIL").pipe(Config.option),
apiToken: Config.string("T3CODE_BITBUCKET_API_TOKEN").pipe(Config.option),
});
export class BitbucketApiError extends Schema.TaggedErrorClass<BitbucketApiError>()(
"BitbucketApiError",
{
operation: Schema.String,
detail: Schema.String,
status: Schema.optional(Schema.Number),
cause: Schema.optional(Schema.Defect),
},
) {
override get message(): string {
return `Bitbucket API failed in ${this.operation}: ${this.detail}`;
}
}
const RawBitbucketRepositorySchema = Schema.Struct({
full_name: TrimmedNonEmptyString,
links: Schema.Struct({
html: Schema.optional(
Schema.Struct({
href: TrimmedNonEmptyString,
}),
),
clone: Schema.optional(
Schema.Array(
Schema.Struct({
name: TrimmedNonEmptyString,
href: TrimmedNonEmptyString,
}),
),
),
}),
mainbranch: Schema.optional(
Schema.NullOr(
Schema.Struct({
name: TrimmedNonEmptyString,
}),
),
),
});
const BitbucketUserSchema = Schema.Struct({
username: Schema.optional(TrimmedNonEmptyString),
display_name: Schema.optional(TrimmedNonEmptyString),
account_id: Schema.optional(TrimmedNonEmptyString),
});
export interface BitbucketRepositoryLocator {
readonly workspace: string;
readonly repoSlug: string;
}
export interface BitbucketApiShape {
readonly probeAuth: Effect.Effect<SourceControlProviderAuth, never>;
readonly listPullRequests: (input: {
readonly cwd: string;
readonly context?: SourceControlProvider.SourceControlProviderContext;
readonly headSelector: string;
readonly source?: SourceControlProvider.SourceControlRefSelector;
readonly state: "open" | "closed" | "merged" | "all";
readonly limit?: number;
}) => Effect.Effect<
ReadonlyArray<BitbucketPullRequests.NormalizedBitbucketPullRequestRecord>,
BitbucketApiError
>;
readonly getPullRequest: (input: {
readonly cwd: string;
readonly context?: SourceControlProvider.SourceControlProviderContext;
readonly reference: string;
}) => Effect.Effect<
BitbucketPullRequests.NormalizedBitbucketPullRequestRecord,
BitbucketApiError
>;
readonly getRepositoryCloneUrls: (input: {
readonly cwd: string;
readonly context?: SourceControlProvider.SourceControlProviderContext;
readonly repository: string;
}) => Effect.Effect<SourceControlRepositoryCloneUrls, BitbucketApiError>;
readonly createRepository: (input: {
readonly cwd: string;
readonly repository: string;
readonly visibility: SourceControlRepositoryVisibility;
}) => Effect.Effect<SourceControlRepositoryCloneUrls, BitbucketApiError>;
readonly createPullRequest: (input: {
readonly cwd: string;
readonly context?: SourceControlProvider.SourceControlProviderContext;
readonly baseBranch: string;
readonly headSelector: string;
readonly source?: SourceControlProvider.SourceControlRefSelector;
readonly target?: SourceControlProvider.SourceControlRefSelector;
readonly title: string;
readonly bodyFile: string;
}) => Effect.Effect<void, BitbucketApiError>;
readonly getDefaultBranch: (input: {
readonly cwd: string;
readonly context?: SourceControlProvider.SourceControlProviderContext;
}) => Effect.Effect<string | null, BitbucketApiError>;
readonly checkoutPullRequest: (input: {
readonly cwd: string;
readonly context?: SourceControlProvider.SourceControlProviderContext;
readonly reference: string;
readonly force?: boolean;
}) => Effect.Effect<void, BitbucketApiError>;
}
export class BitbucketApi extends Context.Service<BitbucketApi, BitbucketApiShape>()(
"t3/source-control/BitbucketApi",
) {}
function nonEmpty(value: string | undefined): Option.Option<string> {
const trimmed = value?.trim();
return trimmed === undefined || trimmed.length === 0 ? Option.none() : Option.some(trimmed);
}
function normalizeChangeRequestId(reference: string): string {
const trimmed = reference.trim().replace(/^#/, "");
const urlMatch = /(?:pull-requests|pullrequests|pull-request|pull|pr)\/(\d+)(?:\D.*)?$/i.exec(
trimmed,
);
return urlMatch?.[1] ?? trimmed;
}
function sourceWorkspace(input: {
readonly headSelector: string;
readonly source?: SourceControlProvider.SourceControlRefSelector;
}): string | undefined {
if (input.source?.owner) return input.source.owner;
return SourceControlProvider.parseSourceControlOwnerRef(input.headSelector)?.owner;
}
function toBitbucketStates(state: "open" | "closed" | "merged" | "all"): ReadonlyArray<string> {
switch (state) {
case "open":
return ["OPEN"];
case "closed":
return ["DECLINED", "SUPERSEDED"];
case "merged":
return ["MERGED"];
case "all":
return ["OPEN", "MERGED", "DECLINED", "SUPERSEDED"];
}
}
function bitbucketQueryString(filters: ReadonlyArray<string>): string {
return filters.join(" AND ");
}
function bitbucketStateFilter(states: ReadonlyArray<string>): string {
return states.length === 1
? `state = "${states[0]}"`
: `(${states.map((state) => `state = "${state}"`).join(" OR ")})`;
}
function parseBitbucketRepositorySlug(value: string): BitbucketRepositoryLocator | null {
const normalized = value.trim().replace(/\.git$/u, "");
const parts = normalized.split("/").filter((part) => part.length > 0);
if (parts.length < 2) return null;
const workspace = parts.at(-2);
const repoSlug = parts.at(-1);
return workspace && repoSlug ? { workspace, repoSlug } : null;
}
function requireRepositoryLocator(
operation: string,
repository: string,
): Effect.Effect<BitbucketRepositoryLocator, BitbucketApiError> {
const locator = parseBitbucketRepositorySlug(repository);
return locator
? Effect.succeed(locator)
: Effect.fail(
new BitbucketApiError({
operation,
detail: "Bitbucket repositories must be specified as workspace/repository.",
}),
);
}
function parseBitbucketRemoteUrl(remoteUrl: string): BitbucketRepositoryLocator | null {
const trimmed = remoteUrl.trim();
if (trimmed.startsWith("git@")) {
const pathStart = trimmed.indexOf(":");
return pathStart < 0 ? null : parseBitbucketRepositorySlug(trimmed.slice(pathStart + 1));
}
try {
return parseBitbucketRepositorySlug(new URL(trimmed).pathname);
} catch {
return null;
}
}
function normalizeRepositoryCloneUrls(
raw: Schema.Schema.Type<typeof RawBitbucketRepositorySchema>,
): SourceControlRepositoryCloneUrls {
const httpClone =
raw.links.clone?.find((entry) => entry.name.toLowerCase() === "https")?.href ??
raw.links.html?.href;
const sshClone = raw.links.clone?.find((entry) => entry.name.toLowerCase() === "ssh")?.href;
return {
nameWithOwner: raw.full_name,
url: httpClone ?? raw.links.html?.href ?? raw.full_name,
sshUrl: sshClone ?? httpClone ?? raw.full_name,
};
}
function shouldPreferSshRemote(originRemoteUrl: string | null): boolean {
const trimmed = originRemoteUrl?.trim() ?? "";
return trimmed.startsWith("git@") || trimmed.startsWith("ssh://");
}
function selectCloneUrl(input: {
readonly cloneUrls: SourceControlRepositoryCloneUrls;
readonly originRemoteUrl: string | null;
}): string {
return shouldPreferSshRemote(input.originRemoteUrl)
? input.cloneUrls.sshUrl
: input.cloneUrls.url;
}
function checkoutBranchName(input: {
readonly pullRequestId: number;
readonly headBranch: string;
readonly isCrossRepository: boolean;
}): string {
if (!input.isCrossRepository) {
return input.headBranch;
}
return `t3code/pr-${input.pullRequestId}/${sanitizeBranchFragment(input.headBranch)}`;
}
function repositoryNameWithOwner(
repository: Schema.Schema.Type<
typeof BitbucketPullRequests.BitbucketPullRequestSchema
>["source"]["repository"],
): string | null {
const fullName = repository?.full_name?.trim() ?? "";
return fullName.length > 0 ? fullName : null;
}
function repositoryOwnerName(repositoryName: string): string {
return repositoryName.split("/")[0]?.trim() || "bitbucket";
}
function authFromConfig(
config: Config.Success<typeof BitbucketApiEnvConfig>,
): SourceControlProviderAuth {
if (Option.isSome(config.accessToken)) {
return {
status: "unknown",
account: Option.none(),
host: Option.some("bitbucket.org"),
detail: Option.some("Bitbucket access token is configured."),
};
}
if (Option.isSome(config.email) && Option.isSome(config.apiToken)) {
return {
status: "unknown",
account: config.email,
host: Option.some("bitbucket.org"),
detail: Option.some("Bitbucket API token is configured."),
};
}
return {
status: "unauthenticated",
account: Option.none(),
host: Option.some("bitbucket.org"),
detail: Option.some(
"Set T3CODE_BITBUCKET_EMAIL and T3CODE_BITBUCKET_API_TOKEN, or T3CODE_BITBUCKET_ACCESS_TOKEN.",
),
};
}
function requestError(operation: string, cause: unknown): BitbucketApiError {
return new BitbucketApiError({
operation,
detail: cause instanceof Error ? cause.message : String(cause),
cause,
});
}
function isBitbucketApiError(cause: unknown): cause is BitbucketApiError {
return Schema.is(BitbucketApiError)(cause);
}
function responseError(
operation: string,
response: HttpClientResponse.HttpClientResponse,
): Effect.Effect<never, BitbucketApiError> {
return response.text.pipe(
Effect.catch(() => Effect.succeed("")),
Effect.flatMap((body) =>
Effect.fail(
new BitbucketApiError({
operation,
status: response.status,
detail:
body.trim().length > 0
? `Bitbucket returned HTTP ${response.status}: ${body.trim()}`
: `Bitbucket returned HTTP ${response.status}.`,
}),
),
),
);
}
export const make = Effect.fn("makeBitbucketApi")(function* () {
const config = yield* BitbucketApiEnvConfig;
const httpClient = yield* HttpClient.HttpClient;
const fileSystem = yield* FileSystem.FileSystem;
const git = yield* GitVcsDriver.GitVcsDriver;
const vcsRegistry = yield* VcsDriverRegistry.VcsDriverRegistry;
const apiUrl = (path: string) => `${config.baseUrl.replace(/\/+$/u, "")}${path}`;
const withAuth = (request: HttpClientRequest.HttpClientRequest) => {
if (Option.isSome(config.accessToken)) {
return request.pipe(HttpClientRequest.bearerToken(config.accessToken.value));
}
if (Option.isSome(config.email) && Option.isSome(config.apiToken)) {
return request.pipe(HttpClientRequest.basicAuth(config.email.value, config.apiToken.value));
}
return request;
};
const decodeResponse = <S extends Schema.Top>(
operation: string,
schema: S,
response: HttpClientResponse.HttpClientResponse,
): Effect.Effect<S["Type"], BitbucketApiError, S["DecodingServices"]> =>
HttpClientResponse.matchStatus({
"2xx": (success) =>
HttpClientResponse.schemaBodyJson(schema)(success).pipe(
Effect.mapError(
(cause) =>
new BitbucketApiError({
operation,
detail: "Bitbucket returned invalid JSON for the requested resource.",
cause,
}),
),
),
orElse: (failed) => responseError(operation, failed),
})(response);
const executeJson = <S extends Schema.Top>(
operation: string,
request: HttpClientRequest.HttpClientRequest,
schema: S,
): Effect.Effect<S["Type"], BitbucketApiError, S["DecodingServices"]> =>
httpClient.execute(withAuth(request.pipe(HttpClientRequest.acceptJson))).pipe(
Effect.mapError((cause) => requestError(operation, cause)),
Effect.flatMap((response) => decodeResponse(operation, schema, response)),
);
const resolveRepository = Effect.fn("BitbucketApi.resolveRepository")(function* (input: {
readonly cwd: string;
readonly context?: SourceControlProvider.SourceControlProviderContext;
readonly repository?: string;
}) {
const fromRepository =
input.repository !== undefined ? parseBitbucketRepositorySlug(input.repository) : null;
if (fromRepository) return fromRepository;
const fromContext =
input.context?.provider.kind === "bitbucket"
? parseBitbucketRemoteUrl(input.context.remoteUrl)
: null;
if (fromContext) return fromContext;
const handle = yield* vcsRegistry.resolve({ cwd: input.cwd }).pipe(
Effect.mapError(
(cause) =>
new BitbucketApiError({
operation: "resolveRepository",
detail: `Failed to resolve VCS repository for ${input.cwd}.`,
cause,
}),
),
);
const remotes = yield* handle.driver.listRemotes(input.cwd).pipe(
Effect.mapError(
(cause) =>
new BitbucketApiError({
operation: "resolveRepository",
detail: `Failed to list remotes for ${input.cwd}.`,
cause,
}),
),
);
for (const remote of remotes.remotes) {
if (detectSourceControlProviderFromRemoteUrl(remote.url)?.kind !== "bitbucket") continue;
const parsed = parseBitbucketRemoteUrl(remote.url);
if (parsed) return parsed;
}
return yield* new BitbucketApiError({
operation: "resolveRepository",
detail: `No Bitbucket repository remote was detected for ${input.cwd}.`,
});
});
const getRepository = (input: {
readonly cwd: string;
readonly context?: SourceControlProvider.SourceControlProviderContext;
readonly repository?: string;
}) =>
resolveRepository(input).pipe(
Effect.flatMap((repository) =>
executeJson(
"getRepository",
HttpClientRequest.get(
apiUrl(
`/repositories/${encodeURIComponent(repository.workspace)}/${encodeURIComponent(repository.repoSlug)}`,
),
),
RawBitbucketRepositorySchema,
),
),
);
const getRawPullRequestFromRepository = (
repository: BitbucketRepositoryLocator,
reference: string,
) =>
executeJson(
"getPullRequest",
HttpClientRequest.get(
apiUrl(
`/repositories/${encodeURIComponent(repository.workspace)}/${encodeURIComponent(repository.repoSlug)}/pullrequests/${encodeURIComponent(normalizeChangeRequestId(reference))}`,
),
),
BitbucketPullRequests.BitbucketPullRequestSchema,
);
const getRawPullRequest = (input: {
readonly cwd: string;
readonly context?: SourceControlProvider.SourceControlProviderContext;
readonly reference: string;
}) =>
resolveRepository(input).pipe(
Effect.flatMap((repository) => getRawPullRequestFromRepository(repository, input.reference)),
);
const readConfigValueNullable = (cwd: string, key: string) =>
git.readConfigValue(cwd, key).pipe(Effect.catch(() => Effect.succeed(null)));
const resolveCheckoutRemote = Effect.fn("BitbucketApi.resolveCheckoutRemote")(function* (input: {
readonly cwd: string;
readonly context?: SourceControlProvider.SourceControlProviderContext;
readonly destinationRepository: BitbucketRepositoryLocator;
readonly sourceRepositoryName: string;
readonly isCrossRepository: boolean;
}) {
if (
input.context?.provider.kind === "bitbucket" &&
!input.isCrossRepository &&
parseBitbucketRemoteUrl(input.context.remoteUrl) !== null
) {
return input.context.remoteName;
}
if (!input.isCrossRepository) {
const remoteName = yield* git
.resolvePrimaryRemoteName(input.cwd)
.pipe(Effect.catch(() => Effect.succeed(null)));
if (remoteName) return remoteName;
}
const cloneUrls = yield* getRepository({
cwd: input.cwd,
repository: input.sourceRepositoryName,
...(input.context ? { context: input.context } : {}),
}).pipe(Effect.map(normalizeRepositoryCloneUrls));
const originRemoteUrl = yield* readConfigValueNullable(input.cwd, "remote.origin.url");
return yield* git.ensureRemote({
cwd: input.cwd,
preferredName: input.isCrossRepository
? repositoryOwnerName(input.sourceRepositoryName)
: input.destinationRepository.workspace,
url: selectCloneUrl({ cloneUrls, originRemoteUrl }),
});
});
return BitbucketApi.of({
probeAuth: executeJson(
"probeAuth",
HttpClientRequest.get(apiUrl("/user")),
BitbucketUserSchema,
).pipe(
Effect.map((user) => ({
status: "authenticated" as const,
account: nonEmpty(user.username ?? user.display_name ?? user.account_id),
host: Option.some("bitbucket.org"),
detail: Option.none<string>(),
})),
Effect.catch(() => Effect.succeed(authFromConfig(config))),
),
listPullRequests: (input) =>
resolveRepository(input).pipe(
Effect.flatMap((repository) => {
const states = toBitbucketStates(input.state);
const query: Record<string, string | ReadonlyArray<string>> = {
pagelen: String(Math.max(1, Math.min(input.limit ?? 20, 50))),
sort: "-updated_on",
q: bitbucketQueryString([
`source.branch.name = "${SourceControlProvider.sourceBranch(input).replaceAll('"', '\\"')}"`,
bitbucketStateFilter(states),
]),
state: states,
};
return executeJson(
"listPullRequests",
HttpClientRequest.get(
apiUrl(
`/repositories/${encodeURIComponent(repository.workspace)}/${encodeURIComponent(repository.repoSlug)}/pullrequests`,
),
{ urlParams: query },
),
BitbucketPullRequests.BitbucketPullRequestListSchema,
);
}),
Effect.map((list) =>
list.values.map(BitbucketPullRequests.normalizeBitbucketPullRequestRecord),
),
),
getPullRequest: (input) =>
getRawPullRequest(input).pipe(
Effect.map(BitbucketPullRequests.normalizeBitbucketPullRequestRecord),
),
getRepositoryCloneUrls: (input) =>
getRepository(input).pipe(Effect.map(normalizeRepositoryCloneUrls)),
createRepository: (input) =>
requireRepositoryLocator("createRepository", input.repository).pipe(
Effect.flatMap((repository) =>
executeJson(
"createRepository",
HttpClientRequest.post(
apiUrl(
`/repositories/${encodeURIComponent(repository.workspace)}/${encodeURIComponent(repository.repoSlug)}`,
),
).pipe(
HttpClientRequest.bodyJsonUnsafe({
scm: "git",
is_private: input.visibility === "private",
}),
),
RawBitbucketRepositorySchema,
),
),
Effect.map(normalizeRepositoryCloneUrls),
),
createPullRequest: (input) =>
Effect.gen(function* () {
const repository = yield* resolveRepository(input);
const description = yield* fileSystem.readFileString(input.bodyFile).pipe(
Effect.mapError(
(cause) =>
new BitbucketApiError({
operation: "createPullRequest",
detail: `Failed to read pull request body file ${input.bodyFile}.`,
cause,
}),
),
);
const sourceOwner = sourceWorkspace(input);
const body = {
title: input.title,
description,
source: {
branch: {
name: SourceControlProvider.sourceBranch(input),
},
...(sourceOwner
? {
repository: {
full_name: `${sourceOwner}/${input.source?.repository ?? repository.repoSlug}`,
},
}
: {}),
},
destination: {
branch: {
name: input.target?.refName ?? input.baseBranch,
},
},
};
yield* executeJson(
"createPullRequest",
HttpClientRequest.post(
apiUrl(
`/repositories/${encodeURIComponent(repository.workspace)}/${encodeURIComponent(repository.repoSlug)}/pullrequests`,
),
).pipe(HttpClientRequest.bodyJsonUnsafe(body)),
BitbucketPullRequests.BitbucketPullRequestSchema,
);
}),
getDefaultBranch: (input) =>
getRepository(input).pipe(Effect.map((repository) => repository.mainbranch?.name ?? null)),
// Bitbucket Cloud pull requests are Git-backed and Bitbucket does not provide
// an official checkout CLI. This provider-local path uses GitVcsDriver as a
// narrow escape hatch to materialize Bitbucket PR refs. Do not generalize this
// as the source-control provider model: if we support non-Git-compatible
// hosting providers or native JJ/Sapling checkout flows, move this into a
// VCS-specific change-request checkout capability.
checkoutPullRequest: (input) =>
Effect.gen(function* () {
const destinationRepository = yield* resolveRepository(input);
const pullRequest = yield* getRawPullRequestFromRepository(
destinationRepository,
input.reference,
);
const destinationRepositoryName =
repositoryNameWithOwner(pullRequest.destination.repository) ??
`${destinationRepository.workspace}/${destinationRepository.repoSlug}`;
const sourceRepositoryName =
repositoryNameWithOwner(pullRequest.source.repository) ?? destinationRepositoryName;
const isCrossRepository = sourceRepositoryName !== destinationRepositoryName;
const remoteName = yield* resolveCheckoutRemote({
cwd: input.cwd,
destinationRepository,
sourceRepositoryName,
isCrossRepository,
...(input.context ? { context: input.context } : {}),
});
const remoteBranch = pullRequest.source.branch.name;
const localBranch = checkoutBranchName({
pullRequestId: pullRequest.id,
headBranch: remoteBranch,
isCrossRepository,
});
const localBranchNames = yield* git.listLocalBranchNames(input.cwd);
const localBranchExists = localBranchNames.includes(localBranch);
if (input.force === true || !localBranchExists) {
yield* git.fetchRemoteBranch({
cwd: input.cwd,
remoteName,
remoteBranch,
localBranch,
});
} else {
yield* git.fetchRemoteTrackingBranch({
cwd: input.cwd,
remoteName,
remoteBranch,
});
}
yield* git.setBranchUpstream({
cwd: input.cwd,
branch: localBranch,
remoteName,
remoteBranch,
});
yield* Effect.scoped(git.switchRef({ cwd: input.cwd, refName: localBranch }));
}).pipe(
Effect.mapError((cause) =>
isBitbucketApiError(cause)
? cause
: new BitbucketApiError({
operation: "checkoutPullRequest",
detail: cause instanceof Error ? cause.message : String(cause),
cause,
}),
),
),
});
});
export const layer = Layer.effect(BitbucketApi, make());
@@ -0,0 +1,126 @@
import { assert, it } from "@effect/vitest";
import { Effect, Layer, Option } from "effect";
import * as BitbucketApi from "./BitbucketApi.ts";
import * as BitbucketSourceControlProvider from "./BitbucketSourceControlProvider.ts";
function makeProvider(bitbucket: Partial<BitbucketApi.BitbucketApiShape>) {
return BitbucketSourceControlProvider.make().pipe(
Effect.provide(Layer.mock(BitbucketApi.BitbucketApi)(bitbucket)),
);
}
it.effect("maps Bitbucket PR summaries into provider-neutral change requests", () =>
Effect.gen(function* () {
const provider = yield* makeProvider({
getPullRequest: () =>
Effect.succeed({
number: 42,
title: "Add Bitbucket provider",
url: "https://bitbucket.org/pingdotgg/t3code/pull-requests/42",
baseRefName: "main",
headRefName: "feature/source-control",
state: "open",
updatedAt: Option.none(),
isCrossRepository: true,
headRepositoryNameWithOwner: "fork/t3code",
headRepositoryOwnerLogin: "fork",
}),
});
const changeRequest = yield* provider.getChangeRequest({
cwd: "/repo",
reference: "42",
});
assert.deepStrictEqual(changeRequest, {
provider: "bitbucket",
number: 42,
title: "Add Bitbucket provider",
url: "https://bitbucket.org/pingdotgg/t3code/pull-requests/42",
baseRefName: "main",
headRefName: "feature/source-control",
state: "open",
updatedAt: Option.none(),
isCrossRepository: true,
headRepositoryNameWithOwner: "fork/t3code",
headRepositoryOwnerLogin: "fork",
});
}),
);
it.effect("lists Bitbucket PRs through provider-neutral input names", () =>
Effect.gen(function* () {
let listInput: Parameters<BitbucketApi.BitbucketApiShape["listPullRequests"]>[0] | null = null;
const provider = yield* makeProvider({
listPullRequests: (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 Bitbucket PRs through provider-neutral input names", () =>
Effect.gen(function* () {
let createInput: Parameters<BitbucketApi.BitbucketApiShape["createPullRequest"]>[0] | null =
null;
const provider = yield* makeProvider({
createPullRequest: (input) => {
createInput = input;
return Effect.void;
},
});
yield* provider.createChangeRequest({
cwd: "/repo",
baseRefName: "main",
headSelector: "owner:feature/provider",
title: "Provider PR",
bodyFile: "/tmp/body.md",
});
assert.deepStrictEqual(createInput, {
cwd: "/repo",
baseBranch: "main",
headSelector: "owner:feature/provider",
source: {
owner: "owner",
refName: "feature/provider",
},
title: "Provider PR",
bodyFile: "/tmp/body.md",
});
}),
);
it.effect("uses Bitbucket API repository detection for default branch lookup", () =>
Effect.gen(function* () {
let cwdInput: string | null = null;
const provider = yield* makeProvider({
getDefaultBranch: (input) => {
cwdInput = input.cwd;
return Effect.succeed("main");
},
});
const defaultBranch = yield* provider.getDefaultBranch({ cwd: "/repo" });
assert.strictEqual(defaultBranch, "main");
assert.strictEqual(cwdInput, "/repo");
}),
);
@@ -0,0 +1,126 @@
import { Effect, Layer, Option } from "effect";
import { SourceControlProviderError, type ChangeRequest } from "@t3tools/contracts";
import * as BitbucketApi from "./BitbucketApi.ts";
import * as BitbucketPullRequests from "./bitbucketPullRequests.ts";
import * as SourceControlProvider from "./SourceControlProvider.ts";
import type * as SourceControlProviderDiscovery from "./SourceControlProviderDiscovery.ts";
function providerError(
operation: string,
cause: BitbucketApi.BitbucketApiError,
): SourceControlProviderError {
return new SourceControlProviderError({
provider: "bitbucket",
operation,
detail: cause.detail,
cause,
});
}
function toChangeRequest(
summary: BitbucketPullRequests.NormalizedBitbucketPullRequestRecord,
): ChangeRequest {
return {
provider: "bitbucket",
number: summary.number,
title: summary.title,
url: summary.url,
baseRefName: summary.baseRefName,
headRefName: summary.headRefName,
state: summary.state,
updatedAt: summary.updatedAt ?? Option.none(),
...(summary.isCrossRepository !== undefined
? { isCrossRepository: summary.isCrossRepository }
: {}),
...(summary.headRepositoryNameWithOwner !== undefined
? { headRepositoryNameWithOwner: summary.headRepositoryNameWithOwner }
: {}),
...(summary.headRepositoryOwnerLogin !== undefined
? { headRepositoryOwnerLogin: summary.headRepositoryOwnerLogin }
: {}),
};
}
export const make = Effect.fn("makeBitbucketSourceControlProvider")(function* () {
const bitbucket = yield* BitbucketApi.BitbucketApi;
return SourceControlProvider.SourceControlProvider.of({
kind: "bitbucket",
listChangeRequests: (input) => {
const source = SourceControlProvider.sourceControlRefFromInput(input);
return bitbucket
.listPullRequests({
cwd: input.cwd,
...(input.context ? { context: input.context } : {}),
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) =>
bitbucket.getPullRequest(input).pipe(
Effect.map(toChangeRequest),
Effect.mapError((error) => providerError("getChangeRequest", error)),
),
createChangeRequest: (input) => {
const source = SourceControlProvider.sourceControlRefFromInput(input);
return bitbucket
.createPullRequest({
cwd: input.cwd,
...(input.context ? { context: input.context } : {}),
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) =>
bitbucket
.getRepositoryCloneUrls(input)
.pipe(Effect.mapError((error) => providerError("getRepositoryCloneUrls", error))),
createRepository: (input) =>
bitbucket
.createRepository(input)
.pipe(Effect.mapError((error) => providerError("createRepository", error))),
getDefaultBranch: (input) =>
bitbucket
.getDefaultBranch({
cwd: input.cwd,
...(input.context ? { context: input.context } : {}),
})
.pipe(Effect.mapError((error) => providerError("getDefaultBranch", error))),
checkoutChangeRequest: (input) =>
bitbucket
.checkoutPullRequest({
cwd: input.cwd,
...(input.context ? { context: input.context } : {}),
reference: input.reference,
...(input.force !== undefined ? { force: input.force } : {}),
})
.pipe(Effect.mapError((error) => providerError("checkoutChangeRequest", error))),
});
});
export const layer = Layer.effect(SourceControlProvider.SourceControlProvider, make());
export const makeDiscovery = Effect.fn("makeBitbucketSourceControlProviderDiscovery")(function* () {
const bitbucket = yield* BitbucketApi.BitbucketApi;
return {
type: "api",
kind: "bitbucket",
label: "Bitbucket",
installHint:
"Set T3CODE_BITBUCKET_EMAIL and T3CODE_BITBUCKET_API_TOKEN on the server (use a Bitbucket API token with pull request and repository scopes).",
probeAuth: bitbucket.probeAuth,
} satisfies SourceControlProviderDiscovery.SourceControlApiDiscoverySpec;
});
@@ -1,13 +1,12 @@
import { assert, it } from "@effect/vitest";
import { assert, it, afterEach, describe, expect, vi } from "@effect/vitest";
import { Effect, Layer } from "effect";
import { ChildProcessSpawner } from "effect/unstable/process";
import { VcsProcessExitError, type VcsError } from "@t3tools/contracts";
import { afterEach, describe, expect, vi } from "vitest";
import { VcsProcess, type VcsProcessInput, type VcsProcessOutput } from "../vcs/VcsProcess.ts";
import * as VcsProcess from "../vcs/VcsProcess.ts";
import * as GitHubCli from "./GitHubCli.ts";
const processOutput = (stdout: string): VcsProcessOutput => ({
const processOutput = (stdout: string): VcsProcess.VcsProcessOutput => ({
exitCode: ChildProcessSpawner.ExitCode(0),
stdout,
stderr: "",
@@ -15,11 +14,11 @@ const processOutput = (stdout: string): VcsProcessOutput => ({
stderrTruncated: false,
});
const mockRun = vi.fn<(input: VcsProcessInput) => Effect.Effect<VcsProcessOutput, VcsError>>();
const mockRun = vi.fn<VcsProcess.VcsProcessShape["run"]>();
const layer = GitHubCli.layer.pipe(
Layer.provide(
Layer.mock(VcsProcess)({
Layer.mock(VcsProcess.VcsProcess)({
run: mockRun,
}),
),
+8 -12
View File
@@ -6,12 +6,8 @@ import {
type VcsError,
} from "@t3tools/contracts";
import { VcsProcess, type VcsProcessOutput } from "../vcs/VcsProcess.ts";
import {
decodeGitHubPullRequestJson,
decodeGitHubPullRequestListJson,
formatGitHubJsonDecodeError,
} from "./gitHubPullRequests.ts";
import * as VcsProcess from "../vcs/VcsProcess.ts";
import * as GitHubPullRequests from "./gitHubPullRequests.ts";
const DEFAULT_TIMEOUT_MS = 30_000;
@@ -48,7 +44,7 @@ export interface GitHubCliShape {
readonly cwd: string;
readonly args: ReadonlyArray<string>;
readonly timeoutMs?: number;
}) => Effect.Effect<VcsProcessOutput, GitHubCliError>;
}) => Effect.Effect<VcsProcess.VcsProcessOutput, GitHubCliError>;
readonly listOpenPullRequests: (input: {
readonly cwd: string;
@@ -226,7 +222,7 @@ function decodeGitHubJson<S extends Schema.Top>(
}
export const make = Effect.fn("makeGitHubCli")(function* () {
const process = yield* VcsProcess;
const process = yield* VcsProcess.VcsProcess;
const execute: GitHubCliShape["execute"] = (input) =>
process
@@ -261,13 +257,13 @@ export const make = Effect.fn("makeGitHubCli")(function* () {
Effect.flatMap((raw) =>
raw.length === 0
? Effect.succeed([])
: Effect.sync(() => decodeGitHubPullRequestListJson(raw)).pipe(
: Effect.sync(() => GitHubPullRequests.decodeGitHubPullRequestListJson(raw)).pipe(
Effect.flatMap((decoded) => {
if (!Result.isSuccess(decoded)) {
return Effect.fail(
new GitHubCliError({
operation: "listOpenPullRequests",
detail: `GitHub CLI returned invalid PR list JSON: ${formatGitHubJsonDecodeError(decoded.failure)}`,
detail: `GitHub CLI returned invalid PR list JSON: ${GitHubPullRequests.formatGitHubJsonDecodeError(decoded.failure)}`,
cause: decoded.failure,
}),
);
@@ -293,13 +289,13 @@ export const make = Effect.fn("makeGitHubCli")(function* () {
}).pipe(
Effect.map((result) => result.stdout.trim()),
Effect.flatMap((raw) =>
Effect.sync(() => decodeGitHubPullRequestJson(raw)).pipe(
Effect.sync(() => GitHubPullRequests.decodeGitHubPullRequestJson(raw)).pipe(
Effect.flatMap((decoded) => {
if (!Result.isSuccess(decoded)) {
return Effect.fail(
new GitHubCliError({
operation: "getPullRequest",
detail: `GitHub CLI returned invalid pull request JSON: ${formatGitHubJsonDecodeError(decoded.failure)}`,
detail: `GitHub CLI returned invalid pull request JSON: ${GitHubPullRequests.formatGitHubJsonDecodeError(decoded.failure)}`,
cause: decoded.failure,
}),
);
@@ -2,11 +2,11 @@ import { assert, it } from "@effect/vitest";
import { DateTime, Effect, Layer, Option } from "effect";
import { ChildProcessSpawner } from "effect/unstable/process";
import { GitHubCli, type GitHubCliShape } from "./GitHubCli.ts";
import type { VcsProcessOutput } from "../vcs/VcsProcess.ts";
import * as VcsProcess from "../vcs/VcsProcess.ts";
import * as GitHubCli from "./GitHubCli.ts";
import * as GitHubSourceControlProvider from "./GitHubSourceControlProvider.ts";
const processResult = (stdout: string): VcsProcessOutput => ({
const processResult = (stdout: string): VcsProcess.VcsProcessOutput => ({
exitCode: ChildProcessSpawner.ExitCode(0),
stdout,
stderr: "",
@@ -14,8 +14,10 @@ const processResult = (stdout: string): VcsProcessOutput => ({
stderrTruncated: false,
});
function makeProvider(github: Partial<GitHubCliShape>) {
return GitHubSourceControlProvider.make().pipe(Effect.provide(Layer.mock(GitHubCli)(github)));
function makeProvider(github: Partial<GitHubCli.GitHubCliShape>) {
return GitHubSourceControlProvider.make().pipe(
Effect.provide(Layer.mock(GitHubCli.GitHubCli)(github)),
);
}
it.effect("maps GitHub PR summaries into provider-neutral change requests", () =>
@@ -127,7 +129,7 @@ it.effect("treats empty non-open change request listing output as no results", (
it.effect("creates GitHub PRs through provider-neutral input names", () =>
Effect.gen(function* () {
let createInput: Parameters<GitHubCliShape["createPullRequest"]>[0] | null = null;
let createInput: Parameters<GitHubCli.GitHubCliShape["createPullRequest"]>[0] | null = null;
const provider = yield* makeProvider({
createPullRequest: (input) => {
createInput = input;
@@ -5,11 +5,15 @@ import {
type ChangeRequestState,
} from "@t3tools/contracts";
import { GitHubCli, type GitHubCliError, type GitHubPullRequestSummary } from "./GitHubCli.ts";
import { decodeGitHubPullRequestListJson } from "./gitHubPullRequests.ts";
import { SourceControlProvider, type SourceControlProviderShape } from "./SourceControlProvider.ts";
import * as GitHubCli from "./GitHubCli.ts";
import * as GitHubPullRequests from "./gitHubPullRequests.ts";
import * as SourceControlProvider from "./SourceControlProvider.ts";
import * as SourceControlProviderDiscovery from "./SourceControlProviderDiscovery.ts";
function providerError(operation: string, cause: GitHubCliError): SourceControlProviderError {
function providerError(
operation: string,
cause: GitHubCli.GitHubCliError,
): SourceControlProviderError {
return new SourceControlProviderError({
provider: "github",
operation,
@@ -18,7 +22,7 @@ function providerError(operation: string, cause: GitHubCliError): SourceControlP
});
}
function toChangeRequest(summary: GitHubPullRequestSummary): ChangeRequest {
function toChangeRequest(summary: GitHubCli.GitHubPullRequestSummary): ChangeRequest {
return {
provider: "github",
number: summary.number,
@@ -40,75 +44,119 @@ function toChangeRequest(summary: GitHubPullRequestSummary): ChangeRequest {
};
}
export const make = Effect.fn("makeGitHubSourceControlProvider")(function* () {
const github = yield* GitHubCli;
function parseGitHubAuth(input: SourceControlProviderDiscovery.SourceControlAuthProbeInput) {
const output = SourceControlProviderDiscovery.combinedAuthOutput(input);
const account = SourceControlProviderDiscovery.matchFirst(output, [
/Logged in to .* account\s+([^\s(]+)/iu,
/Logged in to .* as\s+([^\s(]+)/iu,
]);
const host = SourceControlProviderDiscovery.parseCliHost(output);
const listChangeRequests: SourceControlProviderShape["listChangeRequests"] = (input) => {
if (input.state === "open") {
if (input.exitCode !== 0) {
return SourceControlProviderDiscovery.providerAuth({
status: "unauthenticated",
host,
detail:
SourceControlProviderDiscovery.firstSafeAuthLine(output) ??
"Run `gh auth login` to authenticate GitHub CLI.",
});
}
if (account) {
return SourceControlProviderDiscovery.providerAuth({ status: "authenticated", account, host });
}
return SourceControlProviderDiscovery.providerAuth({
status: "unknown",
host,
detail:
SourceControlProviderDiscovery.firstSafeAuthLine(output) ??
"GitHub CLI auth status could not be parsed.",
});
}
export const discovery = {
type: "cli",
kind: "github",
label: "GitHub",
executable: "gh",
versionArgs: ["--version"],
authArgs: ["auth", "status"],
parseAuth: parseGitHubAuth,
installHint:
"Install the GitHub command-line tool (`gh`) via https://cli.github.com/ or your package manager (for example `brew install gh`).",
} satisfies SourceControlProviderDiscovery.SourceControlCliDiscoverySpec;
export const make = Effect.fn("makeGitHubSourceControlProvider")(function* () {
const github = yield* GitHubCli.GitHubCli;
const listChangeRequests: SourceControlProvider.SourceControlProviderShape["listChangeRequests"] =
(input) => {
if (input.state === "open") {
return github
.listOpenPullRequests({
cwd: input.cwd,
headSelector: input.headSelector,
...(input.limit !== undefined ? { limit: input.limit } : {}),
})
.pipe(
Effect.map((items) => items.map(toChangeRequest)),
Effect.mapError((error) => providerError("listChangeRequests", error)),
);
}
const stateArg: ChangeRequestState | "all" = input.state;
return github
.listOpenPullRequests({
.execute({
cwd: input.cwd,
headSelector: input.headSelector,
...(input.limit !== undefined ? { limit: input.limit } : {}),
args: [
"pr",
"list",
"--head",
input.headSelector,
"--state",
stateArg,
"--limit",
String(input.limit ?? 20),
"--json",
"number,title,url,baseRefName,headRefName,state,mergedAt,updatedAt,isCrossRepository,headRepository,headRepositoryOwner",
],
})
.pipe(
Effect.map((items) => items.map(toChangeRequest)),
Effect.mapError((error) => providerError("listChangeRequests", error)),
Effect.flatMap((result) => {
const raw = result.stdout.trim();
if (raw.length === 0) {
return Effect.succeed([]);
}
return Effect.sync(() => GitHubPullRequests.decodeGitHubPullRequestListJson(raw)).pipe(
Effect.flatMap((decoded) =>
Result.isSuccess(decoded)
? Effect.succeed(
decoded.success.map((item) => ({
...toChangeRequest(item),
updatedAt: item.updatedAt,
})),
)
: Effect.fail(
new SourceControlProviderError({
provider: "github",
operation: "listChangeRequests",
detail: "GitHub CLI returned invalid change request JSON.",
cause: decoded.failure,
}),
),
),
);
}),
Effect.mapError((error) =>
Schema.is(SourceControlProviderError)(error)
? error
: providerError("listChangeRequests", error),
),
);
}
};
const stateArg: ChangeRequestState | "all" = input.state;
return github
.execute({
cwd: input.cwd,
args: [
"pr",
"list",
"--head",
input.headSelector,
"--state",
stateArg,
"--limit",
String(input.limit ?? 20),
"--json",
"number,title,url,baseRefName,headRefName,state,mergedAt,updatedAt,isCrossRepository,headRepository,headRepositoryOwner",
],
})
.pipe(
Effect.flatMap((result) => {
const raw = result.stdout.trim();
if (raw.length === 0) {
return Effect.succeed([]);
}
return Effect.sync(() => decodeGitHubPullRequestListJson(raw)).pipe(
Effect.flatMap((decoded) =>
Result.isSuccess(decoded)
? Effect.succeed(
decoded.success.map((item) => ({
...toChangeRequest(item),
updatedAt: item.updatedAt,
})),
)
: Effect.fail(
new SourceControlProviderError({
provider: "github",
operation: "listChangeRequests",
detail: "GitHub CLI returned invalid change request JSON.",
cause: decoded.failure,
}),
),
),
);
}),
Effect.mapError((error) =>
Schema.is(SourceControlProviderError)(error)
? error
: providerError("listChangeRequests", error),
),
);
};
return SourceControlProvider.of({
return SourceControlProvider.SourceControlProvider.of({
kind: "github",
listChangeRequests,
getChangeRequest: (input) =>
@@ -145,4 +193,4 @@ export const make = Effect.fn("makeGitHubSourceControlProvider")(function* () {
});
});
export const layer = Layer.effect(SourceControlProvider, make());
export const layer = Layer.effect(SourceControlProvider.SourceControlProvider, make());
@@ -1,25 +1,24 @@
import { assert, it } from "@effect/vitest";
import { assert, it, afterEach, expect, vi } 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 VcsProcess from "../vcs/VcsProcess.ts";
import * as GitLabCli from "./GitLabCli.ts";
const mockedRun = vi.fn<VcsProcessShape["run"]>();
const mockedRun = vi.fn<VcsProcess.VcsProcessShape["run"]>();
const layer = it.layer(
GitLabCli.layer.pipe(
Layer.provide(
Layer.mock(VcsProcess)({
Layer.mock(VcsProcess.VcsProcess)({
run: mockedRun,
}),
),
),
);
function processOutput(stdout: string): VcsProcessOutput {
function processOutput(stdout: string): VcsProcess.VcsProcessOutput {
return {
exitCode: ChildProcessSpawner.ExitCode(0),
stdout,
+16 -18
View File
@@ -2,13 +2,9 @@ import { Context, Effect, Layer, Option, Result, Schema, SchemaIssue, type DateT
import { TrimmedNonEmptyString, type SourceControlRepositoryVisibility } from "@t3tools/contracts";
import {
decodeGitLabMergeRequestJson,
decodeGitLabMergeRequestListJson,
formatGitLabJsonDecodeError,
} from "./gitLabMergeRequests.ts";
import { VcsProcess, type VcsProcessOutput } from "../vcs/VcsProcess.ts";
import type { SourceControlRefSelector } from "./SourceControlProvider.ts";
import * as VcsProcess from "../vcs/VcsProcess.ts";
import * as GitLabMergeRequests from "./gitLabMergeRequests.ts";
import type * as SourceControlProvider from "./SourceControlProvider.ts";
const DEFAULT_TIMEOUT_MS = 30_000;
@@ -46,12 +42,12 @@ export interface GitLabCliShape {
readonly cwd: string;
readonly args: ReadonlyArray<string>;
readonly timeoutMs?: number;
}) => Effect.Effect<VcsProcessOutput, GitLabCliError>;
}) => Effect.Effect<VcsProcess.VcsProcessOutput, GitLabCliError>;
readonly listMergeRequests: (input: {
readonly cwd: string;
readonly headSelector: string;
readonly source?: SourceControlRefSelector;
readonly source?: SourceControlProvider.SourceControlRefSelector;
readonly state: "open" | "closed" | "merged" | "all";
readonly limit?: number;
}) => Effect.Effect<ReadonlyArray<GitLabMergeRequestSummary>, GitLabCliError>;
@@ -76,8 +72,8 @@ export interface GitLabCliShape {
readonly cwd: string;
readonly baseBranch: string;
readonly headSelector: string;
readonly source?: SourceControlRefSelector;
readonly target?: SourceControlRefSelector;
readonly source?: SourceControlProvider.SourceControlRefSelector;
readonly target?: SourceControlProvider.SourceControlRefSelector;
readonly title: string;
readonly bodyFile: string;
}) => Effect.Effect<void, GitLabCliError>;
@@ -220,12 +216,14 @@ function normalizeHeadSelector(headSelector: string): string {
function sourceRefName(input: {
readonly headSelector: string;
readonly source?: SourceControlRefSelector;
readonly source?: SourceControlProvider.SourceControlRefSelector;
}): string {
return input.source?.refName ?? normalizeHeadSelector(input.headSelector);
}
function sourceProjectIdentifier(source: SourceControlRefSelector | undefined): string | null {
function sourceProjectIdentifier(
source: SourceControlProvider.SourceControlRefSelector | undefined,
): string | null {
return source?.repository ?? source?.owner ?? null;
}
@@ -252,7 +250,7 @@ function parseRepositoryPath(repository: string): {
}
export const make = Effect.fn("makeGitLabCli")(function* () {
const process = yield* VcsProcess;
const process = yield* VcsProcess.VcsProcess;
const execute: GitLabCliShape["execute"] = (input) =>
process
@@ -286,13 +284,13 @@ export const make = Effect.fn("makeGitLabCli")(function* () {
Effect.flatMap((raw) =>
raw.length === 0
? Effect.succeed([])
: Effect.sync(() => decodeGitLabMergeRequestListJson(raw)).pipe(
: Effect.sync(() => GitLabMergeRequests.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)}`,
detail: `GitLab CLI returned invalid MR list JSON: ${GitLabMergeRequests.formatGitLabJsonDecodeError(decoded.failure)}`,
cause: decoded.failure,
}),
);
@@ -310,13 +308,13 @@ export const make = Effect.fn("makeGitLabCli")(function* () {
}).pipe(
Effect.map((result) => result.stdout.trim()),
Effect.flatMap((raw) =>
Effect.sync(() => decodeGitLabMergeRequestJson(raw)).pipe(
Effect.sync(() => GitLabMergeRequests.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)}`,
detail: `GitLab CLI returned invalid merge request JSON: ${GitLabMergeRequests.formatGitLabJsonDecodeError(decoded.failure)}`,
cause: decoded.failure,
}),
);
@@ -1,11 +1,13 @@
import { assert, it } from "@effect/vitest";
import { Effect, Layer, Option } from "effect";
import { GitLabCli, type GitLabCliShape } from "./GitLabCli.ts";
import * as GitLabCli from "./GitLabCli.ts";
import * as GitLabSourceControlProvider from "./GitLabSourceControlProvider.ts";
function makeProvider(gitlab: Partial<GitLabCliShape>) {
return GitLabSourceControlProvider.make().pipe(Effect.provide(Layer.mock(GitLabCli)(gitlab)));
function makeProvider(gitlab: Partial<GitLabCli.GitLabCliShape>) {
return GitLabSourceControlProvider.make().pipe(
Effect.provide(Layer.mock(GitLabCli.GitLabCli)(gitlab)),
);
}
it.effect("maps GitLab MR summaries into provider-neutral change requests", () =>
@@ -48,7 +50,7 @@ it.effect("maps GitLab MR summaries into provider-neutral change requests", () =
it.effect("lists GitLab MRs through provider-neutral input names", () =>
Effect.gen(function* () {
let listInput: Parameters<GitLabCliShape["listMergeRequests"]>[0] | null = null;
let listInput: Parameters<GitLabCli.GitLabCliShape["listMergeRequests"]>[0] | null = null;
const provider = yield* makeProvider({
listMergeRequests: (input) => {
listInput = input;
@@ -74,7 +76,7 @@ it.effect("lists GitLab MRs through provider-neutral input names", () =>
it.effect("creates GitLab MRs through provider-neutral input names", () =>
Effect.gen(function* () {
let createInput: Parameters<GitLabCliShape["createMergeRequest"]>[0] | null = null;
let createInput: Parameters<GitLabCli.GitLabCliShape["createMergeRequest"]>[0] | null = null;
const provider = yield* makeProvider({
createMergeRequest: (input) => {
createInput = input;
@@ -1,10 +1,14 @@
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";
import * as GitLabCli from "./GitLabCli.ts";
import * as SourceControlProvider from "./SourceControlProvider.ts";
import * as SourceControlProviderDiscovery from "./SourceControlProviderDiscovery.ts";
function providerError(operation: string, cause: GitLabCliError): SourceControlProviderError {
function providerError(
operation: string,
cause: GitLabCli.GitLabCliError,
): SourceControlProviderError {
return new SourceControlProviderError({
provider: "gitlab",
operation,
@@ -13,7 +17,7 @@ function providerError(operation: string, cause: GitLabCliError): SourceControlP
});
}
function toChangeRequest(summary: GitLabMergeRequestSummary): ChangeRequest {
function toChangeRequest(summary: GitLabCli.GitLabMergeRequestSummary): ChangeRequest {
return {
provider: "gitlab",
number: summary.number,
@@ -35,27 +39,57 @@ function toChangeRequest(summary: GitLabMergeRequestSummary): ChangeRequest {
};
}
function sourceFromInput(input: {
readonly headSelector: string;
readonly source?: SourceControlRefSelector;
}): SourceControlRefSelector | undefined {
if (input.source) {
return input.source;
function parseGitLabAuth(input: SourceControlProviderDiscovery.SourceControlAuthProbeInput) {
const output = SourceControlProviderDiscovery.combinedAuthOutput(input);
const account = SourceControlProviderDiscovery.matchFirst(output, [
/Logged in to .* as\s+([^\s(]+)/iu,
/Logged in to .* account\s+([^\s(]+)/iu,
/account:\s*([^\s(]+)/iu,
]);
const host = SourceControlProviderDiscovery.parseCliHost(output);
if (input.exitCode !== 0) {
return SourceControlProviderDiscovery.providerAuth({
status: "unauthenticated",
host,
detail:
SourceControlProviderDiscovery.firstSafeAuthLine(output) ??
"Run `glab auth login` to authenticate GitLab CLI.",
});
}
const match = /^([^:/\s]+):(.+)$/u.exec(input.headSelector.trim());
const owner = match?.[1]?.trim();
const refName = match?.[2]?.trim();
return owner && refName ? { owner, refName } : undefined;
if (account) {
return SourceControlProviderDiscovery.providerAuth({ status: "authenticated", account, host });
}
return SourceControlProviderDiscovery.providerAuth({
status: "unknown",
host,
detail:
SourceControlProviderDiscovery.firstSafeAuthLine(output) ??
"GitLab CLI auth status could not be parsed.",
});
}
export const make = Effect.fn("makeGitLabSourceControlProvider")(function* () {
const gitlab = yield* GitLabCli;
export const discovery = {
type: "cli",
kind: "gitlab",
label: "GitLab",
executable: "glab",
versionArgs: ["--version"],
authArgs: ["auth", "status"],
parseAuth: parseGitLabAuth,
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 SourceControlProviderDiscovery.SourceControlCliDiscoverySpec;
return SourceControlProvider.of({
export const make = Effect.fn("makeGitLabSourceControlProvider")(function* () {
const gitlab = yield* GitLabCli.GitLabCli;
return SourceControlProvider.SourceControlProvider.of({
kind: "gitlab",
listChangeRequests: (input) => {
const source = sourceFromInput(input);
const source = SourceControlProvider.sourceControlRefFromInput(input);
return gitlab
.listMergeRequests({
cwd: input.cwd,
@@ -75,7 +109,7 @@ export const make = Effect.fn("makeGitLabSourceControlProvider")(function* () {
Effect.mapError((error) => providerError("getChangeRequest", error)),
),
createChangeRequest: (input) => {
const source = sourceFromInput(input);
const source = SourceControlProvider.sourceControlRefFromInput(input);
return gitlab
.createMergeRequest({
cwd: input.cwd,
@@ -107,4 +141,4 @@ export const make = Effect.fn("makeGitLabSourceControlProvider")(function* () {
});
});
export const layer = Layer.effect(SourceControlProvider, make());
export const layer = Layer.effect(SourceControlProvider.SourceControlProvider, make());
@@ -5,8 +5,34 @@ import { ChildProcessSpawner } from "effect/unstable/process";
import { VcsProcessSpawnError } from "@t3tools/contracts";
import { ServerConfig } from "../config.ts";
import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
import * as VcsProcess from "../vcs/VcsProcess.ts";
import { SourceControlDiscovery, layer } from "./SourceControlDiscovery.ts";
import * as AzureDevOpsCli from "./AzureDevOpsCli.ts";
import * as BitbucketApi from "./BitbucketApi.ts";
import * as GitHubCli from "./GitHubCli.ts";
import * as GitLabCli from "./GitLabCli.ts";
import * as SourceControlDiscovery from "./SourceControlDiscovery.ts";
import * as SourceControlProviderRegistry from "./SourceControlProviderRegistry.ts";
const sourceControlProviderRegistryTestLayer = (input: {
readonly bitbucket: Partial<BitbucketApi.BitbucketApiShape>;
readonly process: Partial<VcsProcess.VcsProcessShape>;
}) =>
SourceControlProviderRegistry.layer.pipe(
Layer.provide(
Layer.mergeAll(
ServerConfig.layerTest(process.cwd(), { prefix: "t3-source-control-registry-test-" }).pipe(
Layer.provide(NodeServices.layer),
),
Layer.mock(AzureDevOpsCli.AzureDevOpsCli)({}),
Layer.mock(BitbucketApi.BitbucketApi)(input.bitbucket),
Layer.mock(GitHubCli.GitHubCli)({}),
Layer.mock(GitLabCli.GitLabCli)({}),
Layer.mock(VcsDriverRegistry.VcsDriverRegistry)({}),
Layer.mock(VcsProcess.VcsProcess)(input.process),
),
),
);
const processOutput = (
stdout: string,
@@ -22,39 +48,53 @@ const processOutput = (
stderrTruncated: false,
});
it.effect("reports implemented tools separately from locally available CLIs", () => {
const testLayer = layer.pipe(
Layer.provide(
ServerConfig.layerTest(process.cwd(), { prefix: "t3-source-control-discovery-" }),
),
Layer.provide(
Layer.mock(VcsProcess.VcsProcess)({
run: (input) => {
if (input.command === "git") {
return Effect.succeed(processOutput("git version 2.51.0\n"));
}
if (input.command === "gh" && input.args[0] === "--version") {
return Effect.succeed(processOutput("gh version 2.83.0\n"));
}
if (input.command === "gh" && input.args.join(" ") === "auth status") {
return Effect.succeed(
processOutput(`github.com
it.effect("reports implemented tools separately from locally available executables", () => {
const processMock = {
run: (input: VcsProcess.VcsProcessInput) => {
if (input.command === "git") {
return Effect.succeed(processOutput("git version 2.51.0\n"));
}
if (input.command === "gh" && input.args[0] === "--version") {
return Effect.succeed(processOutput("gh version 2.83.0\n"));
}
if (input.command === "gh" && input.args.join(" ") === "auth status") {
return Effect.succeed(
processOutput(`github.com
Logged in to github.com account juliusmarminge (keyring)
- Active account: true
- Git operations protocol: ssh
- Token: gho_************************************
- Token scopes: 'admin:public_key', 'gist', 'read:org', 'repo'
`),
);
}
return Effect.fail(
new VcsProcessSpawnError({
operation: input.operation,
command: input.command,
cwd: input.cwd,
cause: new Error(`${input.command} not found`),
}),
);
);
}
return Effect.fail(
new VcsProcessSpawnError({
operation: input.operation,
command: input.command,
cwd: input.cwd,
cause: new Error(`${input.command} not found`),
}),
);
},
} satisfies Partial<VcsProcess.VcsProcessShape>;
const testLayer = SourceControlDiscovery.layer.pipe(
Layer.provide(
ServerConfig.layerTest(process.cwd(), { prefix: "t3-source-control-discovery-" }),
),
Layer.provide(Layer.mock(VcsProcess.VcsProcess)(processMock)),
Layer.provide(
sourceControlProviderRegistryTestLayer({
process: processMock,
bitbucket: {
probeAuth: Effect.succeed({
status: "unauthenticated",
account: Option.none(),
host: Option.some("bitbucket.org"),
detail: Option.some(
"Set T3CODE_BITBUCKET_EMAIL and T3CODE_BITBUCKET_API_TOKEN, or T3CODE_BITBUCKET_ACCESS_TOKEN.",
),
}),
},
}),
),
@@ -62,7 +102,7 @@ Logged in to github.com account juliusmarminge (keyring)
);
return Effect.gen(function* () {
const discovery = yield* SourceControlDiscovery;
const discovery = yield* SourceControlDiscovery.SourceControlDiscovery;
const result = yield* discovery.discover;
assert.deepStrictEqual(
@@ -79,7 +119,6 @@ Logged in to github.com account juliusmarminge (keyring)
assert.deepStrictEqual(
result.sourceControlProviders.map((item) => ({
kind: item.kind,
implemented: item.implemented,
status: item.status,
auth: item.auth.status,
account: item.auth.account,
@@ -87,88 +126,89 @@ Logged in to github.com account juliusmarminge (keyring)
[
{
kind: "github",
implemented: true,
status: "available",
auth: "authenticated",
account: Option.some("juliusmarminge"),
},
{
kind: "gitlab",
implemented: true,
status: "missing",
auth: "unknown",
account: Option.none(),
},
{
kind: "azure-devops",
implemented: false,
status: "missing",
auth: "unknown",
account: Option.none(),
},
{
kind: "bitbucket",
implemented: false,
status: "missing",
auth: "unknown",
status: "available",
auth: "unauthenticated",
account: Option.none(),
},
],
);
const bitbucket = result.sourceControlProviders.find((item) => item.kind === "bitbucket");
assert.ok(bitbucket);
assert.strictEqual("executable" in bitbucket, false);
assert.strictEqual(bitbucket.executable, undefined);
}).pipe(Effect.provide(testLayer));
});
it.effect("probes provider authentication without exposing token details", () => {
const testLayer = layer.pipe(
Layer.provide(
ServerConfig.layerTest(process.cwd(), { prefix: "t3-source-control-auth-discovery-" }),
),
Layer.provide(
Layer.mock(VcsProcess.VcsProcess)({
run: (input) => {
if (input.args[0] === "--version") {
return Effect.succeed(processOutput(`${input.command} version test\n`));
}
if (input.command === "gh" && input.args.join(" ") === "auth status") {
return Effect.succeed(
processOutput(`github.com
const processMock = {
run: (input: VcsProcess.VcsProcessInput) => {
if (input.args[0] === "--version") {
return Effect.succeed(processOutput(`${input.command} version test\n`));
}
if (input.command === "gh" && input.args.join(" ") === "auth status") {
return Effect.succeed(
processOutput(`github.com
Logged in to github.com account octocat (keyring)
- Token: gho_************************************
- Token scopes: 'repo'
`),
);
}
if (input.command === "glab" && input.args.join(" ") === "auth status") {
return Effect.succeed(
processOutput(`gitlab.com
);
}
if (input.command === "glab" && input.args.join(" ") === "auth status") {
return Effect.succeed(
processOutput(`gitlab.com
Logged in to gitlab.com as gitlab-user
`),
);
}
if (
input.command === "az" &&
input.args.join(" ") === "account show --query user.name -o tsv"
) {
return Effect.succeed(processOutput("[email protected]\n"));
}
if (input.command === "bb" && input.args.join(" ") === "auth status") {
return Effect.succeed(
processOutput(`bitbucket.org
Logged in as bitbucket-user
`),
);
}
return Effect.fail(
new VcsProcessSpawnError({
operation: input.operation,
command: input.command,
cwd: input.cwd,
cause: new Error(`${input.command} not found`),
}),
);
);
}
if (
input.command === "az" &&
input.args.join(" ") === "account show --query user.name -o tsv"
) {
return Effect.succeed(processOutput("[email protected]\n"));
}
return Effect.fail(
new VcsProcessSpawnError({
operation: input.operation,
command: input.command,
cwd: input.cwd,
cause: new Error(`${input.command} not found`),
}),
);
},
} satisfies Partial<VcsProcess.VcsProcessShape>;
const testLayer = SourceControlDiscovery.layer.pipe(
Layer.provide(
ServerConfig.layerTest(process.cwd(), { prefix: "t3-source-control-auth-discovery-" }),
),
Layer.provide(Layer.mock(VcsProcess.VcsProcess)(processMock)),
Layer.provide(
sourceControlProviderRegistryTestLayer({
process: processMock,
bitbucket: {
probeAuth: Effect.succeed({
status: "authenticated",
account: Option.some("bitbucket-user"),
host: Option.some("bitbucket.org"),
detail: Option.none(),
}),
},
}),
),
@@ -176,7 +216,7 @@ Logged in as bitbucket-user
);
return Effect.gen(function* () {
const discovery = yield* SourceControlDiscovery;
const discovery = yield* SourceControlDiscovery.SourceControlDiscovery;
const result = yield* discovery.discover;
assert.deepStrictEqual(
@@ -207,9 +247,9 @@ Logged in as bitbucket-user
},
{
kind: "bitbucket",
auth: "unknown",
account: Option.none(),
detail: Option.some("Bitbucket provider support is not available yet."),
auth: "authenticated",
account: Option.some("bitbucket-user"),
detail: Option.none(),
},
],
);
@@ -1,8 +1,5 @@
import {
type SourceControlProviderAuth,
type SourceControlDiscoveryResult,
type SourceControlProviderDiscoveryItem,
type SourceControlProviderKind,
type VcsDiscoveryItem,
type VcsDriverKind,
} from "@t3tools/contracts";
@@ -10,6 +7,8 @@ import { Context, Effect, Layer, Option } from "effect";
import { ServerConfig } from "../config.ts";
import * as VcsProcess from "../vcs/VcsProcess.ts";
import * as SourceControlProviderDiscovery from "./SourceControlProviderDiscovery.ts";
import * as SourceControlProviderRegistry from "./SourceControlProviderRegistry.ts";
interface DiscoveryProbe {
readonly label: string;
@@ -25,18 +24,6 @@ type VcsProbe = DiscoveryProbe & {
readonly versionArgs: ReadonlyArray<string>;
};
type ProviderProbe = DiscoveryProbe & {
readonly kind: SourceControlProviderKind;
readonly authArgs?: ReadonlyArray<string>;
readonly parseAuth?: (input: AuthProbeInput) => SourceControlProviderAuth;
};
interface AuthProbeInput {
readonly stdout: string;
readonly stderr: string;
readonly exitCode: VcsProcess.VcsProcessOutput["exitCode"];
}
interface DiscoveryProbeResult<Kind extends string> {
readonly kind: Kind;
readonly label: string;
@@ -67,203 +54,6 @@ const VCS_PROBES: ReadonlyArray<VcsProbe> = [
},
];
const SOURCE_CONTROL_PROVIDER_PROBES: ReadonlyArray<ProviderProbe> = [
{
kind: "github",
label: "GitHub",
executable: "gh",
versionArgs: ["--version"],
authArgs: ["auth", "status"],
parseAuth: parseGitHubAuth,
implemented: true,
installHint: "Install GitHub CLI with `brew install gh` or from https://cli.github.com/.",
},
{
kind: "gitlab",
label: "GitLab",
executable: "glab",
versionArgs: ["--version"],
authArgs: ["auth", "status"],
parseAuth: parseGitLabAuth,
implemented: true,
installHint:
"Install GitLab CLI with `brew install glab` or from https://gitlab.com/gitlab-org/cli.",
},
{
kind: "azure-devops",
label: "Azure DevOps",
executable: "az",
versionArgs: ["--version"],
authArgs: ["account", "show", "--query", "user.name", "-o", "tsv"],
parseAuth: parseAzureAuth,
implemented: false,
installHint:
"Install Azure CLI with `brew install azure-cli`, then add Azure DevOps support with `az extension add --name azure-devops`.",
},
{
kind: "bitbucket",
label: "Bitbucket",
implemented: false,
installHint: "Bitbucket provider support is not available yet.",
},
];
function firstNonEmptyLine(text: string): Option.Option<string> {
const line = text
.split(/\r?\n/)
.map((entry) => entry.trim())
.find((entry) => entry.length > 0);
return line === undefined ? Option.none() : Option.some(line);
}
function detailFromCause(cause: unknown): Option.Option<string> {
if (cause instanceof Error && cause.message.trim().length > 0) {
return Option.some(cause.message.trim());
}
return Option.none();
}
function authAccount(account: string | undefined): Option.Option<string> {
const trimmed = account?.trim();
return trimmed === undefined || trimmed.length === 0 ? Option.none() : Option.some(trimmed);
}
function authHost(host: string | undefined): Option.Option<string> {
const trimmed = host?.trim();
return trimmed === undefined || trimmed.length === 0 ? Option.none() : Option.some(trimmed);
}
function authDetail(detail: string | undefined): Option.Option<string> {
const trimmed = detail?.trim();
return trimmed === undefined || trimmed.length === 0 ? Option.none() : Option.some(trimmed);
}
function providerAuth(input: {
readonly status: SourceControlProviderAuth["status"];
readonly account?: string | undefined;
readonly host?: string | undefined;
readonly detail?: string | undefined;
}): SourceControlProviderAuth {
return {
status: input.status,
account: authAccount(input.account),
host: authHost(input.host),
detail: authDetail(input.detail),
};
}
function unknownAuth(detail?: string): SourceControlProviderAuth {
return providerAuth({ status: "unknown", detail });
}
function combinedAuthOutput(input: AuthProbeInput): string {
return [input.stdout, input.stderr].filter((entry) => entry.trim().length > 0).join("\n");
}
function sanitizedAuthLines(text: string): ReadonlyArray<string> {
return text
.split(/\r?\n/)
.map((entry) => entry.trim())
.filter((entry) => entry.length > 0)
.filter((entry) => !/^[-\s]*token(?:\s+scopes?)?:/iu.test(entry));
}
function firstSafeAuthLine(text: string): string | undefined {
return sanitizedAuthLines(text)[0];
}
function parseCliHost(text: string): string | undefined {
return sanitizedAuthLines(text)
.map((line) => line.replace(/^[^a-z0-9]+/iu, ""))
.find((line) => /^[a-z0-9][a-z0-9.-]*(?::\d+)?$/iu.test(line));
}
function matchFirst(text: string, patterns: ReadonlyArray<RegExp>): string | undefined {
for (const pattern of patterns) {
const match = pattern.exec(text);
const value = match?.[1]?.trim();
if (value && value.length > 0) return value;
}
return undefined;
}
function parseGitHubAuth(input: AuthProbeInput): SourceControlProviderAuth {
const output = combinedAuthOutput(input);
const account = matchFirst(output, [
/Logged in to .* account\s+([^\s(]+)/iu,
/Logged in to .* as\s+([^\s(]+)/iu,
]);
const host = parseCliHost(output);
if (input.exitCode !== 0) {
return providerAuth({
status: "unauthenticated",
host,
detail: firstSafeAuthLine(output) ?? "Run `gh auth login` to authenticate GitHub CLI.",
});
}
if (account) {
return providerAuth({ status: "authenticated", account, host });
}
return providerAuth({
status: "unknown",
host,
detail: firstSafeAuthLine(output) ?? "GitHub CLI auth status could not be parsed.",
});
}
function parseGitLabAuth(input: AuthProbeInput): SourceControlProviderAuth {
const output = combinedAuthOutput(input);
const account = matchFirst(output, [
/Logged in to .* as\s+([^\s(]+)/iu,
/Logged in to .* account\s+([^\s(]+)/iu,
/account:\s*([^\s(]+)/iu,
]);
const host = parseCliHost(output);
if (input.exitCode !== 0) {
return providerAuth({
status: "unauthenticated",
host,
detail: firstSafeAuthLine(output) ?? "Run `glab auth login` to authenticate GitLab CLI.",
});
}
if (account) {
return providerAuth({ status: "authenticated", account, host });
}
return providerAuth({
status: "unknown",
host,
detail: firstSafeAuthLine(output) ?? "GitLab CLI auth status could not be parsed.",
});
}
function parseAzureAuth(input: AuthProbeInput): SourceControlProviderAuth {
const account = input.stdout.trim().split(/\r?\n/)[0]?.trim();
if (input.exitCode !== 0) {
return providerAuth({
status: "unauthenticated",
detail:
firstSafeAuthLine(combinedAuthOutput(input)) ?? "Run `az login` to authenticate Azure CLI.",
});
}
if (account && account.length > 0) {
return providerAuth({ status: "authenticated", account, host: "dev.azure.com" });
}
return providerAuth({
status: "unknown",
host: "dev.azure.com",
detail: "Azure CLI account status could not be parsed.",
});
}
export interface SourceControlDiscoveryShape {
readonly discover: Effect.Effect<SourceControlDiscoveryResult>;
}
@@ -278,8 +68,10 @@ export const layer = Layer.effect(
Effect.gen(function* () {
const config = yield* ServerConfig;
const process = yield* VcsProcess.VcsProcess;
const sourceControlProviders =
yield* SourceControlProviderRegistry.SourceControlProviderRegistry;
const probe = <Kind extends VcsDriverKind | SourceControlProviderKind>(
const probe = <Kind extends VcsDriverKind>(
input: DiscoveryProbe & { readonly kind: Kind },
): Effect.Effect<DiscoveryProbeResult<Kind>> => {
const executable = input.executable;
@@ -316,8 +108,9 @@ export const layer = Layer.effect(
executable,
implemented: input.implemented,
status: "available" as const,
version: Option.orElse(firstNonEmptyLine(result.stdout), () =>
firstNonEmptyLine(result.stderr),
version: Option.orElse(
SourceControlProviderDiscovery.firstNonEmptyLine(result.stdout),
() => SourceControlProviderDiscovery.firstNonEmptyLine(result.stderr),
),
installHint: input.installHint,
detail: Option.none<string>(),
@@ -332,74 +125,19 @@ export const layer = Layer.effect(
status: "missing" as const,
version: Option.none<string>(),
installHint: input.installHint,
detail: detailFromCause(cause),
detail: SourceControlProviderDiscovery.detailFromCause(cause),
} satisfies DiscoveryProbeResult<Kind>),
),
);
};
const probeProvider = (input: ProviderProbe) =>
probe(input).pipe(
Effect.flatMap((item) => {
const executable = input.executable;
const authArgs = input.authArgs;
const parseAuth = input.parseAuth;
if (!executable || !authArgs || !parseAuth) {
return Effect.succeed({
...item,
auth: unknownAuth(input.installHint),
} satisfies SourceControlProviderDiscoveryItem);
}
if (item.status !== "available") {
return Effect.succeed({
...item,
auth: unknownAuth("CLI is not installed."),
} satisfies SourceControlProviderDiscoveryItem);
}
return process
.run({
operation: "source-control.discovery.auth",
command: executable,
args: authArgs,
cwd: config.cwd,
allowNonZeroExit: true,
timeoutMs: 5_000,
maxOutputBytes: 8_000,
truncateOutputAtMaxBytes: true,
})
.pipe(
Effect.map(
(result) =>
({
...item,
auth: parseAuth(result),
}) satisfies SourceControlProviderDiscoveryItem,
),
Effect.catch((cause) =>
Effect.succeed({
...item,
auth: unknownAuth(Option.getOrUndefined(detailFromCause(cause))),
} satisfies SourceControlProviderDiscoveryItem),
),
);
}),
);
return SourceControlDiscovery.of({
discover: Effect.all({
versionControlSystems: Effect.all(
VCS_PROBES.map((entry) => probe(entry)) as ReadonlyArray<Effect.Effect<VcsDiscoveryItem>>,
{ concurrency: "unbounded" },
),
sourceControlProviders: Effect.all(
SOURCE_CONTROL_PROVIDER_PROBES.map((entry) => probeProvider(entry)) as ReadonlyArray<
Effect.Effect<SourceControlProviderDiscoveryItem>
>,
{ concurrency: "unbounded" },
),
sourceControlProviders: sourceControlProviders.discover,
}),
});
}),
@@ -21,6 +21,33 @@ export interface SourceControlRefSelector {
readonly repository?: string;
}
export function parseSourceControlOwnerRef(
headSelector: string,
): SourceControlRefSelector | undefined {
const match = /^([^:/\s]+):(.+)$/u.exec(headSelector.trim());
const owner = match?.[1]?.trim();
const refName = match?.[2]?.trim();
return owner && refName ? { owner, refName } : undefined;
}
export function normalizeSourceBranch(headSelector: string): string {
return parseSourceControlOwnerRef(headSelector)?.refName ?? headSelector.trim();
}
export function sourceBranch(input: {
readonly headSelector: string;
readonly source?: SourceControlRefSelector;
}): string {
return input.source?.refName ?? normalizeSourceBranch(input.headSelector);
}
export function sourceControlRefFromInput(input: {
readonly headSelector: string;
readonly source?: SourceControlRefSelector;
}): SourceControlRefSelector | undefined {
return input.source ?? parseSourceControlOwnerRef(input.headSelector);
}
export interface SourceControlProviderShape {
readonly kind: SourceControlProviderKind;
readonly listChangeRequests: (input: {
@@ -0,0 +1,237 @@
import type {
SourceControlProviderAuth,
SourceControlProviderDiscoveryItem,
SourceControlProviderKind,
} from "@t3tools/contracts";
import { Effect, Option } from "effect";
import type * as VcsProcess from "../vcs/VcsProcess.ts";
export interface SourceControlAuthProbeInput {
readonly stdout: string;
readonly stderr: string;
readonly exitCode: VcsProcess.VcsProcessOutput["exitCode"];
}
interface SourceControlDiscoverySpecBase {
readonly kind: SourceControlProviderKind;
readonly label: string;
readonly installHint: string;
}
export type SourceControlCliDiscoverySpec = SourceControlDiscoverySpecBase & {
readonly type: "cli";
readonly executable: string;
readonly versionArgs: ReadonlyArray<string>;
readonly authArgs: ReadonlyArray<string>;
readonly parseAuth: (input: SourceControlAuthProbeInput) => SourceControlProviderAuth;
};
export type SourceControlApiDiscoverySpec = SourceControlDiscoverySpecBase & {
readonly type: "api";
readonly probeAuth: Effect.Effect<SourceControlProviderAuth, never>;
};
export type SourceControlProviderDiscoverySpec =
| SourceControlCliDiscoverySpec
| SourceControlApiDiscoverySpec;
interface DiscoveryProbeResult {
readonly kind: SourceControlProviderKind;
readonly label: string;
readonly executable: string;
readonly status: "available" | "missing";
readonly version: Option.Option<string>;
readonly installHint: string;
readonly detail: Option.Option<string>;
}
export function firstNonEmptyLine(text: string): Option.Option<string> {
const line = text
.split(/\r?\n/)
.map((entry) => entry.trim())
.find((entry) => entry.length > 0);
return line === undefined ? Option.none() : Option.some(line);
}
export function detailFromCause(cause: unknown): Option.Option<string> {
if (cause instanceof Error && cause.message.trim().length > 0) {
return Option.some(cause.message.trim());
}
return Option.none();
}
function authAccount(account: string | undefined): Option.Option<string> {
const trimmed = account?.trim();
return trimmed === undefined || trimmed.length === 0 ? Option.none() : Option.some(trimmed);
}
function authHost(host: string | undefined): Option.Option<string> {
const trimmed = host?.trim();
return trimmed === undefined || trimmed.length === 0 ? Option.none() : Option.some(trimmed);
}
function authDetail(detail: string | undefined): Option.Option<string> {
const trimmed = detail?.trim();
return trimmed === undefined || trimmed.length === 0 ? Option.none() : Option.some(trimmed);
}
export function providerAuth(input: {
readonly status: SourceControlProviderAuth["status"];
readonly account?: string | undefined;
readonly host?: string | undefined;
readonly detail?: string | undefined;
}): SourceControlProviderAuth {
return {
status: input.status,
account: authAccount(input.account),
host: authHost(input.host),
detail: authDetail(input.detail),
};
}
export function unknownAuth(detail?: string): SourceControlProviderAuth {
return providerAuth({ status: "unknown", detail });
}
export function combinedAuthOutput(input: SourceControlAuthProbeInput): string {
return [input.stdout, input.stderr].filter((entry) => entry.trim().length > 0).join("\n");
}
function sanitizedAuthLines(text: string): ReadonlyArray<string> {
return text
.split(/\r?\n/)
.map((entry) => entry.trim())
.filter((entry) => entry.length > 0)
.filter((entry) => !/^[-\s]*token(?:\s+scopes?)?:/iu.test(entry));
}
export function firstSafeAuthLine(text: string): string | undefined {
return sanitizedAuthLines(text)[0];
}
export function parseCliHost(text: string): string | undefined {
return sanitizedAuthLines(text)
.map((line) => line.replace(/^[^a-z0-9]+/iu, ""))
.find((line) => /^[a-z0-9][a-z0-9.-]*(?::\d+)?$/iu.test(line));
}
export function matchFirst(text: string, patterns: ReadonlyArray<RegExp>): string | undefined {
for (const pattern of patterns) {
const match = pattern.exec(text);
const value = match?.[1]?.trim();
if (value && value.length > 0) return value;
}
return undefined;
}
function probeCli(input: {
readonly spec: SourceControlCliDiscoverySpec;
readonly process: VcsProcess.VcsProcessShape;
readonly cwd: string;
}): Effect.Effect<DiscoveryProbeResult> {
return input.process
.run({
operation: "source-control.discovery.probe",
command: input.spec.executable,
args: input.spec.versionArgs,
cwd: input.cwd,
timeoutMs: 5_000,
maxOutputBytes: 8_000,
truncateOutputAtMaxBytes: true,
})
.pipe(
Effect.map(
(result) =>
({
kind: input.spec.kind,
label: input.spec.label,
executable: input.spec.executable,
status: "available" as const,
version: Option.orElse(firstNonEmptyLine(result.stdout), () =>
firstNonEmptyLine(result.stderr),
),
installHint: input.spec.installHint,
detail: Option.none<string>(),
}) satisfies DiscoveryProbeResult,
),
Effect.catch((cause) =>
Effect.succeed({
kind: input.spec.kind,
label: input.spec.label,
executable: input.spec.executable,
status: "missing" as const,
version: Option.none<string>(),
installHint: input.spec.installHint,
detail: detailFromCause(cause),
} satisfies DiscoveryProbeResult),
),
);
}
export function probeSourceControlProvider(input: {
readonly spec: SourceControlProviderDiscoverySpec;
readonly process: VcsProcess.VcsProcessShape;
readonly cwd: string;
}): Effect.Effect<SourceControlProviderDiscoveryItem> {
if (input.spec.type === "api") {
return input.spec.probeAuth.pipe(
Effect.map(
(auth) =>
({
kind: input.spec.kind,
label: input.spec.label,
status: "available" as const,
version: Option.none<string>(),
installHint: input.spec.installHint,
detail: Option.none<string>(),
auth,
}) satisfies SourceControlProviderDiscoveryItem,
),
);
}
const spec = input.spec;
return probeCli({
spec,
process: input.process,
cwd: input.cwd,
}).pipe(
Effect.flatMap((item) => {
if (item.status !== "available") {
return Effect.succeed({
...item,
auth: unknownAuth("Hosting integration command was not found on the server PATH."),
} satisfies SourceControlProviderDiscoveryItem);
}
return input.process
.run({
operation: "source-control.discovery.auth",
command: spec.executable,
args: spec.authArgs,
cwd: input.cwd,
allowNonZeroExit: true,
timeoutMs: 5_000,
maxOutputBytes: 8_000,
truncateOutputAtMaxBytes: true,
})
.pipe(
Effect.map(
(result) =>
({
...item,
auth: spec.parseAuth(result),
}) satisfies SourceControlProviderDiscoveryItem,
),
Effect.catch((cause) =>
Effect.succeed({
...item,
auth: unknownAuth(Option.getOrUndefined(detailFromCause(cause))),
} satisfies SourceControlProviderDiscoveryItem),
),
);
}),
);
}
@@ -1,11 +1,16 @@
import { assert, it } from "@effect/vitest";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { DateTime, Effect, Layer, Option } from "effect";
import { GitHubCli } from "./GitHubCli.ts";
import { GitLabCli } from "./GitLabCli.ts";
import { ServerConfig } from "../config.ts";
import type * as VcsDriver from "../vcs/VcsDriver.ts";
import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
import * as VcsProcess from "../vcs/VcsProcess.ts";
import * as AzureDevOpsCli from "./AzureDevOpsCli.ts";
import * as BitbucketApi from "./BitbucketApi.ts";
import * as GitHubCli from "./GitHubCli.ts";
import * as GitLabCli from "./GitLabCli.ts";
import * as SourceControlProviderRegistry from "./SourceControlProviderRegistry.ts";
import { VcsDriverRegistry } from "../vcs/VcsDriverRegistry.ts";
import type { VcsDriverShape } from "../vcs/VcsDriver.ts";
const TEST_EPOCH = DateTime.makeUnsafe("1970-01-01T00:00:00.000Z");
@@ -29,10 +34,10 @@ function makeRegistry(input: {
expiresAt: Option.none(),
},
}),
} satisfies Partial<VcsDriverShape>;
} satisfies Partial<VcsDriver.VcsDriverShape>;
const registryLayer = Layer.mock(VcsDriverRegistry)({
get: () => Effect.succeed(driver as unknown as VcsDriverShape),
const registryLayer = Layer.mock(VcsDriverRegistry.VcsDriverRegistry)({
get: () => Effect.succeed(driver as unknown as VcsDriver.VcsDriverShape),
resolve: () =>
Effect.succeed({
kind: "git",
@@ -46,13 +51,23 @@ function makeRegistry(input: {
expiresAt: Option.none(),
},
},
driver: driver as unknown as VcsDriverShape,
driver: driver as unknown as VcsDriver.VcsDriverShape,
}),
});
return SourceControlProviderRegistry.make().pipe(
Effect.provide(
Layer.mergeAll(registryLayer, Layer.mock(GitHubCli)({}), Layer.mock(GitLabCli)({})),
Layer.mergeAll(
registryLayer,
Layer.mock(AzureDevOpsCli.AzureDevOpsCli)({}),
Layer.mock(BitbucketApi.BitbucketApi)({}),
Layer.mock(GitHubCli.GitHubCli)({}),
Layer.mock(GitLabCli.GitLabCli)({}),
Layer.mock(VcsProcess.VcsProcess)({}),
ServerConfig.layerTest(process.cwd(), { prefix: "t3-source-control-registry-test-" }).pipe(
Layer.provide(NodeServices.layer),
),
),
),
);
}
@@ -93,6 +108,30 @@ it.effect("routes GitLab remotes to the GitLab provider", () =>
}),
);
it.effect("routes Bitbucket remotes to the Bitbucket provider", () =>
Effect.gen(function* () {
const registry = yield* makeRegistry({
remotes: [{ name: "origin", url: "[email protected]:pingdotgg/t3code.git" }],
});
const provider = yield* registry.resolve({ cwd: "/repo" });
assert.strictEqual(provider.kind, "bitbucket");
}),
);
it.effect("routes Azure DevOps remotes to the Azure DevOps provider", () =>
Effect.gen(function* () {
const registry = yield* makeRegistry({
remotes: [{ name: "origin", url: "https://dev.azure.com/acme/project/_git/repo" }],
});
const provider = yield* registry.resolve({ cwd: "/repo" });
assert.strictEqual(provider.kind, "azure-devops");
}),
);
it.effect("falls back to a non-origin remote when origin is not configured", () =>
Effect.gen(function* () {
const registry = yield* makeRegistry({
@@ -1,40 +1,46 @@
import { Cache, Context, Duration, Effect, Exit, Layer } from "effect";
import { SourceControlProviderError } from "@t3tools/contracts";
import {
SourceControlProviderError,
type SourceControlProviderDiscoveryItem,
} from "@t3tools/contracts";
import type { SourceControlProviderKind } from "@t3tools/contracts";
import { detectSourceControlProviderFromRemoteUrl } from "@t3tools/shared/sourceControl";
import {
SourceControlProvider,
type SourceControlProviderContext,
type SourceControlProviderShape,
} from "./SourceControlProvider.ts";
import * as AzureDevOpsSourceControlProvider from "./AzureDevOpsSourceControlProvider.ts";
import * as BitbucketSourceControlProvider from "./BitbucketSourceControlProvider.ts";
import * as GitHubSourceControlProvider from "./GitHubSourceControlProvider.ts";
import * as GitLabSourceControlProvider from "./GitLabSourceControlProvider.ts";
import { VcsDriverRegistry } from "../vcs/VcsDriverRegistry.ts";
import * as SourceControlProvider from "./SourceControlProvider.ts";
import * as SourceControlProviderDiscovery from "./SourceControlProviderDiscovery.ts";
import { ServerConfig } from "../config.ts";
import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
import * as VcsProcess from "../vcs/VcsProcess.ts";
const PROVIDER_DETECTION_CACHE_CAPACITY = 2_048;
const PROVIDER_DETECTION_CACHE_TTL = Duration.seconds(5);
export interface SourceControlProviderRegistration {
readonly kind: SourceControlProviderKind;
readonly provider: SourceControlProviderShape;
readonly provider: SourceControlProvider.SourceControlProviderShape;
readonly discovery: SourceControlProviderDiscovery.SourceControlProviderDiscoverySpec;
}
export interface SourceControlProviderHandle {
readonly provider: SourceControlProviderShape;
readonly context: SourceControlProviderContext | null;
readonly provider: SourceControlProvider.SourceControlProviderShape;
readonly context: SourceControlProvider.SourceControlProviderContext | null;
}
export interface SourceControlProviderRegistryShape {
readonly get: (
kind: SourceControlProviderKind,
) => Effect.Effect<SourceControlProviderShape, SourceControlProviderError>;
) => Effect.Effect<SourceControlProvider.SourceControlProviderShape, SourceControlProviderError>;
readonly resolveHandle: (input: {
readonly cwd: string;
}) => Effect.Effect<SourceControlProviderHandle, SourceControlProviderError>;
readonly resolve: (input: {
readonly cwd: string;
}) => Effect.Effect<SourceControlProviderShape, SourceControlProviderError>;
}) => Effect.Effect<SourceControlProvider.SourceControlProviderShape, SourceControlProviderError>;
readonly discover: Effect.Effect<ReadonlyArray<SourceControlProviderDiscoveryItem>>;
}
export class SourceControlProviderRegistry extends Context.Service<
@@ -42,7 +48,9 @@ export class SourceControlProviderRegistry extends Context.Service<
SourceControlProviderRegistryShape
>()("t3/source-control/SourceControlProviderRegistry") {}
function unsupportedProvider(kind: SourceControlProviderKind): SourceControlProviderShape {
function unsupportedProvider(
kind: SourceControlProviderKind,
): SourceControlProvider.SourceControlProviderShape {
const unsupported = (operation: string) =>
Effect.fail(
new SourceControlProviderError({
@@ -52,7 +60,7 @@ function unsupportedProvider(kind: SourceControlProviderKind): SourceControlProv
}),
);
return SourceControlProvider.of({
return SourceControlProvider.SourceControlProvider.of({
kind,
listChangeRequests: () => unsupported("listChangeRequests"),
getChangeRequest: () => unsupported("getChangeRequest"),
@@ -78,7 +86,7 @@ function selectProviderContext(
readonly name: string;
readonly url: string;
}>,
): SourceControlProviderContext | null {
): SourceControlProvider.SourceControlProviderContext | null {
const candidates = remotes
.map((remote) => {
const provider = detectSourceControlProviderFromRemoteUrl(remote.url);
@@ -90,7 +98,7 @@ function selectProviderContext(
}
: null;
})
.filter((value): value is SourceControlProviderContext => value !== null);
.filter((value): value is SourceControlProvider.SourceControlProviderContext => value !== null);
return (
candidates.find((candidate) => candidate.remoteName === "origin") ??
@@ -100,12 +108,60 @@ function selectProviderContext(
);
}
function bindProviderContext(
provider: SourceControlProvider.SourceControlProviderShape,
context: SourceControlProvider.SourceControlProviderContext | null,
): SourceControlProvider.SourceControlProviderShape {
if (context === null) {
return provider;
}
return SourceControlProvider.SourceControlProvider.of({
kind: provider.kind,
listChangeRequests: (input) =>
provider.listChangeRequests({
...input,
context: input.context ?? context,
}),
getChangeRequest: (input) =>
provider.getChangeRequest({
...input,
context: input.context ?? context,
}),
createChangeRequest: (input) =>
provider.createChangeRequest({
...input,
context: input.context ?? context,
}),
getRepositoryCloneUrls: (input) =>
provider.getRepositoryCloneUrls({
...input,
context: input.context ?? context,
}),
createRepository: (input) => provider.createRepository(input),
getDefaultBranch: (input) =>
provider.getDefaultBranch({
...input,
context: input.context ?? context,
}),
checkoutChangeRequest: (input) =>
provider.checkoutChangeRequest({
...input,
context: input.context ?? context,
}),
});
}
export const makeWithProviders = Effect.fn("makeSourceControlProviderRegistryWithProviders")(
function* (registrations: ReadonlyArray<SourceControlProviderRegistration>) {
const vcsRegistry = yield* VcsDriverRegistry;
const providers = new Map<SourceControlProviderKind, SourceControlProviderShape>(
registrations.map((registration) => [registration.kind, registration.provider]),
);
const config = yield* ServerConfig;
const process = yield* VcsProcess.VcsProcess;
const vcsRegistry = yield* VcsDriverRegistry.VcsDriverRegistry;
const providers = new Map<
SourceControlProviderKind,
SourceControlProvider.SourceControlProviderShape
>(registrations.map((registration) => [registration.kind, registration.provider]));
const discoverySpecs = registrations.map((registration) => registration.discovery);
const get: SourceControlProviderRegistryShape["get"] = (kind) =>
Effect.succeed(providers.get(kind) ?? unsupportedProvider(kind));
@@ -125,7 +181,7 @@ export const makeWithProviders = Effect.fn("makeSourceControlProviderRegistryWit
const providerContextCache = yield* Cache.makeWith<
string,
SourceControlProviderContext | null,
SourceControlProvider.SourceControlProviderContext | null,
SourceControlProviderError
>(detectProviderContext, {
capacity: PROVIDER_DETECTION_CACHE_CAPACITY,
@@ -136,8 +192,9 @@ export const makeWithProviders = Effect.fn("makeSourceControlProviderRegistryWit
Cache.get(providerContextCache, input.cwd).pipe(
Effect.map((context) => {
const kind = context?.provider.kind ?? "unknown";
const provider = providers.get(kind) ?? unsupportedProvider(kind);
return {
provider: providers.get(kind) ?? unsupportedProvider(kind),
provider: bindProviderContext(provider, context),
context,
} satisfies SourceControlProviderHandle;
}),
@@ -147,6 +204,16 @@ export const makeWithProviders = Effect.fn("makeSourceControlProviderRegistryWit
get,
resolveHandle,
resolve: (input) => resolveHandle(input).pipe(Effect.map((handle) => handle.provider)),
discover: Effect.all(
discoverySpecs.map((spec) =>
SourceControlProviderDiscovery.probeSourceControlProvider({
spec,
process,
cwd: config.cwd,
}),
),
{ concurrency: "unbounded" },
),
});
},
);
@@ -154,14 +221,29 @@ export const makeWithProviders = Effect.fn("makeSourceControlProviderRegistryWit
export const make = Effect.fn("makeSourceControlProviderRegistry")(function* () {
const github = yield* GitHubSourceControlProvider.make();
const gitlab = yield* GitLabSourceControlProvider.make();
const bitbucket = yield* BitbucketSourceControlProvider.make();
const bitbucketDiscovery = yield* BitbucketSourceControlProvider.makeDiscovery();
const azureDevOps = yield* AzureDevOpsSourceControlProvider.make();
return yield* makeWithProviders([
{
kind: "github",
provider: github,
discovery: GitHubSourceControlProvider.discovery,
},
{
kind: "gitlab",
provider: gitlab,
discovery: GitLabSourceControlProvider.discovery,
},
{
kind: "azure-devops",
provider: azureDevOps,
discovery: AzureDevOpsSourceControlProvider.discovery,
},
{
kind: "bitbucket",
provider: bitbucket,
discovery: bitbucketDiscovery,
},
]);
});
@@ -6,14 +6,10 @@ import { ChildProcessSpawner } from "effect/unstable/process";
import { GitCommandError, type SourceControlProviderError } from "@t3tools/contracts";
import { ServerConfig } from "../config.ts";
import {
GitVcsDriver,
type ExecuteGitResult,
type GitVcsDriverShape,
} from "../vcs/GitVcsDriver.ts";
import { SourceControlProviderRegistry } from "./SourceControlProviderRegistry.ts";
import type { SourceControlProviderShape } from "./SourceControlProvider.ts";
import { SourceControlRepositoryService, layer } from "./SourceControlRepositoryService.ts";
import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
import type * as SourceControlProvider from "./SourceControlProvider.ts";
import * as SourceControlProviderRegistry from "./SourceControlProviderRegistry.ts";
import * as SourceControlRepositoryService from "./SourceControlRepositoryService.ts";
const CLONE_URLS = {
nameWithOwner: "octocat/t3code",
@@ -22,8 +18,8 @@ const CLONE_URLS = {
};
function makeProvider(
overrides: Partial<SourceControlProviderShape> = {},
): SourceControlProviderShape {
overrides: Partial<SourceControlProvider.SourceControlProviderShape> = {},
): SourceControlProvider.SourceControlProviderShape {
const unsupported = (operation: string) =>
Effect.die(`unexpected provider operation ${operation}`) as Effect.Effect<
never,
@@ -43,7 +39,7 @@ function makeProvider(
};
}
function processOutput(): ExecuteGitResult {
function processOutput(): GitVcsDriver.ExecuteGitResult {
return {
exitCode: ChildProcessSpawner.ExitCode(0),
stdout: "",
@@ -54,17 +50,17 @@ function processOutput(): ExecuteGitResult {
}
function makeLayer(input: {
readonly provider?: SourceControlProviderShape;
readonly git?: Partial<GitVcsDriverShape>;
readonly provider?: SourceControlProvider.SourceControlProviderShape;
readonly git?: Partial<GitVcsDriver.GitVcsDriverShape>;
}) {
return layer.pipe(
return SourceControlRepositoryService.layer.pipe(
Layer.provide(
Layer.mock(SourceControlProviderRegistry)({
Layer.mock(SourceControlProviderRegistry.SourceControlProviderRegistry)({
get: () => Effect.succeed(input.provider ?? makeProvider()),
}),
),
Layer.provide(
Layer.mock(GitVcsDriver)({
Layer.mock(GitVcsDriver.GitVcsDriver)({
execute: () => Effect.succeed(processOutput()),
ensureRemote: () => Effect.succeed("origin"),
pushCurrentBranch: () =>
@@ -93,7 +89,7 @@ it.effect("looks up repositories through the requested provider without search",
});
return Effect.gen(function* () {
const service = yield* SourceControlRepositoryService;
const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
const result = yield* service.lookupRepository({
provider: "github",
repository: "octocat/t3code",
@@ -115,7 +111,7 @@ it.effect("clones a looked-up repository into the requested destination", () =>
const cloneCalls: Array<{ cwd: string; args: ReadonlyArray<string> }> = [];
yield* Effect.gen(function* () {
const service = yield* SourceControlRepositoryService;
const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
const result = yield* service.cloneRepository({
provider: "github",
repository: "octocat/t3code",
@@ -167,7 +163,7 @@ it.effect("publishes by creating the repository, adding a remote, and pushing up
});
return Effect.gen(function* () {
const service = yield* SourceControlRepositoryService;
const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
const result = yield* service.publishRepository({
cwd: "/workspace",
provider: "github",
@@ -222,7 +218,7 @@ it.effect("publishes to the remote name returned by ensureRemote", () => {
const pushCalls: Array<{ cwd: string; remoteName: string | null | undefined }> = [];
return Effect.gen(function* () {
const service = yield* SourceControlRepositoryService;
const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
const result = yield* service.publishRepository({
cwd: "/workspace",
provider: "github",
@@ -258,7 +254,7 @@ it.effect("publishes to the remote name returned by ensureRemote", () => {
it.effect("publish succeeds with status remote_added when the local repo has no commits", () => {
let pushCalls = 0;
return Effect.gen(function* () {
const service = yield* SourceControlRepositoryService;
const service = yield* SourceControlRepositoryService.SourceControlRepositoryService;
const result = yield* service.publishRepository({
cwd: "/workspace",
provider: "github",
@@ -1,4 +1,4 @@
import OS from "node:os";
import * as NodeOS from "node:os";
import { Context, Effect, FileSystem, Layer, Path, Schema } from "effect";
import {
@@ -15,8 +15,8 @@ import {
} from "@t3tools/contracts";
import { ServerConfig } from "../config.ts";
import { GitVcsDriver } from "../vcs/GitVcsDriver.ts";
import { SourceControlProviderRegistry } from "./SourceControlProviderRegistry.ts";
import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
import * as SourceControlProviderRegistry from "./SourceControlProviderRegistry.ts";
export interface SourceControlRepositoryServiceShape {
readonly lookupRepository: (
@@ -102,10 +102,10 @@ function selectRemoteUrl(
function expandHomePath(input: string, path: Path.Path): string {
if (input === "~") {
return OS.homedir();
return NodeOS.homedir();
}
if (input.startsWith("~/") || input.startsWith("~\\")) {
return path.join(OS.homedir(), input.slice(2));
return path.join(NodeOS.homedir(), input.slice(2));
}
return input;
}
@@ -113,9 +113,9 @@ function expandHomePath(input: string, path: Path.Path): string {
export const make = Effect.fn("makeSourceControlRepositoryService")(function* () {
const config = yield* ServerConfig;
const fileSystem = yield* FileSystem.FileSystem;
const git = yield* GitVcsDriver;
const git = yield* GitVcsDriver.GitVcsDriver;
const path = yield* Path.Path;
const providers = yield* SourceControlProviderRegistry;
const providers = yield* SourceControlProviderRegistry.SourceControlProviderRegistry;
const ensureConcreteProvider = (input: {
readonly operation: string;
@@ -0,0 +1,106 @@
import { Cause, DateTime, Exit, Option, Result, Schema } from "effect";
import { PositiveInt, TrimmedNonEmptyString } from "@t3tools/contracts";
import { decodeJsonResult, formatSchemaError } from "@t3tools/shared/schemaJson";
export interface NormalizedAzureDevOpsPullRequestRecord {
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>;
}
const AzureDevOpsPullRequestSchema = Schema.Struct({
pullRequestId: PositiveInt,
title: TrimmedNonEmptyString,
url: Schema.optional(Schema.String),
sourceRefName: TrimmedNonEmptyString,
targetRefName: TrimmedNonEmptyString,
status: Schema.String,
creationDate: Schema.optional(Schema.OptionFromNullOr(Schema.DateTimeUtcFromString)),
closedDate: Schema.optional(Schema.OptionFromNullOr(Schema.DateTimeUtcFromString)),
_links: Schema.optional(
Schema.Struct({
web: Schema.optional(
Schema.Struct({
href: Schema.String,
}),
),
}),
),
});
function trimOptionalString(value: string | null | undefined): string | null {
const trimmed = value?.trim() ?? "";
return trimmed.length > 0 ? trimmed : null;
}
function normalizeRefName(refName: string): string {
return refName.trim().replace(/^refs\/heads\//, "");
}
function normalizeAzureDevOpsPullRequestState(status: string): "open" | "closed" | "merged" {
switch (status.trim().toLowerCase()) {
case "completed":
return "merged";
case "abandoned":
return "closed";
default:
return "open";
}
}
function normalizeAzureDevOpsPullRequestRecord(
raw: Schema.Schema.Type<typeof AzureDevOpsPullRequestSchema>,
): NormalizedAzureDevOpsPullRequestRecord {
return {
number: raw.pullRequestId,
title: raw.title,
url: trimOptionalString(raw._links?.web?.href) ?? trimOptionalString(raw.url) ?? "",
baseRefName: normalizeRefName(raw.targetRefName),
headRefName: normalizeRefName(raw.sourceRefName),
state: normalizeAzureDevOpsPullRequestState(raw.status),
updatedAt: (raw.closedDate ?? Option.none()).pipe(
Option.orElse(() => raw.creationDate ?? Option.none()),
),
};
}
const decodeAzureDevOpsPullRequestList = decodeJsonResult(Schema.Array(Schema.Unknown));
const decodeAzureDevOpsPullRequest = decodeJsonResult(AzureDevOpsPullRequestSchema);
const decodeAzureDevOpsPullRequestEntry = Schema.decodeUnknownExit(AzureDevOpsPullRequestSchema);
export const formatAzureDevOpsJsonDecodeError = formatSchemaError;
export function decodeAzureDevOpsPullRequestListJson(
raw: string,
): Result.Result<
ReadonlyArray<NormalizedAzureDevOpsPullRequestRecord>,
Cause.Cause<Schema.SchemaError>
> {
const result = decodeAzureDevOpsPullRequestList(raw);
if (Result.isSuccess(result)) {
const pullRequests: NormalizedAzureDevOpsPullRequestRecord[] = [];
for (const entry of result.success) {
const decodedEntry = decodeAzureDevOpsPullRequestEntry(entry);
if (Exit.isFailure(decodedEntry)) {
continue;
}
pullRequests.push(normalizeAzureDevOpsPullRequestRecord(decodedEntry.value));
}
return Result.succeed(pullRequests);
}
return Result.fail(result.failure);
}
export function decodeAzureDevOpsPullRequestJson(
raw: string,
): Result.Result<NormalizedAzureDevOpsPullRequestRecord, Cause.Cause<Schema.SchemaError>> {
const result = decodeAzureDevOpsPullRequest(raw);
if (Result.isSuccess(result)) {
return Result.succeed(normalizeAzureDevOpsPullRequestRecord(result.success));
}
return Result.fail(result.failure);
}
@@ -0,0 +1,104 @@
import { DateTime, Option, Schema } from "effect";
import { PositiveInt, TrimmedNonEmptyString } from "@t3tools/contracts";
export interface NormalizedBitbucketPullRequestRecord {
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 const BitbucketRepositoryRefSchema = Schema.Struct({
full_name: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
workspace: Schema.optional(
Schema.NullOr(
Schema.Struct({
slug: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
}),
),
),
});
export const BitbucketPullRequestBranchSchema = Schema.Struct({
repository: Schema.optional(Schema.NullOr(BitbucketRepositoryRefSchema)),
branch: Schema.Struct({
name: TrimmedNonEmptyString,
}),
});
export const BitbucketPullRequestSchema = Schema.Struct({
id: PositiveInt,
title: TrimmedNonEmptyString,
state: Schema.optional(Schema.NullOr(Schema.String)),
updated_on: Schema.optional(Schema.OptionFromNullOr(Schema.DateTimeUtcFromString)),
links: Schema.Struct({
html: Schema.Struct({
href: TrimmedNonEmptyString,
}),
}),
source: BitbucketPullRequestBranchSchema,
destination: BitbucketPullRequestBranchSchema,
});
export const BitbucketPullRequestListSchema = Schema.Struct({
values: Schema.Array(BitbucketPullRequestSchema),
next: Schema.optional(TrimmedNonEmptyString),
});
function trimOptionalString(value: string | null | undefined): string | null {
const trimmed = value?.trim() ?? "";
return trimmed.length > 0 ? trimmed : null;
}
function repositoryOwner(repository: Schema.Schema.Type<typeof BitbucketRepositoryRefSchema>) {
return (
trimOptionalString(repository.workspace?.slug) ??
(repository.full_name?.includes("/") ? (repository.full_name.split("/")[0] ?? null) : null)
);
}
function normalizeBitbucketPullRequestState(state: string | null | undefined) {
switch (state?.trim().toUpperCase()) {
case "MERGED":
return "merged" as const;
case "DECLINED":
case "SUPERSEDED":
return "closed" as const;
case "OPEN":
default:
return "open" as const;
}
}
export function normalizeBitbucketPullRequestRecord(
raw: Schema.Schema.Type<typeof BitbucketPullRequestSchema>,
): NormalizedBitbucketPullRequestRecord {
const headRepositoryNameWithOwner = trimOptionalString(raw.source.repository?.full_name);
const baseRepositoryNameWithOwner = trimOptionalString(raw.destination.repository?.full_name);
const headRepositoryOwnerLogin = raw.source.repository
? repositoryOwner(raw.source.repository)
: null;
const isCrossRepository =
headRepositoryNameWithOwner !== null &&
baseRepositoryNameWithOwner !== null &&
headRepositoryNameWithOwner !== baseRepositoryNameWithOwner;
return {
number: raw.id,
title: raw.title,
url: raw.links.html.href,
baseRefName: raw.destination.branch.name,
headRefName: raw.source.branch.name,
state: normalizeBitbucketPullRequestState(raw.state),
updatedAt: raw.updated_on ?? Option.none(),
...(isCrossRepository ? { isCrossRepository: true } : {}),
...(headRepositoryNameWithOwner ? { headRepositoryNameWithOwner } : {}),
...(headRepositoryOwnerLogin ? { headRepositoryOwnerLogin } : {}),
};
}