From c3bf9e65c4d36801192ef5e2b904f9a1e5bfcb71 Mon Sep 17 00:00:00 2001 From: Dan Cryer Date: Mon, 23 Feb 2015 15:58:14 +0000 Subject: [PATCH] Add support for Mercurial SSH-based clones. --- PHPCI/Model/Build/MercurialBuild.php | 75 +++++++++++++++++++++++----- 1 file changed, 63 insertions(+), 12 deletions(-) diff --git a/PHPCI/Model/Build/MercurialBuild.php b/PHPCI/Model/Build/MercurialBuild.php index 500b5372..0f38940b 100644 --- a/PHPCI/Model/Build/MercurialBuild.php +++ b/PHPCI/Model/Build/MercurialBuild.php @@ -13,36 +13,87 @@ use PHPCI\Model\Build; use PHPCI\Builder; /** -* Mercurial Build Model -* @author Pavel Gopanenko -* @package PHPCI -* @subpackage Core -*/ + * Mercurial Build Model + * @author Pavel Gopanenko + * @package PHPCI + * @subpackage Core + */ class MercurialBuild extends Build { /** - * Get the URL to be used to clone this remote repository. - */ + * Get the URL to be used to clone this remote repository. + */ protected function getCloneUrl() { return $this->getProject()->getReference(); } /** - * Create a working copy by cloning, copying, or similar. - */ + * Create a working copy by cloning, copying, or similar. + */ public function createWorkingCopy(Builder $builder, $buildPath) { - $this->cloneByHttp($builder, $buildPath); + $key = trim($this->getProject()->getSshPublicKey()); + + if (!empty($key) && strpos($this->getProject()->getReference(), 'ssh') > -1) { + $success = $this->cloneBySsh($builder, $buildPath); + } else { + $success = $this->cloneByHttp($builder, $buildPath); + } + + if (!$success) { + $builder->logFailure('Failed to clone remote git repository.'); + return false; + } return $this->handleConfig($builder, $buildPath); } /** - * Use an mercurial clone. - */ + * Use a HTTP-based Mercurial clone. + */ protected function cloneByHttp(Builder $builder, $cloneTo) { return $builder->executeCommand('hg clone %s "%s" -r %s', $this->getCloneUrl(), $cloneTo, $this->getBranch()); } + + /** + * Use an SSH-based Mercurial clone. + */ + protected function cloneBySsh(Builder $builder, $cloneTo) + { + $keyFile = $this->writeSshKey(); + + // Do the git clone: + $cmd = 'hg clone --ssh "ssh -i '.$keyFile.'" %s "%s"'; + $success = $builder->executeCommand($cmd, $this->getCloneUrl(), $cloneTo); + + if ($success) { + $success = $this->postCloneSetup($builder, $cloneTo); + } + + // Remove the key file: + unlink($keyFile); + return $success; + } + + /** + * Handle post-clone tasks (switching branch, etc.) + * @param Builder $builder + * @param $cloneTo + * @return bool + */ + protected function postCloneSetup(Builder $builder, $cloneTo) + { + $success = true; + $commit = $this->getCommitId(); + + // Allow switching to a specific branch: + if (!empty($commit) && $commit != 'Manual') { + $cmd = 'cd "%s" && hg checkout %s'; + $success = $builder->executeCommand($cmd, $cloneTo, $this->getBranch()); + } + + return $success; + } }