|
| 1 | +import { type CiDescriptor, type CiGitHints } from "@allurereport/core-api"; |
| 2 | + |
| 3 | +import { resolveRepositoryFromGitUrl, stripRefsHeads } from "../helpers/gitProvider.js"; |
| 4 | +import { getEnv } from "../utils.js"; |
| 5 | + |
| 6 | +const parseBranchFromSourceVersion = (sourceVersion: string): string | undefined => { |
| 7 | + const branchMatch = sourceVersion.match(/refs\/heads\/(?<branch>[^/^]+)/)?.groups?.branch; |
| 8 | + |
| 9 | + if (branchMatch) { |
| 10 | + return branchMatch; |
| 11 | + } |
| 12 | + |
| 13 | + const branchTrigger = getEnv("CODEBUILD_WEBHOOK_TRIGGER"); |
| 14 | + |
| 15 | + if (branchTrigger.startsWith("branch/")) { |
| 16 | + return branchTrigger.slice("branch/".length); |
| 17 | + } |
| 18 | + |
| 19 | + return undefined; |
| 20 | +}; |
| 21 | + |
| 22 | +const parsePullRequestFromSourceVersion = (sourceVersion: string): string | undefined => { |
| 23 | + const prPrefixMatch = sourceVersion.match(/^pr\/(?<id>\d+)$/i)?.groups?.id; |
| 24 | + |
| 25 | + if (prPrefixMatch) { |
| 26 | + return prPrefixMatch; |
| 27 | + } |
| 28 | + |
| 29 | + return sourceVersion.match(/refs\/pull\/(?<id>\d+)\//)?.groups?.id; |
| 30 | +}; |
| 31 | + |
| 32 | +const parsePullRequestFromWebhookTrigger = (): string | undefined => { |
| 33 | + const trigger = getEnv("CODEBUILD_WEBHOOK_TRIGGER"); |
| 34 | + |
| 35 | + return trigger.match(/^pr\/(?<id>\d+)$/i)?.groups?.id; |
| 36 | +}; |
| 37 | + |
| 38 | +export const resolveAmazonGitHints = (ci: CiDescriptor): CiGitHints => { |
| 39 | + const repoUrl = getEnv("CODEBUILD_SOURCE_REPO_URL"); |
| 40 | + const repository = repoUrl ? resolveRepositoryFromGitUrl(repoUrl) : undefined; |
| 41 | + |
| 42 | + if (!repository) { |
| 43 | + return {}; |
| 44 | + } |
| 45 | + |
| 46 | + const sourceVersion = getEnv("CODEBUILD_SOURCE_VERSION"); |
| 47 | + const pullRequestId = parsePullRequestFromWebhookTrigger() || parsePullRequestFromSourceVersion(sourceVersion); |
| 48 | + const pullRequest = pullRequestId |
| 49 | + ? { |
| 50 | + id: pullRequestId, |
| 51 | + url: ci.pullRequestUrl || undefined, |
| 52 | + title: ci.pullRequestName || undefined, |
| 53 | + } |
| 54 | + : undefined; |
| 55 | + |
| 56 | + const headRef = getEnv("CODEBUILD_WEBHOOK_HEAD_REF"); |
| 57 | + |
| 58 | + return { |
| 59 | + provider: repository.provider, |
| 60 | + repository: { |
| 61 | + slug: repository.slug, |
| 62 | + url: repository.url, |
| 63 | + }, |
| 64 | + sourceBranch: |
| 65 | + (headRef ? stripRefsHeads(headRef) : undefined) || |
| 66 | + parseBranchFromSourceVersion(sourceVersion) || |
| 67 | + ci.jobRunBranch || |
| 68 | + undefined, |
| 69 | + targetBranch: stripRefsHeads(getEnv("CODEBUILD_WEBHOOK_BASE_REF")) || undefined, |
| 70 | + pullRequest, |
| 71 | + }; |
| 72 | +}; |
0 commit comments