From b89900ac595a55b16db3de75454064fb18b01ca9 Mon Sep 17 00:00:00 2001 From: Alex Skrypnyk Date: Tue, 24 Apr 2018 20:35:11 +1000 Subject: [PATCH] Fixed not correctly working in detached repo. --- src/ArtefactTrait.php | 40 +++++++++++++++++++++++++++++++++++++++- tests/TagTest.php | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 73 insertions(+), 1 deletion(-) create mode 100644 tests/TagTest.php diff --git a/src/ArtefactTrait.php b/src/ArtefactTrait.php index 12cd80f..a474345 100644 --- a/src/ArtefactTrait.php +++ b/src/ArtefactTrait.php @@ -257,7 +257,7 @@ protected function resolveOptions(array $options) $srcPath = !empty($options['src']) ? $this->fsGetAbsolutePath($options['src']) : $this->fsGetRootDir(); $this->gitSetSrcRepo($srcPath); - $this->originalBranch = $this->gitGetCurrentBranch($this->src); + $this->originalBranch = $this->resolveOriginalBranch($this->src); $this->setDstBranch($options['branch']); $this->artefactBranch = $this->dstBranch.'-artefact'; @@ -388,6 +388,44 @@ public static function modeDiff() return 'diff'; } + /** + * Resolve original branch to handle detached repositories. + * + * Usually, repository become detached when a tag is checked out. + * + * @param string $location + * Path to repository. + * + * @return null|string + * Branch or detachment source. + * @throws \Exception + * If neither branch nor detachment source is not found. + */ + protected function resolveOriginalBranch($location) + { + $branch = $this->gitGetCurrentBranch($location); + + // Repository could be in detached state. If this the case - we need to + // capture the source of detachment, if exist. + if ($branch == 'HEAD') { + $branch = null; + $result = $this->gitCommandRun($location, 'branch'); + $branchList = array_filter(preg_split('/\R/', $result->getMessage())); + + foreach ($branchList as $branch) { + if (preg_match('/\* \(.*detached .* ([^\)]+)\)/', $branch, $matches)) { + $branch = $matches[1]; + break; + } + } + if (empty($branch)) { + throw new \Exception('Unable to determine detachment source'); + } + } + + return $branch; + } + /** * Set the branch in the remote repository where commits will be pushed to. * diff --git a/tests/TagTest.php b/tests/TagTest.php new file mode 100644 index 0000000..a4f685c --- /dev/null +++ b/tests/TagTest.php @@ -0,0 +1,34 @@ +mode = 'force-push'; + parent::setUp(); + } + + public function testDetachedTag() + { + $this->gitCreateFixtureCommits(2); + $this->gitAddTag($this->src, 'tag1'); + $this->gitCheckout($this->src, 'tag1'); + $srcBranches = $this->runGitCommand('branch'); + + $output = $this->assertBuildSuccess(); + $this->assertContains('Mode: force-push', $output); + $this->assertContains('Will push: Yes', $output); + + $this->assertFixtureCommits(2, $this->dst, 'testbranch', ['Deployment commit']); + $this->assertEquals($srcBranches, $this->runGitCommand('branch'), 'Cleanup has correctly returned to the previous branch.'); + } +}