GitDownloader.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  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\Downloader;
  12. use Composer\Package\PackageInterface;
  13. use Composer\Util\Git as GitUtil;
  14. use Composer\Util\Platform;
  15. use Composer\Util\ProcessExecutor;
  16. use Composer\IO\IOInterface;
  17. use Composer\Util\Filesystem;
  18. use Composer\Config;
  19. /**
  20. * @author Jordi Boggiano <j.boggiano@seld.be>
  21. */
  22. class GitDownloader extends VcsDownloader implements DvcsDownloaderInterface
  23. {
  24. private $hasStashedChanges = false;
  25. private $hasDiscardedChanges = false;
  26. private $gitUtil;
  27. public function __construct(IOInterface $io, Config $config, ProcessExecutor $process = null, Filesystem $fs = null)
  28. {
  29. parent::__construct($io, $config, $process, $fs);
  30. $this->gitUtil = new GitUtil($this->io, $this->config, $this->process, $this->filesystem);
  31. }
  32. /**
  33. * {@inheritDoc}
  34. */
  35. public function doDownload(PackageInterface $package, $path, $url)
  36. {
  37. GitUtil::cleanEnv();
  38. $path = $this->normalizePath($path);
  39. $cachePath = $this->config->get('cache-vcs-dir').'/'.preg_replace('{[^a-z0-9.]}i', '-', $url).'/';
  40. $cacheOptions = '';
  41. $ref = $package->getSourceReference();
  42. $flag = Platform::isWindows() ? '/D ' : '';
  43. // --dissociate option is only available since git 2.3.0-rc0
  44. $gitVersion = $this->gitUtil->getVersion();
  45. $msg = "Cloning ".$this->getShortHash($ref);
  46. if ($gitVersion && version_compare($gitVersion, '2.3.0-rc0', '>=')) {
  47. $this->io->writeError('', true, IOInterface::DEBUG);
  48. $this->io->writeError(sprintf(' Cloning to cache at %s', ProcessExecutor::escape($cachePath)), true, IOInterface::DEBUG);
  49. try {
  50. $this->gitUtil->syncMirror($url, $cachePath);
  51. if (is_dir($cachePath)) {
  52. $cacheOptions = sprintf('--dissociate --reference %s ', ProcessExecutor::escape($cachePath));
  53. $msg = "Cloning ".$this->getShortHash($ref).' from cache';
  54. }
  55. } catch (\RuntimeException $e) {
  56. }
  57. }
  58. $command = 'git clone --no-checkout %s %s '.$cacheOptions.'&& cd '.$flag.'%2$s && git remote add composer %1$s && git fetch composer';
  59. $this->io->writeError($msg);
  60. $commandCallable = function ($url) use ($ref, $path, $command) {
  61. return sprintf($command, ProcessExecutor::escape($url), ProcessExecutor::escape($path), ProcessExecutor::escape($ref));
  62. };
  63. $this->gitUtil->runCommand($commandCallable, $url, $path, true);
  64. if ($url !== $package->getSourceUrl()) {
  65. $this->updateOriginUrl($path, $package->getSourceUrl());
  66. } else {
  67. $this->setPushUrl($path, $url);
  68. }
  69. if ($newRef = $this->updateToCommit($path, $ref, $package->getPrettyVersion(), $package->getReleaseDate())) {
  70. if ($package->getDistReference() === $package->getSourceReference()) {
  71. $package->setDistReference($newRef);
  72. }
  73. $package->setSourceReference($newRef);
  74. }
  75. }
  76. /**
  77. * {@inheritDoc}
  78. */
  79. public function doUpdate(PackageInterface $initial, PackageInterface $target, $path, $url)
  80. {
  81. GitUtil::cleanEnv();
  82. if (!$this->hasMetadataRepository($path)) {
  83. throw new \RuntimeException('The .git directory is missing from '.$path.', see https://getcomposer.org/commit-deps for more information');
  84. }
  85. $updateOriginUrl = false;
  86. if (
  87. 0 === $this->process->execute('git remote -v', $output, $path)
  88. && preg_match('{^origin\s+(?P<url>\S+)}m', $output, $originMatch)
  89. && preg_match('{^composer\s+(?P<url>\S+)}m', $output, $composerMatch)
  90. ) {
  91. if ($originMatch['url'] === $composerMatch['url'] && $composerMatch['url'] !== $target->getSourceUrl()) {
  92. $updateOriginUrl = true;
  93. }
  94. }
  95. $ref = $target->getSourceReference();
  96. $this->io->writeError(" Checking out ".$this->getShortHash($ref));
  97. $command = 'git remote set-url composer %s && git rev-parse --quiet --verify %s^{commit} || (git fetch composer && git fetch --tags composer)';
  98. $commandCallable = function ($url) use ($command, $ref) {
  99. return sprintf($command, ProcessExecutor::escape($url), ProcessExecutor::escape($ref));
  100. };
  101. $this->gitUtil->runCommand($commandCallable, $url, $path);
  102. if ($newRef = $this->updateToCommit($path, $ref, $target->getPrettyVersion(), $target->getReleaseDate())) {
  103. if ($target->getDistReference() === $target->getSourceReference()) {
  104. $target->setDistReference($newRef);
  105. }
  106. $target->setSourceReference($newRef);
  107. }
  108. if ($updateOriginUrl) {
  109. $this->updateOriginUrl($path, $target->getSourceUrl());
  110. }
  111. }
  112. /**
  113. * {@inheritDoc}
  114. */
  115. public function getLocalChanges(PackageInterface $package, $path)
  116. {
  117. GitUtil::cleanEnv();
  118. if (!$this->hasMetadataRepository($path)) {
  119. return;
  120. }
  121. $command = 'git status --porcelain --untracked-files=no';
  122. if (0 !== $this->process->execute($command, $output, $path)) {
  123. throw new \RuntimeException('Failed to execute ' . $command . "\n\n" . $this->process->getErrorOutput());
  124. }
  125. return trim($output) ?: null;
  126. }
  127. public function getUnpushedChanges(PackageInterface $package, $path)
  128. {
  129. GitUtil::cleanEnv();
  130. $path = $this->normalizePath($path);
  131. if (!$this->hasMetadataRepository($path)) {
  132. return;
  133. }
  134. $command = 'git show-ref --head -d';
  135. if (0 !== $this->process->execute($command, $output, $path)) {
  136. throw new \RuntimeException('Failed to execute ' . $command . "\n\n" . $this->process->getErrorOutput());
  137. }
  138. $refs = trim($output);
  139. if (!preg_match('{^([a-f0-9]+) HEAD$}mi', $refs, $match)) {
  140. // could not match the HEAD for some reason
  141. return;
  142. }
  143. $headRef = $match[1];
  144. if (!preg_match_all('{^'.$headRef.' refs/heads/(.+)$}mi', $refs, $matches)) {
  145. // not on a branch, we are either on a not-modified tag or some sort of detached head, so skip this
  146. return;
  147. }
  148. // use the first match as branch name for now
  149. $branch = $matches[1][0];
  150. $unpushedChanges = null;
  151. // do two passes, as if we find anything we want to fetch and then re-try
  152. for ($i = 0; $i <= 1; $i++) {
  153. // try to find the a matching branch name in the composer remote
  154. foreach ($matches[1] as $candidate) {
  155. if (preg_match('{^[a-f0-9]+ refs/remotes/((?:composer|origin)/'.preg_quote($candidate).')$}mi', $refs, $match)) {
  156. $branch = $candidate;
  157. $remoteBranch = $match[1];
  158. break;
  159. }
  160. }
  161. // if it doesn't exist, then we assume it is an unpushed branch
  162. // this is bad as we have no reference point to do a diff so we just bail listing
  163. // the branch as being unpushed
  164. if (!isset($remoteBranch)) {
  165. $unpushedChanges = 'Branch ' . $branch . ' could not be found on the origin remote and appears to be unpushed';
  166. } else {
  167. $command = sprintf('git diff --name-status %s...%s --', $remoteBranch, $branch);
  168. if (0 !== $this->process->execute($command, $output, $path)) {
  169. throw new \RuntimeException('Failed to execute ' . $command . "\n\n" . $this->process->getErrorOutput());
  170. }
  171. $unpushedChanges = trim($output) ?: null;
  172. }
  173. // first pass and we found unpushed changes, fetch from both remotes to make sure we have up to date
  174. // remotes and then try again as outdated remotes can sometimes cause false-positives
  175. if ($unpushedChanges && $i === 0) {
  176. $this->process->execute('git fetch composer && git fetch origin', $output, $path);
  177. }
  178. // abort after first pass if we didn't find anything
  179. if (!$unpushedChanges) {
  180. break;
  181. }
  182. }
  183. return $unpushedChanges;
  184. }
  185. /**
  186. * {@inheritDoc}
  187. */
  188. protected function cleanChanges(PackageInterface $package, $path, $update)
  189. {
  190. GitUtil::cleanEnv();
  191. $path = $this->normalizePath($path);
  192. $unpushed = $this->getUnpushedChanges($package, $path);
  193. if ($unpushed && ($this->io->isInteractive() || $this->config->get('discard-changes') !== true)) {
  194. throw new \RuntimeException('Source directory ' . $path . ' has unpushed changes on the current branch: '."\n".$unpushed);
  195. }
  196. if (!$changes = $this->getLocalChanges($package, $path)) {
  197. return;
  198. }
  199. if (!$this->io->isInteractive()) {
  200. $discardChanges = $this->config->get('discard-changes');
  201. if (true === $discardChanges) {
  202. return $this->discardChanges($path);
  203. }
  204. if ('stash' === $discardChanges) {
  205. if (!$update) {
  206. return parent::cleanChanges($package, $path, $update);
  207. }
  208. return $this->stashChanges($path);
  209. }
  210. return parent::cleanChanges($package, $path, $update);
  211. }
  212. $changes = array_map(function ($elem) {
  213. return ' '.$elem;
  214. }, preg_split('{\s*\r?\n\s*}', $changes));
  215. $this->io->writeError(' <error>The package has modified files:</error>');
  216. $this->io->writeError(array_slice($changes, 0, 10));
  217. if (count($changes) > 10) {
  218. $this->io->writeError(' <info>' . (count($changes) - 10) . ' more files modified, choose "v" to view the full list</info>');
  219. }
  220. while (true) {
  221. switch ($this->io->ask(' <info>Discard changes [y,n,v,d,'.($update ? 's,' : '').'?]?</info> ', '?')) {
  222. case 'y':
  223. $this->discardChanges($path);
  224. break 2;
  225. case 's':
  226. if (!$update) {
  227. goto help;
  228. }
  229. $this->stashChanges($path);
  230. break 2;
  231. case 'n':
  232. throw new \RuntimeException('Update aborted');
  233. case 'v':
  234. $this->io->writeError($changes);
  235. break;
  236. case 'd':
  237. $this->viewDiff($path);
  238. break;
  239. case '?':
  240. default:
  241. help:
  242. $this->io->writeError(array(
  243. ' y - discard changes and apply the '.($update ? 'update' : 'uninstall'),
  244. ' n - abort the '.($update ? 'update' : 'uninstall').' and let you manually clean things up',
  245. ' v - view modified files',
  246. ' d - view local modifications (diff)',
  247. ));
  248. if ($update) {
  249. $this->io->writeError(' s - stash changes and try to reapply them after the update');
  250. }
  251. $this->io->writeError(' ? - print help');
  252. break;
  253. }
  254. }
  255. }
  256. /**
  257. * {@inheritDoc}
  258. */
  259. protected function reapplyChanges($path)
  260. {
  261. $path = $this->normalizePath($path);
  262. if ($this->hasStashedChanges) {
  263. $this->hasStashedChanges = false;
  264. $this->io->writeError(' <info>Re-applying stashed changes</info>');
  265. if (0 !== $this->process->execute('git stash pop', $output, $path)) {
  266. throw new \RuntimeException("Failed to apply stashed changes:\n\n".$this->process->getErrorOutput());
  267. }
  268. }
  269. $this->hasDiscardedChanges = false;
  270. }
  271. /**
  272. * Updates the given path to the given commit ref
  273. *
  274. * @param string $path
  275. * @param string $reference
  276. * @param string $branch
  277. * @param \DateTime $date
  278. * @throws \RuntimeException
  279. * @return null|string if a string is returned, it is the commit reference that was checked out if the original could not be found
  280. */
  281. protected function updateToCommit($path, $reference, $branch, $date)
  282. {
  283. $force = $this->hasDiscardedChanges || $this->hasStashedChanges ? '-f ' : '';
  284. // This uses the "--" sequence to separate branch from file parameters.
  285. //
  286. // Otherwise git tries the branch name as well as file name.
  287. // If the non-existent branch is actually the name of a file, the file
  288. // is checked out.
  289. $template = 'git checkout '.$force.'%s -- && git reset --hard %1$s --';
  290. $branch = preg_replace('{(?:^dev-|(?:\.x)?-dev$)}i', '', $branch);
  291. $branches = null;
  292. if (0 === $this->process->execute('git branch -r', $output, $path)) {
  293. $branches = $output;
  294. }
  295. // check whether non-commitish are branches or tags, and fetch branches with the remote name
  296. $gitRef = $reference;
  297. if (!preg_match('{^[a-f0-9]{40}$}', $reference)
  298. && $branches
  299. && preg_match('{^\s+composer/'.preg_quote($reference).'$}m', $branches)
  300. ) {
  301. $command = sprintf('git checkout '.$force.'-B %s %s -- && git reset --hard %2$s --', ProcessExecutor::escape($branch), ProcessExecutor::escape('composer/'.$reference));
  302. if (0 === $this->process->execute($command, $output, $path)) {
  303. return;
  304. }
  305. }
  306. // try to checkout branch by name and then reset it so it's on the proper branch name
  307. if (preg_match('{^[a-f0-9]{40}$}', $reference)) {
  308. // add 'v' in front of the branch if it was stripped when generating the pretty name
  309. if (!preg_match('{^\s+composer/'.preg_quote($branch).'$}m', $branches) && preg_match('{^\s+composer/v'.preg_quote($branch).'$}m', $branches)) {
  310. $branch = 'v' . $branch;
  311. }
  312. $command = sprintf('git checkout %s --', ProcessExecutor::escape($branch));
  313. $fallbackCommand = sprintf('git checkout '.$force.'-B %s %s --', ProcessExecutor::escape($branch), ProcessExecutor::escape('composer/'.$branch));
  314. if (0 === $this->process->execute($command, $output, $path)
  315. || 0 === $this->process->execute($fallbackCommand, $output, $path)
  316. ) {
  317. $command = sprintf('git reset --hard %s --', ProcessExecutor::escape($reference));
  318. if (0 === $this->process->execute($command, $output, $path)) {
  319. return;
  320. }
  321. }
  322. }
  323. $command = sprintf($template, ProcessExecutor::escape($gitRef));
  324. if (0 === $this->process->execute($command, $output, $path)) {
  325. return;
  326. }
  327. // reference was not found (prints "fatal: reference is not a tree: $ref")
  328. if (false !== strpos($this->process->getErrorOutput(), $reference)) {
  329. $this->io->writeError(' <warning>'.$reference.' is gone (history was rewritten?)</warning>');
  330. }
  331. throw new \RuntimeException(GitUtil::sanitizeUrl('Failed to execute ' . $command . "\n\n" . $this->process->getErrorOutput()));
  332. }
  333. protected function updateOriginUrl($path, $url)
  334. {
  335. $this->process->execute(sprintf('git remote set-url origin %s', ProcessExecutor::escape($url)), $output, $path);
  336. $this->setPushUrl($path, $url);
  337. }
  338. protected function setPushUrl($path, $url)
  339. {
  340. // set push url for github projects
  341. if (preg_match('{^(?:https?|git)://'.GitUtil::getGitHubDomainsRegex($this->config).'/([^/]+)/([^/]+?)(?:\.git)?$}', $url, $match)) {
  342. $protocols = $this->config->get('github-protocols');
  343. $pushUrl = 'git@'.$match[1].':'.$match[2].'/'.$match[3].'.git';
  344. if (!in_array('ssh', $protocols, true)) {
  345. $pushUrl = 'https://' . $match[1] . '/'.$match[2].'/'.$match[3].'.git';
  346. }
  347. $cmd = sprintf('git remote set-url --push origin %s', ProcessExecutor::escape($pushUrl));
  348. $this->process->execute($cmd, $ignoredOutput, $path);
  349. }
  350. }
  351. /**
  352. * {@inheritDoc}
  353. */
  354. protected function getCommitLogs($fromReference, $toReference, $path)
  355. {
  356. $path = $this->normalizePath($path);
  357. $command = sprintf('git log %s..%s --pretty=format:"%%h - %%an: %%s"', $fromReference, $toReference);
  358. if (0 !== $this->process->execute($command, $output, $path)) {
  359. throw new \RuntimeException('Failed to execute ' . $command . "\n\n" . $this->process->getErrorOutput());
  360. }
  361. return $output;
  362. }
  363. /**
  364. * @param $path
  365. * @throws \RuntimeException
  366. */
  367. protected function discardChanges($path)
  368. {
  369. $path = $this->normalizePath($path);
  370. if (0 !== $this->process->execute('git reset --hard', $output, $path)) {
  371. throw new \RuntimeException("Could not reset changes\n\n:".$this->process->getErrorOutput());
  372. }
  373. $this->hasDiscardedChanges = true;
  374. }
  375. /**
  376. * @param $path
  377. * @throws \RuntimeException
  378. */
  379. protected function stashChanges($path)
  380. {
  381. $path = $this->normalizePath($path);
  382. if (0 !== $this->process->execute('git stash --include-untracked', $output, $path)) {
  383. throw new \RuntimeException("Could not stash changes\n\n:".$this->process->getErrorOutput());
  384. }
  385. $this->hasStashedChanges = true;
  386. }
  387. /**
  388. * @param $path
  389. * @throws \RuntimeException
  390. */
  391. protected function viewDiff($path)
  392. {
  393. $path = $this->normalizePath($path);
  394. if (0 !== $this->process->execute('git diff HEAD', $output, $path)) {
  395. throw new \RuntimeException("Could not view diff\n\n:".$this->process->getErrorOutput());
  396. }
  397. $this->io->writeError($output);
  398. }
  399. protected function normalizePath($path)
  400. {
  401. if (Platform::isWindows() && strlen($path) > 0) {
  402. $basePath = $path;
  403. $removed = array();
  404. while (!is_dir($basePath) && $basePath !== '\\') {
  405. array_unshift($removed, basename($basePath));
  406. $basePath = dirname($basePath);
  407. }
  408. if ($basePath === '\\') {
  409. return $path;
  410. }
  411. $path = rtrim(realpath($basePath) . '/' . implode('/', $removed), '/');
  412. }
  413. return $path;
  414. }
  415. /**
  416. * {@inheritDoc}
  417. */
  418. protected function hasMetadataRepository($path)
  419. {
  420. $path = $this->normalizePath($path);
  421. return is_dir($path.'/.git');
  422. }
  423. protected function getShortHash($reference)
  424. {
  425. if (!$this->io->isVerbose() && preg_match('{^[0-9a-f]{40}$}', $reference)) {
  426. return substr($reference, 0, 10);
  427. }
  428. return $reference;
  429. }
  430. }