123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573 |
- <?php
- namespace Composer\Repository\Vcs;
- use Composer\Config;
- use Composer\Downloader\TransportException;
- use Composer\Json\JsonFile;
- use Composer\Cache;
- use Composer\IO\IOInterface;
- use Composer\Util\GitHub;
- use Composer\Util\Http\Response;
- class GitHubDriver extends VcsDriver
- {
- protected $cache;
- protected $owner;
- protected $repository;
- protected $tags;
- protected $branches;
- protected $rootIdentifier;
- protected $repoData;
- protected $hasIssues;
- protected $infoCache = array();
- protected $isPrivate = false;
- private $isArchived = false;
- private $fundingInfo;
-
- protected $gitDriver;
-
- public function initialize()
- {
- preg_match('#^(?:(?:https?|git)://([^/]+)/|git@([^:]+):/?)([^/]+)/(.+?)(?:\.git|/)?$#', $this->url, $match);
- $this->owner = $match[3];
- $this->repository = $match[4];
- $this->originUrl = strtolower(!empty($match[1]) ? $match[1] : $match[2]);
- if ($this->originUrl === 'www.github.com') {
- $this->originUrl = 'github.com';
- }
- $this->cache = new Cache($this->io, $this->config->get('cache-repo-dir').'/'.$this->originUrl.'/'.$this->owner.'/'.$this->repository);
- if ( $this->config->get('use-github-api') === false || (isset($this->repoConfig['no-api']) && $this->repoConfig['no-api'] ) ){
- $this->setupGitDriver($this->url);
- return;
- }
- $this->fetchRootIdentifier();
- }
- public function getRepositoryUrl()
- {
- return 'https://'.$this->originUrl.'/'.$this->owner.'/'.$this->repository;
- }
-
- public function getRootIdentifier()
- {
- if ($this->gitDriver) {
- return $this->gitDriver->getRootIdentifier();
- }
- return $this->rootIdentifier;
- }
-
- public function getUrl()
- {
- if ($this->gitDriver) {
- return $this->gitDriver->getUrl();
- }
- return 'https://' . $this->originUrl . '/'.$this->owner.'/'.$this->repository.'.git';
- }
-
- protected function getApiUrl()
- {
- if ('github.com' === $this->originUrl) {
- $apiUrl = 'api.github.com';
- } else {
- $apiUrl = $this->originUrl . '/api/v3';
- }
- return 'https://' . $apiUrl;
- }
-
- public function getSource($identifier)
- {
- if ($this->gitDriver) {
- return $this->gitDriver->getSource($identifier);
- }
- if ($this->isPrivate) {
-
-
- $url = $this->generateSshUrl();
- } else {
- $url = $this->getUrl();
- }
- return array('type' => 'git', 'url' => $url, 'reference' => $identifier);
- }
-
- public function getDist($identifier)
- {
- $url = $this->getApiUrl() . '/repos/'.$this->owner.'/'.$this->repository.'/zipball/'.$identifier;
- return array('type' => 'zip', 'url' => $url, 'reference' => $identifier, 'shasum' => '');
- }
-
- public function getComposerInformation($identifier)
- {
- if ($this->gitDriver) {
- return $this->gitDriver->getComposerInformation($identifier);
- }
- if (!isset($this->infoCache[$identifier])) {
- if ($this->shouldCache($identifier) && $res = $this->cache->read($identifier)) {
- return $this->infoCache[$identifier] = JsonFile::parseJson($res);
- }
- $composer = $this->getBaseComposerInformation($identifier);
- if ($composer) {
-
- if (!isset($composer['support']['source'])) {
- $label = array_search($identifier, $this->getTags()) ?: array_search($identifier, $this->getBranches()) ?: $identifier;
- $composer['support']['source'] = sprintf('https://%s/%s/%s/tree/%s', $this->originUrl, $this->owner, $this->repository, $label);
- }
- if (!isset($composer['support']['issues']) && $this->hasIssues) {
- $composer['support']['issues'] = sprintf('https://%s/%s/%s/issues', $this->originUrl, $this->owner, $this->repository);
- }
- if (!isset($composer['abandoned']) && $this->isArchived) {
- $composer['abandoned'] = true;
- }
- if (!isset($composer['funding']) && $funding = $this->getFundingInfo()) {
- $composer['funding'] = $funding;
- }
- }
- if ($this->shouldCache($identifier)) {
- $this->cache->write($identifier, json_encode($composer));
- }
- $this->infoCache[$identifier] = $composer;
- }
- return $this->infoCache[$identifier];
- }
- private function getFundingInfo()
- {
- if (null !== $this->fundingInfo) {
- return $this->fundingInfo;
- }
- if ($this->originUrl !== 'github.com') {
- return $this->fundingInfo = false;
- }
- foreach (array($this->getApiUrl() . '/repos/'.$this->owner.'/'.$this->repository.'/contents/.github/FUNDING.yml', $this->getApiUrl() . '/repos/'.$this->owner.'/.github/contents/FUNDING.yml') as $file) {
- try {
- $response = $this->httpDownloader->get($file, array(
- 'retry-auth-failure' => false,
- ))->decodeJson();
- } catch (TransportException $e) {
- continue;
- }
- if (empty($response['content']) || $response['encoding'] !== 'base64' || !($funding = base64_decode($response['content']))) {
- continue;
- }
- break;
- }
- if (empty($funding)) {
- return $this->fundingInfo = false;
- }
- $result = array();
- $key = null;
- foreach (preg_split('{\r?\n}', $funding) as $line) {
- $line = preg_replace('{#.*}', '', $line);
- $line = trim($line);
- if (preg_match('{^(\w+)\s*:\s*(.+)$}', $line, $match)) {
- if (preg_match('{^\[.*\]$}', $match[2])) {
- foreach (array_map('trim', preg_split('{[\'"]?\s*,\s*[\'"]?}', substr($match[2], 1, -1))) as $item) {
- $result[] = array('type' => $match[1], 'url' => trim($item, '"\' '));
- }
- } else {
- $result[] = array('type' => $match[1], 'url' => trim($match[2], '"\' '));
- }
- $key = null;
- } elseif (preg_match('{^(\w+)\s*:$}', $line, $match)) {
- $key = $match[1];
- } elseif ($key && preg_match('{^-\s*(.+)$}', $line, $match)) {
- $result[] = array('type' => $key, 'url' => trim($match[1], '"\' '));
- }
- }
- foreach ($result as $key => $item) {
- switch ($item['type']) {
- case 'tidelift':
- $result[$key]['url'] = 'https://tidelift.com/funding/github/' . $item['url'];
- break;
- case 'github':
- $result[$key]['url'] = 'https://github.com/' . basename($item['url']);
- break;
- case 'patreon':
- $result[$key]['url'] = 'https://www.patreon.com/' . basename($item['url']);
- break;
- case 'otechie':
- $result[$key]['url'] = 'https://otechie.com/' . basename($item['url']);
- break;
- case 'open_collective':
- $result[$key]['url'] = 'https://opencollective.com/' . basename($item['url']);
- break;
- case 'liberapay':
- $result[$key]['url'] = 'https://liberapay.com/' . basename($item['url']);
- break;
- case 'ko_fi':
- $result[$key]['url'] = 'https://ko-fi.com/' . basename($item['url']);
- break;
- case 'issuehunt':
- $result[$key]['url'] = 'https://issuehunt.io/r/' . $item['url'];
- break;
- case 'community_bridge':
- $result[$key]['url'] = 'https://funding.communitybridge.org/projects/' . basename($item['url']);
- break;
- }
- }
- return $this->fundingInfo = $result;
- }
-
- public function getFileContent($file, $identifier)
- {
- if ($this->gitDriver) {
- return $this->gitDriver->getFileContent($file, $identifier);
- }
- $resource = $this->getApiUrl() . '/repos/'.$this->owner.'/'.$this->repository.'/contents/' . $file . '?ref='.urlencode($identifier);
- $resource = $this->getContents($resource)->decodeJson();
- if (empty($resource['content']) || $resource['encoding'] !== 'base64' || !($content = base64_decode($resource['content']))) {
- throw new \RuntimeException('Could not retrieve ' . $file . ' for '.$identifier);
- }
- return $content;
- }
-
- public function getChangeDate($identifier)
- {
- if ($this->gitDriver) {
- return $this->gitDriver->getChangeDate($identifier);
- }
- $resource = $this->getApiUrl() . '/repos/'.$this->owner.'/'.$this->repository.'/commits/'.urlencode($identifier);
- $commit = $this->getContents($resource)->decodeJson();
- return new \DateTime($commit['commit']['committer']['date']);
- }
-
- public function getTags()
- {
- if ($this->gitDriver) {
- return $this->gitDriver->getTags();
- }
- if (null === $this->tags) {
- $this->tags = array();
- $resource = $this->getApiUrl() . '/repos/'.$this->owner.'/'.$this->repository.'/tags?per_page=100';
- do {
- $response = $this->getContents($resource);
- $tagsData = $response->decodeJson();
- foreach ($tagsData as $tag) {
- $this->tags[$tag['name']] = $tag['commit']['sha'];
- }
- $resource = $this->getNextPage($response);
- } while ($resource);
- }
- return $this->tags;
- }
-
- public function getBranches()
- {
- if ($this->gitDriver) {
- return $this->gitDriver->getBranches();
- }
- if (null === $this->branches) {
- $this->branches = array();
- $resource = $this->getApiUrl() . '/repos/'.$this->owner.'/'.$this->repository.'/git/refs/heads?per_page=100';
- $branchBlacklist = array('gh-pages');
- do {
- $response = $this->getContents($resource);
- $branchData = $response->decodeJson();
- foreach ($branchData as $branch) {
- $name = substr($branch['ref'], 11);
- if (!in_array($name, $branchBlacklist)) {
- $this->branches[$name] = $branch['object']['sha'];
- }
- }
- $resource = $this->getNextPage($response);
- } while ($resource);
- }
- return $this->branches;
- }
-
- public static function supports(IOInterface $io, Config $config, $url, $deep = false)
- {
- if (!preg_match('#^((?:https?|git)://([^/]+)/|git@([^:]+):/?)([^/]+)/(.+?)(?:\.git|/)?$#', $url, $matches)) {
- return false;
- }
- $originUrl = !empty($matches[2]) ? $matches[2] : $matches[3];
- if (!in_array(strtolower(preg_replace('{^www\.}i', '', $originUrl)), $config->get('github-domains'))) {
- return false;
- }
- if (!extension_loaded('openssl')) {
- $io->writeError('Skipping GitHub driver for '.$url.' because the OpenSSL PHP extension is missing.', true, IOInterface::VERBOSE);
- return false;
- }
- return true;
- }
-
- public function getRepoData()
- {
- $this->fetchRootIdentifier();
- return $this->repoData;
- }
-
- protected function generateSshUrl()
- {
- if (false !== strpos($this->originUrl, ':')) {
- return 'ssh://git@' . $this->originUrl . '/'.$this->owner.'/'.$this->repository.'.git';
- }
- return 'git@' . $this->originUrl . ':'.$this->owner.'/'.$this->repository.'.git';
- }
-
- protected function getContents($url, $fetchingRepoData = false)
- {
- try {
- return parent::getContents($url);
- } catch (TransportException $e) {
- $gitHubUtil = new GitHub($this->io, $this->config, $this->process, $this->httpDownloader);
- switch ($e->getCode()) {
- case 401:
- case 404:
-
- if (!$fetchingRepoData) {
- throw $e;
- }
- if ($gitHubUtil->authorizeOAuth($this->originUrl)) {
- return parent::getContents($url);
- }
- if (!$this->io->isInteractive()) {
- if ($this->attemptCloneFallback()) {
- return new Response(array('url' => 'dummy'), 200, array(), 'null');
- }
- }
- $scopesIssued = array();
- $scopesNeeded = array();
- if ($headers = $e->getHeaders()) {
- if ($scopes = Response::findHeaderValue($headers, 'X-OAuth-Scopes')) {
- $scopesIssued = explode(' ', $scopes);
- }
- if ($scopes = Response::findHeaderValue($headers, 'X-Accepted-OAuth-Scopes')) {
- $scopesNeeded = explode(' ', $scopes);
- }
- }
- $scopesFailed = array_diff($scopesNeeded, $scopesIssued);
-
-
- if (!$headers || !count($scopesNeeded) || count($scopesFailed)) {
- $gitHubUtil->authorizeOAuthInteractively($this->originUrl, 'Your GitHub credentials are required to fetch private repository metadata (<info>'.$this->url.'</info>)');
- }
- return parent::getContents($url);
- case 403:
- if (!$this->io->hasAuthentication($this->originUrl) && $gitHubUtil->authorizeOAuth($this->originUrl)) {
- return parent::getContents($url);
- }
- if (!$this->io->isInteractive() && $fetchingRepoData) {
- if ($this->attemptCloneFallback()) {
- return new Response(array('url' => 'dummy'), 200, array(), 'null');
- }
- }
- $rateLimited = $gitHubUtil->isRateLimited($e->getHeaders());
- if (!$this->io->hasAuthentication($this->originUrl)) {
- if (!$this->io->isInteractive()) {
- $this->io->writeError('<error>GitHub API limit exhausted. Failed to get metadata for the '.$this->url.' repository, try running in interactive mode so that you can enter your GitHub credentials to increase the API limit</error>');
- throw $e;
- }
- $gitHubUtil->authorizeOAuthInteractively($this->originUrl, 'API limit exhausted. Enter your GitHub credentials to get a larger API limit (<info>'.$this->url.'</info>)');
- return parent::getContents($url);
- }
- if ($rateLimited) {
- $rateLimit = $gitHubUtil->getRateLimit($e->getHeaders());
- $this->io->writeError(sprintf(
- '<error>GitHub API limit (%d calls/hr) is exhausted. You are already authorized so you have to wait until %s before doing more requests</error>',
- $rateLimit['limit'],
- $rateLimit['reset']
- ));
- }
- throw $e;
- default:
- throw $e;
- }
- }
- }
-
- protected function fetchRootIdentifier()
- {
- if ($this->repoData) {
- return;
- }
- $repoDataUrl = $this->getApiUrl() . '/repos/'.$this->owner.'/'.$this->repository;
- $this->repoData = $this->getContents($repoDataUrl, true)->decodeJson();
- if (null === $this->repoData && null !== $this->gitDriver) {
- return;
- }
- $this->owner = $this->repoData['owner']['login'];
- $this->repository = $this->repoData['name'];
- $this->isPrivate = !empty($this->repoData['private']);
- if (isset($this->repoData['default_branch'])) {
- $this->rootIdentifier = $this->repoData['default_branch'];
- } elseif (isset($this->repoData['master_branch'])) {
- $this->rootIdentifier = $this->repoData['master_branch'];
- } else {
- $this->rootIdentifier = 'master';
- }
- $this->hasIssues = !empty($this->repoData['has_issues']);
- $this->isArchived = !empty($this->repoData['archived']);
- }
- protected function attemptCloneFallback()
- {
- $this->isPrivate = true;
- try {
-
-
-
-
- $this->setupGitDriver($this->generateSshUrl());
- return true;
- } 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 GitHub credentials</error>');
- throw $e;
- }
- }
- protected function setupGitDriver($url)
- {
- $this->gitDriver = new GitDriver(
- array('url' => $url),
- $this->io,
- $this->config,
- $this->httpDownloader,
- $this->process
- );
- $this->gitDriver->initialize();
- }
- protected function getNextPage(Response $response)
- {
- $header = $response->getHeader('link');
- $links = explode(',', $header);
- foreach ($links as $link) {
- if (preg_match('{<(.+?)>; *rel="next"}', $link, $match)) {
- return $match[1];
- }
- }
- }
- }
|