protected function getRepo($dir, $create = false)
 {
     $manager = $this->managers()->getManagerOf('file');
     $internalPath = $manager->toInternalPath($dir);
     $config = $this->getConfig()->read();
     if (!isset($config['enabled']) || $config['enabled'] != true) {
         throw new RuntimeException('Cannot open git repository "' . $dir . '" (git filesystems are disabled in "' . self::CONFIG_FILE . '")', 403);
     }
     $opts = array();
     if (!empty($config['gitCommand'])) {
         $opts['command'] = $config['gitCommand'];
     }
     if (is_array($config['environmentVariables'])) {
         $opts['environment_variables'] = $config['environmentVariables'];
     }
     if (is_int($config['processTimeout'])) {
         $opts['process_timeout'] = (int) $config['processTimeout'];
     }
     if ($manager->isDir($dir . '/.git')) {
         $repo = new Repository($internalPath, $opts);
     } else {
         if ($create) {
             $repo = \Gitonomy\Git\Admin::init($internalPath, false, $opts);
             $manager->write($dir . '/.gitignore', '/.*');
             // Ignore hidden files
             $this->addFilesToRepo($repo, '*');
             $this->commitRepo($repo, 'Initial commit');
         } else {
             throw new InvalidArgumentException('"' . $dir . '": not a git repository', 404);
         }
     }
     return $repo;
 }
示例#2
0
 public static function createRepository()
 {
     $tmp = sys_get_temp_dir() . 'gitonomybrowser_foobar';
     if (!is_dir($tmp)) {
         Admin::cloneTo($tmp, self::TEST_REPOSITORY);
     }
     return new Repository($tmp);
 }
示例#3
0
 public function handle()
 {
     $path = $this->repo->repoPath();
     if (!$this->fs->isDirectory($path) && !$this->fs->makeDirectory($path, 0755, true)) {
         throw new \RuntimeException(sprintf("Cannot create repo dir %s", $path));
     }
     Admin::cloneTo($path, $this->repo->url, true, config('git.options'));
     $this->repo->git()->run('config', ['remote.origin.fetch', 'refs/heads/*:refs/heads/*']);
 }
示例#4
0
 /**
  * Creates a fixture test repository.
  *
  * @return Repository
  */
 public static function createFoobarRepository($bare = true)
 {
     if (null === self::$localRepository) {
         self::$localRepository = Admin::cloneTo(self::createTempDir(), self::REPOSITORY_URL, $bare, self::getOptions());
     }
     $repository = self::$localRepository->cloneTo(self::createTempDir(), $bare, self::getOptions());
     self::registerDeletion($repository);
     return $repository;
 }
示例#5
0
 /**
  * Method called when a project is created
  */
 public function onProjectCreate(ProjectEvent $event)
 {
     $project = $event->getProject();
     $path = $this->getPath($project);
     Admin::init($path);
     $repository = $this->getGitRepository($project);
     $project->setRepository($repository);
     $project->setRepositorySize($repository->getSize());
 }
示例#6
0
 public function testOk()
 {
     $finder = new RepositoriesFinder();
     $tmpDir = tempnam(sys_get_temp_dir(), 'gitlib_');
     unlink($tmpDir);
     mkdir($tmpDir . '/folder/subfolder', 0777, true);
     Admin::init($tmpDir . '/folder/subfolder/A', false);
     Admin::init($tmpDir . '/folder/B', false);
     Admin::init($tmpDir . '/C', false);
     $repositories = $finder->getRepositories($tmpDir);
     $this->assertCount(3, $repositories);
     $this->assertInstanceOf('Gitonomy\\Git\\Repository', reset($repositories));
 }
示例#7
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     if (getcwd()) {
         if (\Gitonomy\Git\Admin::isValidRepository(getcwd())) {
             // Repo is valid, drop the bare example file there
             copy(__DIR__ . '/../../../stuff/deployerfile.json.template', getcwd() . '/deployerfile');
             $output->writeln('Repository initialized!');
         } else {
             throw new \Exception('"' . getcwd() . '" does not appear to contain a Git repository!');
         }
     } else {
         throw new \Exception('Could not access "' . getcwd() . '"');
     }
 }
示例#8
0
文件: TestStartup.php 项目: phpbb/epv
 /**
  * Init a git repository
  *
  * @param string $git    Location of the git repo
  * @param string $branch branch to checkout
  *
  * @throws Exception\TestException
  * @return string local directory of the cloned repo
  */
 private function initGit($git, $branch)
 {
     if (empty($branch)) {
         $branch = 'master';
     }
     $this->output->writeln(sprintf("Checkout %s from git on branch %s.", $git, $branch));
     $tmpdir = sys_get_temp_dir();
     $uniq = $tmpdir . DIRECTORY_SEPARATOR . uniqid();
     @mkdir($uniq);
     if (!file_exists($uniq)) {
         throw new TestException('Unable to create tmp directory');
     }
     Admin::cloneBranchTo($uniq, $git, $branch, false);
     return $uniq;
 }
 public static function load($name, Framework $framework)
 {
     $cacheKey = "chaki/packages/{$framework}/{$name}";
     if (false === ($packageData = Cache::fetch($cacheKey))) {
         // get repo
         $repoPath = static::$sharedCacheDirectory . "/{$name}.git";
         if (is_dir($repoPath)) {
             $repo = new Repository($repoPath);
         } else {
             $chakiData = @file_get_contents('http://chaki.io/packages/' . $name . '?format=json');
             if (!$chakiData || !($chakiData = @json_decode($chakiData, true))) {
                 Cache::store($cacheKey, null, static::$packageCacheTime);
                 return null;
             }
             $repo = \Gitonomy\Git\Admin::cloneTo($repoPath, 'https://github.com/' . $chakiData['data']['GitHubPath'] . '.git', true);
         }
         // choose best branch
         $references = $repo->getReferences();
         $branchName = null;
         $frameworkVersionStack = explode('.', $framework->getVersion());
         while (count($frameworkVersionStack) && ($branchName = $framework->getName() . '/' . implode('/', $frameworkVersionStack)) && !$references->hasBranch($branchName)) {
             array_pop($frameworkVersionStack);
             $branchName = null;
         }
         if (!$branchName && $references->hasBranch($framework->getName())) {
             $branchName = $framework->getName();
         }
         if (!$branchName) {
             $branchName = 'master';
         }
         // read packages.json
         $packageConfig = @json_decode(Util::cleanJson($repo->run('show', ["{$branchName}:package.json"])), true);
         if (!$packageConfig || empty($packageConfig['name'])) {
             throw new \Exception('Could not parse package.json for ' . $repo->getPath() . '#' . $branchName);
         }
         if ($name != $packageConfig['name']) {
             throw new \Exception("Name from package.json does not match package directory name for chaki package {$name}");
         }
         // build and cache package data
         $packageData = ['path' => $repoPath, 'branch' => $branchName, 'name' => $name, 'config' => $packageConfig];
         Cache::store($cacheKey, $packageData, static::$packageCacheTime);
     }
     return $packageData ? new static($packageData['name'], $packageData['config'], $packageData['path'], $packageData['branch']) : null;
 }
示例#10
0
 /**
  * Clone a module from drupal.org.
  *
  * @param string $project_name
  *   The (machine) name of the module/project that needs to be downloaded.
  * @param string $branch
  *   The branch that needs to be cloned. By default we will use the 8.x-1.x
  *   branch.
  */
 public static function retrieveModule($project_name, $branch = "8.x-1.x")
 {
     $branch = "origin/" . $branch;
     $path = self::getProjectDir($project_name);
     $url = self::DRUPAL_GIT_BASE_URL . '/' . $project_name;
     // Check if the repository is still available in the tmp folder.
     if (file_exists($path)) {
         $repository = new Repository($path);
     } else {
         $repository = Admin::cloneTo($path, $url, false);
     }
     try {
         $repository->getWorkingCopy()->checkout($branch);
         drupal_set_message(t('Successfully cloned branch @branch of @module.', array('@branch' => $branch, '@module' => $project_name)));
     } catch (\Exception $e) {
         drupal_set_message(t('Something went wrong while cloning the repository. Please check the logs for more information.'), 'error');
         watchdog_exception('checkstyle', $e);
     }
 }
示例#11
0
 /**
  * @Given /^I run in project "([^"]*)" as "([^"]*)":$/
  */
 public function iRunInProjectAs($project, $username, PyStringNode $commands)
 {
     $commands = $commands->getLines();
     $this->run(function ($kernel) use($project, $username, $commands) {
         $em = $kernel->getContainer()->get('doctrine')->getManager();
         $project = $em->getRepository('GitonomyCoreBundle:Project')->findOneByName($project);
         $user = $em->getRepository('GitonomyCoreBundle:User')->findOneByUsername($username);
         // create temp folders
         do {
             $dir = sys_get_temp_dir() . '/shell_' . md5(mt_rand());
         } while (is_dir($dir));
         mkdir($dir, 0777, true);
         register_shutdown_function(function () use($dir) {
             $iterator = new \RecursiveDirectoryIterator($dir, \FilesystemIterator::SKIP_DOTS | \FilesystemIterator::FOLLOW_SYMLINKS);
             $iterator = new \RecursiveIteratorIterator($iterator, \RecursiveIteratorIterator::CHILD_FIRST);
             foreach ($iterator as $file) {
                 if (!is_link($file)) {
                     chmod($file, 0777);
                 }
                 if (is_dir($file)) {
                     rmdir($file);
                 } else {
                     unlink($file);
                 }
             }
             chmod($dir, 0777);
             rmdir($dir);
         });
         $repo = Admin::cloneTo($dir, $project->getRepository()->getPath(), false);
         foreach ($commands as $command) {
             $process = new Process($command);
             $process->setWorkingDirectory($dir);
             $env = array('GITONOMY_USER' => $username, 'GITONOMY_PROJECT' => $project->getSlug());
             $env = array_merge($_SERVER, $env);
             $process->setEnv($env);
             $process->run();
             if (!$process->isSuccessful()) {
                 throw new \RuntimeException(sprintf("Execution of command '%s' failed: \n%s\n%s", $command, $process->getOutput(), $process->getErrorOutput()));
             }
         }
     });
 }
示例#12
0
 /**
  * Execute the console command.
  *
  * @return mixed
  */
 public function fire()
 {
     // Open file systems
     $disk = Storage::disk(config('wikiclone.storage_provider'));
     $repository = 'https://github.com/' . config('wikiclone.repository') . '.wiki.git';
     $localRepositoryPath = tempnam(sys_get_temp_dir(), 'repo');
     $parser = new MarkdownDoc();
     // Clone the wiki repository
     $this->info("Cloning into repository {$repository}...");
     unlink($localRepositoryPath);
     Admin::cloneTo($localRepositoryPath, $repository, false, ['--depth=1']);
     // Clear existing documentation
     $this->info("Clearing existing documentation");
     $disk->delete($disk->files());
     // Convert .md to .html
     $this->info("Converting documentation");
     foreach (scandir($localRepositoryPath) as $file) {
         if (!ends_with($file, '.md')) {
             continue;
         }
         // Convert markdown to html
         $html = $parser->transform(file_get_contents("{$localRepositoryPath}/{$file}"));
         if (strlen(config('wikiclone.url_prefix'))) {
             $html = preg_replace('/<a href="((?!http:\\/\\/|https:\\/\\/|#).*)">(.*)<\\/a>/', '<a href="' . config('wikiclone.url_prefix') . '/$1">$2</a>', $html);
         }
         foreach (config('wikiclone.html_replacements') as $set) {
             $html = str_replace($set['search'], $set['replace'], $html);
         }
         // Store the documentation
         $name = substr($file, 0, strlen($file) - strlen('.md'));
         $name = str_replace(' ', '-', $name);
         $name = str_replace('/', '', $name);
         $disk->put($name, $html);
         $this->info("Storing {$name}");
     }
     // Delete the repository
     $this->info("Deleting local repository");
     self::rrmdir($localRepositoryPath);
 }
示例#13
0
 /**
  * Clones the current repository to a new directory and return instance of new repository.
  *
  * @param string $path path to the new repository in which current repository will be cloned
  * @param bool   $bare flag indicating if repository is bare or has a working-copy
  *
  * @return Repository the newly created repository
  */
 public function cloneTo($path, $bare = true, array $options = array())
 {
     return Admin::cloneTo($path, $this->gitDir, $bare, $options);
 }
 /**
  * @expectedException LogicException
  */
 public function testNoWorkingCopyInBare()
 {
     $path = self::createTempDir();
     $repo = Admin::init($path, true, self::getOptions());
     $repo->getWorkingCopy();
 }
示例#15
0
 /**
  * @param string $attribute
  * @param string $value
  * @return bool
  */
 public function validateGitUrl($attribute, $value)
 {
     return Admin::isValidRepository($value, config('git.options'));
 }
示例#16
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $repository = $input->getArgument('repository');
     $revision = $input->getArgument('revision');
     $configuration = $input->getOption('configuration');
     $bag = $input->getOption('bag');
     $force = $input->getOption('force-redeploy');
     // -> Check that the revision matches what we expect
     preg_match('#^(tag|branch|rev):(.*)#iu', $revision, $matches);
     if (count($matches) < 3) {
         throw new \Exception('You must correctly specify the tag/branch/revision you want to deploy!' . "\n" . 'Check "help deploy" for an explanation.');
     } else {
         $type = $matches[1];
         $version = $matches[2];
     }
     // -> Get logged-in service
     $instance = \GitDeployer\AppInstance::getInstance();
     $appService = $instance->service();
     $appService->setInstances($input, $output, $this->getHelperSet());
     // .. and storage
     $storage = $instance->storage();
     $hasBeenFound = false;
     $this->showMessage('INIT', 'Getting repository...', $output);
     foreach ($appService->getProjects() as $key => $project) {
         if ($project->name() == $repository) {
             $hasBeenFound = true;
             $status = $storage->getDeploymentStatus($project);
             // -> Check if we have already been added to Git-Deployer yet
             if (!$status->added()) {
                 throw new \Exception('This repository is not yet added to Git-Deployer!' . "\n" . 'Please add it first via the add command.');
             }
             // -> Check we are not deploying the same version again. Ask
             // if we do, so the user can decide
             if ($status->isDeployd()) {
                 if ($status->getDeployedVersion() == $revision && !$force) {
                     $helper = $this->getHelper('question');
                     $question = new ConfirmationQuestion('Version ' . $status->getDeployedVersion() . ' was already deployed on ' . $status->deployedWhen() . '. Continue anyway? (y/[n]) ', false);
                     if (!$helper->ask($input, $output, $question)) {
                         break;
                     }
                 }
             }
             // -> Now clone it to a temp directory, if it doesn't exist already
             $tmpDir = sys_get_temp_dir() . '/git-deploy-' . strtolower($project->name());
             if (\Gitonomy\Git\Admin::isValidRepository($tmpDir)) {
                 $this->showMessage('GIT', 'Pulling latest changes from repository...', $output);
                 $repository = \Gitonomy\Git\Admin::init($tmpDir, false);
                 $repository->run('pull');
             } else {
                 $this->showMessage('GIT', 'Cloning repository...', $output);
                 $repository = \Gitonomy\Git\Admin::cloneTo($tmpDir, $project->url(), false);
             }
             // -> Check out the correct branch/revision/tag
             $this->showMessage('GIT', 'Checking out ' . $revision . '...', $output);
             $wc = $repository->getWorkingCopy();
             $wc->checkout($version);
             // -> Open .deployerfile and parse it
             $this->showMessage('DEPLOY', 'Checking .deployerfile...', $output);
             if (file_exists($tmpDir . '/.deployerfile')) {
                 $deployerfile = json_decode(file_get_contents($tmpDir . '/.deployerfile'));
             } else {
                 throw new \Exception('This repository has no .deployerfile!' . "\n" . 'Please add one first!');
             }
             if ($deployerfile == null) {
                 throw new \Exception('Could not parse .deployerfile: ' . json_last_error_msg() . "\n" . 'Please check that your JSON is valid!');
             }
             // -> Load the correct deployer from the .deployerfile, and fire it up with
             // the correct configuration options
             if (!isset($deployerfile->type)) {
                 throw new \Exception('Could not parse .deployerfile: ' . "\n" . 'Please specify a deployer via the "type" option!');
             }
             if (!isset($deployerfile->configurations) || isset($deployerfile->configurations) && !is_object($deployerfile->configurations)) {
                 throw new \Exception('Could not parse .deployerfile: ' . "\n" . 'Please specify at least one deployment configuration in the "configurations" option!');
             }
             // -> Get available configurations, and if not set, ask the user
             // which configuration to use
             $configs = get_object_vars($deployerfile->configurations);
             if ($configuration == null && count(get_object_vars($deployerfile->configurations)) > 1) {
                 // If no configuration has been specified via command line,
                 // ask the user which one to use
                 $confignames = array();
                 foreach ($configs as $name => $values) {
                     $confignames[] = $name;
                 }
                 // -> Get storage service to use
                 $question = new ChoiceQuestion('Which deployment configuration would you like to use?', $confignames);
                 $question->setValidator(function ($answer) use($configs, $confignames) {
                     if (!isset($configs[$confignames[$answer]])) {
                         throw new \RuntimeException('Please select a correct value!');
                     }
                     return $confignames[$answer];
                 });
                 $configuration = $helper->ask($input, $output, $question);
             } elseif ($configuration != null) {
                 // Try to use the current specified configuration
                 if (!isset($configs[$configuration])) {
                     throw new \Exception('The configuration "' . $configuration . '" was not found in this .deployefile!');
                 }
             } else {
                 foreach ($configs as $name => $values) {
                     $configuration = $name;
                 }
             }
             // -> Merge the current configuration inheritance chain, if any
             if (!isset($deployerfile->inheritance)) {
                 $mergedConfig = json_decode(json_encode($configs[$configuration]), true);
             } else {
                 $chain = $deployerfile->inheritance;
                 $minChainFound = false;
                 $smallerChain = array();
                 foreach ($chain as $key) {
                     if ($key == $configuration) {
                         $minChainFound = true;
                         $smallerChain[] = $key;
                     } else {
                         if ($minChainFound) {
                             $smallerChain[] = $key;
                         }
                     }
                 }
                 if (count($smallerChain) > 1) {
                     $mergedConfig = array();
                     foreach (array_reverse($smallerChain) as $configmerge) {
                         $mergedConfig = array_replace_recursive($mergedConfig, json_decode(json_encode($configs[$configmerge]), true));
                     }
                 } else {
                     $mergedConfig = json_decode(json_encode($configs[$smallerChain[0]]), true);
                 }
             }
             // -> Check if we have saved parameter bags, and offer the user
             // to choose one if so, or use the one provided from the command line
             $xdg = new \XdgBaseDir\Xdg();
             $bagPath = $xdg->getHomeConfigDir() . '/git-deployer';
             if ($bag != null) {
                 if (!file_exists($bagPath . '/' . $project->name() . '-' . $bag . '.bag')) {
                     throw new \Exception('This parameter bag has not been found!' . "\n" . 'Please check your naming!');
                 } else {
                     $answers = unserialize(file_get_contents($bagPath . '/' . $project->name() . '-' . $bag . '.bag'));
                 }
             } else {
                 $availableBags = array();
                 if (file_exists($bagPath)) {
                     $dh = opendir($bagPath);
                     while (($file = readdir($dh)) !== false) {
                         $fileInfo = pathinfo($file);
                         if ($fileInfo['extension'] == 'bag') {
                             if (stristr($fileInfo['filename'], $project->name())) {
                                 $availableBags[] = str_replace($project->name() . '-', '', $fileInfo['filename']);
                             }
                         }
                     }
                     closedir($dh);
                 }
                 if (count($availableBags) > 0) {
                     array_unshift($availableBags, "Don't use a bag");
                     $helper = $this->getHelper('question');
                     $question = new ChoiceQuestion('One or more parameter bags have been found. Which one do you want to use?', $availableBags);
                     $question->setValidator(function ($answer) use($availableBags) {
                         if ($answer == 0) {
                             return false;
                         }
                         if (!isset($availableBags[$answer])) {
                             throw new \RuntimeException('Please select a correct value!');
                         }
                         return $availableBags[$answer];
                     });
                     $parameterBag = $helper->ask($input, $output, $question);
                     if ($parameterBag) {
                         $answers = unserialize(file_get_contents($bagPath . '/' . $project->name() . '-' . $parameterBag . '.bag'));
                     } else {
                         $answers = array();
                     }
                 } else {
                     $answers = array();
                 }
             }
             // -> Replace placeholders in our config using parameter bags
             $bagModified = false;
             if (isset($deployerfile->parameters)) {
                 foreach ($deployerfile->parameters as $key => $questionhelp) {
                     if (!isset($answers[$key])) {
                         $helper = $this->getHelper('question');
                         $question = new Question($questionhelp . ' ');
                         $questionanswer = $helper->ask($input, $output, $question);
                         if ($questionanswer == null) {
                             $answers[$key] = '';
                         } else {
                             $answers[$key] = $questionanswer;
                         }
                         $bagModified = true;
                     }
                 }
                 // -> Ask the user to save this parameter bag
                 if ($bagModified) {
                     $helper = $this->getHelper('question');
                     $question = new ConfirmationQuestion('Do you want to save these answers in a parameter bag for next time? ([y]/n) ', true);
                     if ($helper->ask($input, $output, $question)) {
                         $question = new Question('Please provide a name for the new (or existing, will overwrite) parameter bag: ');
                         $question->setValidator(function ($answer) {
                             if (strlen($answer) < 1) {
                                 throw new \RuntimeException('Please provide a name for this parameter bag!');
                             } else {
                                 if (!preg_match('#\\w+#iu', $answer)) {
                                     throw new \RuntimeException('The name provided for this parameter bag is invalid!');
                                 }
                             }
                             return $answer;
                         });
                         $bagname = $helper->ask($input, $output, $question);
                         // -> Save this bag!
                         $xdg = new \XdgBaseDir\Xdg();
                         $savePath = $xdg->getHomeConfigDir() . '/git-deployer';
                         $saveFile = $savePath . '/' . $project->name() . '-' . $bagname . '.bag';
                         if (!file_exists($savePath)) {
                             mkdir($savePath);
                         }
                         file_put_contents($saveFile, serialize($answers));
                     }
                 }
                 // -> Now traverse the array to replace the values, and as such
                 // get our merged config ready to pass it into the deployer
                 $replacedConfig = $this->replacePlaceholders($mergedConfig, $answers);
             }
             // -> Execute the requested deployer with our merged configuration array
             $deployer = \GitDeployer\Deployers\BaseDeployer::createServiceInstance(ucwords($deployerfile->type), $input, $output, $this->getHelperSet());
             list($statusok, $trace) = $deployer->deploy($project, $tmpDir, $replacedConfig);
             // -> Check if the deployment went well, return any errors,
             // or update the deployment status for the project otherwise
             if ($statusok) {
                 $status->deployedWhen(date('c'));
                 $status->deployedType($type);
                 $status->deployedString($version);
                 $storage->setDeploymentStatus($project, $status);
             } else {
                 $output->writeln($trace);
                 throw new \Exception('Deployment did not completely finish! See trace above.');
             }
             // -> Finish up!
             $this->showMessage('FINISH', '<info>Done!</info>', $output);
             break;
         }
     }
     if (!$hasBeenFound) {
         throw new \Exception('Project "' . $repository . '" could not be found! Please check your spelling!');
     }
 }
示例#17
0
 public function initializeRepository()
 {
     // sanity checks
     if (!($remote = $this->getConfig('remote'))) {
         throw new \Exception('"remote" config required');
     }
     // get paths
     $repoPath = $this->getRepositoryPath();
     if (!is_dir($repoPath)) {
         mkdir($repoPath, 0777, true);
     }
     // check if there is an existing repo
     if (is_dir("{$repoPath}/.git")) {
         throw new \Exception("{$repoPath} already contains a .git repo directory");
     }
     // write git wrapper to file
     $gitWrapperPath = "{$repoPath}.git.sh";
     $gitWrapper = '#!/bin/bash' . PHP_EOL;
     $gitWrapper .= 'ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no';
     $gitWrapper .= ' -i ' . $this->getPrivateKeyPath();
     $gitWrapper .= ' $1 $2';
     file_put_contents($gitWrapperPath, $gitWrapper);
     chmod($gitWrapperPath, 0700);
     // create new repo
     $git = \Gitonomy\Git\Admin::init($repoPath, false, ['environment_variables' => ['GIT_SSH' => $gitWrapperPath]]);
     // add remote
     $git->run('remote', ['add', 'origin', $remote]);
     // fetch remote branches
     $git->run('fetch', ['--all']);
     // create local working branch
     $originBranch = $this->getConfig('originBranch') ?: 'master';
     $workingBranch = $this->getConfig('workingBranch') ?: $originBranch;
     $git->run('checkout', ['-b', $workingBranch, "origin/{$originBranch}"]);
     return true;
 }
 public function testCreateExistingRepository()
 {
     $repoName = 'test';
     $rootPath = realpath(__DIR__ . '/../../../../var/data');
     $repoPath = $rootPath . '/' . $repoName;
     $fs = new Filesystem();
     $fs->mkdir($repoPath);
     $repo = \Gitonomy\Git\Admin::init($repoPath, false);
     $this->setExpectedException('\\InvalidArgumentException');
     $repoService = new RepositoryService($rootPath);
     $testRepo = $repoService->createRepository($repoName);
 }
 /**
  * @expectedException RuntimeException
  */
 public function testExistingFile()
 {
     $file = $this->tmpDir . '/test';
     touch($file);
     Admin::init($file, true, self::getOptions());
 }
示例#20
0
 /**
  * @param $gitUrl
  * @return Repository
  * @throws \Gitonomy\Git\Exception\RuntimeException
  * @throws \Gitonomy\Git\Exception\InvalidArgumentException
  */
 protected function gitRepositoryByUrl($gitUrl)
 {
     $reposStoragePath = $this->getPathToForRepositoryUrl($gitUrl);
     if (is_dir($reposStoragePath)) {
         $repository = $this->getRepositoryByPath($reposStoragePath);
         $repository->run('fetch', ['origin', '+refs/heads/*:refs/heads/*', '--prune']);
         return $repository;
     } else {
         $repository = Admin::cloneTo($reposStoragePath, $gitUrl);
         return $repository;
     }
 }
示例#21
0
 public function testCloneRepository()
 {
     $newDir = self::createTempDir();
     $args = array();
     $new = Admin::cloneRepository($newDir, self::REPOSITORY_URL, $args, self::getOptions());
     self::registerDeletion($new);
     $newRefs = array_keys($new->getReferences()->getAll());
     $this->assertTrue(in_array('refs/heads/master', $newRefs));
     $this->assertTrue(in_array('refs/tags/0.1', $newRefs));
     $this->assertEquals($newDir . '/.git', $new->getGitDir());
     $this->assertEquals($newDir, $new->getWorkingDir());
 }
 /**
  * Fully initializes the git clone entity after it has been created or loaded.
  *
  * @param bool $force
  *   Toggle determining whether or not to force a reinitialization.
  *
  * @return GitClone
  *   The current GitClone entity instance.
  *
  * @see GitClone::save()
  * @see EntityController::load()
  *
  * @chainable
  */
 public function init($force = FALSE)
 {
     if (!$force && isset($this->initialized)) {
         return $this;
     }
     $this->initialized = TRUE;
     // Ensure a Gitonomy repository is instantiated.
     if (!$force && !isset($this->repository)) {
         $options = _git_clone_gitonomy_options();
         if (($path = $this->getPath(FALSE)) && !empty($this->url)) {
             $git_exists = file_exists("{$path}/.git");
             if (!$git_exists && in_array($this->refType, self::$allowedRefs)) {
                 try {
                     $this->repository = Admin::init($path, FALSE, $options);
                     $this->run('remote', array('add', 'origin', $this->url));
                 } catch (\Exception $e) {
                     drupal_set_message($e->getMessage(), 'error');
                 }
             } elseif ($git_exists && in_array($this->refType, self::$allowedRefs)) {
                 $this->repository = new Repository($path, $options);
             }
         } else {
             $temp_dir = 'temporary://git_clone-' . drupal_hash_base64(REQUEST_TIME);
             if (file_prepare_directory($temp_dir, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS)) {
                 $temp_dir = drupal_realpath($temp_dir);
                 drupal_register_shutdown_function(function () use($temp_dir) {
                     if (file_exists($temp_dir)) {
                         file_unmanaged_delete_recursive($temp_dir);
                     }
                 });
                 try {
                     $this->repository = Admin::init($temp_dir, FALSE, $options);
                 } catch (\Exception $e) {
                     watchdog('git_clone', $e->getMessage(), WATCHDOG_ERROR);
                 }
             }
             if (!$this->repository) {
                 drupal_set_message(t('Unable to create temporary git clone repository: @directory. Please verify your system temporary directory is writable.', array('@directory' => $temp_dir)), 'error');
             }
         }
     }
     // Initialize the settings.
     $this->getSettings();
     // Initialize the refs.
     $this->getRefs($force);
     return $this;
 }