From 9fea656e75ad6e3452feb2cac46a6c1239cd7f74 Mon Sep 17 00:00:00 2001 From: Pieter Hoste Date: Thu, 11 May 2023 10:29:06 +0200 Subject: [PATCH] Adds feature to check if a branch name exists in a repository without cloning it. (#202) --- src/Gitonomy/Git/Admin.php | 24 ++++++++++++++++++++++++ tests/Gitonomy/Git/Tests/AdminTest.php | 18 ++++++++++++++++++ 2 files changed, 42 insertions(+) diff --git a/src/Gitonomy/Git/Admin.php b/src/Gitonomy/Git/Admin.php index 7b64cd77..7b32794c 100644 --- a/src/Gitonomy/Git/Admin.php +++ b/src/Gitonomy/Git/Admin.php @@ -67,6 +67,30 @@ public static function isValidRepository($url, array $options = []) return $process->isSuccessFul(); } + /** + * Checks the validity of a git repository url without cloning it and + * check if a certain branch exists in that repository. + * + * This will use the `ls-remote` command of git against the given url. + * Usually, this command returns 0 when successful, and 128 when the + * repository is not found. + * + * @param string $url url of repository to check + * @param string $branchName name of branch to check + * @param array $options options for Repository creation + * + * @return bool true if url is valid and branch exists + */ + public static function isValidRepositoryAndBranch($url, $branchName, array $options = []) + { + $process = static::getProcess('ls-remote', ['--heads', $url, $branchName], $options); + + $process->run(); + $processOutput = $process->getOutput(); + + return $process->isSuccessFul() && strpos($processOutput, $branchName) !== false; + } + /** * Clone a repository to a local path. * diff --git a/tests/Gitonomy/Git/Tests/AdminTest.php b/tests/Gitonomy/Git/Tests/AdminTest.php index 3bd29f50..0f7460fa 100644 --- a/tests/Gitonomy/Git/Tests/AdminTest.php +++ b/tests/Gitonomy/Git/Tests/AdminTest.php @@ -155,6 +155,24 @@ public function testCheckInvalidRepository() $this->assertFalse(Admin::isValidRepository($url)); } + /** + * @dataProvider provideFoobar + */ + public function testCheckValidRepositoryAndBranch($repository) + { + $url = $repository->getGitDir(); + $this->assertTrue(Admin::isValidRepositoryAndBranch($url, 'master')); + } + + /** + * @dataProvider provideFoobar + */ + public function testCheckInvalidRepositoryAndBranch($repository) + { + $url = $repository->getGitDir(); + $this->assertFalse(Admin::isValidRepositoryAndBranch($url, 'invalid-branch-name')); + } + public function testExistingFile() { $this->expectException(RuntimeException::class);