GitLabDriver.php 15 KB

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