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:
1 parent
adc3c9327a
commit
649418f01f
13 files changed
+1403
-1777
No files matched your search
@@ -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);
|
||||
}
|
||||
Reference in new issue
Block a user