Open History to see the last commit
1import type { GitHubSettings, SourceControlProviderAuth } from "@t3tools/contracts";
2
3export type GitHubDiscoveredAccount = NonNullable<SourceControlProviderAuth["accounts"]>[number];
4
5export interface GitHubHostGroup {
6 readonly host: string;
7 /** gh's active stored login, the one used when Settings pin nothing. */
8 readonly activeAccount: string | null;
9 /** Stored logins that work and can be pinned with `gh auth token --user`. */
10 readonly selectable: ReadonlyArray<string>;
11 /** Logins gh holds but cannot use; shown with their error. */
12 readonly broken: ReadonlyArray<GitHubDiscoveredAccount>;
13 /** Set when GH_TOKEN or a sibling overrides every stored login for this host. */
14 readonly environmentVariable: string | null;
15}
16
17/** Groups gh's logins by host, in the order gh reported the hosts. */
18export function groupGitHubAccounts(
19 accounts: ReadonlyArray<GitHubDiscoveredAccount>,
20): ReadonlyArray<GitHubHostGroup> {
21 const hosts = [...new Set(accounts.map((entry) => entry.host))];
22 return hosts.map((host) => {
23 const entries = accounts.filter((entry) => entry.host === host);
24 const stored = entries.filter((entry) => entry.environmentVariable === undefined);
25 const selectable = stored.filter((entry) => entry.authenticated);
26 return {
27 host,
28 activeAccount: (selectable.find((entry) => entry.active) ?? selectable[0])?.account ?? null,
29 selectable: selectable.map((entry) => entry.account),
30 broken: stored.filter((entry) => !entry.authenticated),
31 environmentVariable:
32 entries.find((entry) => entry.environmentVariable)?.environmentVariable ?? null,
33 };
34 });
35}
36
37/**
38 * The full `hosts` map after one host changes. Hosts left on gh's defaults (enabled,
39 * no pinned account) are dropped so settings only hold real choices.
40 */
41export function nextGitHubHosts(
42 current: GitHubSettings["hosts"],
43 host: string,
44 change: { readonly enabled?: boolean; readonly account?: string | null },
45): GitHubSettings["hosts"] {
46 const previous = current[host];
47 const enabled = change.enabled ?? previous?.enabled ?? true;
48 const account = change.account === undefined ? previous?.account : (change.account ?? undefined);
49 const { [host]: _replaced, ...rest } = current;
50 if (enabled && account === undefined) return rest;
51 return { ...rest, [host]: { enabled, ...(account === undefined ? {} : { account }) } };
52}