GitHubDriver.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  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. use Composer\Util\Http\Response;
  19. use Composer\Util\RemoteFilesystem;
  20. /**
  21. * @author Jordi Boggiano <j.boggiano@seld.be>
  22. */
  23. class GitHubDriver extends VcsDriver
  24. {
  25. protected $cache;
  26. protected $owner;
  27. protected $repository;
  28. protected $tags;
  29. protected $branches;
  30. protected $rootIdentifier;
  31. protected $repoData;
  32. protected $hasIssues;
  33. protected $infoCache = array();
  34. protected $isPrivate = false;
  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 = !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. }
  144. if ($this->shouldCache($identifier)) {
  145. $this->cache->write($identifier, json_encode($composer));
  146. }
  147. $this->infoCache[$identifier] = $composer;
  148. }
  149. return $this->infoCache[$identifier];
  150. }
  151. /**
  152. * {@inheritdoc}
  153. */
  154. public function getFileContent($file, $identifier)
  155. {
  156. if ($this->gitDriver) {
  157. return $this->gitDriver->getFileContent($file, $identifier);
  158. }
  159. $resource = $this->getApiUrl() . '/repos/'.$this->owner.'/'.$this->repository.'/contents/' . $file . '?ref='.urlencode($identifier);
  160. $resource = $this->getContents($resource)->decodeJson();
  161. if (empty($resource['content']) || $resource['encoding'] !== 'base64' || !($content = base64_decode($resource['content']))) {
  162. throw new \RuntimeException('Could not retrieve ' . $file . ' for '.$identifier);
  163. }
  164. return $content;
  165. }
  166. /**
  167. * {@inheritdoc}
  168. */
  169. public function getChangeDate($identifier)
  170. {
  171. if ($this->gitDriver) {
  172. return $this->gitDriver->getChangeDate($identifier);
  173. }
  174. $resource = $this->getApiUrl() . '/repos/'.$this->owner.'/'.$this->repository.'/commits/'.urlencode($identifier);
  175. $commit = $this->getContents($resource)->decodeJson();
  176. return new \DateTime($commit['commit']['committer']['date']);
  177. }
  178. /**
  179. * {@inheritDoc}
  180. */
  181. public function getTags()
  182. {
  183. if ($this->gitDriver) {
  184. return $this->gitDriver->getTags();
  185. }
  186. if (null === $this->tags) {
  187. $this->tags = array();
  188. $resource = $this->getApiUrl() . '/repos/'.$this->owner.'/'.$this->repository.'/tags?per_page=100';
  189. do {
  190. $response = $this->getContents($resource);
  191. $tagsData = $response->decodeJson();
  192. foreach ($tagsData as $tag) {
  193. $this->tags[$tag['name']] = $tag['commit']['sha'];
  194. }
  195. $resource = $this->getNextPage($response);
  196. } while ($resource);
  197. }
  198. return $this->tags;
  199. }
  200. /**
  201. * {@inheritDoc}
  202. */
  203. public function getBranches()
  204. {
  205. if ($this->gitDriver) {
  206. return $this->gitDriver->getBranches();
  207. }
  208. if (null === $this->branches) {
  209. $this->branches = array();
  210. $resource = $this->getApiUrl() . '/repos/'.$this->owner.'/'.$this->repository.'/git/refs/heads?per_page=100';
  211. $branchBlacklist = array('gh-pages');
  212. do {
  213. $response = $this->getContents($resource);
  214. $branchData = $response->decodeJson();
  215. foreach ($branchData as $branch) {
  216. $name = substr($branch['ref'], 11);
  217. if (!in_array($name, $branchBlacklist)) {
  218. $this->branches[$name] = $branch['object']['sha'];
  219. }
  220. }
  221. $resource = $this->getNextPage($response);
  222. } while ($resource);
  223. }
  224. return $this->branches;
  225. }
  226. /**
  227. * {@inheritDoc}
  228. */
  229. public static function supports(IOInterface $io, Config $config, $url, $deep = false)
  230. {
  231. if (!preg_match('#^((?:https?|git)://([^/]+)/|git@([^:]+):)([^/]+)/(.+?)(?:\.git|/)?$#', $url, $matches)) {
  232. return false;
  233. }
  234. $originUrl = !empty($matches[2]) ? $matches[2] : $matches[3];
  235. if (!in_array(preg_replace('{^www\.}i', '', $originUrl), $config->get('github-domains'))) {
  236. return false;
  237. }
  238. if (!extension_loaded('openssl')) {
  239. $io->writeError('Skipping GitHub driver for '.$url.' because the OpenSSL PHP extension is missing.', true, IOInterface::VERBOSE);
  240. return false;
  241. }
  242. return true;
  243. }
  244. /**
  245. * Gives back the loaded <github-api>/repos/<owner>/<repo> result
  246. *
  247. * @return array|null
  248. */
  249. public function getRepoData()
  250. {
  251. $this->fetchRootIdentifier();
  252. return $this->repoData;
  253. }
  254. /**
  255. * Generate an SSH URL
  256. *
  257. * @return string
  258. */
  259. protected function generateSshUrl()
  260. {
  261. return 'git@' . $this->originUrl . ':'.$this->owner.'/'.$this->repository.'.git';
  262. }
  263. /**
  264. * {@inheritDoc}
  265. */
  266. protected function getContents($url, $fetchingRepoData = false)
  267. {
  268. try {
  269. return parent::getContents($url);
  270. } catch (TransportException $e) {
  271. $gitHubUtil = new GitHub($this->io, $this->config, $this->process, $this->httpDownloader);
  272. switch ($e->getCode()) {
  273. case 401:
  274. case 404:
  275. // try to authorize only if we are fetching the main /repos/foo/bar data, otherwise it must be a real 404
  276. if (!$fetchingRepoData) {
  277. throw $e;
  278. }
  279. if ($gitHubUtil->authorizeOAuth($this->originUrl)) {
  280. return parent::getContents($url);
  281. }
  282. if (!$this->io->isInteractive()) {
  283. if ($this->attemptCloneFallback()) {
  284. return new Response(array('url' => 'dummy'), 200, array(), 'null');
  285. }
  286. }
  287. $scopesIssued = array();
  288. $scopesNeeded = array();
  289. if ($headers = $e->getHeaders()) {
  290. if ($scopes = RemoteFilesystem::findHeaderValue($headers, 'X-OAuth-Scopes')) {
  291. $scopesIssued = explode(' ', $scopes);
  292. }
  293. if ($scopes = RemoteFilesystem::findHeaderValue($headers, 'X-Accepted-OAuth-Scopes')) {
  294. $scopesNeeded = explode(' ', $scopes);
  295. }
  296. }
  297. $scopesFailed = array_diff($scopesNeeded, $scopesIssued);
  298. // non-authenticated requests get no scopesNeeded, so ask for credentials
  299. // authenticated requests which failed some scopes should ask for new credentials too
  300. if (!$headers || !count($scopesNeeded) || count($scopesFailed)) {
  301. $gitHubUtil->authorizeOAuthInteractively($this->originUrl, 'Your GitHub credentials are required to fetch private repository metadata (<info>'.$this->url.'</info>)');
  302. }
  303. return parent::getContents($url);
  304. case 403:
  305. if (!$this->io->hasAuthentication($this->originUrl) && $gitHubUtil->authorizeOAuth($this->originUrl)) {
  306. return parent::getContents($url);
  307. }
  308. if (!$this->io->isInteractive() && $fetchingRepoData) {
  309. if ($this->attemptCloneFallback()) {
  310. return new Response(array('url' => 'dummy'), 200, array(), 'null');
  311. }
  312. }
  313. $rateLimited = $gitHubUtil->isRateLimited($e->getHeaders());
  314. if (!$this->io->hasAuthentication($this->originUrl)) {
  315. if (!$this->io->isInteractive()) {
  316. $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>');
  317. throw $e;
  318. }
  319. $gitHubUtil->authorizeOAuthInteractively($this->originUrl, 'API limit exhausted. Enter your GitHub credentials to get a larger API limit (<info>'.$this->url.'</info>)');
  320. return parent::getContents($url);
  321. }
  322. if ($rateLimited) {
  323. $rateLimit = $gitHubUtil->getRateLimit($e->getHeaders());
  324. $this->io->writeError(sprintf(
  325. '<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>',
  326. $rateLimit['limit'],
  327. $rateLimit['reset']
  328. ));
  329. }
  330. throw $e;
  331. default:
  332. throw $e;
  333. }
  334. }
  335. }
  336. /**
  337. * Fetch root identifier from GitHub
  338. *
  339. * @throws TransportException
  340. */
  341. protected function fetchRootIdentifier()
  342. {
  343. if ($this->repoData) {
  344. return;
  345. }
  346. $repoDataUrl = $this->getApiUrl() . '/repos/'.$this->owner.'/'.$this->repository;
  347. $this->repoData = $this->getContents($repoDataUrl, true)->decodeJson();
  348. if (null === $this->repoData && null !== $this->gitDriver) {
  349. return;
  350. }
  351. $this->owner = $this->repoData['owner']['login'];
  352. $this->repository = $this->repoData['name'];
  353. $this->isPrivate = !empty($this->repoData['private']);
  354. if (isset($this->repoData['default_branch'])) {
  355. $this->rootIdentifier = $this->repoData['default_branch'];
  356. } elseif (isset($this->repoData['master_branch'])) {
  357. $this->rootIdentifier = $this->repoData['master_branch'];
  358. } else {
  359. $this->rootIdentifier = 'master';
  360. }
  361. $this->hasIssues = !empty($this->repoData['has_issues']);
  362. }
  363. protected function attemptCloneFallback()
  364. {
  365. $this->isPrivate = true;
  366. try {
  367. // If this repository may be private (hard to say for sure,
  368. // GitHub returns 404 for private repositories) and we
  369. // cannot ask for authentication credentials (because we
  370. // are not interactive) then we fallback to GitDriver.
  371. $this->setupGitDriver($this->generateSshUrl());
  372. return true;
  373. } catch (\RuntimeException $e) {
  374. $this->gitDriver = null;
  375. $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>');
  376. throw $e;
  377. }
  378. }
  379. protected function setupGitDriver($url)
  380. {
  381. $this->gitDriver = new GitDriver(
  382. array('url' => $url),
  383. $this->io,
  384. $this->config,
  385. $this->httpDownloader,
  386. $this->process
  387. );
  388. $this->gitDriver->initialize();
  389. }
  390. protected function getNextPage(Response $response)
  391. {
  392. $header = $response->getHeader('link');
  393. $links = explode(',', $header);
  394. foreach ($links as $link) {
  395. if (preg_match('{<(.+?)>; *rel="next"}', $link, $match)) {
  396. return $match[1];
  397. }
  398. }
  399. }
  400. }