GitHubDriver.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520
  1. <?php
  2. /*
  3. * This file is part of Composer.
  4. *
  5. * (c) Nils Adermann <naderman@naderman.de>
  6. * Jordi Boggiano <j.boggiano@seld.be>
  7. *
  8. * For the full copyright and license information, please view the LICENSE
  9. * file that was distributed with this source code.
  10. */
  11. namespace Composer\Repository\Vcs;
  12. use Composer\Config;
  13. use Composer\Downloader\TransportException;
  14. use Composer\Json\JsonFile;
  15. use Composer\Cache;
  16. use Composer\IO\IOInterface;
  17. use Composer\Util\GitHub;
  18. /**
  19. * @author Jordi Boggiano <j.boggiano@seld.be>
  20. */
  21. class GitHubDriver extends VcsDriver
  22. {
  23. protected $cache;
  24. protected $owner;
  25. protected $repository;
  26. protected $tags;
  27. protected $branches;
  28. protected $rootIdentifier;
  29. protected $repoData;
  30. protected $hasIssues;
  31. protected $infoCache = array();
  32. protected $isPrivate = false;
  33. private $isArchived = false;
  34. private $fundingInfo;
  35. /**
  36. * Git Driver
  37. *
  38. * @var GitDriver
  39. */
  40. protected $gitDriver;
  41. /**
  42. * {@inheritDoc}
  43. */
  44. public function initialize()
  45. {
  46. preg_match('#^(?:(?:https?|git)://([^/]+)/|git@([^:]+):/?)([^/]+)/(.+?)(?:\.git|/)?$#', $this->url, $match);
  47. $this->owner = $match[3];
  48. $this->repository = $match[4];
  49. $this->originUrl = strtolower(!empty($match[1]) ? $match[1] : $match[2]);
  50. if ($this->originUrl === 'www.github.com') {
  51. $this->originUrl = 'github.com';
  52. }
  53. $this->cache = new Cache($this->io, $this->config->get('cache-repo-dir').'/'.$this->originUrl.'/'.$this->owner.'/'.$this->repository);
  54. if ( $this->config->get('use-github-api') === false || (isset($this->repoConfig['no-api']) && $this->repoConfig['no-api'] ) ){
  55. $this->setupGitDriver($this->url);
  56. return;
  57. }
  58. $this->fetchRootIdentifier();
  59. }
  60. public function getRepositoryUrl()
  61. {
  62. return 'https://'.$this->originUrl.'/'.$this->owner.'/'.$this->repository;
  63. }
  64. /**
  65. * {@inheritDoc}
  66. */
  67. public function getRootIdentifier()
  68. {
  69. if ($this->gitDriver) {
  70. return $this->gitDriver->getRootIdentifier();
  71. }
  72. return $this->rootIdentifier;
  73. }
  74. /**
  75. * {@inheritDoc}
  76. */
  77. public function getUrl()
  78. {
  79. if ($this->gitDriver) {
  80. return $this->gitDriver->getUrl();
  81. }
  82. return 'https://' . $this->originUrl . '/'.$this->owner.'/'.$this->repository.'.git';
  83. }
  84. /**
  85. * {@inheritDoc}
  86. */
  87. protected function getApiUrl()
  88. {
  89. if ('github.com' === $this->originUrl) {
  90. $apiUrl = 'api.github.com';
  91. } else {
  92. $apiUrl = $this->originUrl . '/api/v3';
  93. }
  94. return 'https://' . $apiUrl;
  95. }
  96. /**
  97. * {@inheritDoc}
  98. */
  99. public function getSource($identifier)
  100. {
  101. if ($this->gitDriver) {
  102. return $this->gitDriver->getSource($identifier);
  103. }
  104. if ($this->isPrivate) {
  105. // Private GitHub repositories should be accessed using the
  106. // SSH version of the URL.
  107. $url = $this->generateSshUrl();
  108. } else {
  109. $url = $this->getUrl();
  110. }
  111. return array('type' => 'git', 'url' => $url, 'reference' => $identifier);
  112. }
  113. /**
  114. * {@inheritDoc}
  115. */
  116. public function getDist($identifier)
  117. {
  118. $url = $this->getApiUrl() . '/repos/'.$this->owner.'/'.$this->repository.'/zipball/'.$identifier;
  119. return array('type' => 'zip', 'url' => $url, 'reference' => $identifier, 'shasum' => '');
  120. }
  121. /**
  122. * {@inheritDoc}
  123. */
  124. public function getComposerInformation($identifier)
  125. {
  126. if ($this->gitDriver) {
  127. return $this->gitDriver->getComposerInformation($identifier);
  128. }
  129. if (!isset($this->infoCache[$identifier])) {
  130. if ($this->shouldCache($identifier) && $res = $this->cache->read($identifier)) {
  131. return $this->infoCache[$identifier] = JsonFile::parseJson($res);
  132. }
  133. $composer = $this->getBaseComposerInformation($identifier);
  134. if ($composer) {
  135. // specials for github
  136. if (!isset($composer['support']['source'])) {
  137. $label = array_search($identifier, $this->getTags()) ?: array_search($identifier, $this->getBranches()) ?: $identifier;
  138. $composer['support']['source'] = sprintf('https://%s/%s/%s/tree/%s', $this->originUrl, $this->owner, $this->repository, $label);
  139. }
  140. if (!isset($composer['support']['issues']) && $this->hasIssues) {
  141. $composer['support']['issues'] = sprintf('https://%s/%s/%s/issues', $this->originUrl, $this->owner, $this->repository);
  142. }
  143. if (!isset($composer['abandoned']) && $this->isArchived) {
  144. $composer['abandoned'] = true;
  145. }
  146. if (!isset($composer['funding']) && $funding = $this->getFundingInfo()) {
  147. $composer['funding'] = $funding;
  148. }
  149. }
  150. if ($this->shouldCache($identifier)) {
  151. $this->cache->write($identifier, json_encode($composer));
  152. }
  153. $this->infoCache[$identifier] = $composer;
  154. }
  155. return $this->infoCache[$identifier];
  156. }
  157. private function getFundingInfo()
  158. {
  159. if (null !== $this->fundingInfo) {
  160. return $this->fundingInfo;
  161. }
  162. if ($this->originUrl !== 'github.com') {
  163. return $this->fundingInfo = false;
  164. }
  165. $graphql = 'query{repository(owner:"'.$this->owner.'",name:"'.$this->repository.'"){fundingLinks{platform,url}}}';
  166. try {
  167. $result = $this->remoteFilesystem->getContents($this->originUrl, 'https://api.github.com/graphql', false, array(
  168. 'http' => array(
  169. 'method' => 'POST',
  170. 'content' => json_encode(array('query' => $graphql)),
  171. 'header' => array('Content-Type: application/json'),
  172. ),
  173. 'retry-auth-failure' => false,
  174. ));
  175. } catch (\TransportException $e) {
  176. return $this->fundingInfo = false;
  177. }
  178. $result = json_decode($result, true);
  179. if (empty($result['data']['repository']['fundingLinks'])) {
  180. return $this->fundingInfo = false;
  181. }
  182. return $this->fundingInfo = array_map(function ($link) {
  183. return array('type' => strtolower($link['platform']), 'url' => $link['url']);
  184. }, $result['data']['repository']['fundingLinks']);
  185. }
  186. /**
  187. * {@inheritdoc}
  188. */
  189. public function getFileContent($file, $identifier)
  190. {
  191. if ($this->gitDriver) {
  192. return $this->gitDriver->getFileContent($file, $identifier);
  193. }
  194. $resource = $this->getApiUrl() . '/repos/'.$this->owner.'/'.$this->repository.'/contents/' . $file . '?ref='.urlencode($identifier);
  195. $resource = JsonFile::parseJson($this->getContents($resource));
  196. if (empty($resource['content']) || $resource['encoding'] !== 'base64' || !($content = base64_decode($resource['content']))) {
  197. throw new \RuntimeException('Could not retrieve ' . $file . ' for '.$identifier);
  198. }
  199. return $content;
  200. }
  201. /**
  202. * {@inheritdoc}
  203. */
  204. public function getChangeDate($identifier)
  205. {
  206. if ($this->gitDriver) {
  207. return $this->gitDriver->getChangeDate($identifier);
  208. }
  209. $resource = $this->getApiUrl() . '/repos/'.$this->owner.'/'.$this->repository.'/commits/'.urlencode($identifier);
  210. $commit = JsonFile::parseJson($this->getContents($resource), $resource);
  211. return new \DateTime($commit['commit']['committer']['date']);
  212. }
  213. /**
  214. * {@inheritDoc}
  215. */
  216. public function getTags()
  217. {
  218. if ($this->gitDriver) {
  219. return $this->gitDriver->getTags();
  220. }
  221. if (null === $this->tags) {
  222. $this->tags = array();
  223. $resource = $this->getApiUrl() . '/repos/'.$this->owner.'/'.$this->repository.'/tags?per_page=100';
  224. do {
  225. $tagsData = JsonFile::parseJson($this->getContents($resource), $resource);
  226. foreach ($tagsData as $tag) {
  227. $this->tags[$tag['name']] = $tag['commit']['sha'];
  228. }
  229. $resource = $this->getNextPage();
  230. } while ($resource);
  231. }
  232. return $this->tags;
  233. }
  234. /**
  235. * {@inheritDoc}
  236. */
  237. public function getBranches()
  238. {
  239. if ($this->gitDriver) {
  240. return $this->gitDriver->getBranches();
  241. }
  242. if (null === $this->branches) {
  243. $this->branches = array();
  244. $resource = $this->getApiUrl() . '/repos/'.$this->owner.'/'.$this->repository.'/git/refs/heads?per_page=100';
  245. $branchBlacklist = array('gh-pages');
  246. do {
  247. $branchData = JsonFile::parseJson($this->getContents($resource), $resource);
  248. foreach ($branchData as $branch) {
  249. $name = substr($branch['ref'], 11);
  250. if (!in_array($name, $branchBlacklist)) {
  251. $this->branches[$name] = $branch['object']['sha'];
  252. }
  253. }
  254. $resource = $this->getNextPage();
  255. } while ($resource);
  256. }
  257. return $this->branches;
  258. }
  259. /**
  260. * {@inheritDoc}
  261. */
  262. public static function supports(IOInterface $io, Config $config, $url, $deep = false)
  263. {
  264. if (!preg_match('#^((?:https?|git)://([^/]+)/|git@([^:]+):/?)([^/]+)/(.+?)(?:\.git|/)?$#', $url, $matches)) {
  265. return false;
  266. }
  267. $originUrl = !empty($matches[2]) ? $matches[2] : $matches[3];
  268. if (!in_array(strtolower(preg_replace('{^www\.}i', '', $originUrl)), $config->get('github-domains'))) {
  269. return false;
  270. }
  271. if (!extension_loaded('openssl')) {
  272. $io->writeError('Skipping GitHub driver for '.$url.' because the OpenSSL PHP extension is missing.', true, IOInterface::VERBOSE);
  273. return false;
  274. }
  275. return true;
  276. }
  277. /**
  278. * Gives back the loaded <github-api>/repos/<owner>/<repo> result
  279. *
  280. * @return array|null
  281. */
  282. public function getRepoData()
  283. {
  284. $this->fetchRootIdentifier();
  285. return $this->repoData;
  286. }
  287. /**
  288. * Generate an SSH URL
  289. *
  290. * @return string
  291. */
  292. protected function generateSshUrl()
  293. {
  294. if (false !== strpos($this->originUrl, ':')) {
  295. return 'ssh://git@' . $this->originUrl . '/'.$this->owner.'/'.$this->repository.'.git';
  296. }
  297. return 'git@' . $this->originUrl . ':'.$this->owner.'/'.$this->repository.'.git';
  298. }
  299. /**
  300. * {@inheritDoc}
  301. */
  302. protected function getContents($url, $fetchingRepoData = false)
  303. {
  304. try {
  305. return parent::getContents($url);
  306. } catch (TransportException $e) {
  307. $gitHubUtil = new GitHub($this->io, $this->config, $this->process, $this->remoteFilesystem);
  308. switch ($e->getCode()) {
  309. case 401:
  310. case 404:
  311. // try to authorize only if we are fetching the main /repos/foo/bar data, otherwise it must be a real 404
  312. if (!$fetchingRepoData) {
  313. throw $e;
  314. }
  315. if ($gitHubUtil->authorizeOAuth($this->originUrl)) {
  316. return parent::getContents($url);
  317. }
  318. if (!$this->io->isInteractive()) {
  319. return $this->attemptCloneFallback();
  320. }
  321. $scopesIssued = array();
  322. $scopesNeeded = array();
  323. if ($headers = $e->getHeaders()) {
  324. if ($scopes = $this->remoteFilesystem->findHeaderValue($headers, 'X-OAuth-Scopes')) {
  325. $scopesIssued = explode(' ', $scopes);
  326. }
  327. if ($scopes = $this->remoteFilesystem->findHeaderValue($headers, 'X-Accepted-OAuth-Scopes')) {
  328. $scopesNeeded = explode(' ', $scopes);
  329. }
  330. }
  331. $scopesFailed = array_diff($scopesNeeded, $scopesIssued);
  332. // non-authenticated requests get no scopesNeeded, so ask for credentials
  333. // authenticated requests which failed some scopes should ask for new credentials too
  334. if (!$headers || !count($scopesNeeded) || count($scopesFailed)) {
  335. $gitHubUtil->authorizeOAuthInteractively($this->originUrl, 'Your GitHub credentials are required to fetch private repository metadata (<info>'.$this->url.'</info>)');
  336. }
  337. return parent::getContents($url);
  338. case 403:
  339. if (!$this->io->hasAuthentication($this->originUrl) && $gitHubUtil->authorizeOAuth($this->originUrl)) {
  340. return parent::getContents($url);
  341. }
  342. if (!$this->io->isInteractive() && $fetchingRepoData) {
  343. return $this->attemptCloneFallback();
  344. }
  345. $rateLimited = $gitHubUtil->isRateLimited($e->getHeaders());
  346. if (!$this->io->hasAuthentication($this->originUrl)) {
  347. if (!$this->io->isInteractive()) {
  348. $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>');
  349. throw $e;
  350. }
  351. $gitHubUtil->authorizeOAuthInteractively($this->originUrl, 'API limit exhausted. Enter your GitHub credentials to get a larger API limit (<info>'.$this->url.'</info>)');
  352. return parent::getContents($url);
  353. }
  354. if ($rateLimited) {
  355. $rateLimit = $gitHubUtil->getRateLimit($e->getHeaders());
  356. $this->io->writeError(sprintf(
  357. '<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>',
  358. $rateLimit['limit'],
  359. $rateLimit['reset']
  360. ));
  361. }
  362. throw $e;
  363. default:
  364. throw $e;
  365. }
  366. }
  367. }
  368. /**
  369. * Fetch root identifier from GitHub
  370. *
  371. * @throws TransportException
  372. */
  373. protected function fetchRootIdentifier()
  374. {
  375. if ($this->repoData) {
  376. return;
  377. }
  378. $repoDataUrl = $this->getApiUrl() . '/repos/'.$this->owner.'/'.$this->repository;
  379. $this->repoData = JsonFile::parseJson($this->getContents($repoDataUrl, true), $repoDataUrl);
  380. if (null === $this->repoData && null !== $this->gitDriver) {
  381. return;
  382. }
  383. $this->owner = $this->repoData['owner']['login'];
  384. $this->repository = $this->repoData['name'];
  385. $this->isPrivate = !empty($this->repoData['private']);
  386. if (isset($this->repoData['default_branch'])) {
  387. $this->rootIdentifier = $this->repoData['default_branch'];
  388. } elseif (isset($this->repoData['master_branch'])) {
  389. $this->rootIdentifier = $this->repoData['master_branch'];
  390. } else {
  391. $this->rootIdentifier = 'master';
  392. }
  393. $this->hasIssues = !empty($this->repoData['has_issues']);
  394. $this->isArchived = !empty($this->repoData['archived']);
  395. }
  396. protected function attemptCloneFallback()
  397. {
  398. $this->isPrivate = true;
  399. try {
  400. // If this repository may be private (hard to say for sure,
  401. // GitHub returns 404 for private repositories) and we
  402. // cannot ask for authentication credentials (because we
  403. // are not interactive) then we fallback to GitDriver.
  404. $this->setupGitDriver($this->generateSshUrl());
  405. return;
  406. } catch (\RuntimeException $e) {
  407. $this->gitDriver = null;
  408. $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>');
  409. throw $e;
  410. }
  411. }
  412. protected function setupGitDriver($url)
  413. {
  414. $this->gitDriver = new GitDriver(
  415. array('url' => $url),
  416. $this->io,
  417. $this->config,
  418. $this->process,
  419. $this->remoteFilesystem
  420. );
  421. $this->gitDriver->initialize();
  422. }
  423. protected function getNextPage()
  424. {
  425. $headers = $this->remoteFilesystem->getLastHeaders();
  426. foreach ($headers as $header) {
  427. if (preg_match('{^link:\s*(.+?)\s*$}i', $header, $match)) {
  428. $links = explode(',', $match[1]);
  429. foreach ($links as $link) {
  430. if (preg_match('{<(.+?)>; *rel="next"}', $link, $match)) {
  431. return $match[1];
  432. }
  433. }
  434. }
  435. }
  436. }
  437. }