Open History to see the last commit
1import * as Result from "effect/Result";
2
3import type { GitHubAccountSelection, ServerSettings } from "@t3tools/contracts";
4
5export type GitHubCredentialTarget =
6 | { readonly host?: undefined; readonly repositories?: undefined }
7 | { readonly host?: string; readonly repositories: ReadonlyArray<string> };
8
9export interface GitHubCredentialRoute {
10 readonly host: string;
11 readonly key: string;
12 readonly account: GitHubAccountSelection | undefined;
13}
14
15export interface GitHubCredentialRoutingError {
16 readonly _tag: "SelectionConflict";
17 readonly repositories: ReadonlyArray<string>;
18}
19
20type GitHubCredentialSettings = Pick<ServerSettings, "githubAccountRouting">;
21
22function accountKey(host: string, account: GitHubAccountSelection): string {
23 return `${host.toLowerCase()}\n${account.login.toLowerCase()}\n${account.tokenSource}`;
24}
25
26/** Selects an account without reading credentials or performing any other effects. */
27export function selectCredentialRoute(
28 settings: GitHubCredentialSettings,
29 target: GitHubCredentialTarget,
30): Result.Result<GitHubCredentialRoute, GitHubCredentialRoutingError> {
31 const host = (target.host ?? "github.com").toLowerCase();
32 const routing = Object.entries(settings.githubAccountRouting).find(
33 ([accountHost]) => accountHost.toLowerCase() === host,
34 )?.[1];
35 const overrides = new Map(
36 Object.entries(routing?.ownerOverrides ?? {}).map(([owner, account]) => [
37 owner.toLowerCase(),
38 account,
39 ]),
40 );
41 const defaultAccount = routing?.defaultAccount;
42 const repositories = target.repositories ?? [];
43 const accounts =
44 repositories.length === 0
45 ? [defaultAccount]
46 : repositories.map((repository) => {
47 const owner = repository.trim().split("/")[0]?.toLowerCase();
48 return owner === undefined ? defaultAccount : (overrides.get(owner) ?? defaultAccount);
49 });
50 const byKey = new Map(
51 accounts.map((account) => [
52 account === undefined ? `active:${host}` : accountKey(host, account),
53 account,
54 ]),
55 );
56 if (byKey.size > 1) {
57 return Result.fail({ _tag: "SelectionConflict", repositories: [...repositories] });
58 }
59 const [key, account] = byKey.entries().next().value ?? [`active:${host}`, undefined];
60 return Result.succeed({ host, key, account });
61}