GitHubDriver.php 15 KB

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