BitbucketDriver.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  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 bool
  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. return false;
  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. return true;
  97. }
  98. /**
  99. * {@inheritDoc}
  100. */
  101. public function getComposerInformation($identifier)
  102. {
  103. if ($this->fallbackDriver) {
  104. return $this->fallbackDriver->getComposerInformation($identifier);
  105. }
  106. if (!isset($this->infoCache[$identifier])) {
  107. if ($this->shouldCache($identifier) && $res = $this->cache->read($identifier)) {
  108. return $this->infoCache[$identifier] = JsonFile::parseJson($res);
  109. }
  110. $composer = $this->getBaseComposerInformation($identifier);
  111. // specials for bitbucket
  112. if (!isset($composer['support']['source'])) {
  113. $label = array_search(
  114. $identifier,
  115. $this->getTags()
  116. ) ?: array_search(
  117. $identifier,
  118. $this->getBranches()
  119. ) ?: $identifier;
  120. if (array_key_exists($label, $tags = $this->getTags())) {
  121. $hash = $tags[$label];
  122. } elseif (array_key_exists($label, $branches = $this->getBranches())) {
  123. $hash = $branches[$label];
  124. }
  125. if (! isset($hash)) {
  126. $composer['support']['source'] = sprintf(
  127. 'https://%s/%s/%s/src',
  128. $this->originUrl,
  129. $this->owner,
  130. $this->repository
  131. );
  132. } else {
  133. $composer['support']['source'] = sprintf(
  134. 'https://%s/%s/%s/src/%s/?at=%s',
  135. $this->originUrl,
  136. $this->owner,
  137. $this->repository,
  138. $hash,
  139. $label
  140. );
  141. }
  142. }
  143. if (!isset($composer['support']['issues']) && $this->hasIssues) {
  144. $composer['support']['issues'] = sprintf(
  145. 'https://%s/%s/%s/issues',
  146. $this->originUrl,
  147. $this->owner,
  148. $this->repository
  149. );
  150. }
  151. if (!isset($composer['homepage'])) {
  152. $composer['homepage'] = empty($this->website) ? $this->homeUrl : $this->website;
  153. }
  154. $this->infoCache[$identifier] = $composer;
  155. if ($this->shouldCache($identifier)) {
  156. $this->cache->write($identifier, json_encode($composer));
  157. }
  158. }
  159. return $this->infoCache[$identifier];
  160. }
  161. /**
  162. * {@inheritdoc}
  163. */
  164. public function getFileContent($file, $identifier)
  165. {
  166. if ($this->fallbackDriver) {
  167. return $this->fallbackDriver->getFileContent($file, $identifier);
  168. }
  169. if (strpos($identifier, '/') !== false) {
  170. $branches = $this->getBranches();
  171. if (isset($branches[$identifier])) {
  172. $identifier = $branches[$identifier];
  173. }
  174. }
  175. $resource = sprintf(
  176. 'https://api.bitbucket.org/1.0/repositories/%s/%s/raw/%s/%s',
  177. $this->owner,
  178. $this->repository,
  179. $identifier,
  180. $file
  181. );
  182. return $this->getContentsWithOAuthCredentials($resource);
  183. }
  184. /**
  185. * {@inheritdoc}
  186. */
  187. public function getChangeDate($identifier)
  188. {
  189. if ($this->fallbackDriver) {
  190. return $this->fallbackDriver->getChangeDate($identifier);
  191. }
  192. $resource = sprintf(
  193. 'https://api.bitbucket.org/2.0/repositories/%s/%s/commit/%s?fields=date',
  194. $this->owner,
  195. $this->repository,
  196. $identifier
  197. );
  198. $commit = JsonFile::parseJson($this->getContentsWithOAuthCredentials($resource), $resource);
  199. return new \DateTime($commit['date']);
  200. }
  201. /**
  202. * {@inheritDoc}
  203. */
  204. public function getSource($identifier)
  205. {
  206. if ($this->fallbackDriver) {
  207. return $this->fallbackDriver->getSource($identifier);
  208. }
  209. return array('type' => $this->vcsType, 'url' => $this->getUrl(), 'reference' => $identifier);
  210. }
  211. /**
  212. * {@inheritDoc}
  213. */
  214. public function getDist($identifier)
  215. {
  216. if ($this->fallbackDriver) {
  217. return $this->fallbackDriver->getDist($identifier);
  218. }
  219. $url = sprintf(
  220. 'https://bitbucket.org/%s/%s/get/%s.zip',
  221. $this->owner,
  222. $this->repository,
  223. $identifier
  224. );
  225. return array('type' => 'zip', 'url' => $url, 'reference' => $identifier, 'shasum' => '');
  226. }
  227. /**
  228. * {@inheritDoc}
  229. */
  230. public function getTags()
  231. {
  232. if ($this->fallbackDriver) {
  233. return $this->fallbackDriver->getTags();
  234. }
  235. if (null === $this->tags) {
  236. $this->tags = array();
  237. $resource = sprintf(
  238. '%s?%s',
  239. $this->tagsUrl,
  240. http_build_query(
  241. array(
  242. 'pagelen' => 100,
  243. 'fields' => 'values.name,values.target.hash,next',
  244. 'sort' => '-target.date',
  245. ),
  246. null,
  247. '&'
  248. )
  249. );
  250. $hasNext = true;
  251. while ($hasNext) {
  252. $tagsData = JsonFile::parseJson($this->getContentsWithOAuthCredentials($resource), $resource);
  253. foreach ($tagsData['values'] as $data) {
  254. $this->tags[$data['name']] = $data['target']['hash'];
  255. }
  256. if (empty($tagsData['next'])) {
  257. $hasNext = false;
  258. } else {
  259. $resource = $tagsData['next'];
  260. }
  261. }
  262. if ($this->vcsType === 'hg') {
  263. unset($this->tags['tip']);
  264. }
  265. }
  266. return $this->tags;
  267. }
  268. /**
  269. * {@inheritDoc}
  270. */
  271. public function getBranches()
  272. {
  273. if ($this->fallbackDriver) {
  274. return $this->fallbackDriver->getBranches();
  275. }
  276. if (null === $this->branches) {
  277. $this->branches = array();
  278. $resource = sprintf(
  279. '%s?%s',
  280. $this->branchesUrl,
  281. http_build_query(
  282. array(
  283. 'pagelen' => 100,
  284. 'fields' => 'values.name,values.target.hash,values.heads,next',
  285. 'sort' => '-target.date',
  286. ),
  287. null,
  288. '&'
  289. )
  290. );
  291. $hasNext = true;
  292. while ($hasNext) {
  293. $branchData = JsonFile::parseJson($this->getContentsWithOAuthCredentials($resource), $resource);
  294. foreach ($branchData['values'] as $data) {
  295. // skip headless branches which seem to be deleted branches that bitbucket nevertheless returns in the API
  296. if ($this->vcsType === 'hg' && empty($data['heads'])) {
  297. continue;
  298. }
  299. $this->branches[$data['name']] = $data['target']['hash'];
  300. }
  301. if (empty($branchData['next'])) {
  302. $hasNext = false;
  303. } else {
  304. $resource = $branchData['next'];
  305. }
  306. }
  307. }
  308. return $this->branches;
  309. }
  310. /**
  311. * Get the remote content.
  312. *
  313. * @param string $url The URL of content
  314. * @param bool $fetchingRepoData
  315. *
  316. * @return mixed The result
  317. */
  318. protected function getContentsWithOAuthCredentials($url, $fetchingRepoData = false)
  319. {
  320. try {
  321. return parent::getContents($url);
  322. } catch (TransportException $e) {
  323. $bitbucketUtil = new Bitbucket($this->io, $this->config, $this->process, $this->remoteFilesystem);
  324. if (403 === $e->getCode() || (401 === $e->getCode() && strpos($e->getMessage(), 'Could not authenticate against') === 0)) {
  325. if (!$this->io->hasAuthentication($this->originUrl)
  326. && $bitbucketUtil->authorizeOAuth($this->originUrl)
  327. ) {
  328. return parent::getContents($url);
  329. }
  330. if (!$this->io->isInteractive() && $fetchingRepoData) {
  331. return $this->attemptCloneFallback();
  332. }
  333. }
  334. throw $e;
  335. }
  336. }
  337. /**
  338. * Generate an SSH URL
  339. *
  340. * @return string
  341. */
  342. abstract protected function generateSshUrl();
  343. protected function attemptCloneFallback()
  344. {
  345. try {
  346. $this->setupFallbackDriver($this->generateSshUrl());
  347. } catch (\RuntimeException $e) {
  348. $this->fallbackDriver = null;
  349. $this->io->writeError(
  350. '<error>Failed to clone the ' . $this->generateSshUrl() . ' repository, try running in interactive mode'
  351. . ' so that you can enter your Bitbucket OAuth consumer credentials</error>'
  352. );
  353. throw $e;
  354. }
  355. }
  356. /**
  357. * @param string $url
  358. * @return void
  359. */
  360. abstract protected function setupFallbackDriver($url);
  361. /**
  362. * @param array $cloneLinks
  363. * @return void
  364. */
  365. protected function parseCloneUrls(array $cloneLinks)
  366. {
  367. foreach ($cloneLinks as $cloneLink) {
  368. if ($cloneLink['name'] === 'https') {
  369. // Format: https://(user@)bitbucket.org/{user}/{repo}
  370. // Strip username from URL (only present in clone URL's for private repositories)
  371. $this->cloneHttpsUrl = preg_replace('/https:\/\/([^@]+@)?/', 'https://', $cloneLink['href']);
  372. }
  373. }
  374. }
  375. /**
  376. * @return array|null
  377. */
  378. protected function getMainBranchData()
  379. {
  380. $resource = sprintf(
  381. 'https://api.bitbucket.org/1.0/repositories/%s/%s/main-branch',
  382. $this->owner,
  383. $this->repository
  384. );
  385. return JsonFile::parseJson($this->getContentsWithOAuthCredentials($resource), $resource);
  386. }
  387. }