GitHubDriver.php 17 KB

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