| 1 | import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients"; |
| 2 | |
| 3 | const PULL_REQUEST_NUMBER_PATTERN = /^#?(\d+)$/; |
| 4 | |
| 5 | /** |
| 6 | * The change request a pasted reference names: a host's change request URL, returned as is, or |
| 7 | * a bare number. A host's checkout command, such as `gh pr checkout 42`, is read for its |
| 8 | * argument first. Null for anything else, such as a branch name. |
| 9 | */ |
| 10 | export function parsePullRequestReference(input: string): string | null { |
| 11 | const trimmed = input.trim(); |
| 12 | if (trimmed.length === 0) { |
| 13 | return null; |
| 14 | } |
| 15 | |
| 16 | const normalizedInput = |
| 17 | sourceControlClients.definitions |
| 18 | .map((definition) => definition.checkoutCommandArgument(trimmed)) |
| 19 | .find((argument) => argument !== null) ?? trimmed; |
| 20 | if (normalizedInput.length === 0) { |
| 21 | return null; |
| 22 | } |
| 23 | |
| 24 | if ( |
| 25 | sourceControlClients.definitions.some((definition) => |
| 26 | definition.isChangeRequestReference(normalizedInput), |
| 27 | ) |
| 28 | ) { |
| 29 | return normalizedInput; |
| 30 | } |
| 31 | |
| 32 | const numberMatch = PULL_REQUEST_NUMBER_PATTERN.exec(normalizedInput); |
| 33 | if (numberMatch?.[1]) { |
| 34 | return numberMatch[1]; |
| 35 | } |
| 36 | |
| 37 | return null; |
| 38 | } |