Main entry point for browsing a Git repository.
저자: Alexandre Salomé (alexandre.salome@gmail.com)
예제 #1
0
 /**
  * @inheritdoc
  */
 public function getName(Repository $repository)
 {
     $name = basename($repository->getPath());
     if (preg_match('/^(.*)\\.git$/', $name, $vars)) {
         return $vars[1];
     }
     return $name;
 }
예제 #2
0
 public function get($hash, $array = false)
 {
     $commit = $this->repository->getCommit($hash);
     if ($array) {
         return $this->commitToArray($commit);
     }
     return $commit;
 }
예제 #3
0
 /**
  * @return FilesCollection
  */
 public function locate()
 {
     $allFiles = trim($this->repository->run('ls-files'));
     $filePaths = preg_split("/\r\n|\n|\r/", $allFiles);
     $files = array();
     foreach ($filePaths as $file) {
         $files[] = new SplFileInfo($file, dirname($file), $file);
     }
     return new FilesCollection($files);
 }
예제 #4
0
 /**
  * @return FilesCollection
  */
 public function locate()
 {
     $allFiles = trim($this->repository->run('ls-files'));
     $filePaths = explode(PHP_EOL, $allFiles);
     $files = array();
     foreach ($filePaths as $file) {
         $files[] = new SplFileInfo($file, dirname($file), $file);
     }
     return new FilesCollection($files);
 }
예제 #5
0
 function it_will_list_all_diffed_files(Repository $repository)
 {
     $files = array('file1.txt', 'file2.txt');
     $repository->run('ls-files')->willReturn(implode(PHP_EOL, $files));
     $result = $this->locate();
     $result->shouldBeAnInstanceOf('GrumPHP\\Collection\\FilesCollection');
     $result[0]->getPathname()->shouldBe('file1.txt');
     $result[1]->getPathname()->shouldBe('file2.txt');
     $result->getIterator()->count()->shouldBe(2);
 }
예제 #6
0
 public static function registerDeletion(Repository $repository)
 {
     register_shutdown_function(function () use($repository) {
         if ($repository->getWorkingDir()) {
             $dir = $repository->getWorkingDir();
         } else {
             $dir = $repository->getGitDir();
         }
         AbstractTest::deleteDir($dir);
     });
 }
예제 #7
0
 /**
  * @param $repository
  * @return string
  * @throws \Swis\GoT\Exception\CannotFindRemoteException
  */
 protected function getRemoteUrl(Repository $repository)
 {
     try {
         $process = new Process('git config --get remote.origin.url');
         $process->setWorkingDirectory($repository->getPath());
         $process->run();
         $output = trim($process->getOutput());
     } catch (\Exception $e) {
         throw new Exception\CannotFindRemoteException();
     }
     return $output;
 }
예제 #8
0
 /**
  * Injects Logger inside the repository.
  */
 public function addRepository(Repository $repository)
 {
     if (null !== $repository->getLogger()) {
         throw new \RuntimeException('A logger is already injected in repository.');
     }
     $name = $repository->getGitDir();
     $logger = new Logger($name);
     $handler = new TestHandler();
     $logger->pushHandler($handler);
     $this->handlers[$name] = $handler;
     $repository->setLogger($logger);
 }
예제 #9
0
파일: GitDown.php 프로젝트: skizu/gitdown
 /**
  * Set git repo commit id to look up
  *
  * @param $commitHash string
  */
 public function setCommit($commitHash)
 {
     try {
         $this->commit = $this->repository->getCommit($commitHash);
     } catch (GitInvalidArgumentException $e) {
         throw new InvalidArgumentException($e->getMessage());
     } catch (GitRuntimeException $e) {
         throw new RuntimeException($e->getMessage());
     } catch (GitReferenceNotFoundException $e) {
         throw new ReferenceNotFoundException($e->getMessage());
     }
 }
예제 #10
0
 function it_will_list_all_diffed_files(Repository $repository, Diff $diff)
 {
     $changedFile = $this->mockFile('file1.txt');
     $movedFile = $this->mockFile('file2.txt', true);
     $deletedFile = $this->mockFile('file3.txt', false, true);
     $repository->getDiff('HEAD')->willReturn($diff);
     $diff->getFiles()->willReturn(array($changedFile, $movedFile, $deletedFile));
     $result = $this->locate();
     $result->shouldBeAnInstanceOf('GrumPHP\\Collection\\FilesCollection');
     $result[0]->getPathname()->shouldBe('file1.txt');
     $result[1]->getPathname()->shouldBe('file2.txt');
     $result->getIterator()->count()->shouldBe(2);
 }
예제 #11
0
 /**
  * @return FilesCollection
  */
 public function locate()
 {
     $diff = $this->repository->getWorkingCopy()->getDiffStaged();
     $files = array();
     /** @var File $file */
     foreach ($diff->getFiles() as $file) {
         if ($file->isDeletion()) {
             continue;
         }
         $fileName = $file->isRename() ? $file->getNewName() : $file->getName();
         $files[] = new SplFileInfo($fileName, dirname($fileName), $file);
     }
     return new FilesCollection($files);
 }
예제 #12
0
 function it_will_list_all_diffed_files(Repository $repository, Diff $diff, WorkingCopy $workingCopy)
 {
     $changedFile = $this->mockFile('file1.txt');
     $movedFile = $this->mockFile('file2.txt', true);
     $deletedFile = $this->mockFile('file3.txt', false, true);
     $repository->getWorkingCopy()->willReturn($workingCopy);
     $workingCopy->getDiffStaged()->willReturn($diff);
     $diff->getFiles()->willReturn([$changedFile, $movedFile, $deletedFile]);
     $result = $this->locateFromGitRepository();
     $result->shouldBeAnInstanceOf(FilesCollection::class);
     $result[0]->getPathname()->shouldBe('file1.txt');
     $result[1]->getPathname()->shouldBe('file2.txt');
     $result->getIterator()->count()->shouldBe(2);
 }
예제 #13
0
파일: Log.php 프로젝트: beubi/gitlib
 /**
  * Count commits, without offset or limit.
  *
  * @return int
  */
 public function countCommits()
 {
     if (count($this->revisions)) {
         $output = $this->repository->run('rev-list', array_merge(array('--count'), $this->revisions->getAsTextArray(), array('--'), $this->paths));
     } else {
         $output = $this->repository->run('rev-list', array_merge(array('--count', '--all', '--'), $this->paths));
     }
     return (int) $output;
 }
예제 #14
0
 public function getNewBlob()
 {
     if (null === $this->repository) {
         throw new \RuntimeException('Repository is missing to return Blob object.');
     }
     if ($this->isDeletion()) {
         throw new \LogicException('Can\'t return new Blob on a deletion');
     }
     return $this->repository->getBlob($this->newIndex);
 }
예제 #15
0
 /**
  * @return string
  */
 protected function guessGitDir()
 {
     $defaultGitDir = $this->config->getGitDir();
     try {
         $topLevel = $this->repository->run('rev-parse', array('--show-toplevel'));
     } catch (Exception $e) {
         return $defaultGitDir;
     }
     return rtrim($this->paths()->getRelativePath($topLevel), '/');
 }
예제 #16
0
 /**
  * {@inheritdoc}
  */
 public function getCommits()
 {
     /** @var \Gitonomy\Git\Log $log */
     $log = $this->repository->getLog($this->options['revision'], null, null, $this->options['limit']);
     if (!$log->countCommits()) {
         throw new \RuntimeException('No commits found');
     }
     $this->counters['total'] = $log->countCommits();
     $commits = $log->getIterator();
     foreach ($commits as $commitData) {
         /** @var \Gitonomy\Git\Commit $commitData */
         $commit = $this->createCommit($commitData);
         if ($this->skipCommit($commit)) {
             $this->counters['skipped']++;
             continue;
         }
         $this->counters['analyzed']++;
         (yield $commit);
     }
 }
 /**
  * Constructs a revision list from a variety of types.
  *
  * @param mixed $revisions can be a string, an array of strings or an array of Revision, Branch, Tag, Commit
  */
 public function __construct(Repository $repository, $revisions)
 {
     if (is_string($revisions)) {
         $revisions = array($repository->getRevision($revisions));
     } elseif ($revisions instanceof Revision) {
         $revisions = array($revisions);
     } elseif (!is_array($revisions)) {
         throw new \InvalidArgumentException(sprintf('Expected a string, a Revision or an array, got a "%s".', is_object($revisions) ? get_class($revisions) : gettype($revisions)));
     }
     if (count($revisions) == 0) {
         throw new \InvalidArgumentException(sprintf("Empty revision list not allowed"));
     }
     foreach ($revisions as $i => $revision) {
         if (is_string($revision)) {
             $revisions[$i] = new Revision($repository, $revision);
         } elseif (!$revision instanceof Revision) {
             throw new \InvalidArgumentException(sprintf('Expected a "Revision", got a "%s".', is_object($revision) ? get_class($revision) : gettype($revision)));
         }
     }
     $this->revisions = $revisions;
 }
예제 #18
0
 public function run($command, $args = [])
 {
     $output = parent::run($command, $args);
     if ('diff-tree' === $command && null !== $this->perlCommand) {
         $p = ProcessBuilder::create([$this->perlCommand, __DIR__ . '/../Resources/bin/git-diff-highlight'])->setInput($output)->getProcess();
         $p->run();
         if ($p->isSuccessful()) {
             $output = $p->getOutput();
         }
     }
     return $output;
 }
예제 #19
0
 /**
  * @throws \DebugBar\DebugBarException
  */
 public function boot()
 {
     $debugbar = $this->app['debugbar'];
     if ($debugbar instanceof LaravelDebugbar && $debugbar->isEnabled()) {
         /**
          * CodeCollector获取代码提交和版本信息
          */
         $codeCollector = new MessagesCollector('code');
         $codeCollector->addMessage('enviroment:' . $this->app->environment());
         //package "sebastian/version": "1.*"  required
         if (class_exists(Version::class)) {
             $version = static::appVersion($this->app['config']->get('app.version'));
             $codeCollector->addMessage('base path:' . base_path());
             $codeCollector->addMessage("version:\n" . $version);
         }
         if (class_exists(Repository::class)) {
             $repository = new \Gitonomy\Git\Repository(base_path());
             $head = $repository->getHeadCommit();
             $log = $head->getLog(null, null, 5);
             $commits = array();
             foreach ($log->getCommits() as $commit) {
                 $commits[] = $this->commitMessageArray($commit);
             }
             $codeCollector->addMessage("current commit:\n" . $head->getRevision(), 'HEAD');
             $codeCollector->addMessage($commits, 'git-log');
         }
         $debugbar->addCollector($codeCollector);
         /**
          * ServerCollector获取服务器信息
          */
         $serverCollector = new MessagesCollector('sever');
         $serverCollector->addMessage(php_uname(), 'uname');
         $serverCollector->addMessage("sapi_name:" . php_sapi_name(), 'phpinfo');
         $serverCollector->addMessage("PHP version:" . PHP_VERSION, 'phpinfo');
         $serverCollector->addMessage("Zend_Version:" . zend_version(), 'phpinfo');
         $serverCollector->addMessage(sys_getloadavg(), 'load');
         $debugbar->addCollector($serverCollector);
     }
 }
 /**
  * @return void
  */
 private function doPopStash()
 {
     if (!$this->stashIsApplied) {
         return;
     }
     try {
         $this->io->write('<fg=yellow>Reapplying unstaged changes from stash.</fg=yellow>');
         $this->repository->run('stash', array('pop', '--quiet'));
     } catch (Exception $e) {
         throw new RuntimeException('The stashed changes could not be applied. Please run `git stash pop` manually!' . 'More info: ' . $e->__toString(), 0, $e);
     }
     $this->stashIsApplied = false;
 }
예제 #21
0
 /**
  * Returns all lines of the blame.
  *
  * @return array
  */
 public function getLines()
 {
     if (null !== $this->lines) {
         return $this->lines;
     }
     $args = array('-p');
     if (null !== $this->lineRange) {
         $args[] = '-L';
         $args[] = $this->lineRange;
     }
     $args[] = $this->revision->getRevision();
     $args[] = '--';
     $args[] = $this->file;
     $parser = new BlameParser($this->repository);
     $parser->parse($this->repository->run('blame', $args));
     $this->lines = $parser->lines;
     return $this->lines;
 }
예제 #22
0
 /**
  * Runs git commands on the repository.
  *
  * This is a wrapper around \Gitonomy\Git\Repository::run(). The GitClone
  * entity must catch whether or not the repository has actually been
  * initialized and any errors produced from the command executed.
  *
  * @param string $command
  *   Git command to run (checkout, branch, tag).
  * @param array $args
  *   Arguments of git command.
  * @param bool $return_output
  *   Toggle determining whether or not to return the output from $command.
  *
  * @return FALSE|string|GitClone
  *   Anytime there is an error, the return value will always be FALSE.
  *   If $return_output is set, the output of $command is returned.
  *   Otherwise, the current GitClone instance is returned for chainability.
  *
  * @see \Gitonomy\Git\Repository::run()
  *
  * @chainable
  */
 protected function run($command, array $args = array(), $return_output = FALSE)
 {
     $return = $return_output ? '' : $this;
     $command_hook = _git_clone_hook_name($command);
     $context = array('output' => $return_output);
     drupal_alter('git_clone_pre_' . $command_hook, $args, $this, $context);
     try {
         $output = $this->repository->run($command, $args);
         $this->log($command, $args, $output);
         drupal_alter('git_clone_post_' . $command_hook, $output, $this, $context);
         if ($return_output) {
             $return = $output;
         }
     } catch (\Exception $e) {
         watchdog('git_clone', $e->getMessage(), array(), WATCHDOG_ERROR);
         $return = FALSE;
     }
     return $return;
 }
예제 #23
0
 /**
  * @return Log
  */
 public function getLog($paths = null, $offset = null, $limit = null)
 {
     return $this->repository->getLog($this, $paths, $offset, $limit);
 }
예제 #24
0
 /**
  * @return FilesCollection
  */
 public function locateFromGitRepository()
 {
     $diff = $this->repository->getWorkingCopy()->getDiffStaged();
     return $this->parseFilesFromDiff($diff);
 }
 function it_should_pop_changes_when_an_error_occurs(Repository $repository)
 {
     $event = new RunnerEvent(new TasksCollection(), new GitPreCommitContext(new FilesCollection()), new TaskResultCollection());
     $repository->run('stash', Argument::containing('save'))->shouldBeCalled();
     $repository->run('stash', Argument::containing('pop'))->shouldBeCalled();
     $this->saveStash($event);
     $this->handleErrors();
 }
예제 #26
0
 public function renderStatus(\Twig_Environment $env, Repository $repository)
 {
     $wc = $repository->getWorkingCopy();
     return $this->renderBlock($env, 'status', array('diff_staged' => $wc->getDiffStaged(), 'diff_pending' => $wc->getDiffPending()));
 }
예제 #27
0
 /**
  * Mark commit by version tag
  *
  * @param string $hash     commit id
  * @param int $forthNumber @see VersionGenerator::version
  * @param string $tag
  */
 public function markCommit($hash, $forthNumber = null, $tag = "")
 {
     $version = 'v' . $this->version($forthNumber, $tag);
     $this->repo->getReferences()->createTag($version, $hash);
     $this->repo->run('push', array('origin', $version));
 }
예제 #28
0
 protected function run($command, array $args = array())
 {
     return $this->repository->run($command, $args);
 }
예제 #29
0
 public function parse()
 {
     $kwfTrlElements = array();
     if ($this->_kwfPoFilePath) {
         $this->_output->writeln('<info>Reading kwf-po file</info>');
         $kwfPoFile = \Sepia\PoParser::parseFile($this->_kwfPoFilePath);
         $trlElementsExtractor = new TrlElementsExtractor($kwfPoFile);
         $kwfTrlElements = $trlElementsExtractor->extractTrlElements();
     }
     $initDir = getcwd();
     $this->_output->writeln('<info>Changing into directory</info>');
     $repository = new Repository($this->_directory);
     $wc = $repository->getWorkingCopy();
     if ($wc->getDiffPending()->getRawDiff() != '' || $wc->getDiffStaged()->getRawDiff() != '') {
         $this->_output->writeln('<error>Uncommited changes</error>');
         exit;
     }
     chdir($initDir);
     $initBranch = trim($repository->run('rev-parse', array('--abbrev-ref', 'HEAD')));
     $trlElements = array();
     $errors = array();
     $repository = new Repository($this->_directory);
     $repository->run('fetch', array('origin'));
     if ($this->_kwfPoFilePath) {
         $this->_output->writeln('<info>Iterating over branches matching "^[1-9]+.[0-9]+$"</info>');
     } else {
         $this->_output->writeln('<info>Iterating over branches matching "^[3-9]+.[0-9]+$" and >=3.9</info>');
     }
     foreach ($repository->getReferences()->getBranches() as $branch) {
         $branchName = $branch->getName();
         if (strpos($branchName, 'origin/') === false) {
             continue;
         }
         $splited = explode('/', $branchName);
         $isVersionNumber = preg_match('/^[0-9]+.[0-9]+$/i', $splited[1]);
         if (sizeof($splited) >= 3) {
             continue;
         }
         if (!$isVersionNumber && $splited[1] != 'master' && $splited[1] != 'production') {
             continue;
         }
         if (!$this->_kwfPoFilePath && $isVersionNumber && version_compare($splited[1], '3.9', '<')) {
             continue;
         }
         $this->_output->writeln("<info>Checking out branch: {$branchName}</info>");
         $wc->checkout($branchName);
         // parse package
         $this->_output->writeln('Parsing source directory...');
         $parser = new ParseAll($this->_directory, $this->_output);
         $parser->setIgnoredFiles($this->_ignoredFiles);
         $trlElements = array_merge($parser->parseDirectoryForTrl(), $trlElements);
         $newErrors = $parser->getErrors();
         foreach ($newErrors as $key => $error) {
             $newErrors[$key]['branch'] = $branchName;
         }
         $errors = array_merge($newErrors, $errors);
     }
     $wc->checkout($initBranch);
     $sources = array();
     $filteredTrlElements = array();
     foreach ($trlElements as $trlElement) {
         $sources[$trlElement['source']] = true;
         if ($trlElement['source'] == $this->_source) {
             $filteredTrlElements[] = $trlElement;
         }
     }
     $trlElements = $filteredTrlElements;
     // generate po file
     $this->_output->writeln('Generate Po-File...');
     touch($this->_poFilePath);
     $this->_output->writeln($this->_poFilePath);
     $poFileGenerator = new PoFileGenerator($trlElements, $kwfTrlElements);
     $poFile = $poFileGenerator->generatePoFileObject($this->_poFilePath);
     $poFile->writeFile($this->_poFilePath);
     $this->_output->writeln('');
     $this->_output->writeln('Trl Errors:');
     foreach ($trlElements as $trlElement) {
         if (isset($trlElement['error_short']) && $trlElement['error_short']) {
             var_dump($trlElement);
         }
     }
     if (count($errors)) {
         $this->_output->writeln('');
         $this->_output->writeln('Php Parse-Errors:');
         foreach ($errors as $error) {
             $this->_output->writeln('  Branch: ' . $error['branch'] . ' | File: ' . $error['file']);
             $this->_output->writeln('    Error:' . $error['error']->getMessage());
             $this->_output->writeln('  -------------------------------------');
         }
     }
     $this->_output->writeln('');
     $this->_output->writeln('Every branch has been parsed an data is collected in ' . $this->_poFilePath);
     $this->_output->writeln('');
     $this->_output->writeln('1. Please check the mentioned Parse-Errors');
     $this->_output->writeln('2. Upload and translate file from ' . $this->_poFilePath . ' to lingohub or translate in another way');
     $this->_output->writeln('3. When using lingohub call "./vendor/bin/lingohub downloadTranslations" after translating');
     $this->_output->writeln('');
 }
예제 #30
0
 public function __construct($path, array $options = array())
 {
     parent::__construct($path, $options);
     $this->setName(basename($this->getPath()));
 }