Skip to content

Commit 174540e

Browse files
committed
fix(server): preserve Enterprise targeting after API migration
1 parent a9a7122 commit 174540e

6 files changed

Lines changed: 218 additions & 92 deletions

File tree

‎apps/server/src/pullRequest/PullRequestService.test.ts‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@ import * as Layer from "effect/Layer";
1212
import * as Option from "effect/Option";
1313
import * as Stream from "effect/Stream";
1414
import * as TestClock from "effect/testing/TestClock";
15-
import { ChildProcessSpawner } from "effect/unstable/process";
1615
import type {
1716
OrchestrationProjectShell,
1817
ProjectId,

‎apps/server/src/sourceControl/GitHubCli.test.ts‎

Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,8 @@ import * as VcsProcess from "../vcs/VcsProcess.ts";
1313
import * as GitHubApi from "./GitHubApi.ts";
1414
import * as GitHubCli from "./GitHubCli.ts";
1515
import * as GitHubCredentials from "./GitHubCredentials.ts";
16+
import * as GitHubSourceControlProvider from "./GitHubSourceControlProvider.ts";
17+
import { HostProcessEnvironment } from "@t3tools/shared/hostProcess";
1618

1719
const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
1820

@@ -595,3 +597,110 @@ describe("GitHubCli.checkoutPullRequest", () => {
595597
assert.strictEqual(name("main", false), "main");
596598
});
597599
});
600+
601+
it.live.each([
602+
"[email protected]:team/project.git",
603+
"ssh://[email protected]/team/project.git",
604+
"https://code.example.test/team/project.git",
605+
])("keeps Enterprise operations on the selected remote: %s", (remoteUrl) => {
606+
const graphql: GitHubApi.GitHubGraphQlInput[] = [];
607+
const rest: GitHubApi.GitHubRestInput[] = [];
608+
const api = {
609+
graphql: (input: GitHubApi.GitHubGraphQlInput) =>
610+
Effect.sync(() => {
611+
graphql.push(input);
612+
const pr = {
613+
...node(42, "feature", "team"),
614+
url: "https://code.example.test/team/project/pull/42",
615+
isCrossRepository: false,
616+
headRepository: { name: "project", nameWithOwner: "team/project" },
617+
};
618+
return encodeJson({
619+
data: {
620+
repository:
621+
input.operation === "getPullRequest" ? { pullRequest: pr } : { h0: { nodes: [pr] } },
622+
},
623+
});
624+
}),
625+
rest: (input: GitHubApi.GitHubRestInput) =>
626+
Effect.sync(() => {
627+
rest.push(input);
628+
return restResponse({
629+
full_name: "team/project",
630+
html_url: `https://${input.host}/team/project`,
631+
ssh_url: `git@${input.host}:team/project.git`,
632+
default_branch: "main",
633+
});
634+
}),
635+
};
636+
const { layer, git } = harness({
637+
remotes: remotesOutput(
638+
["origin", "[email protected]:team/project.git"],
639+
["enterprise", remoteUrl],
640+
),
641+
api,
642+
});
643+
return Effect.gen(function* () {
644+
const provider = yield* GitHubSourceControlProvider.make;
645+
const fs = yield* FileSystem.FileSystem;
646+
const bodyFile = yield* fs.makeTempFileScoped({ suffix: ".md" });
647+
yield* fs.writeFileString(bodyFile, "Enterprise PR");
648+
const input = {
649+
cwd: "/repo",
650+
context: {
651+
provider: {
652+
kind: "github" as const,
653+
name: "GitHub Self-Hosted",
654+
baseUrl: "https://code.example.test",
655+
},
656+
remoteName: "enterprise",
657+
remoteUrl,
658+
},
659+
};
660+
for (const state of ["open", "closed"] as const) {
661+
const prs = yield* provider.listChangeRequests({
662+
...input,
663+
state,
664+
headSelector: "feature",
665+
});
666+
assert.strictEqual(prs[0]?.url, "https://code.example.test/team/project/pull/42");
667+
}
668+
yield* provider.getChangeRequest({ ...input, reference: "42" });
669+
yield* provider.getChangeRequest({ ...input, reference: "feature" });
670+
yield* provider.createChangeRequest({
671+
...input,
672+
baseRefName: "main",
673+
headSelector: "feature",
674+
title: "PR",
675+
bodyFile,
676+
});
677+
assert.strictEqual(yield* provider.getDefaultBranch(input), "main");
678+
yield* provider.checkoutChangeRequest({ ...input, reference: "42" });
679+
yield* provider.getRepositoryCloneUrls({ ...input, repository: "team/other" });
680+
yield* provider.getRepositoryCloneUrls({ ...input, repository: "github.com/team/explicit" });
681+
assert.strictEqual(graphql.length, 5);
682+
for (const request of graphql) {
683+
assert.strictEqual(request.host, "code.example.test");
684+
assert.strictEqual(request.variables?.owner, "team");
685+
assert.strictEqual(request.variables?.name, "project");
686+
}
687+
assert.deepStrictEqual(
688+
rest.map(({ host, path }) => [host, path]),
689+
[
690+
["code.example.test", "repos/team/project/pulls"],
691+
["code.example.test", "repos/team/project"],
692+
["code.example.test", "repos/team/other"],
693+
["github.com", "repos/team/explicit"],
694+
],
695+
);
696+
assert.deepStrictEqual(git.find(([name]) => name === "fetchRemoteTrackingBranch")?.[1], {
697+
cwd: "/repo",
698+
remoteName: "enterprise",
699+
remoteBranch: "feature",
700+
});
701+
}).pipe(
702+
Effect.provide(Layer.mergeAll(layer, NodeServices.layer, Layer.mock(GitHubApi.GitHubApi)(api))),
703+
Effect.provideService(HostProcessEnvironment, { GH_REPO: "github.com/wrong/repo" }),
704+
Effect.scoped,
705+
);
706+
});

‎apps/server/src/sourceControl/GitHubCli.ts‎

Lines changed: 19 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -731,7 +731,11 @@ export const make = Effect.gen(function* () {
731731
readonly rateLimitHost?: string | undefined;
732732
readonly allowReserve: boolean;
733733
}) {
734-
const locator = yield* resolveRepository({ cwd: input.cwd, host: input.rateLimitHost, repository: input.repository });
734+
const locator = yield* resolveRepository({
735+
cwd: input.cwd,
736+
host: input.rateLimitHost,
737+
repository: input.repository,
738+
});
735739
const limit = Math.min(Math.max(Math.trunc(input.limit), 1), 100);
736740
// `owner:branch` names a fork's branch. GitHub filters on the branch name only, so the
737741
// owner is matched on the rows it returns.
@@ -784,7 +788,7 @@ export const make = Effect.gen(function* () {
784788
state: "all",
785789
limit: 1,
786790
rateLimitHost: input.rateLimitHost,
787-
repository: input.repository,
791+
repository: input.repository,
788792
allowReserve: true,
789793
}))[0];
790794
if (found === undefined) {
@@ -799,7 +803,11 @@ export const make = Effect.gen(function* () {
799803
const locator =
800804
parsed.kind === "url"
801805
? parsed.locator
802-
: yield* resolveRepository({ cwd: input.cwd, host: input.rateLimitHost, repository: input.repository });
806+
: yield* resolveRepository({
807+
cwd: input.cwd,
808+
host: input.rateLimitHost,
809+
repository: input.repository,
810+
});
803811
const decodeFailure = (cause: unknown) =>
804812
new GitHubPullRequestDecodeError({ command: "gh", cwd: input.cwd, cause });
805813
const decoded = yield* graphqlJson(
@@ -877,8 +885,7 @@ export const make = Effect.gen(function* () {
877885
)(function* (input) {
878886
const reference = parsePullRequestReference(input.reference);
879887
const pullRequest = yield* readPullRequest(input);
880-
const base =
881-
reference.kind === "url" ? reference.locator : yield* resolveRepository(input);
888+
const base = reference.kind === "url" ? reference.locator : yield* resolveRepository(input);
882889
const baseNameWithOwner = `${base.owner}/${base.name}`.toLowerCase();
883890
const headNameWithOwner = pullRequest.headRepositoryNameWithOwner ?? null;
884891
const isCrossRepository =
@@ -898,7 +905,8 @@ export const make = Effect.gen(function* () {
898905
.find(
899906
(match) =>
900907
match !== null &&
901-
gitHubApiHostForRemote(match[2]!) === base.host &&
908+
(gitHubApiHostForRemote(match[2]!) ??
909+
normalizeGitRemoteUrl(match[2]!).split("/")[0]) === base.host &&
902910
normalizeGitRemoteUrl(match[2]!).split("/").slice(1).join("/") ===
903911
nameWithOwner.toLowerCase(),
904912
)?.[1] ?? null;
@@ -1078,7 +1086,11 @@ export const make = Effect.gen(function* () {
10781086
}),
10791087
getDefaultBranch: (input) =>
10801088
Effect.gen(function* () {
1081-
const locator = yield* resolveRepository({ cwd: input.cwd, host: input.rateLimitHost, repository: input.repository });
1089+
const locator = yield* resolveRepository({
1090+
cwd: input.cwd,
1091+
host: input.rateLimitHost,
1092+
repository: input.repository,
1093+
});
10821094
const repository = yield* readRepository(input.cwd, locator);
10831095
const branch = repository.default_branch?.trim() ?? "";
10841096
return branch.length > 0 ? branch : null;

‎apps/server/src/sourceControl/GitHubSourceControlProvider.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -168,6 +168,7 @@ it.effect("lists change request history through the batched head lookup", () =>
168168
state: "all",
169169
limit: 10,
170170
rateLimitHost: "enterprise.test",
171+
repository: "enterprise.test/acme/web",
171172
});
172173
assert.strictEqual(changeRequests[0]?.provider, "github");
173174
assert.strictEqual(changeRequests[0]?.state, "merged");

‎apps/server/src/sourceControl/GitHubSourceControlProvider.ts‎

Lines changed: 44 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -170,7 +170,7 @@ export function parseGitHubAuth(
170170
/**
171171
* Identifies custom GitHub hosts from CLI accounts when DNS naming is inconclusive.
172172
* Matches on host presence, not auth state: `gh auth status --json hosts` lists hosts with
173-
* expired tokens too, and claiming them lets gh's auth error surface as "run `gh auth login`"
173+
* expired tokens too, and claiming them lets the credential error surface as "run `gh auth login`"
174174
* instead of "unsupported host". Returns null without a matching account.
175175
*/
176176
function refineUnknownGitHubRemote(input: SourceControlUnknownRemoteRefinementInput) {
@@ -283,19 +283,21 @@ export const makeDiscovery = Effect.gen(function* () {
283283
} satisfies SourceControlProviderDiscoveryItem;
284284
}),
285285
refineUnknownRemote: ({ cwd, context }) =>
286-
process.run({
287-
operation: "source-control.discovery.refine-unknown-remote",
288-
command: discovery.executable,
289-
args: discovery.authArgs,
290-
cwd,
291-
allowNonZeroExit: true,
292-
timeoutMs: 5_000,
293-
maxOutputBytes: 8_000,
294-
appendTruncationMarker: true,
295-
}).pipe(
296-
Effect.map((auth) => refineUnknownGitHubRemote({ cwd, context, auth })),
297-
Effect.orElseSucceed(() => null),
298-
),
286+
process
287+
.run({
288+
operation: "source-control.discovery.refine-unknown-remote",
289+
command: discovery.executable,
290+
args: discovery.authArgs,
291+
cwd,
292+
allowNonZeroExit: true,
293+
timeoutMs: 5_000,
294+
maxOutputBytes: 8_000,
295+
appendTruncationMarker: true,
296+
})
297+
.pipe(
298+
Effect.map((auth) => refineUnknownGitHubRemote({ cwd, context, auth })),
299+
Effect.orElseSucceed(() => null),
300+
),
299301
} satisfies SourceControlManagedCliDiscoverySpec;
300302
});
301303

@@ -304,7 +306,9 @@ function repositoryTarget(input: {
304306
readonly context?: SourceControlProvider.SourceControlProviderContext;
305307
}) {
306308
if (!input.context) return {};
307-
const host = new URL(input.context.provider.baseUrl).host;
309+
const host =
310+
GitHubCli.gitHubApiHostForRemote(input.context.remoteUrl) ??
311+
new URL(input.context.provider.baseUrl).host;
308312
const remote = normalizeGitRemoteUrl(input.context.remoteUrl);
309313
const path = remote.slice(remote.indexOf("/") + 1);
310314
return { repository: `${host}/${path}` };
@@ -350,7 +354,7 @@ export const make = Effect.gen(function* () {
350354
.listPullRequestsByHead({
351355
cwd: input.cwd,
352356
headSelector: input.headSelector,
353-
...repositoryTarget(input),
357+
...repositoryTarget(input),
354358
state: input.state,
355359
limit: input.limit ?? 20,
356360
...(input.context === undefined
@@ -469,7 +473,7 @@ export const make = Effect.gen(function* () {
469473
cwd: input.cwd,
470474
baseBranch: input.baseRefName,
471475
headSelector: input.headSelector,
472-
...repositoryTarget(input),
476+
...repositoryTarget(input),
473477
title: input.title,
474478
bodyFile: input.bodyFile,
475479
})
@@ -490,27 +494,30 @@ export const make = Effect.gen(function* () {
490494
),
491495
),
492496
getRepositoryCloneUrls: (input) =>
493-
github.getRepositoryCloneUrls({
494-
...input,
495-
repository: input.context && /^[^/]+\/[^/]+$/.test(input.repository)
496-
? `${new URL(input.context.provider.baseUrl).host}/${input.repository}`
497-
: input.repository,
498-
}).pipe(
499-
Effect.mapError(
500-
(error) =>
501-
new SourceControlProviderError({
502-
provider: "github",
503-
operation: "getRepositoryCloneUrls",
504-
command: error.command,
505-
cwd: input.cwd,
506-
repository: SourceControlProvider.transportSafeSourceControlErrorValue(
507-
input.repository,
508-
),
509-
detail: error.message,
510-
cause: error,
511-
}),
497+
github
498+
.getRepositoryCloneUrls({
499+
...input,
500+
repository:
501+
input.context && /^[^/]+\/[^/]+$/.test(input.repository)
502+
? `${new URL(input.context.provider.baseUrl).host}/${input.repository}`
503+
: input.repository,
504+
})
505+
.pipe(
506+
Effect.mapError(
507+
(error) =>
508+
new SourceControlProviderError({
509+
provider: "github",
510+
operation: "getRepositoryCloneUrls",
511+
command: error.command,
512+
cwd: input.cwd,
513+
repository: SourceControlProvider.transportSafeSourceControlErrorValue(
514+
input.repository,
515+
),
516+
detail: error.message,
517+
cause: error,
518+
}),
519+
),
512520
),
513-
),
514521
createRepository: (input) =>
515522
github.createRepository(input).pipe(
516523
Effect.mapError(

0 commit comments

Comments
 (0)