GitDownloader.php 22 KB

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