GitDownloader.php 22 KB

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