|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Hypernode\Deploy\Stdlib; |
| 4 | + |
| 5 | +use function Deployer\get; |
| 6 | + |
| 7 | +class TargetFinder |
| 8 | +{ |
| 9 | + public function getTarget(): string |
| 10 | + { |
| 11 | + $branch = get('branch', 'HEAD'); |
| 12 | + if (!empty($branch) && $branch != 'HEAD') { |
| 13 | + return $branch; |
| 14 | + } |
| 15 | + |
| 16 | + $branch = $this->getBranchFromCI(); |
| 17 | + if (!empty($branch)) { |
| 18 | + return $branch; |
| 19 | + } |
| 20 | + |
| 21 | + return get('branch', 'HEAD'); |
| 22 | + } |
| 23 | + |
| 24 | + private function getBranchFromCI(): ?string |
| 25 | + { |
| 26 | + // Check GitHub Actions |
| 27 | + if ($githubBranch = getenv('GITHUB_HEAD_REF')) { |
| 28 | + return $githubBranch; |
| 29 | + } |
| 30 | + if ($githubBaseRef = getenv('GITHUB_REF')) { |
| 31 | + return $this->parseGithubRef($githubBaseRef); |
| 32 | + } |
| 33 | + |
| 34 | + // Check GitLab CI |
| 35 | + if ($gitlabBranch = getenv('CI_COMMIT_REF_NAME')) { |
| 36 | + return $gitlabBranch; |
| 37 | + } |
| 38 | + |
| 39 | + // Check Bitbucket Pipelines |
| 40 | + if ($bitbucketBranch = getenv('BITBUCKET_BRANCH')) { |
| 41 | + return $bitbucketBranch; |
| 42 | + } |
| 43 | + |
| 44 | + // Check Azure Pipelines |
| 45 | + if ($azureBranch = getenv('BUILD_SOURCEBRANCH')) { |
| 46 | + return $this->parseAzureBranch($azureBranch); |
| 47 | + } |
| 48 | + |
| 49 | + return null; |
| 50 | + } |
| 51 | + |
| 52 | + private function parseGithubRef(string $ref): ?string |
| 53 | + { |
| 54 | + // Extract branch or tag name from refs/heads/ or refs/tags/ |
| 55 | + if (preg_match('#refs/heads/(.+)#', $ref, $matches)) { |
| 56 | + return $matches[1]; |
| 57 | + } |
| 58 | + if (preg_match('#refs/tags/(.+)#', $ref, $matches)) { |
| 59 | + return $matches[1]; |
| 60 | + } |
| 61 | + |
| 62 | + return null; |
| 63 | + } |
| 64 | + |
| 65 | + private function parseAzureBranch(string $branch): ?string |
| 66 | + { |
| 67 | + // Extract branch name from refs/heads/ |
| 68 | + if (strpos($branch, 'refs/heads/') === 0) { |
| 69 | + return substr($branch, strlen('refs/heads/')); |
| 70 | + } |
| 71 | + |
| 72 | + return $branch; |
| 73 | + } |
| 74 | +} |
0 commit comments