| 1 | import type { EnvironmentProject } from "@t3tools/client-runtime/state/models"; |
| 2 | |
| 3 | export type PullRequestEnvironmentTarget = { |
| 4 | readonly environmentId: string; |
| 5 | readonly projectId: string; |
| 6 | readonly repository: string; |
| 7 | readonly host?: string; |
| 8 | }; |
| 9 | |
| 10 | /** |
| 11 | * Another connected environment holding the pull request's repository, for when the one it was |
| 12 | * opened in is unreachable. Null while the original is connected or no other copy exists. |
| 13 | */ |
| 14 | export function pullRequestFallbackEnvironment( |
| 15 | target: PullRequestEnvironmentTarget, |
| 16 | projects: ReadonlyArray<EnvironmentProject>, |
| 17 | connectedEnvironmentIds: ReadonlySet<string>, |
| 18 | ) { |
| 19 | if (connectedEnvironmentIds.has(target.environmentId)) return null; |
| 20 | const own = projects.find( |
| 21 | (project) => project.environmentId === target.environmentId && project.id === target.projectId, |
| 22 | ); |
| 23 | const host = target.host ?? own?.repositoryIdentity?.canonicalKey.split("/")[0]; |
| 24 | if (!host) return null; |
| 25 | const key = `${host}/${target.repository}`.toLowerCase(); |
| 26 | const copy = projects.find( |
| 27 | (project) => |
| 28 | project.environmentId !== target.environmentId && |
| 29 | connectedEnvironmentIds.has(project.environmentId) && |
| 30 | project.repositoryIdentity?.canonicalKey.toLowerCase() === key, |
| 31 | ); |
| 32 | return copy ? { environmentId: String(copy.environmentId), projectId: String(copy.id) } : null; |
| 33 | } |