Add remote repository publish and discovery support (#2482)

Co-authored-by: codex <[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-03 18:05:46 -07:00
1 parent f7748a0d65
commit d7969264de
33 files changed
+2502 -157

No files matched your search

@@ -211,6 +211,58 @@ describe("GitHubCli.layer", () => {
}).pipe(Effect.provide(layer)),
);
it.effect("creates repositories and parses clone URLs from create output", () =>
Effect.gen(function* () {
mockRun.mockReturnValueOnce(
Effect.succeed(
processOutput(
"✓ Created repository octocat/codething-mvp on github.com\nhttps://github.com/octocat/codething-mvp\n",
),
),
);
const gh = yield* GitHubCli.GitHubCli;
const result = yield* gh.createRepository({
cwd: "/repo",
repository: "octocat/codething-mvp",
visibility: "private",
});
assert.deepStrictEqual(result, {
nameWithOwner: "octocat/codething-mvp",
url: "https://github.com/octocat/codething-mvp",
sshUrl: "[email protected]:octocat/codething-mvp.git",
});
expect(mockRun).toHaveBeenCalledTimes(1);
expect(mockRun).toHaveBeenNthCalledWith(1, {
operation: "GitHubCli.execute",
command: "gh",
args: ["repo", "create", "octocat/codething-mvp", "--private"],
cwd: "/repo",
timeoutMs: 30_000,
});
}).pipe(Effect.provide(layer)),
);
it.effect("falls back to constructed URLs when create output omits a URL", () =>
Effect.gen(function* () {
mockRun.mockReturnValueOnce(Effect.succeed(processOutput("")));
const gh = yield* GitHubCli.GitHubCli;
const result = yield* gh.createRepository({
cwd: "/repo",
repository: "octocat/codething-mvp",
visibility: "private",
});
assert.deepStrictEqual(result, {
nameWithOwner: "octocat/codething-mvp",
url: "https://github.com/octocat/codething-mvp",
sshUrl: "[email protected]:octocat/codething-mvp.git",
});
}).pipe(Effect.provide(layer)),
);
it.effect("surfaces a friendly error when the pull request is not found", () =>
Effect.gen(function* () {
mockRun.mockReturnValueOnce(
+57 -1
View File
@@ -1,6 +1,10 @@
import { Context, Effect, Layer, Result, Schema, SchemaIssue } from "effect";
import { TrimmedNonEmptyString, type VcsError } from "@t3tools/contracts";
import {
TrimmedNonEmptyString,
type SourceControlRepositoryVisibility,
type VcsError,
} from "@t3tools/contracts";
import { VcsProcess, type VcsProcessOutput } from "../vcs/VcsProcess.ts";
import {
@@ -62,6 +66,12 @@ export interface GitHubCliShape {
readonly repository: string;
}) => Effect.Effect<GitHubRepositoryCloneUrls, GitHubCliError>;
readonly createRepository: (input: {
readonly cwd: string;
readonly repository: string;
readonly visibility: SourceControlRepositoryVisibility;
}) => Effect.Effect<GitHubRepositoryCloneUrls, GitHubCliError>;
readonly createPullRequest: (input: {
readonly cwd: string;
readonly baseBranch: string;
@@ -160,6 +170,43 @@ function normalizeRepositoryCloneUrls(
};
}
/**
* `gh repo create` prints the canonical URL of the new repository on stdout
* (e.g. `https://github.com/owner/repo`). Reading it back here avoids a
* follow-up `gh repo view`, which can race GitHub's GraphQL eventual
* consistency window and falsely report the just-created repo as missing.
*/
function deriveRepositoryCloneUrlsFromCreateOutput(
stdout: string,
repository: string,
): GitHubRepositoryCloneUrls {
const fallbackHost = "github.com";
const match = stdout.match(/https?:\/\/[^\s]+/);
if (match) {
const cleaned = match[0].replace(/\.git$/, "");
try {
const parsed = new URL(cleaned);
const pathname = parsed.pathname.replace(/^\/+|\/+$/g, "");
const segments = pathname.split("/").filter(Boolean);
if (segments.length === 2) {
const nameWithOwner = `${segments[0]}/${segments[1]}`;
return {
nameWithOwner,
url: `${parsed.origin}/${nameWithOwner}`,
sshUrl: `git@${parsed.host}:${nameWithOwner}.git`,
};
}
} catch {
// Fall through to the input-derived defaults below.
}
}
return {
nameWithOwner: repository,
url: `https://${fallbackHost}/${repository}`,
sshUrl: `git@${fallbackHost}:${repository}.git`,
};
}
function decodeGitHubJson<S extends Schema.Top>(
raw: string,
schema: S,
@@ -281,6 +328,15 @@ export const make = Effect.fn("makeGitHubCli")(function* () {
),
Effect.map(normalizeRepositoryCloneUrls),
),
createRepository: (input) =>
execute({
cwd: input.cwd,
args: ["repo", "create", input.repository, `--${input.visibility}`],
}).pipe(
Effect.map((result) =>
deriveRepositoryCloneUrlsFromCreateOutput(result.stdout, input.repository),
),
),
createPullRequest: (input) =>
execute({
cwd: input.cwd,
@@ -130,6 +130,10 @@ export const make = Effect.fn("makeGitHubSourceControlProvider")(function* () {
github
.getRepositoryCloneUrls(input)
.pipe(Effect.mapError((error) => providerError("getRepositoryCloneUrls", error))),
createRepository: (input) =>
github
.createRepository(input)
.pipe(Effect.mapError((error) => providerError("createRepository", error))),
getDefaultBranch: (input) =>
github
.getDefaultBranch(input)
@@ -175,7 +175,7 @@ layer("GitLabCli.layer", (it) => {
assert.deepStrictEqual(result, {
nameWithOwner: "octocat/t3code",
url: "https://gitlab.com/octocat/t3code.git",
url: "https://gitlab.com/octocat/t3code",
sshUrl: "[email protected]:octocat/t3code.git",
});
}),
@@ -217,6 +217,67 @@ layer("GitLabCli.layer", (it) => {
}),
);
it.effect("creates repositories under an explicit namespace", () =>
Effect.gen(function* () {
mockedRun
.mockReturnValueOnce(Effect.succeed(processOutput(JSON.stringify({ id: 1234 }))))
.mockReturnValueOnce(
Effect.succeed(
processOutput(
JSON.stringify({
path_with_namespace: "octocat/t3code",
web_url: "https://gitlab.com/octocat/t3code",
http_url_to_repo: "https://gitlab.com/octocat/t3code.git",
ssh_url_to_repo: "[email protected]:octocat/t3code.git",
}),
),
),
);
const glab = yield* GitLabCli.GitLabCli;
const result = yield* glab.createRepository({
cwd: "/repo",
repository: "octocat/t3code",
visibility: "public",
});
assert.deepStrictEqual(result, {
nameWithOwner: "octocat/t3code",
url: "https://gitlab.com/octocat/t3code",
sshUrl: "[email protected]:octocat/t3code.git",
});
expect(mockedRun).toHaveBeenNthCalledWith(
1,
expect.objectContaining({
command: "glab",
cwd: "/repo",
args: ["api", "namespaces/octocat"],
}),
);
expect(mockedRun).toHaveBeenNthCalledWith(
2,
expect.objectContaining({
command: "glab",
cwd: "/repo",
args: [
"api",
"--method",
"POST",
"projects",
"--raw-field",
"path=t3code",
"--raw-field",
"name=t3code",
"--raw-field",
"visibility=public",
"--raw-field",
"namespace_id=1234",
],
}),
);
}),
);
it.effect("does not pass unsupported force flags when checking out merge requests", () =>
Effect.gen(function* () {
mockedRun.mockReturnValueOnce(Effect.succeed(processOutput("")));
+79 -3
View File
@@ -1,6 +1,6 @@
import { Context, Effect, Layer, Option, Result, Schema, SchemaIssue, type DateTime } from "effect";
import { TrimmedNonEmptyString } from "@t3tools/contracts";
import { TrimmedNonEmptyString, type SourceControlRepositoryVisibility } from "@t3tools/contracts";
import {
decodeGitLabMergeRequestJson,
@@ -66,6 +66,12 @@ export interface GitLabCliShape {
readonly repository: string;
}) => Effect.Effect<GitLabRepositoryCloneUrls, GitLabCliError>;
readonly createRepository: (input: {
readonly cwd: string;
readonly repository: string;
readonly visibility: SourceControlRepositoryVisibility;
}) => Effect.Effect<GitLabRepositoryCloneUrls, GitLabCliError>;
readonly createMergeRequest: (input: {
readonly cwd: string;
readonly baseBranch: string;
@@ -161,12 +167,16 @@ const RawGitLabDefaultBranchSchema = Schema.Struct({
default_branch: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
});
const RawGitLabNamespaceSchema = Schema.Struct({
id: Schema.Number,
});
function normalizeRepositoryCloneUrls(
raw: Schema.Schema.Type<typeof RawGitLabRepositoryCloneUrlsSchema>,
): GitLabRepositoryCloneUrls {
return {
nameWithOwner: raw.path_with_namespace,
url: raw.http_url_to_repo || raw.web_url,
url: raw.web_url,
sshUrl: raw.ssh_url_to_repo,
};
}
@@ -174,7 +184,7 @@ function normalizeRepositoryCloneUrls(
function decodeGitLabJson<S extends Schema.Top>(
raw: string,
schema: S,
operation: "getRepositoryCloneUrls" | "getDefaultBranch",
operation: "getRepositoryCloneUrls" | "getDefaultBranch" | "createRepository",
invalidDetail: string,
): Effect.Effect<S["Type"], GitLabCliError, S["DecodingServices"]> {
return Schema.decodeEffect(Schema.fromJsonString(schema))(raw).pipe(
@@ -228,6 +238,19 @@ function toSummaryWithOptionalUpdatedAt(
return Option.isSome(updatedAt) ? { ...summary, updatedAt } : summary;
}
function parseRepositoryPath(repository: string): {
readonly namespacePath: string | null;
readonly projectPath: string;
} {
const parts = repository
.split("/")
.map((part) => part.trim())
.filter((part) => part.length > 0);
const projectPath = parts.at(-1) ?? repository.trim();
const namespacePath = parts.length > 1 ? parts.slice(0, -1).join("/") : null;
return { namespacePath, projectPath };
}
export const make = Effect.fn("makeGitLabCli")(function* () {
const process = yield* VcsProcess;
@@ -320,6 +343,59 @@ export const make = Effect.fn("makeGitLabCli")(function* () {
),
Effect.map(normalizeRepositoryCloneUrls),
),
createRepository: (input) => {
const { namespacePath, projectPath } = parseRepositoryPath(input.repository);
const namespaceId: Effect.Effect<number | null, GitLabCliError> = namespacePath
? execute({
cwd: input.cwd,
args: ["api", `namespaces/${encodeURIComponent(namespacePath)}`],
}).pipe(
Effect.map((result) => result.stdout.trim()),
Effect.flatMap((raw) =>
decodeGitLabJson(
raw,
RawGitLabNamespaceSchema,
"createRepository",
"GitLab CLI returned invalid namespace JSON.",
),
),
Effect.map((namespace) => namespace.id),
)
: Effect.succeed(null);
return namespaceId.pipe(
Effect.flatMap((resolvedNamespaceId) =>
execute({
cwd: input.cwd,
args: [
"api",
"--method",
"POST",
"projects",
"--raw-field",
`path=${projectPath}`,
"--raw-field",
`name=${projectPath}`,
"--raw-field",
`visibility=${input.visibility}`,
...(resolvedNamespaceId === null
? []
: ["--raw-field", `namespace_id=${resolvedNamespaceId}`]),
],
}),
),
Effect.map((result) => result.stdout.trim()),
Effect.flatMap((raw) =>
decodeGitLabJson(
raw,
RawGitLabRepositoryCloneUrlsSchema,
"createRepository",
"GitLab CLI returned invalid repository JSON.",
),
),
Effect.map(normalizeRepositoryCloneUrls),
);
},
createMergeRequest: (input) => {
const sourceProject = sourceProjectIdentifier(input.source);
return execute({
@@ -92,6 +92,10 @@ export const make = Effect.fn("makeGitLabSourceControlProvider")(function* () {
gitlab
.getRepositoryCloneUrls(input)
.pipe(Effect.mapError((error) => providerError("getRepositoryCloneUrls", error))),
createRepository: (input) =>
gitlab
.createRepository(input)
.pipe(Effect.mapError((error) => providerError("createRepository", error))),
getDefaultBranch: (input) =>
gitlab
.getDefaultBranch(input)
@@ -115,6 +115,9 @@ Logged in to github.com account juliusmarminge (keyring)
},
],
);
const bitbucket = result.sourceControlProviders.find((item) => item.kind === "bitbucket");
assert.ok(bitbucket);
assert.strictEqual("executable" in bitbucket, false);
}).pipe(Effect.provide(testLayer));
});
@@ -204,9 +207,9 @@ Logged in as bitbucket-user
},
{
kind: "bitbucket",
auth: "authenticated",
account: Option.some("bitbucket-user"),
detail: Option.none(),
auth: "unknown",
account: Option.none(),
detail: Option.some("Bitbucket provider support is not available yet."),
},
],
);
@@ -13,20 +13,22 @@ import * as VcsProcess from "../vcs/VcsProcess.ts";
interface DiscoveryProbe {
readonly label: string;
readonly executable: string;
readonly versionArgs: ReadonlyArray<string>;
readonly executable?: string;
readonly versionArgs?: ReadonlyArray<string>;
readonly implemented: boolean;
readonly installHint: string;
}
type VcsProbe = DiscoveryProbe & {
readonly kind: VcsDriverKind;
readonly executable: string;
readonly versionArgs: ReadonlyArray<string>;
};
type ProviderProbe = DiscoveryProbe & {
readonly kind: SourceControlProviderKind;
readonly authArgs: ReadonlyArray<string>;
readonly parseAuth: (input: AuthProbeInput) => SourceControlProviderAuth;
readonly authArgs?: ReadonlyArray<string>;
readonly parseAuth?: (input: AuthProbeInput) => SourceControlProviderAuth;
};
interface AuthProbeInput {
@@ -38,7 +40,7 @@ interface AuthProbeInput {
interface DiscoveryProbeResult<Kind extends string> {
readonly kind: Kind;
readonly label: string;
readonly executable: string;
readonly executable?: string;
readonly implemented: boolean;
readonly status: "available" | "missing";
readonly version: Option.Option<string>;
@@ -101,12 +103,8 @@ const SOURCE_CONTROL_PROVIDER_PROBES: ReadonlyArray<ProviderProbe> = [
{
kind: "bitbucket",
label: "Bitbucket",
executable: "bb",
versionArgs: ["--version"],
authArgs: ["auth", "status"],
parseAuth: parseBitbucketAuth,
implemented: false,
installHint: "Install a Bitbucket CLI (`bb`) and authenticate it for your Bitbucket workspace.",
installHint: "Bitbucket provider support is not available yet.",
},
];
@@ -266,37 +264,6 @@ function parseAzureAuth(input: AuthProbeInput): SourceControlProviderAuth {
});
}
function parseBitbucketAuth(input: AuthProbeInput): SourceControlProviderAuth {
const output = combinedAuthOutput(input);
const account = matchFirst(output, [
/Logged in to .* as\s+([^\s(]+)/iu,
/Logged in as\s+([^\s(]+)/iu,
/account:\s*([^\s(]+)/iu,
/user:\s*([^\s(]+)/iu,
/username:\s*([^\s(]+)/iu,
]);
const host = parseCliHost(output) ?? "bitbucket.org";
if (input.exitCode !== 0) {
return providerAuth({
status: "unauthenticated",
host,
detail:
firstSafeAuthLine(output) ?? "Authenticate the Bitbucket CLI before enabling Bitbucket.",
});
}
if (account) {
return providerAuth({ status: "authenticated", account, host });
}
return providerAuth({
status: "unknown",
host,
detail: firstSafeAuthLine(output) ?? "Bitbucket CLI auth status could not be parsed.",
});
}
export interface SourceControlDiscoveryShape {
readonly discover: Effect.Effect<SourceControlDiscoveryResult>;
}
@@ -314,12 +281,27 @@ export const layer = Layer.effect(
const probe = <Kind extends VcsDriverKind | SourceControlProviderKind>(
input: DiscoveryProbe & { readonly kind: Kind },
): Effect.Effect<DiscoveryProbeResult<Kind>> =>
process
): Effect.Effect<DiscoveryProbeResult<Kind>> => {
const executable = input.executable;
const versionArgs = input.versionArgs;
if (!executable || !versionArgs) {
return Effect.succeed({
kind: input.kind,
label: input.label,
implemented: input.implemented,
status: "missing" as const,
version: Option.none<string>(),
installHint: input.installHint,
detail: Option.some(input.installHint),
} satisfies DiscoveryProbeResult<Kind>);
}
return process
.run({
operation: "source-control.discovery.probe",
command: input.executable,
args: input.versionArgs,
command: executable,
args: versionArgs,
cwd: config.cwd,
timeoutMs: 5_000,
maxOutputBytes: 8_000,
@@ -331,7 +313,7 @@ export const layer = Layer.effect(
({
kind: input.kind,
label: input.label,
executable: input.executable,
executable,
implemented: input.implemented,
status: "available" as const,
version: Option.orElse(firstNonEmptyLine(result.stdout), () =>
@@ -345,7 +327,7 @@ export const layer = Layer.effect(
Effect.succeed({
kind: input.kind,
label: input.label,
executable: input.executable,
executable,
implemented: input.implemented,
status: "missing" as const,
version: Option.none<string>(),
@@ -354,10 +336,22 @@ export const layer = Layer.effect(
} 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,
@@ -368,8 +362,8 @@ export const layer = Layer.effect(
return process
.run({
operation: "source-control.discovery.auth",
command: input.executable,
args: input.authArgs,
command: executable,
args: authArgs,
cwd: config.cwd,
allowNonZeroExit: true,
timeoutMs: 5_000,
@@ -381,7 +375,7 @@ export const layer = Layer.effect(
(result) =>
({
...item,
auth: input.parseAuth(result),
auth: parseAuth(result),
}) satisfies SourceControlProviderDiscoveryItem,
),
Effect.catch((cause) =>
@@ -6,6 +6,7 @@ import type {
SourceControlProviderInfo,
SourceControlProviderKind,
SourceControlRepositoryCloneUrls,
SourceControlRepositoryVisibility,
} from "@t3tools/contracts";
export interface SourceControlProviderContext {
@@ -50,6 +51,11 @@ export interface SourceControlProviderShape {
readonly context?: SourceControlProviderContext;
readonly repository: string;
}) => Effect.Effect<SourceControlRepositoryCloneUrls, SourceControlProviderError>;
readonly createRepository: (input: {
readonly cwd: string;
readonly repository: string;
readonly visibility: SourceControlRepositoryVisibility;
}) => Effect.Effect<SourceControlRepositoryCloneUrls, SourceControlProviderError>;
readonly getDefaultBranch: (input: {
readonly cwd: string;
readonly context?: SourceControlProviderContext;
@@ -58,6 +58,7 @@ function unsupportedProvider(kind: SourceControlProviderKind): SourceControlProv
getChangeRequest: () => unsupported("getChangeRequest"),
createChangeRequest: () => unsupported("createChangeRequest"),
getRepositoryCloneUrls: () => unsupported("getRepositoryCloneUrls"),
createRepository: () => unsupported("createRepository"),
getDefaultBranch: () => unsupported("getDefaultBranch"),
checkoutChangeRequest: () => unsupported("checkoutChangeRequest"),
});
@@ -0,0 +1,322 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import { Effect, FileSystem, Layer } from "effect";
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";
const CLONE_URLS = {
nameWithOwner: "octocat/t3code",
url: "https://github.com/octocat/t3code",
sshUrl: "[email protected]:octocat/t3code.git",
};
function makeProvider(
overrides: Partial<SourceControlProviderShape> = {},
): SourceControlProviderShape {
const unsupported = (operation: string) =>
Effect.die(`unexpected provider operation ${operation}`) as Effect.Effect<
never,
SourceControlProviderError
>;
return {
kind: "github",
listChangeRequests: () => unsupported("listChangeRequests"),
getChangeRequest: () => unsupported("getChangeRequest"),
createChangeRequest: () => unsupported("createChangeRequest"),
getRepositoryCloneUrls: () => Effect.succeed(CLONE_URLS),
createRepository: () => Effect.succeed(CLONE_URLS),
getDefaultBranch: () => Effect.succeed(null),
checkoutChangeRequest: () => unsupported("checkoutChangeRequest"),
...overrides,
};
}
function processOutput(): ExecuteGitResult {
return {
exitCode: ChildProcessSpawner.ExitCode(0),
stdout: "",
stderr: "",
stdoutTruncated: false,
stderrTruncated: false,
};
}
function makeLayer(input: {
readonly provider?: SourceControlProviderShape;
readonly git?: Partial<GitVcsDriverShape>;
}) {
return layer.pipe(
Layer.provide(
Layer.mock(SourceControlProviderRegistry)({
get: () => Effect.succeed(input.provider ?? makeProvider()),
}),
),
Layer.provide(
Layer.mock(GitVcsDriver)({
execute: () => Effect.succeed(processOutput()),
ensureRemote: () => Effect.succeed("origin"),
pushCurrentBranch: () =>
Effect.succeed({
status: "pushed" as const,
branch: "feature/remote-v1",
upstreamBranch: "origin/feature/remote-v1",
setUpstream: true,
}),
...input.git,
}),
),
Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-source-control-repos-" })),
Layer.provideMerge(NodeServices.layer),
);
}
it.effect("looks up repositories through the requested provider without search", () => {
const calls: Array<{ cwd: string; repository: string }> = [];
const provider = makeProvider({
getRepositoryCloneUrls: (input) =>
Effect.sync(() => {
calls.push({ cwd: input.cwd, repository: input.repository });
return CLONE_URLS;
}),
});
return Effect.gen(function* () {
const service = yield* SourceControlRepositoryService;
const result = yield* service.lookupRepository({
provider: "github",
repository: "octocat/t3code",
cwd: "/workspace",
});
assert.deepStrictEqual(result, { provider: "github", ...CLONE_URLS });
assert.deepStrictEqual(calls, [{ cwd: "/workspace", repository: "octocat/t3code" }]);
}).pipe(Effect.provide(makeLayer({ provider })));
});
it.effect("clones a looked-up repository into the requested destination", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const parent = yield* fs.makeTempDirectoryScoped({
prefix: "t3-source-control-clone-parent-",
});
const destinationPath = `${parent}/t3code`;
const cloneCalls: Array<{ cwd: string; args: ReadonlyArray<string> }> = [];
yield* Effect.gen(function* () {
const service = yield* SourceControlRepositoryService;
const result = yield* service.cloneRepository({
provider: "github",
repository: "octocat/t3code",
destinationPath,
protocol: "https",
});
assert.deepStrictEqual(result, {
cwd: destinationPath,
remoteUrl: CLONE_URLS.url,
repository: { provider: "github", ...CLONE_URLS },
});
assert.deepStrictEqual(cloneCalls, [
{
cwd: parent,
args: ["clone", CLONE_URLS.url, "t3code"],
},
]);
}).pipe(
Effect.provide(
makeLayer({
git: {
execute: (input) =>
Effect.sync(() => {
cloneCalls.push({ cwd: input.cwd, args: input.args });
return processOutput();
}),
},
}),
),
);
}).pipe(Effect.provide(NodeServices.layer)),
);
it.effect("publishes by creating the repository, adding a remote, and pushing upstream", () => {
const createCalls: Array<{ cwd: string; repository: string; visibility: string }> = [];
const remoteCalls: Array<{ cwd: string; preferredName: string; url: string }> = [];
const pushCalls: Array<{ cwd: string; remoteName: string | null | undefined }> = [];
const provider = makeProvider({
createRepository: (input) =>
Effect.sync(() => {
createCalls.push({
cwd: input.cwd,
repository: input.repository,
visibility: input.visibility,
});
return CLONE_URLS;
}),
});
return Effect.gen(function* () {
const service = yield* SourceControlRepositoryService;
const result = yield* service.publishRepository({
cwd: "/workspace",
provider: "github",
repository: "octocat/t3code",
visibility: "private",
remoteName: "origin",
protocol: "ssh",
});
assert.deepStrictEqual(result, {
repository: { provider: "github", ...CLONE_URLS },
remoteName: "origin",
remoteUrl: CLONE_URLS.sshUrl,
branch: "feature/remote-v1",
upstreamBranch: "origin/feature/remote-v1",
status: "pushed",
});
assert.deepStrictEqual(createCalls, [
{ cwd: "/workspace", repository: "octocat/t3code", visibility: "private" },
]);
assert.deepStrictEqual(remoteCalls, [
{ cwd: "/workspace", preferredName: "origin", url: CLONE_URLS.sshUrl },
]);
assert.deepStrictEqual(pushCalls, [{ cwd: "/workspace", remoteName: "origin" }]);
}).pipe(
Effect.provide(
makeLayer({
provider,
git: {
ensureRemote: (input) =>
Effect.sync(() => {
remoteCalls.push(input);
return "origin";
}),
pushCurrentBranch: (cwd, _fallbackBranch, options) =>
Effect.sync(() => {
pushCalls.push({ cwd, remoteName: options?.remoteName });
return {
status: "pushed" as const,
branch: "feature/remote-v1",
upstreamBranch: "origin/feature/remote-v1",
setUpstream: true,
};
}),
},
}),
),
);
});
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 result = yield* service.publishRepository({
cwd: "/workspace",
provider: "github",
repository: "octocat/t3code",
visibility: "private",
remoteName: "origin",
protocol: "ssh",
});
assert.equal(result.remoteName, "origin-1");
assert.deepStrictEqual(pushCalls, [{ cwd: "/workspace", remoteName: "origin-1" }]);
}).pipe(
Effect.provide(
makeLayer({
git: {
ensureRemote: () => Effect.succeed("origin-1"),
pushCurrentBranch: (cwd, _fallbackBranch, options) =>
Effect.sync(() => {
pushCalls.push({ cwd, remoteName: options?.remoteName });
return {
status: "pushed" as const,
branch: "feature/remote-v1",
upstreamBranch: `${options?.remoteName ?? "missing"}/feature/remote-v1`,
setUpstream: true,
};
}),
},
}),
),
);
});
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 result = yield* service.publishRepository({
cwd: "/workspace",
provider: "github",
repository: "octocat/t3code",
visibility: "private",
remoteName: "origin",
protocol: "ssh",
});
assert.deepStrictEqual(result, {
repository: { provider: "github", ...CLONE_URLS },
remoteName: "origin",
remoteUrl: CLONE_URLS.sshUrl,
branch: "main",
status: "remote_added",
});
assert.strictEqual(pushCalls, 0);
}).pipe(
Effect.provide(
makeLayer({
git: {
execute: (input) =>
input.args[0] === "rev-parse"
? Effect.fail(
new GitCommandError({
operation: input.operation,
command: "git rev-parse --verify HEAD",
cwd: input.cwd,
detail: "fatal: Needed a single revision",
}),
)
: Effect.succeed(processOutput()),
statusDetails: () =>
Effect.succeed({
isRepo: true,
hasOriginRemote: true,
isDefaultBranch: true,
branch: "main",
upstreamRef: null,
hasWorkingTreeChanges: false,
workingTree: { files: [], insertions: 0, deletions: 0 },
hasUpstream: false,
aheadCount: 0,
behindCount: 0,
aheadOfDefaultCount: 0,
}),
pushCurrentBranch: () =>
Effect.sync(() => {
pushCalls += 1;
return {
status: "pushed" as const,
branch: "main",
upstreamBranch: "origin/main",
setUpstream: true,
};
}),
},
}),
),
);
});
@@ -0,0 +1,320 @@
import OS from "node:os";
import { Context, Effect, FileSystem, Layer, Path, Schema } from "effect";
import {
SourceControlRepositoryError,
type SourceControlCloneRepositoryInput,
type SourceControlCloneRepositoryResult,
type SourceControlCloneProtocol,
type SourceControlProviderKind,
type SourceControlPublishRepositoryInput,
type SourceControlPublishRepositoryResult,
type SourceControlRepositoryCloneUrls,
type SourceControlRepositoryInfo,
type SourceControlRepositoryLookupInput,
} from "@t3tools/contracts";
import { ServerConfig } from "../config.ts";
import { GitVcsDriver } from "../vcs/GitVcsDriver.ts";
import { SourceControlProviderRegistry } from "./SourceControlProviderRegistry.ts";
export interface SourceControlRepositoryServiceShape {
readonly lookupRepository: (
input: SourceControlRepositoryLookupInput,
) => Effect.Effect<SourceControlRepositoryInfo, SourceControlRepositoryError>;
readonly cloneRepository: (
input: SourceControlCloneRepositoryInput,
) => Effect.Effect<SourceControlCloneRepositoryResult, SourceControlRepositoryError>;
readonly publishRepository: (
input: SourceControlPublishRepositoryInput,
) => Effect.Effect<SourceControlPublishRepositoryResult, SourceControlRepositoryError>;
}
export class SourceControlRepositoryService extends Context.Service<
SourceControlRepositoryService,
SourceControlRepositoryServiceShape
>()("t3/source-control/SourceControlRepositoryService") {}
function detailFromUnknown(cause: unknown): string {
if (typeof cause === "object" && cause !== null) {
if ("detail" in cause && typeof cause.detail === "string" && cause.detail.length > 0) {
return cause.detail;
}
if ("message" in cause && typeof cause.message === "string" && cause.message.length > 0) {
return cause.message;
}
}
return "An unexpected source control error occurred.";
}
function repositoryError(input: {
readonly operation: string;
readonly provider: SourceControlProviderKind;
readonly detail: string;
readonly cause?: unknown;
}): SourceControlRepositoryError {
return new SourceControlRepositoryError({
provider: input.provider,
operation: input.operation,
detail: input.detail,
...(input.cause === undefined ? {} : { cause: input.cause }),
});
}
function mapRepositoryError(operation: string, provider: SourceControlProviderKind) {
return Effect.mapError((cause: unknown) =>
Schema.is(SourceControlRepositoryError)(cause)
? cause
: repositoryError({
operation,
provider,
detail: detailFromUnknown(cause),
cause,
}),
);
}
function toRepositoryInfo(
provider: SourceControlProviderKind,
urls: SourceControlRepositoryCloneUrls,
): SourceControlRepositoryInfo {
return {
provider,
nameWithOwner: urls.nameWithOwner,
url: urls.url,
sshUrl: urls.sshUrl,
};
}
function selectRemoteUrl(
urls: SourceControlRepositoryCloneUrls,
protocol: SourceControlCloneProtocol | undefined,
): string {
switch (protocol ?? "auto") {
case "https":
return urls.url;
case "ssh":
case "auto":
return urls.sshUrl;
}
}
function expandHomePath(input: string, path: Path.Path): string {
if (input === "~") {
return OS.homedir();
}
if (input.startsWith("~/") || input.startsWith("~\\")) {
return path.join(OS.homedir(), input.slice(2));
}
return input;
}
export const make = Effect.fn("makeSourceControlRepositoryService")(function* () {
const config = yield* ServerConfig;
const fileSystem = yield* FileSystem.FileSystem;
const git = yield* GitVcsDriver;
const path = yield* Path.Path;
const providers = yield* SourceControlProviderRegistry;
const ensureConcreteProvider = (input: {
readonly operation: string;
readonly provider: SourceControlProviderKind;
}) => {
if (input.provider !== "unknown") {
return Effect.succeed(input.provider);
}
return Effect.fail(
repositoryError({
operation: input.operation,
provider: input.provider,
detail: "Choose a source control provider before continuing.",
}),
);
};
const lookupRepository = Effect.fn("SourceControlRepositoryService.lookupRepository")(function* (
input: SourceControlRepositoryLookupInput,
) {
const providerKind = yield* ensureConcreteProvider({
operation: "lookupRepository",
provider: input.provider,
});
const provider = yield* providers.get(providerKind);
const urls = yield* provider.getRepositoryCloneUrls({
cwd: input.cwd ?? config.cwd,
repository: input.repository.trim(),
});
return toRepositoryInfo(providerKind, urls);
});
const normalizeDestinationPath = Effect.fn("SourceControlRepositoryService.normalizeDestination")(
function* (destinationPath: string) {
const trimmed = destinationPath.trim();
if (trimmed.length === 0) {
return yield* Effect.fail(
repositoryError({
operation: "cloneRepository",
provider: "unknown",
detail: "Choose a destination path before cloning.",
}),
);
}
return path.resolve(expandHomePath(trimmed, path));
},
);
const prepareDestination = Effect.fn("SourceControlRepositoryService.prepareDestination")(
function* (destinationPath: string) {
const normalizedDestination = yield* normalizeDestinationPath(destinationPath);
if (yield* fileSystem.exists(normalizedDestination).pipe(Effect.orElseSucceed(() => false))) {
const entries = yield* fileSystem
.readDirectory(normalizedDestination, { recursive: false })
.pipe(
Effect.mapError((cause) =>
repositoryError({
operation: "cloneRepository",
provider: "unknown",
detail: "Destination path already exists and is not a directory.",
cause,
}),
),
);
if (entries.length > 0) {
return yield* Effect.fail(
repositoryError({
operation: "cloneRepository",
provider: "unknown",
detail: "Destination path already exists and is not empty.",
}),
);
}
} else {
yield* fileSystem.makeDirectory(path.dirname(normalizedDestination), { recursive: true });
}
return {
destinationPath: normalizedDestination,
parentPath: path.dirname(normalizedDestination),
directoryName: path.basename(normalizedDestination),
};
},
);
const cloneRepository = Effect.fn("SourceControlRepositoryService.cloneRepository")(function* (
input: SourceControlCloneRepositoryInput,
) {
const preparedDestination = yield* prepareDestination(input.destinationPath);
let repository: SourceControlRepositoryInfo | null = null;
let remoteUrl = input.remoteUrl?.trim() ?? null;
let provider: SourceControlProviderKind = input.provider ?? "unknown";
if (input.provider && input.repository) {
repository = yield* lookupRepository({
provider: input.provider,
repository: input.repository,
cwd: preparedDestination.parentPath,
});
remoteUrl = selectRemoteUrl(repository, input.protocol);
provider = input.provider;
}
if (!remoteUrl) {
return yield* Effect.fail(
repositoryError({
operation: "cloneRepository",
provider,
detail: "Enter a repository path or clone URL before cloning.",
}),
);
}
yield* git.execute({
operation: "SourceControlRepositoryService.cloneRepository",
cwd: preparedDestination.parentPath,
args: ["clone", remoteUrl, preparedDestination.directoryName],
timeoutMs: 120_000,
maxOutputBytes: 256 * 1024,
});
return {
cwd: preparedDestination.destinationPath,
remoteUrl,
repository,
};
});
const publishRepository = Effect.fn("SourceControlRepositoryService.publishRepository")(
function* (input: SourceControlPublishRepositoryInput) {
const providerKind = yield* ensureConcreteProvider({
operation: "publishRepository",
provider: input.provider,
});
const provider = yield* providers.get(providerKind);
const urls = yield* provider.createRepository({
cwd: input.cwd,
repository: input.repository.trim(),
visibility: input.visibility,
});
const remoteUrl = selectRemoteUrl(urls, input.protocol);
const remoteName = yield* git.ensureRemote({
cwd: input.cwd,
preferredName: input.remoteName?.trim() || "origin",
url: remoteUrl,
});
// An empty local repo (no commits) would make `git push HEAD:...` fail
// with an opaque "src refspec HEAD does not match any". Treat this as a
// partial success: the remote was created and wired up, but there is
// nothing to push yet.
const hasCommits = yield* git
.execute({
operation: "SourceControlRepositoryService.publishRepository.headCheck",
cwd: input.cwd,
args: ["rev-parse", "--verify", "HEAD"],
})
.pipe(
Effect.map(() => true),
Effect.catch(() => Effect.succeed(false)),
);
if (!hasCommits) {
const details = yield* git
.statusDetails(input.cwd)
.pipe(Effect.catch(() => Effect.succeed(null)));
return {
repository: toRepositoryInfo(providerKind, urls),
remoteName,
remoteUrl,
branch: details?.branch ?? "main",
status: "remote_added" as const,
};
}
const pushResult = yield* git.pushCurrentBranch(input.cwd, null, { remoteName });
return {
repository: toRepositoryInfo(providerKind, urls),
remoteName,
remoteUrl,
branch: pushResult.branch,
...(pushResult.upstreamBranch ? { upstreamBranch: pushResult.upstreamBranch } : {}),
status: "pushed" as const,
};
},
);
return SourceControlRepositoryService.of({
lookupRepository: (input) =>
lookupRepository(input).pipe(mapRepositoryError("lookupRepository", input.provider)),
cloneRepository: (input) =>
cloneRepository(input).pipe(
mapRepositoryError("cloneRepository", input.provider ?? "unknown"),
),
publishRepository: (input) =>
publishRepository(input).pipe(mapRepositoryError("publishRepository", input.provider)),
});
});
export const layer = Layer.effect(SourceControlRepositoryService, make());