GitDownloader.php 21 KB

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