123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375 |
- <?php
- /*
- * This file is part of Composer.
- *
- * (c) Nils Adermann <naderman@naderman.de>
- * Jordi Boggiano <j.boggiano@seld.be>
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
- namespace Composer\Repository\Vcs;
- use Composer\Config;
- use Composer\Cache;
- use Composer\IO\IOInterface;
- use Composer\Json\JsonFile;
- use Composer\Downloader\TransportException;
- use Composer\Util\RemoteFilesystem;
- use Composer\Util\GitLab;
- /**
- * Driver for GitLab API, use the Git driver for local checkouts.
- *
- * @author Henrik Bjørnskov <henrik@bjrnskov.dk>
- * @author Jérôme Tamarelle <jerome@tamarelle.net>
- */
- class GitLabDriver extends VcsDriver
- {
- private $scheme;
- private $owner;
- private $repository;
- /**
- * @var array Project data returned by GitLab API
- */
- private $project;
- /**
- * @var array Keeps commits returned by GitLab API
- */
- private $commits = array();
- /**
- * @var array List of tag => reference
- */
- private $tags;
- /**
- * @var array List of branch => reference
- */
- private $branches;
- /**
- * Git Driver
- *
- * @var GitDriver
- */
- protected $gitDriver;
- const URL_REGEX = '#^(?:(?P<scheme>https?)://(?P<domain>.+?)/|git@(?P<domain2>[^:]+):)(?P<owner>[^/]+)/(?P<repo>[^/]+?)(?:\.git|/)?$#';
- /**
- * Extracts information from the repository url.
- *
- * SSH urls use https by default. Set "secure-http": false on the repository config to use http instead.
- *
- * {@inheritDoc}
- */
- public function initialize()
- {
- if (!preg_match(self::URL_REGEX, $this->url, $match)) {
- throw new \InvalidArgumentException('The URL provided is invalid. It must be the HTTP URL of a GitLab project.');
- }
- $this->scheme = !empty($match['scheme']) ? $match['scheme'] : (isset($this->repoConfig['secure-http']) && $this->repoConfig['secure-http'] === false ? 'http' : 'https');
- $this->originUrl = !empty($match['domain']) ? $match['domain'] : $match['domain2'];
- $this->owner = $match['owner'];
- $this->repository = preg_replace('#(\.git)$#', '', $match['repo']);
- $this->cache = new Cache($this->io, $this->config->get('cache-repo-dir').'/'.$this->originUrl.'/'.$this->owner.'/'.$this->repository);
- $this->fetchProject();
- }
- /**
- * Updates the RemoteFilesystem instance.
- * Mainly useful for tests.
- *
- * @internal
- */
- public function setRemoteFilesystem(RemoteFilesystem $remoteFilesystem)
- {
- $this->remoteFilesystem = $remoteFilesystem;
- }
- /**
- * {@inheritdoc}
- */
- public function getFileContent($file, $identifier)
- {
- // Convert the root identifier to a cachable commit id
- if (!preg_match('{[a-f0-9]{40}}i', $identifier)) {
- $branches = $this->getBranches();
- if (isset($branches[$identifier])) {
- $identifier = $branches[$identifier];
- }
- }
- $resource = $this->getApiUrl().'/repository/blobs/'.$identifier.'?filepath=' . $file;
- try {
- $content = $this->getContents($resource);
- } catch (TransportException $e) {
- if ($e->getCode() !== 404) {
- throw $e;
- }
- return null;
- }
- return $content;
- }
- /**
- * {@inheritdoc}
- */
- public function getChangeDate($identifier)
- {
- if (isset($this->commits[$identifier])) {
- return new \DateTime($this->commits[$identifier]['committed_date']);
- }
- return new \DateTime();
- }
- /**
- * {@inheritDoc}
- */
- public function getRepositoryUrl()
- {
- return $this->project['public'] ? $this->project['http_url_to_repo'] : $this->project['ssh_url_to_repo'];
- }
- /**
- * {@inheritDoc}
- */
- public function getUrl()
- {
- return $this->project['web_url'];
- }
- /**
- * {@inheritDoc}
- */
- public function getDist($identifier)
- {
- $url = $this->getApiUrl().'/repository/archive.zip?sha='.$identifier;
- return array('type' => 'zip', 'url' => $url, 'reference' => $identifier, 'shasum' => '');
- }
- /**
- * {@inheritDoc}
- */
- public function getSource($identifier)
- {
- return array('type' => 'git', 'url' => $this->getRepositoryUrl(), 'reference' => $identifier);
- }
- /**
- * {@inheritDoc}
- */
- public function getRootIdentifier()
- {
- return $this->project['default_branch'];
- }
- /**
- * {@inheritDoc}
- */
- public function getBranches()
- {
- if (!$this->branches) {
- $this->branches = $this->getReferences('branches');
- }
- return $this->branches;
- }
- /**
- * {@inheritDoc}
- */
- public function getTags()
- {
- if (!$this->tags) {
- $this->tags = $this->getReferences('tags');
- }
- return $this->tags;
- }
- /**
- * @return string Base URL for GitLab API v3
- */
- public function getApiUrl()
- {
- return $this->scheme.'://'.$this->originUrl.'/api/v3/projects/'.$this->urlEncodeAll($this->owner).'%2F'.$this->urlEncodeAll($this->repository);
- }
- /**
- * Urlencode all non alphanumeric characters. rawurlencode() can not be used as it does not encode `.`
- *
- * @param string $string
- * @return string
- */
- private function urlEncodeAll($string)
- {
- $encoded = '';
- for ($i = 0; isset($string[$i]); $i++) {
- $character = $string[$i];
- if (!ctype_alnum($character) && !in_array($character, array('-', '_'), true)) {
- $character = '%' . sprintf('%02X', ord($character));
- }
- $encoded .= $character;
- }
- return $encoded;
- }
- /**
- * @param string $type
- *
- * @return string[] where keys are named references like tags or branches and the value a sha
- */
- protected function getReferences($type)
- {
- $resource = $this->getApiUrl().'/repository/'.$type;
- $data = JsonFile::parseJson($this->getContents($resource), $resource);
- $references = array();
- foreach ($data as $datum) {
- $references[$datum['name']] = $datum['commit']['id'];
- // Keep the last commit date of a reference to avoid
- // unnecessary API call when retrieving the composer file.
- $this->commits[$datum['commit']['id']] = $datum['commit'];
- }
- return $references;
- }
- protected function fetchProject()
- {
- // we need to fetch the default branch from the api
- $resource = $this->getApiUrl();
- $this->project = JsonFile::parseJson($this->getContents($resource, true), $resource);
- }
- protected function attemptCloneFallback()
- {
- try {
- // If this repository may be private and we
- // cannot ask for authentication credentials (because we
- // are not interactive) then we fallback to GitDriver.
- $this->setupGitDriver($this->generateSshUrl());
- return;
- } catch (\RuntimeException $e) {
- $this->gitDriver = null;
- $this->io->writeError('<error>Failed to clone the '.$this->generateSshUrl().' repository, try running in interactive mode so that you can enter your credentials</error>');
- throw $e;
- }
- }
- /**
- * Generate an SSH URL
- *
- * @return string
- */
- protected function generateSshUrl()
- {
- return 'git@' . $this->originUrl . ':'.$this->owner.'/'.$this->repository.'.git';
- }
- protected function setupGitDriver($url)
- {
- $this->gitDriver = new GitDriver(
- array('url' => $url),
- $this->io,
- $this->config,
- $this->process,
- $this->remoteFilesystem
- );
- $this->gitDriver->initialize();
- }
- /**
- * {@inheritDoc}
- */
- protected function getContents($url, $fetchingRepoData = false)
- {
- try {
- return parent::getContents($url);
- } catch (TransportException $e) {
- $gitLabUtil = new GitLab($this->io, $this->config, $this->process, $this->remoteFilesystem);
- switch ($e->getCode()) {
- case 401:
- case 404:
- // try to authorize only if we are fetching the main /repos/foo/bar data, otherwise it must be a real 404
- if (!$fetchingRepoData) {
- throw $e;
- }
- if ($gitLabUtil->authorizeOAuth($this->originUrl)) {
- return parent::getContents($url);
- }
- if (!$this->io->isInteractive()) {
- return $this->attemptCloneFallback();
- }
- $this->io->writeError('<warning>Failed to download ' . $this->owner . '/' . $this->repository . ':' . $e->getMessage() . '</warning>');
- $gitLabUtil->authorizeOAuthInteractively($this->scheme, $this->originUrl, 'Your credentials are required to fetch private repository metadata (<info>'.$this->url.'</info>)');
- return parent::getContents($url);
- case 403:
- if (!$this->io->hasAuthentication($this->originUrl) && $gitLabUtil->authorizeOAuth($this->originUrl)) {
- return parent::getContents($url);
- }
- if (!$this->io->isInteractive() && $fetchingRepoData) {
- return $this->attemptCloneFallback();
- }
- throw $e;
- default:
- throw $e;
- }
- }
- }
- /**
- * Uses the config `gitlab-domains` to see if the driver supports the url for the
- * repository given.
- *
- * {@inheritDoc}
- */
- public static function supports(IOInterface $io, Config $config, $url, $deep = false)
- {
- if (!preg_match(self::URL_REGEX, $url, $match)) {
- return false;
- }
- $scheme = !empty($match['scheme']) ? $match['scheme'] : null;
- $originUrl = !empty($match['domain']) ? $match['domain'] : $match['domain2'];
- if (!in_array($originUrl, (array) $config->get('gitlab-domains'))) {
- return false;
- }
- if ('https' === $scheme && !extension_loaded('openssl')) {
- $io->writeError('Skipping GitLab driver for '.$url.' because the OpenSSL PHP extension is missing.', true, IOInterface::VERBOSE);
- return false;
- }
- return true;
- }
- }
|