GitLabDriver.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  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\Cache;
  14. use Composer\IO\IOInterface;
  15. use Composer\Json\JsonFile;
  16. use Composer\Downloader\TransportException;
  17. use Composer\Util\RemoteFilesystem;
  18. use Composer\Util\GitLab;
  19. /**
  20. * Driver for GitLab API, use the Git driver for local checkouts.
  21. *
  22. * @author Henrik Bjørnskov <henrik@bjrnskov.dk>
  23. * @author Jérôme Tamarelle <jerome@tamarelle.net>
  24. */
  25. class GitLabDriver extends VcsDriver
  26. {
  27. private $scheme;
  28. private $namespace;
  29. private $repository;
  30. /**
  31. * @var array Project data returned by GitLab API
  32. */
  33. private $project;
  34. /**
  35. * @var array Keeps commits returned by GitLab API
  36. */
  37. private $commits = array();
  38. /**
  39. * @var array List of tag => reference
  40. */
  41. private $tags;
  42. /**
  43. * @var array List of branch => reference
  44. */
  45. private $branches;
  46. /**
  47. * Git Driver
  48. *
  49. * @var GitDriver
  50. */
  51. protected $gitDriver;
  52. /**
  53. * Defaults to true unless we can make sure it is public
  54. *
  55. * @var bool defines whether the repo is private or not
  56. */
  57. private $isPrivate = true;
  58. const URL_REGEX = '#^(?:(?P<scheme>https?)://(?P<domain>.+?)/|git@(?P<domain2>[^:]+):)(?P<parts>.+)/(?P<repo>[^/]+?)(?:\.git|/)?$#';
  59. /**
  60. * Extracts information from the repository url.
  61. *
  62. * SSH urls use https by default. Set "secure-http": false on the repository config to use http instead.
  63. *
  64. * {@inheritDoc}
  65. */
  66. public function initialize()
  67. {
  68. if (!preg_match(self::URL_REGEX, $this->url, $match)) {
  69. throw new \InvalidArgumentException('The URL provided is invalid. It must be the HTTP URL of a GitLab project.');
  70. }
  71. $guessedDomain = !empty($match['domain']) ? $match['domain'] : $match['domain2'];
  72. $configuredDomains = $this->config->get('gitlab-domains');
  73. $urlParts = explode('/', $match['parts']);
  74. $this->scheme = !empty($match['scheme'])
  75. ? $match['scheme']
  76. : (isset($this->repoConfig['secure-http']) && $this->repoConfig['secure-http'] === false ? 'http' : 'https')
  77. ;
  78. $this->originUrl = $this->determineOrigin($configuredDomains, $guessedDomain, $urlParts);
  79. $this->namespace = implode('/', $urlParts);
  80. $this->repository = preg_replace('#(\.git)$#', '', $match['repo']);
  81. $this->cache = new Cache($this->io, $this->config->get('cache-repo-dir').'/'.$this->originUrl.'/'.$this->namespace.'/'.$this->repository);
  82. $this->fetchProject();
  83. }
  84. /**
  85. * Updates the RemoteFilesystem instance.
  86. * Mainly useful for tests.
  87. *
  88. * @internal
  89. */
  90. public function setRemoteFilesystem(RemoteFilesystem $remoteFilesystem)
  91. {
  92. $this->remoteFilesystem = $remoteFilesystem;
  93. }
  94. /**
  95. * {@inheritdoc}
  96. */
  97. public function getFileContent($file, $identifier)
  98. {
  99. if ($this->gitDriver) {
  100. return $this->gitDriver->getFileContent($file, $identifier);
  101. }
  102. // Convert the root identifier to a cachable commit id
  103. if (!preg_match('{[a-f0-9]{40}}i', $identifier)) {
  104. $branches = $this->getBranches();
  105. if (isset($branches[$identifier])) {
  106. $identifier = $branches[$identifier];
  107. }
  108. }
  109. $resource = $this->getApiUrl().'/repository/files/'.$this->urlEncodeAll($file).'/raw?ref='.$identifier;
  110. try {
  111. $content = $this->getContents($resource);
  112. } catch (TransportException $e) {
  113. if ($e->getCode() !== 404) {
  114. throw $e;
  115. }
  116. return null;
  117. }
  118. return $content;
  119. }
  120. /**
  121. * {@inheritdoc}
  122. */
  123. public function getChangeDate($identifier)
  124. {
  125. if ($this->gitDriver) {
  126. return $this->gitDriver->getChangeDate($identifier);
  127. }
  128. if (isset($this->commits[$identifier])) {
  129. return new \DateTime($this->commits[$identifier]['committed_date']);
  130. }
  131. return new \DateTime();
  132. }
  133. /**
  134. * {@inheritDoc}
  135. */
  136. public function getRepositoryUrl()
  137. {
  138. return $this->isPrivate ? $this->project['ssh_url_to_repo'] : $this->project['http_url_to_repo'];
  139. }
  140. /**
  141. * {@inheritDoc}
  142. */
  143. public function getUrl()
  144. {
  145. if ($this->gitDriver) {
  146. return $this->gitDriver->getUrl();
  147. }
  148. return $this->project['web_url'];
  149. }
  150. /**
  151. * {@inheritDoc}
  152. */
  153. public function getDist($identifier)
  154. {
  155. $url = $this->getApiUrl().'/repository/archive.zip?sha='.$identifier;
  156. return array('type' => 'zip', 'url' => $url, 'reference' => $identifier, 'shasum' => '');
  157. }
  158. /**
  159. * {@inheritDoc}
  160. */
  161. public function getSource($identifier)
  162. {
  163. if ($this->gitDriver) {
  164. return $this->gitDriver->getSource($identifier);
  165. }
  166. return array('type' => 'git', 'url' => $this->getRepositoryUrl(), 'reference' => $identifier);
  167. }
  168. /**
  169. * {@inheritDoc}
  170. */
  171. public function getRootIdentifier()
  172. {
  173. if ($this->gitDriver) {
  174. return $this->gitDriver->getRootIdentifier();
  175. }
  176. return $this->project['default_branch'];
  177. }
  178. /**
  179. * {@inheritDoc}
  180. */
  181. public function getBranches()
  182. {
  183. if ($this->gitDriver) {
  184. return $this->gitDriver->getBranches();
  185. }
  186. if (!$this->branches) {
  187. $this->branches = $this->getReferences('branches');
  188. }
  189. return $this->branches;
  190. }
  191. /**
  192. * {@inheritDoc}
  193. */
  194. public function getTags()
  195. {
  196. if ($this->gitDriver) {
  197. return $this->gitDriver->getTags();
  198. }
  199. if (!$this->tags) {
  200. $this->tags = $this->getReferences('tags');
  201. }
  202. return $this->tags;
  203. }
  204. /**
  205. * @return string Base URL for GitLab API v3
  206. */
  207. public function getApiUrl()
  208. {
  209. return $this->scheme.'://'.$this->originUrl.'/api/v4/projects/'.$this->urlEncodeAll($this->namespace).'%2F'.$this->urlEncodeAll($this->repository);
  210. }
  211. /**
  212. * Urlencode all non alphanumeric characters. rawurlencode() can not be used as it does not encode `.`
  213. *
  214. * @param string $string
  215. * @return string
  216. */
  217. private function urlEncodeAll($string)
  218. {
  219. $encoded = '';
  220. for ($i = 0; isset($string[$i]); $i++) {
  221. $character = $string[$i];
  222. if (!ctype_alnum($character) && !in_array($character, array('-', '_'), true)) {
  223. $character = '%' . sprintf('%02X', ord($character));
  224. }
  225. $encoded .= $character;
  226. }
  227. return $encoded;
  228. }
  229. /**
  230. * @param string $type
  231. *
  232. * @return string[] where keys are named references like tags or branches and the value a sha
  233. */
  234. protected function getReferences($type)
  235. {
  236. $perPage = 100;
  237. $resource = $this->getApiUrl().'/repository/'.$type.'?per_page='.$perPage;
  238. $references = array();
  239. do {
  240. $data = JsonFile::parseJson($this->getContents($resource), $resource);
  241. foreach ($data as $datum) {
  242. $references[$datum['name']] = $datum['commit']['id'];
  243. // Keep the last commit date of a reference to avoid
  244. // unnecessary API call when retrieving the composer file.
  245. $this->commits[$datum['commit']['id']] = $datum['commit'];
  246. }
  247. if (count($data) >= $perPage) {
  248. $resource = $this->getNextPage();
  249. } else {
  250. $resource = false;
  251. }
  252. } while ($resource);
  253. return $references;
  254. }
  255. protected function fetchProject()
  256. {
  257. // we need to fetch the default branch from the api
  258. $resource = $this->getApiUrl();
  259. $this->project = JsonFile::parseJson($this->getContents($resource, true), $resource);
  260. $this->isPrivate = $this->project['visibility'] !== 'public';
  261. }
  262. protected function attemptCloneFallback()
  263. {
  264. try {
  265. if ($this->isPrivate === false) {
  266. $url = $this->generatePublicUrl();
  267. } else {
  268. $url = $this->generateSshUrl();
  269. }
  270. // If this repository may be private and we
  271. // cannot ask for authentication credentials (because we
  272. // are not interactive) then we fallback to GitDriver.
  273. $this->setupGitDriver($url);
  274. return;
  275. } catch (\RuntimeException $e) {
  276. $this->gitDriver = null;
  277. $this->io->writeError('<error>Failed to clone the '.$url.' repository, try running in interactive mode so that you can enter your credentials</error>');
  278. throw $e;
  279. }
  280. }
  281. /**
  282. * Generate an SSH URL
  283. *
  284. * @return string
  285. */
  286. protected function generateSshUrl()
  287. {
  288. return 'git@' . $this->originUrl . ':'.$this->namespace.'/'.$this->repository.'.git';
  289. }
  290. protected function generatePublicUrl()
  291. {
  292. return 'https://' . $this->originUrl . '/'.$this->namespace.'/'.$this->repository.'.git';
  293. }
  294. protected function setupGitDriver($url)
  295. {
  296. $this->gitDriver = new GitDriver(
  297. array('url' => $url),
  298. $this->io,
  299. $this->config,
  300. $this->process,
  301. $this->remoteFilesystem
  302. );
  303. $this->gitDriver->initialize();
  304. }
  305. /**
  306. * {@inheritDoc}
  307. */
  308. protected function getContents($url, $fetchingRepoData = false)
  309. {
  310. try {
  311. $res = parent::getContents($url);
  312. if ($fetchingRepoData) {
  313. $json = JsonFile::parseJson($res, $url);
  314. // force auth as the unauthenticated version of the API is broken
  315. if (!isset($json['default_branch'])) {
  316. if (!empty($json['id'])) {
  317. $this->isPrivate = false;
  318. }
  319. throw new TransportException('GitLab API seems to not be authenticated as it did not return a default_branch', 401);
  320. }
  321. }
  322. return $res;
  323. } catch (TransportException $e) {
  324. $gitLabUtil = new GitLab($this->io, $this->config, $this->process, $this->remoteFilesystem);
  325. switch ($e->getCode()) {
  326. case 401:
  327. case 404:
  328. // try to authorize only if we are fetching the main /repos/foo/bar data, otherwise it must be a real 404
  329. if (!$fetchingRepoData) {
  330. throw $e;
  331. }
  332. if ($gitLabUtil->authorizeOAuth($this->originUrl)) {
  333. return parent::getContents($url);
  334. }
  335. if (!$this->io->isInteractive()) {
  336. return $this->attemptCloneFallback();
  337. }
  338. $this->io->writeError('<warning>Failed to download ' . $this->namespace . '/' . $this->repository . ':' . $e->getMessage() . '</warning>');
  339. $gitLabUtil->authorizeOAuthInteractively($this->scheme, $this->originUrl, 'Your credentials are required to fetch private repository metadata (<info>'.$this->url.'</info>)');
  340. return parent::getContents($url);
  341. case 403:
  342. if (!$this->io->hasAuthentication($this->originUrl) && $gitLabUtil->authorizeOAuth($this->originUrl)) {
  343. return parent::getContents($url);
  344. }
  345. if (!$this->io->isInteractive() && $fetchingRepoData) {
  346. return $this->attemptCloneFallback();
  347. }
  348. throw $e;
  349. default:
  350. throw $e;
  351. }
  352. }
  353. }
  354. /**
  355. * Uses the config `gitlab-domains` to see if the driver supports the url for the
  356. * repository given.
  357. *
  358. * {@inheritDoc}
  359. */
  360. public static function supports(IOInterface $io, Config $config, $url, $deep = false)
  361. {
  362. if (!preg_match(self::URL_REGEX, $url, $match)) {
  363. return false;
  364. }
  365. $scheme = !empty($match['scheme']) ? $match['scheme'] : null;
  366. $guessedDomain = !empty($match['domain']) ? $match['domain'] : $match['domain2'];
  367. $urlParts = explode('/', $match['parts']);
  368. if (false === self::determineOrigin((array) $config->get('gitlab-domains'), $guessedDomain, $urlParts)) {
  369. return false;
  370. }
  371. if ('https' === $scheme && !extension_loaded('openssl')) {
  372. $io->writeError('Skipping GitLab driver for '.$url.' because the OpenSSL PHP extension is missing.', true, IOInterface::VERBOSE);
  373. return false;
  374. }
  375. return true;
  376. }
  377. private function getNextPage()
  378. {
  379. $headers = $this->remoteFilesystem->getLastHeaders();
  380. foreach ($headers as $header) {
  381. if (preg_match('{^link:\s*(.+?)\s*$}i', $header, $match)) {
  382. $links = explode(',', $match[1]);
  383. foreach ($links as $link) {
  384. if (preg_match('{<(.+?)>; *rel="next"}', $link, $match)) {
  385. return $match[1];
  386. }
  387. }
  388. }
  389. }
  390. }
  391. /**
  392. * @param array $configuredDomains
  393. * @param string $guessedDomain
  394. * @param array $urlParts
  395. * @return bool|string
  396. */
  397. private static function determineOrigin(array $configuredDomains, $guessedDomain, array &$urlParts)
  398. {
  399. if (in_array($guessedDomain, $configuredDomains)) {
  400. return $guessedDomain;
  401. }
  402. while (null !== ($part = array_shift($urlParts))) {
  403. $guessedDomain .= '/' . $part;
  404. if (in_array($guessedDomain, $configuredDomains)) {
  405. return $guessedDomain;
  406. }
  407. }
  408. return false;
  409. }
  410. }