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); }
/** * 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; }
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/*']); }
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; }
/** * 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); } }
/** * @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())); } } }); }
/** * 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); }
/** * 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); }
/** * @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; } }
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!'); } }