GitHubDriver.php 19 KB

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