feat: GitHub Enterprise source control connector #5089
ClosedJorrinKievit(GitHub profile, opens in a new tab)wants to merge 63 commits into
main fromrefs/pull/5089/headopened View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
- apps/server/src/sourceControl/GitHubSourceControlProvider.ts lines 271 to 273OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -102,0 +253,21 @@253+ cwd: input.cwd,254+ repository: SourceControlProvider.transportSafeSourceControlErrorValue(repository),255+ detail: error.detail,256+ cause: error,257+ }),258+ ),259+ Effect.flatMap((results) => {260+ const match = pickRepositorySearchMatch(repository, results);261+ if (match) {262+ return Effect.succeed(match);263+ }264+ return Effect.fail(265+ new SourceControlProviderError({266+ provider: kind,267+ operation: "getRepositoryCloneUrls",268+ command: "gh",269+ cwd: input.cwd,270+ repository: SourceControlProvider.transportSafeSourceControlErrorValue(repository),271+ detail: `No repository named "${repository}" was found on ${272+ input.host ?? "the configured host"273+ }.`,
- apps/server/src/sourceControl/GitHubSourceControlProvider.ts lines 223 to 223OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -98,0 +203,21 @@203+function isBareRepositoryName(repository: string): boolean {204+ return !repository.includes("/");205+}206+207+// Bare names resolve against the caller's personal namespace on `gh repo208+// view`, which is usually empty on an enterprise host. Prefer the search209+// result whose repo-name segment matches the query exactly (search ranking210+// otherwise happily puts e.g. "core-documentation" ahead of "core").211+function pickRepositorySearchMatch(212+ query: string,213+ results: ReadonlyArray<GitHubCli.GitHubRepositorySearchResult>,214+): string | null {215+ if (results.length === 0) {216+ return null;217+ }218+219+ const normalizedQuery = query.toLowerCase();220+ const exact = results.find(221+ (result) => result.fullName.split("/").pop()?.toLowerCase() === normalizedQuery,222+ );223+ return (exact ?? results[0]!).fullName;apps/web/src/components/GitActionsControl.tsx line 452Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -402,3 +377,19 @@402377 [props.environmentId, props.gitCwd],403378 );404379 const publishRepositoryAction = useSourceControlPublishRepositoryAction(sourceControlScope);380+ const [selectedEnterpriseHost, setSelectedEnterpriseHost] = useState<string | null>(null);381+ const enterpriseHosts = useMemo(() => {382+ const sourceControlProviders = sourceControlDiscovery.data?.sourceControlProviders ?? [];383+ return sourceControlProviders384+ .filter((item) => item.kind === "github-enterprise" && item.status === "available")385+ .flatMap((item) => {386+ const host = Option.getOrNull(item.host);387+ return host ? [host] : [];388+ })389+ .toSorted((left, right) => left.localeCompare(right));390+ }, [sourceControlDiscovery.data]);391+ const activeEnterpriseHost = resolveSelectedEnterpriseHost({392+ selectedHost: selectedEnterpriseHost,393+ availableHosts: enterpriseHosts,394+ });395+ const enterprisePublishProviderOptions = useMemo<ReadonlyArray<PublishProviderOption>>(() => {
- apps/web/src/components/GitActionsControl.tsx line 721OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -680,5 +702,20 @@680- </span>702+ {option.value === "github-enterprise" ? (703+ <span className="min-w-0 flex-1">704+ <span className="block truncate text-sm font-medium text-foreground">705+ {option.label}706+ </span>707+ <span className="block truncate text-xs text-muted-foreground">708+ {option.description}709+ </span>710+ </span>711+ ) : (712+ <span className="min-w-0 flex-1 truncate text-sm font-medium text-foreground">713+ {option.label}714+ </span>715+ )}681716 </RadioPrimitive.Root>682717 );683718 })}684719 </RadioGroup>720+721+ {publishProvider === "github-enterprise" && enterpriseHosts.length > 0 ? (
- apps/web/src/components/GitActionsControl.logic.ts line 477OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -415,0 +457,21 @@457+}458+459+/**460+ * Defaulting to the first host alphabetically strands the user when that host461+ * is the unauthenticated one: its card renders as "Setup Required" rather than462+ * a radio, and the host picker only exists once the card is selected. Prefer a463+ * ready host so there is always a way in.464+ */465+export function resolveSelectedEnterpriseHost(input: {466+ selectedHost: string | null;467+ availableHosts: ReadonlyArray<string>;468+ readyHosts: ReadonlyArray<string>;469+}): string | null {470+ if (input.selectedHost !== null && input.availableHosts.includes(input.selectedHost)) {471+ return input.selectedHost;472+ }473+ return (474+ input.availableHosts.find((host) => input.readyHosts.includes(host)) ??475+ input.availableHosts[0] ??476+ null477+ );
- apps/server/src/sourceControl/GitHubSourceControlProvider.ts line 257Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -98,0 +214,21 @@214+// Bare names resolve against the caller's personal namespace on `gh repo215+// view`, which is usually empty on an enterprise host. Prefer the search216+// result whose repo-name segment matches the query exactly (search ranking217+// otherwise happily puts e.g. "core-documentation" ahead of "core"). Several218+// owners can hold the same repo name, and search ranking is no basis for219+// picking between them, so report that back instead of guessing.220+function pickRepositorySearchMatch(221+ query: string,222+ results: ReadonlyArray<GitHubCli.GitHubRepositorySearchResult>,223+): RepositorySearchMatch {224+ if (results.length === 0) {225+ return { _tag: "none" };226+ }227+228+ const normalizedQuery = query.toLowerCase();229+ const exact = results.filter(230+ (result) => result.fullName.split("/").pop()?.toLowerCase() === normalizedQuery,231+ );232+ if (exact.length > 1) {233+ return { _tag: "ambiguous", candidates: exact.map((result) => result.fullName) };234+ }
- apps/web/src/components/GitActionsControl.logic.ts line 470Resolvedby JorrinKievit(GitHub profile, opens in a new tab)@@ -415,0 +449,21 @@449+ return {450+ ready: false,451+ hint:452+ Option.getOrNull(discovered.auth.detail) ??453+ `${discovered.label} is not authenticated. Open Settings -> Source Control for setup guidance.`,454+ };455+ }456+ return { ready: true, hint: null };457+}458+459+/**460+ * Defaulting to the first host alphabetically strands the user when that host461+ * is the unauthenticated one: its card renders as "Setup Required" rather than462+ * a radio, and the host picker only exists once the card is selected. Prefer a463+ * ready host so there is always a way in.464+ */465+export function resolveSelectedEnterpriseHost(input: {466+ selectedHost: string | null;467+ availableHosts: ReadonlyArray<string>;468+ readyHosts: ReadonlyArray<string>;469+}): string | null {
- apps/server/src/sourceControl/GitHubSourceControlProvider.ts line 261OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -98,0 +241,21 @@241+242+export const makeProvider = (kind: GitHubProviderKind) =>243+ Effect.gen(function* () {244+ const github = yield* GitHubCli.GitHubCli;245+246+ const resolveRepositoryReference = (input: {247+ readonly cwd: string;248+ readonly repository: string;249+ readonly host?: string;250+ }): Effect.Effect<string, SourceControlProviderError> => {251+ const repository = input.repository.trim();252+ if (kind !== "github-enterprise" || !isBareRepositoryName(repository)) {253+ return Effect.succeed(repository);254+ }255+256+ return github257+ .searchRepositories({258+ cwd: input.cwd,259+ query: repository,260+ ...(input.host ? { host: input.host } : {}),261+ })
- apps/web/src/components/GitActionsControl.tsx line 601Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -508,3 +554,4 @@508554 })();509555 }, [510556 canSubmitPublishRepository,557+ currentPublishProvider,
- apps/server/src/sourceControl/GitHubSourceControlProvider.ts line 324Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -98,0 +232,21 @@232+ if (exact.length === 1) {233+ return { _tag: "match", fullName: exact[0]!.fullName };234+ }235+ const candidates = exact.length > 1 ? exact : results;236+ if (candidates.length > 1) {237+ return { _tag: "ambiguous", candidates: candidates.map((result) => result.fullName) };238+ }239+ return { _tag: "match", fullName: candidates[0]!.fullName };240+}241+242+export const makeProvider = (kind: GitHubProviderKind) =>243+ Effect.gen(function* () {244+ const github = yield* GitHubCli.GitHubCli;245+246+ const resolveRepositoryReference = (input: {247+ readonly cwd: string;248+ readonly repository: string;249+ readonly host?: string;250+ }): Effect.Effect<string, SourceControlProviderError> => {251+ const repository = input.repository.trim();252+ if (kind !== "github-enterprise" || !isBareRepositoryName(repository)) {
- apps/server/src/sourceControl/GitHubSourceControlProvider.ts lines 300 to 300OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -98,0 +280,21 @@280+ Effect.mapError(281+ (error) =>282+ new SourceControlProviderError({283+ provider: kind,284+ operation: "getRepositoryCloneUrls",285+ command: error.command,286+ cwd: input.cwd,287+ repository: SourceControlProvider.transportSafeSourceControlErrorValue(repository),288+ detail: error.detail,289+ cause: error,290+ }),291+ ),292+ Effect.flatMap((results) => {293+ const match = pickRepositorySearchMatch(repository, results);294+ if (match._tag === "match") {295+ return Effect.succeed(match.fullName);296+ }297+298+ const safeRepository =299+ SourceControlProvider.transportSafeSourceControlErrorValue(repository);300+ const hostLabel = input.host ?? "the configured host";
- apps/server/src/git/GitManager.ts line 2023Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -1597,4 +1597,4 @@15971597 const rangeContext = yield* gitCore.readRangeContext(cwd, baseRangeRef);15981598 const policy = yield* resolveStylePolicy(cwd, settings.style);15991599 const changeRequestTemplate =1600- settings.style.followChangeRequestTemplates && provider.kind === "github"1600+ settings.style.followChangeRequestTemplates &&
- apps/server/src/sourceControl/GitHubSourceControlProvider.ts line 468OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -201,0 +448,21 @@448+ bodyFile: input.bodyFile,449+ })450+ .pipe(451+ Effect.mapError(452+ (error) =>453+ new SourceControlProviderError({454+ provider: kind,455+ operation: "createChangeRequest",456+ command: error.command,457+ cwd: input.cwd,458+ reference: SourceControlProvider.transportSafeSourceControlErrorValue(459+ input.headSelector,460+ ),461+ detail: error.detail,462+ cause: error,463+ }),464+ ),465+ ),466+ getRepositoryCloneUrls: (input) =>467+ ensureEnterpriseHost({ ...input, operation: "getRepositoryCloneUrls" }).pipe(468+ Effect.andThen(() => resolveRepositoryReference(input)),
- apps/server/src/git/GitManager.ts line 2023Resolvedby JorrinKievit(GitHub profile, opens in a new tab)@@ -1677,4 +1677,4 @@16771677 const rangeContext = yield* gitCore.readRangeContext(cwd, baseRangeRef);16781678 const policy = yield* resolveStylePolicy(cwd, settings.style);16791679 const changeRequestTemplate =1680- settings.style.followChangeRequestTemplates && provider.kind === "github"1680+ settings.style.followChangeRequestTemplates &&
- packages/shared/src/sourceControl.ts line 188OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -168,4 +181,8 @@168181 }169182170183 function isGitHubHost(host: string): boolean {171- return host === "github.com" || host.includes("github");184+ return host === "github.com";185+}186+187+function isGitHubEnterpriseHost(host: string): boolean {188+ return host !== "github.com" && (host.endsWith(".ghe.com") || host.includes("github"));
- apps/server/src/sourceControl/GitHubCli.ts lines 356 to 356OutdatedResolvedby JorrinKievit(GitHub profile, opens in a new tab)@@ -316,3 +353,4 @@316353 command: "gh",317354 args: input.args,318355 cwd: input.cwd,356+ ...(input.host ? { env: { ...globalThis.process.env, GH_HOST: input.host } } : {}),
- apps/server/src/pullRequest/GitHubPullRequestProvider.ts line 122OutdatedResolvedby JorrinKievit(GitHub profile, opens in a new tab)@@ -133,19 +121,2 @@133- .pipe(134- Effect.mapError(fail("listChangeRequests")),135- Effect.flatMap((page) =>136- cli137- .listActorAvatars({138- cwd: input.cwd,139- repository: input.repository,140- host: input.host,141- ids: [...new Set(page.items.flatMap((item) => item.authorId ?? []))],142- })143- // A listing without faces is still a listing, so a failed lookup falls back to144- // the initials rather than taking the rows down with it.145- .pipe(146- Effect.orElseSucceed(() => new Map<string, string>()),147- Effect.map((avatarsByLogin) => ({148- ...page,149- items: page.items.map((item) => ({150- ...item,151- author: withAvatar(item.author, avatarsByLogin, input.host),121+ getViewer: (input) =>122+ cli.getViewerLogin({ cwd: input.cwd }).pipe(Effect.mapError(fail("getViewer"))),
- apps/web/src/pullRequestReference.ts line 5Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -1,2 +1,2 @@11 const GITHUB_PULL_REQUEST_URL_PATTERN =2- /^https:\/\/github\.com\/[^/\s]+\/[^/\s]+\/pull\/(\d+)(?:[/?#].*)?$/i;2+ /^https:\/\/[^/\s]+\/[^/\s]+\/[^/\s]+\/pull\/(\d+)(?:[/?#].*)?$/i;
- apps/web/src/lib/openPullRequestLink.ts line 117OutdatedResolvedby JorrinKievit(GitHub profile, opens in a new tab)@@ -115,4 +111,7 @@115111 const match = /^\/((?:[^/]+\/)*_git\/[^/]+)\/pullrequest\/(\d+)(?:\/|$)/u.exec(url.pathname);116112 return claim(host, match);117113 }118- return null;114+ // GitHub, and any Enterprise install: /{owner}/{repo}/pull/{n}. An Enterprise host is named115+ // whatever its admin chose, so there is no hostname to ask about — a `ghe.com` tenant and a116+ // refined `git.corp.com` are as much GitHub as github.com is.117+ return claim(host, /^\/([^/]+\/[^/]+)\/pull\/(\d+)(?:\/|$)/u.exec(url.pathname));
- apps/server/src/sourceControl/GitHubCli.ts line 584Resolvedby JorrinKievit(GitHub profile, opens in a new tab)@@ -417,0 +468,21 @@468+ "--json",469+ "fullName",470+ ],471+ ...(input.host ? { host: input.host } : {}),472+ }).pipe(473+ Effect.map((result) => result.stdout.trim()),474+ Effect.flatMap((raw) =>475+ raw.length === 0476+ ? Effect.succeed([])477+ : decodeRawGitHubRepositorySearchResults(raw).pipe(478+ Effect.mapError(479+ (cause) =>480+ new GitHubRepositorySearchDecodeError({481+ command: "gh",482+ cwd: input.cwd,483+ cause,484+ }),485+ ),486+ ),487+ ),488+ ),
- apps/server/src/sourceControl/GitHubCli.ts line 391OutdatedResolvedby JorrinKievit(GitHub profile, opens in a new tab)@@ -349,3 +386,6 @@349386 command: "gh",350387 args: input.args,351388 cwd: input.cwd,389+ // `extendEnv` follows `env` down in the runner, so the host environment is merged in and390+ // this is the override alone.391+ ...(input.host ? { env: { GH_HOST: input.host } } : {}),packages/client-runtime/src/operations/projects.ts line 126Resolvedby JorrinKievit(GitHub profile, opens in a new tab)@@ -108 +103,21 @@108103104+const URL_TARGET: AddProjectRemoteTarget = { id: "url", source: "url", host: null };105+106+const BASE_PROVIDER_KINDS: ReadonlyArray<AddProjectRemoteProviderKind> = [107+ "github",108+ "gitlab",109+ "bitbucket",110+ "azure-devops",111+];112+113+const BASE_PROVIDER_TARGETS: ReadonlyArray<AddProjectRemoteTarget> = BASE_PROVIDER_KINDS.map(114+ (kind) => ({ id: kind, source: kind, host: null }),115+);116+117+export function buildAddProjectRemoteTargets(118+ discovery: SourceControlDiscoveryResult | null,119+): ReadonlyArray<AddProjectRemoteTarget> {120+ if (!discovery) return [URL_TARGET, ...BASE_PROVIDER_TARGETS];121+ return [122+ URL_TARGET,123+ ...discovery.sourceControlProviders.flatMap((provider) =>packages/client-runtime/src/operations/projects.ts line 216Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -174,15 +193,16 @@174- }193+ for (const provider of discovery.sourceControlProviders) {194+ if (provider.kind === "unknown") continue;175195 if (provider.status !== "available") {176- readiness[source] = { ready: false, hint: provider.installHint };196+ readiness.set(provider.id, { ready: false, hint: provider.installHint });177197 continue;178198 }179199 if (provider.auth.status === "unauthenticated") {180- readiness[source] = {200+ readiness.set(provider.id, {181201 ready: false,182202 hint:183203 Option.getOrNull(provider.auth.detail) ??184204 `${provider.label} is not authenticated. Open Source Control settings for setup guidance.`,185- };205+ });186206 continue;187207 }188- readiness[source] = { ready: true, hint: null };208+ readiness.set(provider.id, { ready: true, hint: null });
juliusmarminge closed this
Sign in to join this conversation.


Note
Reviews paused#
It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the
reviews.auto_review.auto_pause_after_reviewed_commitssetting.Use the following commands to manage reviews:
@coderabbitai resumeto resume automatic reviews.@coderabbitai reviewto trigger a single review.Use the checkboxes below for quick actions:
📝 Walkthrough
Walkthrough#
The change adds GitHub Enterprise and Forgejo as host-aware source control targets. It updates provider discovery, repository and pull request operations, project cloning, publishing, URL parsing, settings, and mobile presentation.
Changes#
GitHub Enterprise and Forgejo source control
packages/contracts/...,apps/server/src/sourceControl/...,packages/shared/src/sourceControl.tsapps/server/src/sourceControl/GitHubCli.ts,apps/server/src/sourceControl/GitHubSourceControlProvider.ts,apps/server/src/sourceControl/SourceControlRepositoryService.tsapps/server/src/pullRequest/*,apps/server/src/git/GitManager.tspackages/client-runtime/src/operations/projects.ts,apps/web/src/components/CommandPalette.tsx,apps/mobile/src/features/projects/*apps/web/src/components/GitActionsControl.tsx,apps/web/src/state/sourceControlActions.ts,apps/web/src/components/GitActionsControl.logic.tspackages/shared/src/changeRequestUrl.ts,apps/web/src/pullRequestReference.ts,apps/web/src/components/settings/SourceControlSettings.tsx,apps/mobile/src/components/SourceControlIcon.tsxPriority: ➖ Normal
Estimated code review effort: 5 (Critical) | ~90 minutes
Change: Feature · Severity of issue fixed: Medium
Sequence Diagram(s)#
Suggested reviewers:
maria-rcks,bil0000Merge Risk: 🟠 High · up to
a5b75Authenticated operations can target the wrong GitHub host or expose Forgejo tokens over HTTP, while valid pull requests and provider choices can be rejected or hidden. These issues should be fixed before merge.
🚥 Pre-merge checks | ✅ 3 | ❌ 2
❌ Failed checks (2 warnings)#
#5087. The changes add Forgejo provider registration, Forgejo icons and add-project targets, Forgejo publish handling, and F…#5087.✅ Passed checks (3 passed)
#5087requires authenticated enterprise-host discovery, separate provider instances, enterprise remote classification, host-targeted repository and pull-request operations, cloning, publishing, …Full details: Out of Scope Changes check
Explanation
The pull request adds Forgejo/Gitea functionality that is not part of Issue
#5087. The changes add Forgejo provider registration, Forgejo icons and add-project targets, Forgejo publish handling, and Forgejo pull-request URL and CLI parsing. The linked issue only requires GitHub Enterprise support. The added Forgejo behavior is not required to implement the GitHub Enterprise objectives.✨ Finishing Touches
🧪 Generate unit tests (beta)
Comment `@coderabbitai help` to get the list of available commands.