feat(github): use the right account for each repository #6052
ClosedDominicVonk(GitHub profile, opens in a new tab)wants to merge 20 commits into
main fromrefs/pull/6052/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:XL
- apps/server/src/sourceControl/GitHubCli.ts lines 401 to 415OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -310,0 +395,21 @@395+ const byKey = new Map(396+ accounts.map((account) => [397+ account === undefined ? `active:${host}` : selectionKey(account),398+ account,399+ ]),400+ );401+ if (byKey.size > 1) {402+ return yield* new GitHubCliCommandError({403+ command: "gh",404+ cwd: input.cwd,405+ cause: new Error("Repositories require different GitHub accounts."),406+ });407+ }408+ const account = byKey.values().next().value;409+ if (account !== undefined && account.host.toLowerCase() !== host) {410+ return yield* new GitHubCliAuthenticationError({411+ command: "gh",412+ cwd: input.cwd,413+ cause: new Error("The selected GitHub account belongs to a different host."),414+ });415+ }apps/server/src/sourceControl/GitHubCli.ts lines 426 to 430OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -311,3 +412,19 @@412+ cwd: input.cwd,413+ cause: new Error("The selected GitHub account belongs to a different host."),414+ });415+ }416+ return account;417+ });311418312- const execute: GitHubCli["Service"]["execute"] = (input) =>313- process419+ const tokenFor = Effect.fn("GitHubCli.tokenFor")(function* (input: {420+ readonly account: GitHubAccountSelection;421+ readonly cwd: string;422+ }) {423+ if (GITHUB_TOKEN_ENV_SOURCES.has(input.account.tokenSource)) {424+ const token = process.env[input.account.tokenSource]?.trim();425+ if (token !== undefined && token.length > 0) return token;426+ return yield* new GitHubCliAuthenticationError({427+ command: "gh",428+ cwd: input.cwd,429+ cause: new Error("The selected GitHub token environment variable is unavailable."),430+ });
- apps/server/src/sourceControl/GitHubCli.ts line 458OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -313,0 +438,21 @@438+ .run({439+ operation: "GitHubCli.authToken",440+ command: "gh",441+ args: ["auth", "token", "--hostname", input.account.host, "--user", input.account.login],442+ cwd: input.cwd,443+ timeoutMs: DEFAULT_TIMEOUT_MS,444+ })445+ .pipe(446+ Effect.mapError(447+ (cause) => new GitHubCliAuthenticationError({ command: "gh", cwd: input.cwd, cause }),448+ ),449+ );450+ const token = output.stdout.trim();451+ if (token.length === 0) {452+ return yield* new GitHubCliAuthenticationError({453+ command: "gh",454+ cwd: input.cwd,455+ cause: new Error("GitHub CLI returned an empty account token."),456+ });457+ }458+ tokens.set(key, token);apps/server/src/sourceControl/GitHubSourceControlProvider.ts line 24Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -20,3 +21,4 @@2021 type SourceControlCliDiscoverySpec,2122 } from "./SourceControlProviderDiscovery.ts";222324+function authTarget(context: SourceControlProvider.SourceControlProviderContext | undefined) {apps/web/src/components/settings/SourceControlSettings.tsx lines 444 to 446OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -426,3 +437,10 @@426437 );427438 }428439440+function githubAccountKey(account: GitHubAccountSelection): string {441+ return `${account.host}\n${account.login}\n${account.tokenSource}`;442+}443+444+function githubAccountLabel(account: GitHubAccountSelection): string {445+ return `${account.login} · ${account.tokenSource}`;446+}apps/server/src/sourceControl/GitHubCli.ts lines 481 to 481OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -314,11 +461,21 @@461+462+ const run = (input: Parameters<GitHubCli["Service"]["execute"]>[0], env?: NodeJS.ProcessEnv) =>463+ vcsProcess314464 .run({315465 operation: "GitHubCli.execute",316466 command: "gh",317467 args: input.args,318468 cwd: input.cwd,469+ ...(env !== undefined ? { env } : {}),319470 timeoutMs: input.timeoutMs ?? DEFAULT_TIMEOUT_MS,320471 ...(input.stdin !== undefined ? { stdin: input.stdin } : {}),321472 ...(input.maxOutputBytes !== undefined ? { maxOutputBytes: input.maxOutputBytes } : {}),322473 })323474 .pipe(Effect.mapError((error) => fromVcsError({ command: "gh", cwd: input.cwd }, error)));324475476+ const execute: GitHubCli["Service"]["execute"] = Effect.fn("GitHubCli.execute")(477+ function* (input) {478+ const account = yield* accountSelection(input);479+ if (account === undefined) return yield* run(input);480+481+ const host = input.host ?? "github.com";
- apps/server/src/sourceControl/GitHubCli.ts lines 474 to 484Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -311,3 +413,19 @@413+ cause: new Error("The selected GitHub account belongs to a different host."),414+ });415+ }416+ return account;417+ });311418312- const execute: GitHubCli["Service"]["execute"] = (input) =>313- process419+ const tokenFor = Effect.fn("GitHubCli.tokenFor")(function* (input: {420+ readonly account: GitHubAccountSelection;421+ readonly cwd: string;422+ }) {423+ if (GITHUB_TOKEN_ENV_SOURCES.has(input.account.tokenSource)) {424+ const token = process.env[input.account.tokenSource]?.trim();425+ if (token !== undefined && token.length > 0) return token;426+ return yield* new GitHubCliAuthenticationError({427+ command: "gh",428+ cwd: input.cwd,429+ cause: new Error("The selected GitHub token environment variable is unavailable."),430+ });431+ }apps/server/src/sourceControl/GitHubCli.ts lines 401 to 415OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -310,0 +395,21 @@395+ const byKey = new Map(396+ accounts.map((account) => [397+ account === undefined ? `active:${host}` : selectionKey(account),398+ account,399+ ]),400+ );401+ if (byKey.size > 1) {402+ return yield* new GitHubCliCommandError({403+ command: "gh",404+ cwd: input.cwd,405+ cause: new Error("Repositories require different GitHub accounts."),406+ });407+ }408+ const account = byKey.values().next().value;409+ if (account !== undefined && account.host.toLowerCase() !== host) {410+ return yield* new GitHubCliAuthenticationError({411+ command: "gh",412+ cwd: input.cwd,413+ cause: new Error("The selected GitHub account belongs to a different host."),414+ });415+ }apps/server/src/sourceControl/GitHubCli.ts lines 443 to 452Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -307,4 +356,15 @@307356 }308357309358 export const make = Effect.gen(function* () {310- const process = yield* VcsProcess.VcsProcess;359+ const vcsProcess = yield* VcsProcess.VcsProcess;360+ const settings = yield* ServerSettingsService;361+ const tokens = new Map<string, string>();362+363+ const accountSelection = Effect.fn("GitHubCli.accountSelection")(function* (364+ input: GitHubAuthTarget & { readonly cwd: string },365+ ): Effect.fn.Return<GitHubAccountSelection | undefined, GitHubCliError> {366+ const host = (input.host ?? "github.com").toLowerCase();367+ const current = yield* settings.getSettings.pipe(368+ Effect.mapError(369+ (cause) => new GitHubCliCommandError({ command: "gh", cwd: input.cwd, cause }),370+ ),apps/server/src/sourceControl/GitHubCli.test.ts lines 22 to 24OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -18,10 +19,6 @@18191920 const mockRun = vi.fn<VcsProcess.VcsProcess["Service"]["run"]>();202121-const layer = GitHubCli.layer.pipe(22- Layer.provide(23- Layer.mock(VcsProcess.VcsProcess)({24- run: mockRun,25- }),26- ),27-);22+const layerWithSettings = (overrides: Parameters<typeof ServerSettingsService.layerTest>[0] = {}) =>23+ GitHubCli.layer.pipe(24+ Layer.provide(ServerSettingsService.layerTest(overrides)),
- apps/server/src/sourceControl/GitHubCli.ts lines 534 to 536OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -310,0 +516,21 @@516+ command: "gh",517+ cwd: input.cwd,518+ host: input.account.host,519+ login: input.account.login,520+ tokenSource: input.account.tokenSource,521+ reason: "env-missing",522+ });523+ }524+525+ const output = yield* vcsProcess526+ .run({527+ operation: "GitHubCli.authToken",528+ command: "gh",529+ args: ["auth", "token", "--hostname", input.account.host, "--user", input.account.login],530+ cwd: input.cwd,531+ timeoutMs: DEFAULT_TIMEOUT_MS,532+ })533+ .pipe(534+ Effect.mapError(535+ (cause) => new GitHubCliAuthenticationError({ command: "gh", cwd: input.cwd, cause }),536+ ),
- apps/server/src/sourceControl/GitHubSourceControlProvider.ts line 28Resolvedby DominicVonk(GitHub profile, opens in a new tab)@@ -20,3 +21,15 @@2021 type SourceControlCliDiscoverySpec,2122 } from "./SourceControlProviderDiscovery.ts";222324+function authTarget(context: SourceControlProvider.SourceControlProviderContext | undefined) {25+ if (context === undefined) return {};26+ const [normalizedHost, ...path] = normalizeGitRemoteUrl(context.remoteUrl).split("/");27+ let host = normalizedHost;28+ try {29+ const remote = new URL(context.remoteUrl);30+ host = remote.host.toLowerCase();31+ } catch {32+ // SCP-style remotes have no explicit port and already use the normalized host.33+ }34+ return host && path.length >= 2 ? { host, repository: path.join("/") } : {};35+}
- apps/server/src/sourceControl/GitHubCli.ts lines 15 to 15OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -6,8 +6,10 @@66 import * as Schema from "effect/Schema";7788 import {9+ type GitHubAccountSelection,910 TrimmedNonEmptyString,1011 type SourceControlRepositoryVisibility,1112 type VcsError,1213 } from "@t3tools/contracts";131415+import { ServerSettingsService } from "../serverSettings.ts";
- apps/web/src/components/settings/SourceControlSettings.tsx line 533OutdatedResolvedby DominicVonk(GitHub profile, opens in a new tab)@@ -428,0 +513,21 @@513+ const uniqueAccounts = [514+ ...new Map(accounts.map((account) => [githubAccountKey(account), account])).values(),515+ ];516+ const accountsByHost = new Map<string, GitHubAuthAccount[]>();517+ for (const account of uniqueAccounts) {518+ const host = account.host.toLowerCase();519+ const held = accountsByHost.get(host);520+ if (held === undefined) accountsByHost.set(host, [account]);521+ else held.push(account);522+ }523+ const selectableHosts = [...accountsByHost.entries()].filter(524+ ([, hostAccounts]) => hostAccounts.length > 1,525+ );526+ const selectableAccounts = selectableHosts.flatMap(([, hostAccounts]) => hostAccounts);527+ const initialAccount =528+ selectableAccounts.find((account) => account.active) ?? selectableAccounts[0];529+ const [accountKey, setAccountKey] = useState(530+ initialAccount === undefined ? "" : githubAccountKey(initialAccount),531+ );532+533+ if (selectableAccounts.length === 0) return null;
- apps/web/src/components/settings/SourceControlSettings.tsx line 514OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -428,0 +494,21 @@494+}495+496+function GitHubAccountSettings({497+ accounts,498+}: {499+ readonly accounts: ReadonlyArray<GitHubAuthAccount>;500+}) {501+ const settings = usePrimarySettings();502+ const updateSettings = useUpdatePrimarySettings();503+ const [owner, setOwner] = useState("");504+ const uniqueAccounts = [505+ ...new Map(accounts.map((account) => [githubAccountKey(account), account])).values(),506+ ];507+ const accountsByHost = new Map<string, GitHubAuthAccount[]>();508+ for (const account of uniqueAccounts) {509+ const host = account.host.toLowerCase();510+ const held = accountsByHost.get(host);511+ if (held === undefined) accountsByHost.set(host, [account]);512+ else held.push(account);513+ }514+ const selectableHosts = [...accountsByHost.entries()].filter(
- apps/web/src/components/settings/SourceControlSettings.tsx line 817OutdatedResolvedby DominicVonk(GitHub profile, opens in a new tab)@@ -574,4 +813,5 @@574813 headerAction={hasVersionControlSystems ? null : scanButton}575814 >576815 {result.sourceControlProviders.map((item) => (577- <DiscoveryItemRow key={`provider:${item.kind}`} item={item} />816+ <DiscoveryItemRow key={`provider:${item.kind}`} item={item}>817+ {item.kind === "github" ? (
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:XL
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
- apps/server/src/sourceControl/GitHubCli.ts lines 96 to 148Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -79,0 +85,21 @@85+ {86+ command: Schema.Literal("gh"),87+ cwd: Schema.String,88+ host: Schema.String,89+ reason: GitHubCredentials.GitHubCredentialReason,90+ },91+) {92+ get detail(): string {93+ switch (this.reason._tag) {94+ case "SettingsUnavailable":95+ return `GitHub account settings could not be loaded for ${this.host}.`;96+ case "SelectionConflict":97+ return `Repositories on ${this.host} require different GitHub accounts: ${this.reason.repositories.join(", ")}.`;98+ case "HostMismatch":99+ return `GitHub account ${this.reason.login} belongs to ${this.reason.accountHost}, not ${this.host}.`;100+ case "TokenUnavailable":101+ return this.reason.kind === "env-missing"102+ ? `GitHub token source ${this.reason.tokenSource} is unavailable for ${this.reason.login} on ${this.host}.`103+ : `GitHub CLI returned no token for ${this.reason.login} on ${this.host}.`;104+ }105+ }
- apps/server/src/pullRequest/GitHubPullRequestCli.ts lines 710 to 726Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -702,4 +718,7 @@702718 }703719 : {704720 cwd: input.cwd,721+ host: input.host,722+ ...(input.repositories === undefined ? {} : { repositories: input.repositories }),723+ ...(input.repository === undefined ? {} : { repository: input.repository }),705724 args: ["api", "graphql", "--hostname", input.host, "--input", "-"],
- apps/server/src/pullRequest/GitHubPullRequestCli.ts line 677Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -658,9 +666,12 @@658666 const graphql = (input: {659667 readonly cwd: string;660668 readonly host: string;669+ readonly repository: string;661670 readonly query: string;662671 readonly variables: Readonly<Record<string, string>>;663672 }) =>664673 github665674 .execute({666675 cwd: input.cwd,676+ host: input.host,677+ repositories: [input.repository],
- apps/server/src/sourceControl/GitHubCli.ts line 302Resolvedby DominicVonk(GitHub profile, opens in a new tab)@@ -198,0 +282,21 @@282+ "GITHUB_TOKEN",283+ "GH_ENTERPRISE_TOKEN",284+ "GITHUB_ENTERPRISE_TOKEN",285+]);286+287+function definedAuthTarget(input: GitHubAuthTarget): GitHubAuthTarget {288+ if (input.repositories === undefined) return {};289+ return {290+ ...(input.host === undefined ? {} : { host: input.host }),291+ repositories: input.repositories,292+ };293+}294+295+function repositoryAuthTarget(input: {296+ readonly host?: string | undefined;297+ readonly repository: string;298+}): GitHubAuthTarget {299+ return input.host === undefined300+ ? { repositories: [input.repository] }301+ : { host: input.host, repositories: [input.repository] };302+}
DominicVonk(GitHub profile, opens in a new tab) changed the title
Sign in to join this conversation.




Important
Review skipped#
Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the
.coderabbit.yamlfile in this repository. To trigger a single review, invoke the@coderabbitai reviewcommand.⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID:
eca03658-eba4-438a-8d8d-4bbf6e109c6bYou can disable this status message by setting the
reviews.review_statustofalsein the CodeRabbit configuration file.Use the checkbox below for a quick retry:
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
❤️ Share