BitbucketDriver.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  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\Cache;
  13. use Composer\Downloader\TransportException;
  14. use Composer\Json\JsonFile;
  15. use Composer\Util\Bitbucket;
  16. abstract class BitbucketDriver extends VcsDriver
  17. {
  18. /** @var Cache */
  19. protected $cache;
  20. protected $owner;
  21. protected $repository;
  22. protected $hasIssues;
  23. protected $rootIdentifier;
  24. protected $tags;
  25. protected $branches;
  26. protected $infoCache = array();
  27. protected $branchesUrl = '';
  28. protected $tagsUrl = '';
  29. protected $homeUrl = '';
  30. protected $website = '';
  31. protected $cloneHttpsUrl = '';
  32. /**
  33. * @var VcsDriver
  34. */
  35. protected $fallbackDriver;
  36. /** @var string|null if set either git or hg */
  37. protected $vcsType;
  38. /**
  39. * {@inheritDoc}
  40. */
  41. public function initialize()
  42. {
  43. preg_match('#^https?://bitbucket\.org/([^/]+)/([^/]+?)(\.git|/?)$#', $this->url, $match);
  44. $this->owner = $match[1];
  45. $this->repository = $match[2];
  46. $this->originUrl = 'bitbucket.org';
  47. $this->cache = new Cache(
  48. $this->io,
  49. implode('/', array(
  50. $this->config->get('cache-repo-dir'),
  51. $this->originUrl,
  52. $this->owner,
  53. $this->repository
  54. ))
  55. );
  56. }
  57. /**
  58. * {@inheritDoc}
  59. */
  60. public function getUrl()
  61. {
  62. if ($this->fallbackDriver) {
  63. return $this->fallbackDriver->getUrl();
  64. }
  65. return $this->cloneHttpsUrl;
  66. }
  67. /**
  68. * Attempts to fetch the repository data via the BitBucket API and
  69. * sets some parameters which are used in other methods
  70. *
  71. * @return void
  72. */
  73. protected function getRepoData()
  74. {
  75. $resource = sprintf(
  76. 'https://api.bitbucket.org/2.0/repositories/%s/%s?%s',
  77. $this->owner,
  78. $this->repository,
  79. http_build_query(
  80. array('fields' => '-project,-owner'),
  81. null,
  82. '&'
  83. )
  84. );
  85. $repoData = JsonFile::parseJson($this->getContentsWithOAuthCredentials($resource, true), $resource);
  86. if ($this->fallbackDriver) {
  87. throw new BitbucketFallbackException();
  88. }
  89. $this->parseCloneUrls($repoData['links']['clone']);
  90. $this->hasIssues = !empty($repoData['has_issues']);
  91. $this->branchesUrl = $repoData['links']['branches']['href'];
  92. $this->tagsUrl = $repoData['links']['tags']['href'];
  93. $this->homeUrl = $repoData['links']['html']['href'];
  94. $this->website = $repoData['website'];
  95. $this->vcsType = $repoData['scm'];
  96. }
  97. /**
  98. * {@inheritDoc}
  99. */
  100. public function getComposerInformation($identifier)
  101. {
  102. if ($this->fallbackDriver) {
  103. return $this->fallbackDriver->getComposerInformation($identifier);
  104. }
  105. if (!isset($this->infoCache[$identifier])) {
  106. if ($this->shouldCache($identifier) && $res = $this->cache->read($identifier)) {
  107. return $this->infoCache[$identifier] = JsonFile::parseJson($res);
  108. }
  109. $composer = $this->getBaseComposerInformation($identifier);
  110. // specials for bitbucket
  111. if (!isset($composer['support']['source'])) {
  112. $label = array_search(
  113. $identifier,
  114. $this->getTags()
  115. ) ?: array_search(
  116. $identifier,
  117. $this->getBranches()
  118. ) ?: $identifier;
  119. if (array_key_exists($label, $tags = $this->getTags())) {
  120. $hash = $tags[$label];
  121. } elseif (array_key_exists($label, $branches = $this->getBranches())) {
  122. $hash = $branches[$label];
  123. }
  124. if (! isset($hash)) {
  125. $composer['support']['source'] = sprintf(
  126. 'https://%s/%s/%s/src',
  127. $this->originUrl,
  128. $this->owner,
  129. $this->repository
  130. );
  131. } else {
  132. $composer['support']['source'] = sprintf(
  133. 'https://%s/%s/%s/src/%s/?at=%s',
  134. $this->originUrl,
  135. $this->owner,
  136. $this->repository,
  137. $hash,
  138. $label
  139. );
  140. }
  141. }
  142. if (!isset($composer['support']['issues']) && $this->hasIssues) {
  143. $composer['support']['issues'] = sprintf(
  144. 'https://%s/%s/%s/issues',
  145. $this->originUrl,
  146. $this->owner,
  147. $this->repository
  148. );
  149. }
  150. if (!isset($composer['homepage'])) {
  151. $composer['homepage'] = empty($this->website) ? $this->homeUrl : $this->website;
  152. }
  153. $this->infoCache[$identifier] = $composer;
  154. if ($this->shouldCache($identifier)) {
  155. $this->cache->write($identifier, json_encode($composer));
  156. }
  157. }
  158. return $this->infoCache[$identifier];
  159. }
  160. /**
  161. * {@inheritdoc}
  162. */
  163. public function getFileContent($file, $identifier)
  164. {
  165. if ($this->fallbackDriver) {
  166. return $this->fallbackDriver->getFileContent($file, $identifier);
  167. }
  168. $resource = sprintf(
  169. 'https://api.bitbucket.org/1.0/repositories/%s/%s/raw/%s/%s',
  170. $this->owner,
  171. $this->repository,
  172. $identifier,
  173. $file
  174. );
  175. return $this->getContentsWithOAuthCredentials($resource);
  176. }
  177. /**
  178. * {@inheritdoc}
  179. */
  180. public function getChangeDate($identifier)
  181. {
  182. if ($this->fallbackDriver) {
  183. return $this->fallbackDriver->getChangeDate($identifier);
  184. }
  185. $resource = sprintf(
  186. 'https://api.bitbucket.org/2.0/repositories/%s/%s/commit/%s?fields=date',
  187. $this->owner,
  188. $this->repository,
  189. $identifier
  190. );
  191. $commit = JsonFile::parseJson($this->getContentsWithOAuthCredentials($resource), $resource);
  192. return new \DateTime($commit['date']);
  193. }
  194. /**
  195. * {@inheritDoc}
  196. */
  197. public function getSource($identifier)
  198. {
  199. if ($this->fallbackDriver) {
  200. return $this->fallbackDriver->getSource($identifier);
  201. }
  202. return array('type' => $this->vcsType, 'url' => $this->getUrl(), 'reference' => $identifier);
  203. }
  204. /**
  205. * {@inheritDoc}
  206. */
  207. public function getDist($identifier)
  208. {
  209. if ($this->fallbackDriver) {
  210. return $this->fallbackDriver->getDist($identifier);
  211. }
  212. $url = sprintf(
  213. 'https://bitbucket.org/%s/%s/get/%s.zip',
  214. $this->owner,
  215. $this->repository,
  216. $identifier
  217. );
  218. return array('type' => 'zip', 'url' => $url, 'reference' => $identifier, 'shasum' => '');
  219. }
  220. /**
  221. * {@inheritDoc}
  222. */
  223. public function getTags()
  224. {
  225. if ($this->fallbackDriver) {
  226. return $this->fallbackDriver->getTags();
  227. }
  228. if (null === $this->tags) {
  229. $this->tags = array();
  230. $resource = sprintf(
  231. '%s?%s',
  232. $this->tagsUrl,
  233. http_build_query(
  234. array(
  235. 'pagelen' => 100,
  236. 'fields' => 'values.name,values.target.hash,next',
  237. 'sort' => '-target.date'
  238. ),
  239. null,
  240. '&'
  241. )
  242. );
  243. $hasNext = true;
  244. while ($hasNext) {
  245. $tagsData = JsonFile::parseJson($this->getContentsWithOAuthCredentials($resource), $resource);
  246. foreach ($tagsData['values'] as $data) {
  247. $this->tags[$data['name']] = $data['target']['hash'];
  248. }
  249. if (empty($tagsData['next'])) {
  250. $hasNext = false;
  251. } else {
  252. $resource = $tagsData['next'];
  253. }
  254. }
  255. if ($this->vcsType === 'hg') {
  256. unset($this->tags['tip']);
  257. }
  258. }
  259. return $this->tags;
  260. }
  261. /**
  262. * {@inheritDoc}
  263. */
  264. public function getBranches()
  265. {
  266. if ($this->fallbackDriver) {
  267. return $this->fallbackDriver->getBranches();
  268. }
  269. if (null === $this->branches) {
  270. $this->branches = array();
  271. $resource = sprintf(
  272. '%s?%s',
  273. $this->branchesUrl,
  274. http_build_query(
  275. array(
  276. 'pagelen' => 100,
  277. 'fields' => 'values.name,values.target.hash,next',
  278. 'sort' => '-target.date'
  279. ),
  280. null,
  281. '&'
  282. )
  283. );
  284. $hasNext = true;
  285. while ($hasNext) {
  286. $branchData = JsonFile::parseJson($this->getContentsWithOAuthCredentials($resource), $resource);
  287. foreach ($branchData['values'] as $data) {
  288. $this->branches[$data['name']] = $data['target']['hash'];
  289. }
  290. if (empty($branchData['next'])) {
  291. $hasNext = false;
  292. } else {
  293. $resource = $branchData['next'];
  294. }
  295. }
  296. }
  297. return $this->branches;
  298. }
  299. /**
  300. * Get the remote content.
  301. *
  302. * @param string $url The URL of content
  303. * @param bool $fetchingRepoData
  304. *
  305. * @return mixed The result
  306. */
  307. protected function getContentsWithOAuthCredentials($url, $fetchingRepoData = false)
  308. {
  309. try {
  310. return parent::getContents($url);
  311. } catch (TransportException $e) {
  312. $bitbucketUtil = new Bitbucket($this->io, $this->config, $this->process, $this->remoteFilesystem);
  313. if (403 === $e->getCode() || (401 === $e->getCode() && strpos($e->getMessage(), 'Could not authenticate against') === 0)) {
  314. if (!$this->io->hasAuthentication($this->originUrl)
  315. && $bitbucketUtil->authorizeOAuth($this->originUrl)
  316. ) {
  317. return parent::getContents($url);
  318. }
  319. if (!$this->io->isInteractive() && $fetchingRepoData) {
  320. return $this->attemptCloneFallback();
  321. }
  322. }
  323. throw $e;
  324. }
  325. }
  326. /**
  327. * Generate an SSH URL
  328. *
  329. * @return string
  330. */
  331. abstract protected function generateSshUrl();
  332. protected function attemptCloneFallback()
  333. {
  334. try {
  335. $this->setupFallbackDriver($this->generateSshUrl());
  336. } catch (\RuntimeException $e) {
  337. $this->fallbackDriver = null;
  338. $this->io->writeError(
  339. '<error>Failed to clone the ' . $this->generateSshUrl() . ' repository, try running in interactive mode'
  340. . ' so that you can enter your Bitbucket OAuth consumer credentials</error>'
  341. );
  342. throw $e;
  343. }
  344. }
  345. /**
  346. * @param string $url
  347. * @return void
  348. */
  349. abstract protected function setupFallbackDriver($url);
  350. /**
  351. * @param array $cloneLinks
  352. * @return void
  353. */
  354. protected function parseCloneUrls(array $cloneLinks)
  355. {
  356. foreach ($cloneLinks as $cloneLink) {
  357. if ($cloneLink['name'] === 'https') {
  358. // Format: https://(user@)bitbucket.org/{user}/{repo}
  359. // Strip username from URL (only present in clone URL's for private repositories)
  360. $this->cloneHttpsUrl = preg_replace('/https:\/\/([^@]+@)?/', 'https://', $cloneLink['href']);
  361. }
  362. }
  363. }
  364. /**
  365. * @return array|null
  366. */
  367. protected function getMainBranchData()
  368. {
  369. $resource = sprintf(
  370. 'https://api.bitbucket.org/1.0/repositories/%s/%s/main-branch',
  371. $this->owner,
  372. $this->repository
  373. );
  374. return JsonFile::parseJson($this->getContentsWithOAuthCredentials($resource), $resource);
  375. }
  376. }