public function deploy() { // Create the wrapper. $wrapper = new GitWrapper(); $wrapper->streamOutput(); // Iterate through each project. foreach ($this->projects as $name => $project) { // Check out all branches. foreach ($project['branches'] as $branch => $destination) { // Build our git interface. $git = null; if (!is_dir($destination)) { $git = $wrapper->cloneRepository($project['repo'], $destination); } else { $git = new GitWorkingCopy($wrapper, $destination); } // Fetch the latest. $git->fetch('origin'); // Checkout the desired branch. $git->checkout($branch, array('force' => true)); // Reset any local changes. $git->reset(array('hard' => true)); // Pull the latest from the branch. $git->pull('origin', $branch, array('force' => true)); } } }
/** * Execute the command. * * @param InputInterface $input * @param OutputInterface $output * @return void */ protected function execute(InputInterface $input, OutputInterface $output) { $this->setIo($input, $output); /** @var Repository $config */ $config = $this->container['config']; $sourceRepoPath = $config['source.directory']; $sourceRepoUrl = $config['source.git.url']; $sourceRepoBranch = $config['source.git.branch']; $this->checkSourceRepoSettings($sourceRepoPath, $sourceRepoUrl); $output->writeln(["<b>steak pull configuration:</b>", " Source repository remote is <path>{$sourceRepoUrl}</path>", " Source repository branch is <path>{$sourceRepoBranch}</path>", " Path to local repository is <path>{$sourceRepoPath}</path>"], OutputInterface::VERBOSITY_VERBOSE); if ($this->files->exists($sourceRepoPath)) { $workingCopy = $this->git->workingCopy($sourceRepoPath); if (!$workingCopy->isCloned()) { throw new RuntimeException("<path>{$sourceRepoPath}</path> exists but is not a git repository."); } if ($workingCopy->getBranches()->head() != $sourceRepoBranch) { throw new RuntimeException("<path>{$sourceRepoPath}</path> exists but isn't on the <path>{$sourceRepoBranch}</path> branch."); } $this->git->streamOutput(); $workingCopy->pull(); } else { $output->writeln(["The source directory <path>{$sourceRepoPath}</path> does not exist.", " Attempting clone from {$sourceRepoUrl}"]); $this->git->streamOutput(); $this->git->cloneRepository($sourceRepoUrl, $sourceRepoPath, ['single-branch' => true, 'branch' => $sourceRepoBranch]); $output->writeln("<info>Clone complete! Edit your sources in <path>{$sourceRepoPath}</path></info>"); } $output->writeln("Try <comment>steak serve</comment> to fire up the local development server..."); }
/** * @group functional */ public function testTag() { $wrapper = new GitWrapper(); $output = explode("\n", trim($wrapper->git('tag -l', __DIR__ . '/..'))); rsort($output); $this->assertTrue(version_compare($output[0], Version::VERSION, '==')); }
/** * {@inheritdoc} */ public function run($callback = null) { $event = new Event\GitEvent($this->git, $this, $this->command); $dispatcher = $this->git->getDispatcher(); try { // Throw the "git.command.prepare" event prior to executing. $dispatcher->dispatch(Event\GitEvents::GIT_PREPARE, $event); // Execute command if it is not flagged to be bypassed and throw the // "git.command.success" event, otherwise do not execute the comamnd // and throw the "git.command.bypass" event. if ($this->command->notBypassed()) { parent::run($callback); if ($this->isSuccessful()) { $dispatcher->dispatch(Event\GitEvents::GIT_SUCCESS, $event); } else { $output = $this->getErrorOutput(); if (trim($output) == '') { $output = $this->getOutput(); } throw new \RuntimeException($output); } } else { $dispatcher->dispatch(Event\GitEvents::GIT_BYPASS, $event); } } catch (\RuntimeException $e) { $dispatcher->dispatch(Event\GitEvents::GIT_ERROR, $event); throw new GitException($e->getMessage()); } }
public function setUp() { $fileSystem = new Filesystem(); $fileSystem->remove(self::TEST_PATH); $fileSystem->mkdir(self::TEST_PATH); $git = new GitWrapper(); $git->init(self::TEST_PATH); }
/** * @return void */ public function run() { $workingDir = $this->gitWrapper->workingCopy($this->workingDir); $workingDir->fetch(); $workingDir->reset('--hard'); $workingDir->checkout('PRODUCTION'); $workingDir->pull(); }
/** * Clones the source code for this project. */ public function init($path) { $wrapper = new GitWrapper(); $wrapper->streamOutput(); $wrapper->clone($this->app->source_url, $path, array('bare' => TRUE)); chdir($path); $wrapper->git('branch'); }
/** * @param string|null $tag * * @return \GitWrapper\GitWorkingCopy */ public function checkout($tag = null) { $git = $this->gitWrapper->workingCopy($this->getRepositoryDirectory($this)); if (!$git->isCloned()) { $git->clone('git@github.com:' . $this . '.git'); } if ($tag !== null) { $git->checkout($tag, ['f' => true]); } return $git; }
/** * Prepare the build directory as a git repository. * * Maybe there's already a git repo in the build folder, but is it pointing to * the correct origin and is it on the correct branch? Instead of checking for * things that might be wrong, we'll just start from scratch. * * @returns GitWorkingCopy * @throws RuntimeException */ protected function prepareRepository() { $config = $this->container['config']; $this->builder->clean($config['build.directory']); // clear out everything, including .git metadata $workingCopy = $this->git->workingCopy($config['build.directory']); $this->doGitInit($workingCopy, $config['deploy.git.url'], $config['deploy.git.branch']); // start again at last commit $this->builder->clean($config['build.directory'], true); // clear the old content but keep .git folder return $workingCopy; }
/** * Update the vulnerability database (returning any output from the git wrapper) * * @throws \Exception */ public function updateDatabase() { $wrapper = new GitWrapper(); $repositoryPath = __DIR__ . self::REPOSITORY_PATH; if (!file_exists($repositoryPath . '/.git')) { $git = $wrapper->clone(self::REPOSITORY_URL, $repositoryPath); $git->getOutput(); } else { $wrapper->git('pull', $repositoryPath); } $this->replaceJsonFiles(); }
protected function execute(InputInterface $input, OutputInterface $output) { // App $app_name = $input->getArgument('app'); if (empty($app_name)) { $helper = $this->getHelper('question'); $question = new ChoiceQuestion('Which app? ', array_keys($this->director->config['apps']), 0); $app_name = $helper->ask($input, $output, $question); } $app = $this->director->getApp($app_name); // Environment $env_name = $input->getArgument('environment'); if (empty($env_name)) { $helper = $this->getHelper('question'); $question = new ChoiceQuestion('Which environment? ', array_keys($app->environments), 0); $env_name = $helper->ask($input, $output, $question); } $environment = $app->getEnvironment($env_name); $output->writeln('<info>PATH:</info> ' . $environment->getSourcePath()); $output->writeln('<info>BRANCH:</info> ' . $environment->getRepo()->getCurrentBranch()); // Look for .director.yml $config = $environment->getConfig(); if (empty($config)) { $output->writeln('<error>CONFIG:</error> .director.yml not found at ' . $environment->getSourcePath()); } else { $output->writeln('<info>CONFIG:</info> Loaded .director.yml'); } // Show git status $status = $environment->getRepo()->getStatus(); if (!empty($status)) { $wrapper = new GitWrapper(); $wrapper->streamOutput(); chdir($environment->getSourcePath()); $wrapper->git('status'); } // Save to yml $this->director->config['apps'][$app_name]['environments'][$env_name]['config'] = $environment->getConfig(); $this->director->config['apps'][$app_name]['environments'][$env_name]['git_ref'] = $environment->getRepo()->getCurrentBranch(); $this->director->saveData(); $output->writeln("Saved environment details."); // Look for services if (isset($environment->config['services']) && is_array($environment->config['services'])) { foreach ($environment->config['services'] as $service => $type) { $serviceFactory = $this->director->getService($service); if ($serviceFactory) { $output->writeln("<info>SERVICE:</info> {$service}: {$serviceFactory->galaxy_role}"); } else { $output->writeln("<error>SERVICE:</error> {$service}: not found. Use service:add to fix."); $output->writeln("Looking for available {$service} {$type}"); } } } }
/** * Execute the console command. * * @return mixed */ public function handle() { $currentUser = get_current_user(); $privateKey = php_uname('s') == 'Darwin' ? realpath("/Users/{$currentUser}/.ssh/id_rsa") : realpath("/home/{$currentUser}/.ssh/id_rsa"); $blog = base_path('resources/blog/'); $git = new GitWrapper(); $git->setPrivateKey($privateKey); if (!file_exists($blog)) { $git->cloneRepository(config('blog.repository'), $blog); } $git->git('pull origin master', $blog); }
/** * {@inheritDoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $dependencies = $input->getArgument('dependency'); $excludes = $input->getOption('exclude'); $test = $input->getOption('test'); $wrapper = new GitWrapper(); $wrapper->streamOutput(); $projects = Finder::create()->directories()->depth(0)->exclude($excludes)->in(getcwd()); /** @var SplFileInfo $project */ foreach ($projects as $project) { if (!file_exists($project->getPathname() . '/composer.json')) { continue; } try { $this->resetComposer(); $this->versionParser = null; $this->pool = null; chdir($project->getPathname()); $packages = $this->resolveUpdateablePackages($dependencies); if (count($packages) > 0) { $output->writeln(sprintf('<comment> Updating project %s with %s</comment>', $project->getFilename(), implode(', ', $packages))); $git = $wrapper->workingCopy($project->getPathname()); $stashed = false; if ($git->hasChanges()) { $git->run(['stash']); $stashed = true; } $git->pull(); if (!$test) { $exitCode = $this->update($packages); if (0 === $exitCode) { $git->add('composer.json')->add('composer.lock'); // Reissue a install for plugins to work. Slows down :/ $this->resetComposer(); $this->install($output); if ($git->hasChanges()) { $git->commit('Update ' . implode(', ', $packages))->push(); } } } if ($stashed) { $git->run(['stash', 'pop']); } } } catch (\Exception $e) { if ($output instanceof ConsoleOutputInterface) { $this->getApplication()->renderException($e, $output->getErrorOutput()); } else { $this->getApplication()->renderException($e, $output); } } } }
/** * @param LocalPackage $package * * @return GitWorkingCopy */ public function execute(LocalPackage $package) { $git = $this->gitWrapper->cloneRepository($package->getForkSSHRepository(), $package->getFolder()); // @todo parameters $git->config('user.name', 'BOTrelli')->config('user.email', '*****@*****.**'); $git->remote('add', 'upstream', $package->getRepository()); $this->dispatchEvent(StepsEvents::GIT_REMOTE_ADDED, new GitEventMade($git)); $git->checkout($package->getLocalBranch(), array('b' => true)); $this->dispatchEvent(StepsEvents::GIT_CHECKOUT_DONE, new GitEventMade($git)); $git->fetch('upstream'); $this->dispatchEvent(StepsEvents::GIT_FETCHED, new GitEventMade($git)); $git->merge('upstream/master'); $this->dispatchEvent(StepsEvents::GIT_MERGED, new GitEventMade($git)); $git->rebase('master'); $this->dispatchEvent(StepsEvents::GIT_MERGED, new GitEventMade($git)); return $git; }
/** * Executes a bad command. * * @param bool $catch_exception * Whether to catch the exception to continue script execution, defaults * to false. */ public function runBadCommand($catch_exception = false) { try { $this->_wrapper->git('a-bad-command'); } catch (GitException $e) { if (!$catch_exception) { throw $e; } } }
/** * @param $repository * @return array */ public function getRemoteTags($repository) { $refs = []; $result = $this->wrapper->git('ls-remote ' . $repository); $rows = explode(PHP_EOL, trim($result)); foreach ($rows as $row) { list($hash, $ref) = explode("\t", $row, 2); $this->assignHashByRef($refs, $ref, $hash); } return $refs; }
public function deleteConfig(ConfigCrudEvent $event) { $config = \Drupal::config('git_config.config'); $private_key = $config->get('private_key'); $git_url = $config->get('git_url'); $active_dir = \Drupal::config('config_files.config')->get('directory'); if ($active_dir && !empty($private_key) && !empty($git_url)) { $wrapper = new GitWrapper(); $wrapper->setPrivateKey($config->get('private_key')); $git = $wrapper->workingCopy($active_dir); $object = $event->getConfig(); $file_name = $object->getName() . '.yml'; try { $user = \Drupal::currentUser(); $name = $user->getAccount()->getUsername(); $git->rm($file_name)->commit(t('Removed by @name', array('@name' => $name)))->push(); } catch (GitException $e) { drupal_set_message($e->getMessage(), 'warning'); } } }
/** * @inheritdoc */ public function run(&$cmdParams, &$params) { $res = false; $taskRunner = $this->taskRunner; $gitCmd = !empty($cmdParams[0]) ? $taskRunner->parseStringAliases($cmdParams[0]) : ''; if (empty($gitCmd)) { throw new Exception('git: Command cannot be empty'); } $this->controller->stdout('Running git ' . $gitCmd . '...'); if (!$this->controller->dryRun) { $wrapper = false; try { $wrapper = new GitWrapper(); } catch (GitException $e) { Log::throwException($e->getMessage()); } if ($wrapper) { switch ($gitCmd) { case 'clone': $repo = !empty($cmdParams[1]) ? $cmdParams[1] : ''; $destDir = !empty($cmdParams[2]) ? $taskRunner->parsePath($cmdParams[2]) : ''; if (empty($repo) || empty($destDir)) { throw new Exception('git: repository and destination directory cannot be empty'); } $gitOptions = !empty($cmdParams[3]) ? $cmdParams[3] : []; $res = $wrapper->cloneRepository($repo, $destDir, $gitOptions); break; default: $this->controller->stdout("\n"); $this->controller->stderr("Command not supported: {$gitCmd}", Console::FG_RED); break; } } } else { $this->controller->stdout(' [dry run]', Console::FG_YELLOW); } $this->controller->stdout("\n"); return !empty($res); }
/** * @param string $source * @param string $destination * @param array $options * * @return string */ public function process($source, $destination, $options = array()) { $parameters = array(); $options += array('arguments' => array()); foreach ($options['arguments'] as $param => $value) { if (is_numeric($param)) { $parameters[$value] = true; } else { $parameters[$param] = $value; } } $this->wrapper->cloneRepository($source, $destination, $parameters); }
/** * @param $projectId * * @return int The exit code */ public function actionIndex($projectId) { $exitCode = 0; // TODO: read info from the database $projectInfo = (object) (require __DIR__ . '/../projects_tmp/' . $projectId . '.php'); // ------------------------ $home = Shell::getHomeDir(); $this->workspace = $home . DIRECTORY_SEPARATOR . 'workspace' . DIRECTORY_SEPARATOR . $projectInfo->id . "_" . time(); $this->stdout('Fetching into '); $this->stdout($this->workspace . "\n", Console::FG_CYAN); $gitClone = false; try { $wrapper = new GitWrapper(); $gitOptions = []; if (!empty($projectInfo->branch)) { $gitOptions['branch'] = $projectInfo->branch; } $gitClone = $wrapper->cloneRepository($projectInfo->repo, $this->workspace, $gitOptions); } catch (GitException $e) { $this->stderr($e->getMessage(), Console::FG_RED); $exitCode = 1; } if (!empty($projectInfo->rootFolder)) { $this->workspace .= '/' . $projectInfo->rootFolder; } if ($gitClone && $this->run) { // TODO: parametrise deployii folder name / path (relative to workspace) $buildFile = $this->workspace . '/' . $this->getScriptFolder() . '/build.php'; if (file_exists($buildFile)) { $taskRunner = new TaskRunner($this, $buildFile); $exitCode = $taskRunner->run($this->target); } else { $this->stderr("Build file not found: " . $buildFile, Console::FG_RED); $exitCode = 1; } } $this->stdout("\n"); return $exitCode; }
/** * Create directory if it does not exist and init the repository if it's not a repository. */ public function init() { if (!file_exists($localGitPath = $this->getLocalRepoPath())) { mkdir($localGitPath); } if (!file_exists($localGitPath . '.git')) { $git = $this->gitWrapper->init($localGitPath); $git->config('user.name', 'backuppipes')->config('user.email', '*****@*****.**'); } else { $git = $this->gitWrapper->workingCopy($localGitPath); } $this->git = $git; }
/** * Constructs a GitProcess object. * * @param \GitWrapper\GitWrapper $git * @param \GitWrapper\GitCommand $command * @param string|null $cwd */ public function __construct(GitWrapper $git, GitCommand $command, $cwd = null) { $this->git = $git; $this->command = $command; // Build the command line options, flags, and arguments. $binary = ProcessUtils::escapeArgument($git->getGitBinary()); $commandLine = rtrim($binary . ' ' . $command->getCommandLine()); // Resolve the working directory of the Git process. Use the directory // in the command object if it exists. if (null === $cwd) { if (null !== ($directory = $command->getDirectory())) { if (!($cwd = realpath($directory))) { throw new GitException('Path to working directory could not be resolved: ' . $directory); } } } // Finalize the environment variables, an empty array is converted // to null which enherits the environment of the PHP process. $env = $git->getEnvVars(); if (!$env) { $env = null; } parent::__construct($commandLine, $cwd, $env, null, $git->getTimeout(), $git->getProcOptions()); }
/** * Set up the git wrapper and the temporary directory. */ protected function setup() { // @TODO: Allow setting up in an existing dierectory. if (!$this->dir) { // Greate a temporary directory. $tempfile = tempnam(sys_get_temp_dir(), ''); mkdir($tempfile . '.git'); if (file_exists($tempfile)) { unlink($tempfile); } $this->dir = $tempfile . '.git'; $this->git = $this->wrapper->init($this->dir); } $this->git->config('user.name', 'GitMerge')->config('user.email', '*****@*****.**')->config('merge.conflictStyle', 'diff3'); $this->strategy = null; }
/** * Deploy a version to an environment. * * @param $version * A git branch, tag, or sha. */ public function deploy($version) { // Checkout the branch $wrapper = new GitWrapper(); $wrapper->streamOutput(); $git = new GitWorkingCopy($wrapper, $this->getSourcePath()); $git->checkout($version); $git->pull(); // Reload config so any changes get picked up. $this->reloadConfig(); // Run the deploy hooks chdir($this->getSourcePath()); $process = new Process($this->config['hooks']['deploy']); $process->run(function ($type, $buffer) { if (Process::ERR === $type) { // Error echo $buffer; } else { // OK echo $buffer; } }); // Save new branch to yml $this->director->config['apps'][$this->app]['environments'][$this->name]['git_ref'] = $this->getRepo()->getCurrentBranch(); $this->director->saveData(); }
mkdir($cookieDirPath, 0777, true); } foreach ($defaultAuth as $codingUserName => $auth) { requestAPI::logging('当前用户: ' . $auth[0], 'info'); $codingApi = requestAPI::start($codingUserName, $auth, $cookieDirPath); if (!$codingApi->isLogin()) { $bool = $codingApi->login(); if (!$bool) { requestAPI::logging('用户 ' . $codingUserName . ' 登录失败, 不知道原因, 退出....', 'error', true); } } //检查一下Coding上面有没有项目 没有就创建 foreach ($defaultRepository as $repositoryName => $repositoryUrl) { $codingApi->selectProject($repositoryName); } $wrapper = new GitWrapper(); $wrapper->setTimeout(3600); $defaultRepositoryTotal = count($defaultRepository); // 总数量 $i = 1; // 只要一个仓库新建任务就可以了 requestAPI::logging('当前用户 ' . $codingUserName . ' 需要执行 ' . $defaultRepositoryTotal . ' 个仓库', 'info'); foreach ($defaultRepository as $repositoryName => $repositoryUrl) { requestAPI::logging('执行第 ' . $i . ' 个仓库', 'info'); $projectPathName = $repositoryDir . '/' . $repositoryName; // 本地没有这个库 就去 git clone 下来 if (!is_dir($projectPathName)) { requestAPI::logging('本地没有此仓库: ' . $repositoryName . ' 开始从 ' . $repositoryUrl . ' Clone ....', 'info'); $git = $wrapper->cloneRepository($repositoryUrl, $projectPathName); if (!$git) { requestAPI::logging('Clone 失败 ' . $repositoryName . ' 退出...', 'error', true);
private function initRepository() { $gitWrapper = new GitWrapper(); $this->repository = $gitWrapper->workingCopy($this->config->getPath()); }
/** * Returns the GitWorkingCopy object for a given repository. * * @param string $url * The URL of the repository. * * @return \GitWrapper\GitWorkingCopy */ public function getGit($repository) { if (!isset($this->_workingCopies[$repository])) { $name = GitWrapper::parseRepositoryName($repository); $directory = $this->getDataDir() . '/' . $name; $git = $this->getGitWrapper()->workingCopy($directory); if (!$git->isCloned()) { $git->clone($repository); } else { $git->pull()->clearOutput(); } $this->_workingCopies[$repository] = $git; } return $this->_workingCopies[$repository]; }
/** * @return \GitWrapper\GitWorkingCopy */ protected function getWorkingCopy() { $git = new GitWrapper(); $workingCopy = $git->workingCopy($this->repositoryPath); return $workingCopy; }
/** * Deploy a version to an environment. * * @param $version * A git branch, tag, or sha. */ public function deploy($version) { // Checkout the branch $wrapper = new GitWrapper(); $wrapper->streamOutput(); $git = new GitWorkingCopy($wrapper, $this->getSourcePath()); $git->checkout($version); $git->pull(); // Reload config so any changes get picked up. $this->reloadConfig(); // Run the deploy hooks, if there are any. if (isset($this->config['hooks']['deploy']) && !empty($this->config['hooks']['deploy'])) { chdir($this->getSourcePath()); $process = new Process($this->config['hooks']['deploy']); $process->run(function ($type, $buffer) { if (Process::ERR === $type) { // Error echo $buffer; } else { // OK echo $buffer; } }); } // @TODO: Save the environment // @TODO: Create EnvironmentFactory->save(); // Returning the branch for now. The command is saving the info. return $this->getRepo()->getCurrentBranch(); }
/** * Helper function to convert patch list into numbered list. * * @param array $patches_to_search * @return array */ protected function ensureLatestRepo($repo_dir) { if (!$this->ensuredLatestRepo) { $wrapper = new GitWrapper(); $git = $wrapper->workingCopy($repo_dir); $git->pull(); $this->ensuredLatestRepo = TRUE; } }