feat(server): source control, media and discovery use GitHub's API instead of gh (#16321)

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
This commit is contained in:
Julius MarmingeandClaude Opus 5.5 authored and GitHub committed 2026-10-06 13:14:13 -07:00
1 parent adc3c9327a
commit 649418f01f
13 files changed
+1403 -1777

No files matched your search

+15 -13
View File
@@ -16,12 +16,12 @@ import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Redacted from "effect/Redacted";
import * as Path from "effect/Path";
import * as PlatformError from "effect/PlatformError";
import * as Schema from "effect/Schema";
import * as TestClock from "effect/testing/TestClock";
import { HttpClient, HttpClientResponse, HttpServerResponse } from "effect/http";
import { ChildProcessSpawner } from "effect/process";
import { vi } from "vite-plus/test";
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
@@ -35,7 +35,7 @@ import { ASSET_ROUTE_PREFIX, issueAssetUrl, resolveAsset } from "./AssetAccess.t
import * as NativeAppIconResolver from "./NativeAppIconResolver.ts";
import { openMediaFile } from "./MediaFile.ts";
import { symlinksSupported } from "@t3tools/shared/testing/symlinks";
import * as GitHubCli from "../sourceControl/GitHubCli.ts";
import * as GitHubCredentials from "../sourceControl/GitHubCredentials.ts";
import { githubMediaResponse } from "./GitHubMediaFetch.ts";
vi.mock("node:fs/promises", async (importOriginal) => {
@@ -126,7 +126,7 @@ const layerTest = Layer.mergeAll(
).pipe(Layer.provideMerge(NodeServices.layer));
describe("AssetAccess", () => {
it.effect("loads private media immediately after login and reuses the found credential", () => {
it.effect("loads private media immediately after login with the GitHub credential", () => {
let lookups = 0;
const authorizations: Array<string | undefined> = [];
return Effect.gen(function* () {
@@ -138,19 +138,21 @@ describe("AssetAccess", () => {
expect((yield* githubMediaResponse(asset, {})).status).toBe(404);
expect((yield* githubMediaResponse(asset, {})).status).toBe(200);
expect((yield* githubMediaResponse(asset, {})).status).toBe(200);
expect(lookups).toBe(2);
// Caching the token is GitHubCredentials' job; this asks it every time.
expect(lookups).toBe(3);
expect(authorizations).toEqual([undefined, "Bearer signed-in", "Bearer signed-in"]);
}).pipe(
Effect.provide(
Layer.mock(GitHubCli.GitHubCli)({
execute: () =>
Effect.sync(() => ({
exitCode: ChildProcessSpawner.ExitCode(0),
stdout: ++lookups === 1 ? "" : "signed-in",
stderr: "",
stdoutTruncated: false,
stderrTruncated: false,
})),
Layer.mock(GitHubCredentials.GitHubCredentials)({
get: (host) =>
++lookups === 1
? Effect.fail(new GitHubCredentials.GitHubNotSignedInError({ host }))
: Effect.succeed({
host,
token: Redacted.make("signed-in"),
source: "gh" as const,
fingerprint: "fingerprint",
}),
}),
),
Effect.provideService(
+9 -42
View File
@@ -12,7 +12,7 @@ import {
type HttpClientResponse,
} from "effect/http";
import * as GitHubCli from "../sourceControl/GitHubCli.ts";
import * as GitHubCredentials from "../sourceControl/GitHubCredentials.ts";
/**
* Exactly the hosts the credential is for. Everything a redirect leads to — the presigned
@@ -37,8 +37,6 @@ const isCredentialedHost = (url: string) => {
const MAX_REDIRECTS = 3;
/** Following the redirect here, rather than in `fetch`, is what keeps the token on GitHub. */
const MANUAL_REDIRECT: RequestInit = { redirect: "manual" };
const TOKEN_CACHE_TTL_MS = 5 * 60_000;
const TOKEN_CACHE_MAX_ENTRIES = 32;
/** Passed through so a seek in a long video costs one upstream range request, not a full download. */
const FORWARDED_REQUEST_HEADERS = ["range", "if-range"] as const;
const FORWARDED_RESPONSE_HEADERS = [
@@ -57,45 +55,14 @@ const SVG_CONTENT_TYPE = "image/svg+xml";
const SVG_CONTENT_SECURITY_POLICY = "default-src 'none'; style-src 'unsafe-inline'; sandbox";
/**
* A media request per image and one per video seek, each of which would otherwise spawn `gh`.
* The token is what `gh auth token` would print again on the next call, and it is held no longer
* than a signed asset URL lives.
* The github.com credential, or null without one: a public asset still loads, and a private one
* fails the way it does in a browser that is not signed in.
*/
const tokenCache = new Map<string, { readonly at: number; readonly token: Redacted.Redacted }>();
const githubToken = Effect.fn("GitHubMediaFetch.githubToken")(function* (input: {
readonly cwd: string;
readonly host: string;
}) {
// `gh` stores a token per host, not per repository, so the directory it runs in is not part
// of the answer and must not fragment the cache a client could otherwise churn. This route
// pins no credential; if it ever does, the pin belongs in this key.
const key = input.host;
const now = yield* Clock.currentTimeMillis;
const cached = tokenCache.get(key);
if (cached !== undefined && now - cached.at < TOKEN_CACHE_TTL_MS) return cached.token;
const github = yield* GitHubCli.GitHubCli;
// No credential is a normal state: a public asset still loads, and a private one fails the way
// it does in a browser that is not signed in.
const token = yield* github
.execute({
cwd: input.cwd,
args: ["auth", "token", "--hostname", input.host],
env: { GH_DEBUG: "" },
})
.pipe(
Effect.map((output) => output.stdout.trim()),
Effect.orElseSucceed(() => ""),
);
// A login or recovered CLI failure must take effect on the next media request.
if (token.length === 0) return null;
if (tokenCache.size >= TOKEN_CACHE_MAX_ENTRIES) {
tokenCache.delete(tokenCache.keys().next().value!);
}
const redacted = Redacted.make(token);
tokenCache.set(key, { at: now, token: redacted });
return redacted;
});
const githubToken = GitHubCredentials.GitHubCredentials.pipe(
Effect.flatMap((credentials) => credentials.get("github.com")),
Effect.map((credential) => credential.token),
Effect.orElseSucceed(() => null),
);
/**
* Follows GitHub's redirect to the signed object itself, and never carries the credential off
@@ -146,7 +113,7 @@ export const githubMediaResponse = Effect.fn("GitHubMediaFetch.githubMediaRespon
requestHeaders: Record<string, string | undefined>,
) {
// Both media hosts are served by github.com's account, which is the host `gh` stores it under.
const token = yield* githubToken({ cwd: asset.cwd, host: "github.com" });
const token = yield* githubToken;
const forwarded: Record<string, string> = {};
for (const name of FORWARDED_REQUEST_HEADERS) {
const value = requestHeaders[name];
+13 -5
View File
@@ -36,6 +36,7 @@ import {
ThreadId,
} from "@t3tools/contracts";
import * as DateTime from "effect/DateTime";
import * as GitHubApi from "../sourceControl/GitHubApi.ts";
import * as GitHubCli from "../sourceControl/GitHubCli.ts";
import { decodeGitHubPullRequestListJson } from "../sourceControl/gitHubPullRequests.ts";
import * as GitLabCli from "../sourceControl/GitLabCli.ts";
@@ -383,7 +384,11 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
);
const ghCalls: string[] = [];
const execute: GitHubCli.GitHubCli["Service"]["execute"] = (input) => {
// The fake still speaks in gh's command shapes; the service methods below translate to them.
const execute = (input: {
readonly cwd: string;
readonly args: ReadonlyArray<string>;
}): Effect.Effect<VcsProcess.VcsProcessOutput, GitHubCli.GitHubCliError> => {
const args = [...input.args];
ghCalls.push(args.join(" "));
@@ -518,7 +523,6 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
return {
service: {
execute,
// The fake answers the CLI shape, so batched lookups read it the way the fallback does.
listPullRequestsByHead: (input) =>
execute({
@@ -724,7 +728,12 @@ function makeManager(input?: {
discover: Effect.succeed([]),
}),
),
Effect.provide(Layer.succeed(GitHubCli.GitHubCli, gitHubCli)),
Effect.provide(
Layer.merge(
Layer.succeed(GitHubCli.GitHubCli, gitHubCli),
Layer.mock(GitHubApi.GitHubApi)({}),
),
),
),
);
@@ -2660,8 +2669,7 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
provider: "github",
providerOperation: "listChangeRequests",
providerCommand: "gh",
errorDetail:
"GitHub API rate limit exceeded. For the GraphQL quota and reset time, run `gh api graphql -f query='{rateLimit{remaining resetAt}}'`; `gh api rate_limit` reports REST.",
errorDetail: "GitHub API rate limit exceeded. Requests resume when the limit resets.",
});
const loggedText = [
warning?.message ?? "",
+2 -1
View File
@@ -562,7 +562,8 @@ const layerRuntimeCoreDependenciesBase = Layer.mergeAll(
Layer.provideMerge(Layer.merge(ProjectStore.layer, ThreadSearch.layer)),
Layer.provideMerge(layerServerSettings),
// The asset route uses the registry's GitHub credential for private PR media.
Layer.provideMerge(Layer.mergeAll(layerSourceControlProviderRegistry, GitHubCli.layer)),
Layer.provideMerge(layerSourceControlProviderRegistry),
Layer.provideMerge(GitHubCli.layer),
Layer.provideMerge(layerGit),
Layer.provideMerge(layerVcs),
Layer.provideMerge(Layer.mergeAll(layerTerminal, layerPreview, layerDevice)),
+2 -1
View File
@@ -145,6 +145,7 @@ export interface GitHubGraphQlInput {
readonly query: string;
readonly variables?: Readonly<Record<string, unknown>>;
readonly allowReserve?: boolean;
readonly maxResponseBytes?: number;
}
export class GitHubApi extends Context.Service<
@@ -567,7 +568,7 @@ export const make = Effect.gen(function* () {
HttpClientRequest.acceptJson,
HttpClientRequest.bodyJsonUnsafe({ query, variables: input.variables ?? {} }),
),
maxResponseBytes: DEFAULT_MAX_RESPONSE_BYTES,
maxResponseBytes: input.maxResponseBytes ?? DEFAULT_MAX_RESPONSE_BYTES,
allowReserve,
acceptNotModified: false,
graphql: true,
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -3,11 +3,12 @@ import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import { ChildProcessSpawner } from "effect/process";
import * as VcsProcess from "../vcs/VcsProcess.ts";
import * as GitHubApi from "./GitHubApi.ts";
import * as GitHubCli from "./GitHubCli.ts";
import * as GitHubGraphQlBudget from "./githubGraphQlBudget.ts";
import { parseGitHubAuthStatus } from "./gitHubAuthStatus.ts";
import * as GitHubSourceControlProvider from "./GitHubSourceControlProvider.ts";
@@ -25,37 +26,26 @@ const processResult = (
stderrTruncated: false,
});
function makeProvider(github: Partial<GitHubCli.GitHubCli["Service"]>) {
function makeProvider(
github: Partial<GitHubCli.GitHubCli["Service"]>,
api: Partial<GitHubApi.GitHubApi["Service"]> = {},
) {
return GitHubSourceControlProvider.make.pipe(
Effect.provide(Layer.mock(GitHubCli.GitHubCli)(github)),
Effect.provide(
Layer.merge(Layer.mock(GitHubCli.GitHubCli)(github), Layer.mock(GitHubApi.GitHubApi)(api)),
),
);
}
it.effect("uses the enterprise quota for a current-repository default branch read", () =>
Effect.gen(function* () {
// github.com is out of quota; the enterprise read must not be priced against it.
const budget = yield* GitHubGraphQlBudget.GitHubGraphQlBudget;
yield* budget.observe(
"github.com",
'{"data":{"rateLimit":{"cost":1,"limit":5000,"remaining":0,"resetAt":"2099-01-01T00:00:00Z"}}}',
);
const provider = yield* GitHubSourceControlProvider.make;
const branch = yield* provider.getDefaultBranch({
cwd: "/enterprise-repo",
context: {
provider: { kind: "github", name: "GitHub Enterprise", baseUrl: "https://enterprise.test" },
remoteName: "origin",
remoteUrl: "https://enterprise.test/acme/web.git",
},
});
assert.strictEqual(branch, "main");
}).pipe(
Effect.provide(GitHubCli.layer),
Effect.provideService(VcsProcess.VcsProcess, {
run: () => Effect.succeed(processResult("main")),
}),
),
);
const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
const restResponse = (body: string): GitHubApi.GitHubRestResponse => ({
status: 200,
headers: {},
body,
truncated: false,
invalidUtf8: false,
});
it.effect("maps GitHub PR summaries into provider-neutral change requests", () =>
Effect.gen(function* () {
@@ -412,27 +402,20 @@ it.effect.each(["pull", "issues"])(
"resolves %s subjects on the linked host without using the checkout",
(kind) =>
Effect.gen(function* () {
const provider = yield* makeProvider({
execute: (input) => {
assert.deepStrictEqual(input.args, [
"api",
"--hostname",
"github.com",
"repos/owner/repo/issues/42",
"--jq",
"{title, body}",
]);
assert.strictEqual(input.maxOutputBytes, 32_000);
assert.strictEqual(input.timeoutMs, 3_000);
return Effect.succeed({
exitCode: ChildProcessSpawner.ExitCode(0),
stdout: JSON.stringify({ title: "Pairing expiry", body: "Preserve remote access" }),
stderr: "",
stdoutTruncated: false,
stderrTruncated: false,
});
const provider = yield* makeProvider(
{},
{
rest: (input) => {
assert.strictEqual(input.host, "github.com");
assert.strictEqual(input.path, "repos/owner/repo/issues/42");
return Effect.succeed(
restResponse(
encodeJson({ title: "Pairing expiry", body: "Preserve remote access", id: 1 }),
),
);
},
},
});
);
const lookup = provider.resolveLink?.({
cwd: "/unrelated",
url: new URL(`https://github.com/owner/repo/${kind}/42`),
@@ -456,23 +439,20 @@ it.effect.each(["read", "decode"] as const)(
"retains the %s failure without exposing its raw contents",
(stage) =>
Effect.gen(function* () {
const cause = new GitHubCli.GitHubCliCommandError({
command: "gh",
cwd: "/repo",
cause: new Error("private response text"),
});
const provider = yield* makeProvider({
execute: () =>
stage === "read"
? Effect.fail(cause)
: Effect.succeed({
exitCode: ChildProcessSpawner.ExitCode(0),
stdout: "private response text",
stderr: "",
stdoutTruncated: false,
stderrTruncated: false,
}),
const cause = new GitHubApi.GitHubApiResponseError({
host: "github.com",
operation: "resolveLink",
status: 500,
});
const provider = yield* makeProvider(
{},
{
rest: () =>
stage === "read"
? Effect.fail(cause)
: Effect.succeed(restResponse("private response text")),
},
);
const lookup = provider.resolveLink?.({
cwd: "/repo",
url: new URL("https://github.com/owner/repo/issues/42"),
@@ -2,22 +2,33 @@ import * as Schema from "effect/Schema";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import { SourceControlProviderError, type ChangeRequest } from "@t3tools/contracts";
import * as Result from "effect/Result";
import {
SourceControlProviderError,
type ChangeRequest,
type SourceControlProviderDiscoveryItem,
} from "@t3tools/contracts";
import { HostProcessEnvironment } from "@t3tools/shared/hostProcess";
import * as GitHubApi from "./GitHubApi.ts";
import * as GitHubCli from "./GitHubCli.ts";
import { findAuthenticatedGitHubAccount, parseGitHubAuthStatus } from "./gitHubAuthStatus.ts";
import * as SourceControlProvider from "./SourceControlProvider.ts";
import {
combinedAuthOutput,
firstSafeAuthLine,
probeSourceControlProvider,
providerAuth,
type SourceControlAuthProbeInput,
type SourceControlCliDiscoverySpec,
type SourceControlManagedCliDiscoverySpec,
} from "./SourceControlProviderDiscovery.ts";
import * as VcsProcess from "../vcs/VcsProcess.ts";
const decodeLinkSubject = Schema.decodeUnknownEffect(
Schema.fromJsonString(
Schema.Struct({ title: Schema.String, body: Schema.NullOr(Schema.String) }),
Schema.Struct({ title: Schema.String, body: Schema.optional(Schema.NullOr(Schema.String)) }),
),
);
@@ -111,8 +122,70 @@ export const discovery = {
"Install the GitHub command-line tool (`gh`) via https://cli.github.com/ or your package manager (for example `brew install gh`).",
} satisfies SourceControlCliDiscoverySpec;
const decodeViewer = Schema.decodeUnknownOption(
Schema.fromJsonString(Schema.Struct({ login: Schema.String })),
);
/** The environment variable gh would take a github.com token from, if one is set. */
function environmentTokenVariable(environment: NodeJS.ProcessEnv): string | null {
return ["GH_TOKEN", "GITHUB_TOKEN"].find((name) => environment[name]?.trim()) ?? null;
}
/**
* GitHub is usable with a token from the environment or with `gh` to hand one over. An
* environment token is checked against the API, since `gh auth status` may not know it.
*/
export const makeDiscovery = Effect.gen(function* () {
const api = yield* GitHubApi.GitHubApi;
const process = yield* VcsProcess.VcsProcess;
const environment = yield* HostProcessEnvironment;
return {
type: "managed-cli",
kind: discovery.kind,
label: discovery.label,
installHint: discovery.installHint,
probe: Effect.fn("GitHubSourceControlProvider.discovery")(function* (cwd: string) {
const cli = yield* probeSourceControlProvider({ cwd, process, spec: discovery });
const variable = environmentTokenVariable(environment);
if (variable === null) return cli;
const viewer = yield* api
.rest({ host: "github.com", operation: "discovery", path: "user" })
.pipe(Effect.result);
const login = Result.isSuccess(viewer)
? Option.getOrUndefined(decodeViewer(viewer.success.body))?.login
: undefined;
return {
...cli,
status: "available" as const,
auth:
login !== undefined
? providerAuth({
status: "authenticated",
account: login,
host: "github.com",
detail: `Using the token in ${variable} from the server environment.`,
})
: Result.isFailure(viewer) && viewer.failure._tag !== "GitHubApiAuthenticationError"
? // Only a refusal says the token is bad; a network error or a pause says nothing.
providerAuth({
status: "unknown",
host: "github.com",
detail: `Could not check the token in ${variable}: ${viewer.failure.message}`,
})
: providerAuth({
status: "unauthenticated",
host: "github.com",
detail: `GitHub refused the token in ${variable}. Replace it, or unset it to use \`gh auth login\`.`,
}),
} satisfies SourceControlProviderDiscoveryItem;
}),
refineUnknownRemote: () => Effect.succeed(null),
} satisfies SourceControlManagedCliDiscoverySpec;
});
export const make = Effect.gen(function* () {
const github = yield* GitHubCli.GitHubCli;
const api = yield* GitHubApi.GitHubApi;
const listChangeRequests: SourceControlProvider.SourceControlProvider["Service"]["listChangeRequests"] =
(input) => {
@@ -138,7 +211,7 @@ export const make = Effect.gen(function* () {
reference: SourceControlProvider.transportSafeSourceControlErrorValue(
input.headSelector,
),
detail: error.detail,
detail: error.message,
cause: error,
}),
),
@@ -177,7 +250,7 @@ export const make = Effect.gen(function* () {
reference: SourceControlProvider.transportSafeSourceControlErrorValue(
input.headSelector,
),
detail: error.detail,
detail: error.message,
cause: error,
}),
),
@@ -188,15 +261,15 @@ export const make = Effect.gen(function* () {
input: { readonly cwd: string; readonly url: URL },
endpoint: string,
) {
const result = yield* github
.execute({
cwd: input.cwd,
args: ["api", "--hostname", input.url.host, endpoint, "--jq", "{title, body}"],
env: { GH_PROMPT_DISABLED: "1" },
timeoutMs: 3_000,
maxOutputBytes: 32_000,
const result = yield* api
.rest({
host: input.url.host,
operation: "resolveLink",
path: endpoint,
maxResponseBytes: 1_000_000,
})
.pipe(
Effect.timeout("3 seconds"),
Effect.mapError(
(cause) =>
new SourceControlProviderError({
@@ -208,7 +281,7 @@ export const make = Effect.gen(function* () {
}),
),
);
const subject = yield* decodeLinkSubject(result.stdout).pipe(
const subject = yield* decodeLinkSubject(result.body).pipe(
Effect.mapError(
(cause) =>
new SourceControlProviderError({
@@ -220,7 +293,7 @@ export const make = Effect.gen(function* () {
}),
),
);
return { title: subject.title, body: subject.body };
return { title: subject.title, body: subject.body ?? null };
});
return SourceControlProvider.SourceControlProvider.of({
@@ -255,7 +328,7 @@ export const make = Effect.gen(function* () {
reference: SourceControlProvider.transportSafeSourceControlErrorValue(
input.reference,
),
detail: error.detail,
detail: error.message,
cause: error,
}),
),
@@ -280,7 +353,7 @@ export const make = Effect.gen(function* () {
reference: SourceControlProvider.transportSafeSourceControlErrorValue(
input.headSelector,
),
detail: error.detail,
detail: error.message,
cause: error,
}),
),
@@ -297,7 +370,7 @@ export const make = Effect.gen(function* () {
repository: SourceControlProvider.transportSafeSourceControlErrorValue(
input.repository,
),
detail: error.detail,
detail: error.message,
cause: error,
}),
),
@@ -314,7 +387,7 @@ export const make = Effect.gen(function* () {
repository: SourceControlProvider.transportSafeSourceControlErrorValue(
input.repository,
),
detail: error.detail,
detail: error.message,
cause: error,
}),
),
@@ -335,7 +408,7 @@ export const make = Effect.gen(function* () {
operation: "getDefaultBranch",
command: error.command,
cwd: input.cwd,
detail: error.detail,
detail: error.message,
cause: error,
}),
),
@@ -352,7 +425,7 @@ export const make = Effect.gen(function* () {
reference: SourceControlProvider.transportSafeSourceControlErrorValue(
input.reference,
),
detail: error.detail,
detail: error.message,
cause: error,
}),
),
@@ -16,6 +16,7 @@ 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 GitHubApi from "./GitHubApi.ts";
import * as GitHubCli from "./GitHubCli.ts";
import * as GitLabCli from "./GitLabCli.ts";
import * as ForgejoCli from "./ForgejoCli.ts";
@@ -38,6 +39,7 @@ const layerSourceControlProviderRegistryTest = (input: {
Layer.mock(AzureDevOpsCli.AzureDevOpsCli)({}),
Layer.mock(BitbucketApi.BitbucketApi)(input.bitbucket),
Layer.mock(GitHubCli.GitHubCli)({}),
Layer.mock(GitHubApi.GitHubApi)({}),
Layer.mock(GitLabCli.GitLabCli)({}),
Layer.mock(ForgejoCli.ForgejoCli)({ listLogins: () => Effect.succeed([]) }),
Layer.mock(VcsDriverRegistry.VcsDriverRegistry)({}),
@@ -13,6 +13,7 @@ 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 GitHubApi from "./GitHubApi.ts";
import * as GitHubCli from "./GitHubCli.ts";
import * as GitLabCli from "./GitLabCli.ts";
import * as ForgejoCli from "./ForgejoCli.ts";
@@ -41,6 +42,7 @@ function makeRegistry(input: {
}>;
readonly process?: Partial<VcsProcess.VcsProcess["Service"]>;
readonly github?: Partial<GitHubCli.GitHubCli["Service"]>;
readonly githubApi?: Partial<GitHubApi.GitHubApi["Service"]>;
readonly gitlab?: Partial<GitLabCli.GitLabCli["Service"]>;
readonly resolve?: VcsDriverRegistry.VcsDriverRegistry["Service"]["resolve"];
}) {
@@ -95,6 +97,7 @@ function makeRegistry(input: {
Layer.mock(AzureDevOpsCli.AzureDevOpsCli)({}),
Layer.mock(BitbucketApi.BitbucketApi)({}),
Layer.mock(GitHubCli.GitHubCli)(input.github ?? {}),
Layer.mock(GitHubApi.GitHubApi)(input.githubApi ?? {}),
Layer.mock(GitLabCli.GitLabCli)(input.gitlab ?? {}),
Layer.mock(ForgejoCli.ForgejoCli)({ listLogins: () => Effect.succeed([]) }),
ServerConfig.layerTest(process.cwd(), {
@@ -305,9 +308,15 @@ it.effect(
Effect.gen(function* () {
const registry = yield* makeRegistry({
remotes: [{ name: "origin", url: "https://github.com/unrelated/checkout.git" }],
github: {
execute: () =>
Effect.succeed(processOutput(JSON.stringify({ title: "GitHub issue", body: null }))),
githubApi: {
rest: () =>
Effect.succeed({
status: 200,
headers: {},
body: JSON.stringify({ title: "GitHub issue", body: null }),
truncated: false,
invalidUtf8: false,
}),
},
gitlab: {
execute: () =>
@@ -305,6 +305,7 @@ export const makeWithProviders = Effect.fn("makeSourceControlProviderRegistryWit
export const make = Effect.gen(function* () {
const github = yield* GitHubSourceControlProvider.make;
const githubDiscovery = yield* GitHubSourceControlProvider.makeDiscovery;
const gitlab = yield* GitLabSourceControlProvider.make;
const forgejo = yield* ForgejoSourceControlProvider.make;
const forgejoDiscovery = yield* ForgejoSourceControlProvider.makeDiscovery;
@@ -315,7 +316,7 @@ export const make = Effect.gen(function* () {
{
kind: "github",
provider: github,
discovery: GitHubSourceControlProvider.discovery,
discovery: githubDiscovery,
},
{
kind: "gitlab",
@@ -111,7 +111,6 @@ function normalizeGitHubPullRequestRecord(
}
const decodeGitHubPullRequestList = decodeJsonResult(Schema.Array(Schema.Unknown));
const decodeGitHubPullRequest = decodeJsonResult(GitHubPullRequestSchema);
const decodeGitHubPullRequestEntry = Schema.decodeUnknownExit(GitHubPullRequestSchema);
/**
@@ -139,13 +138,3 @@ export function decodeGitHubPullRequestListJson(
> {
return Result.map(decodeGitHubPullRequestList(raw), decodeGitHubPullRequestEntries);
}
export function decodeGitHubPullRequestJson(
raw: string,
): Result.Result<NormalizedGitHubPullRequestRecord, Cause.Cause<Schema.SchemaError>> {
const result = decodeGitHubPullRequest(raw);
if (Result.isSuccess(result)) {
return Result.succeed(normalizeGitHubPullRequestRecord(result.success));
}
return Result.fail(result.failure);
}