GitDownloader.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  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\ProcessExecutor;
  15. use Composer\IO\IOInterface;
  16. use Composer\Util\Filesystem;
  17. use Composer\Config;
  18. /**
  19. * @author Jordi Boggiano <j.boggiano@seld.be>
  20. */
  21. class GitDownloader extends VcsDownloader implements DvcsDownloaderInterface
  22. {
  23. private $hasStashedChanges = false;
  24. private $gitUtil;
  25. public function __construct(IOInterface $io, Config $config, ProcessExecutor $process = null, Filesystem $fs = null)
  26. {
  27. parent::__construct($io, $config, $process, $fs);
  28. $this->gitUtil = new GitUtil($this->io, $this->config, $this->process, $this->filesystem);
  29. }
  30. /**
  31. * {@inheritDoc}
  32. */
  33. public function doDownload(PackageInterface $package, $path, $url)
  34. {
  35. GitUtil::cleanEnv();
  36. $path = $this->normalizePath($path);
  37. $ref = $package->getSourceReference();
  38. $flag = defined('PHP_WINDOWS_VERSION_MAJOR') ? '/D ' : '';
  39. $command = 'git clone --no-checkout %s %s && cd '.$flag.'%2$s && git remote add composer %1$s && git fetch composer';
  40. $this->io->writeError(" Cloning ".$ref);
  41. $commandCallable = function ($url) use ($ref, $path, $command) {
  42. return sprintf($command, ProcessExecutor::escape($url), ProcessExecutor::escape($path), ProcessExecutor::escape($ref));
  43. };
  44. $this->gitUtil->runCommand($commandCallable, $url, $path, true);
  45. if ($url !== $package->getSourceUrl()) {
  46. $url = $package->getSourceUrl();
  47. $this->process->execute(sprintf('git remote set-url origin %s', ProcessExecutor::escape($url)), $output, $path);
  48. }
  49. $this->setPushUrl($path, $url);
  50. if ($newRef = $this->updateToCommit($path, $ref, $package->getPrettyVersion(), $package->getReleaseDate())) {
  51. if ($package->getDistReference() === $package->getSourceReference()) {
  52. $package->setDistReference($newRef);
  53. }
  54. $package->setSourceReference($newRef);
  55. }
  56. }
  57. /**
  58. * {@inheritDoc}
  59. */
  60. public function doUpdate(PackageInterface $initial, PackageInterface $target, $path, $url)
  61. {
  62. GitUtil::cleanEnv();
  63. $path = $this->normalizePath($path);
  64. if (!is_dir($path.'/.git')) {
  65. throw new \RuntimeException('The .git directory is missing from '.$path.', see https://getcomposer.org/commit-deps for more information');
  66. }
  67. $ref = $target->getSourceReference();
  68. $this->io->writeError(" Checking out ".$ref);
  69. $command = 'git remote set-url composer %s && git fetch composer && git fetch --tags composer';
  70. $commandCallable = function ($url) use ($command) {
  71. return sprintf($command, ProcessExecutor::escape($url));
  72. };
  73. $this->gitUtil->runCommand($commandCallable, $url, $path);
  74. if ($newRef = $this->updateToCommit($path, $ref, $target->getPrettyVersion(), $target->getReleaseDate())) {
  75. if ($target->getDistReference() === $target->getSourceReference()) {
  76. $target->setDistReference($newRef);
  77. }
  78. $target->setSourceReference($newRef);
  79. }
  80. }
  81. /**
  82. * {@inheritDoc}
  83. */
  84. public function getLocalChanges(PackageInterface $package, $path)
  85. {
  86. GitUtil::cleanEnv();
  87. $path = $this->normalizePath($path);
  88. if (!is_dir($path.'/.git')) {
  89. return;
  90. }
  91. $command = 'git status --porcelain --untracked-files=no';
  92. if (0 !== $this->process->execute($command, $output, $path)) {
  93. throw new \RuntimeException('Failed to execute ' . $command . "\n\n" . $this->process->getErrorOutput());
  94. }
  95. return trim($output) ?: null;
  96. }
  97. public function getUnpushedChanges($path)
  98. {
  99. GitUtil::cleanEnv();
  100. $path = $this->normalizePath($path);
  101. if (!is_dir($path.'/.git')) {
  102. return;
  103. }
  104. $command = 'git rev-parse --abbrev-ref HEAD';
  105. if (0 !== $this->process->execute($command, $output, $path)) {
  106. throw new \RuntimeException('Failed to execute ' . $command . "\n\n" . $this->process->getErrorOutput());
  107. }
  108. $branch = trim($output);
  109. $command = sprintf('git diff --name-status %s..composer/%s', $branch, $branch);
  110. if (0 !== $this->process->execute($command, $output, $path)) {
  111. throw new \RuntimeException('Failed to execute ' . $command . "\n\n" . $this->process->getErrorOutput());
  112. }
  113. return trim($output) ?: null;
  114. }
  115. /**
  116. * {@inheritDoc}
  117. */
  118. protected function cleanChanges(PackageInterface $package, $path, $update)
  119. {
  120. GitUtil::cleanEnv();
  121. $path = $this->normalizePath($path);
  122. if (null !== $this->getUnpushedChanges($path)) {
  123. throw new \RuntimeException('Source directory ' . $path . ' has unpushed changes on the current branch.');
  124. }
  125. if (!$changes = $this->getLocalChanges($package, $path)) {
  126. return;
  127. }
  128. if (!$this->io->isInteractive()) {
  129. $discardChanges = $this->config->get('discard-changes');
  130. if (true === $discardChanges) {
  131. return $this->discardChanges($path);
  132. }
  133. if ('stash' === $discardChanges) {
  134. if (!$update) {
  135. return parent::cleanChanges($package, $path, $update);
  136. }
  137. return $this->stashChanges($path);
  138. }
  139. return parent::cleanChanges($package, $path, $update);
  140. }
  141. $changes = array_map(function ($elem) {
  142. return ' '.$elem;
  143. }, preg_split('{\s*\r?\n\s*}', $changes));
  144. $this->io->writeError(' <error>The package has modified files:</error>');
  145. $this->io->writeError(array_slice($changes, 0, 10));
  146. if (count($changes) > 10) {
  147. $this->io->writeError(' <info>'.count($changes) - 10 . ' more files modified, choose "v" to view the full list</info>');
  148. }
  149. while (true) {
  150. switch ($this->io->ask(' <info>Discard changes [y,n,v,d,'.($update ? 's,' : '').'?]?</info> ', '?')) {
  151. case 'y':
  152. $this->discardChanges($path);
  153. break 2;
  154. case 's':
  155. if (!$update) {
  156. goto help;
  157. }
  158. $this->stashChanges($path);
  159. break 2;
  160. case 'n':
  161. throw new \RuntimeException('Update aborted');
  162. case 'v':
  163. $this->io->writeError($changes);
  164. break;
  165. case 'd':
  166. $this->viewDiff($path);
  167. break;
  168. case '?':
  169. default:
  170. help:
  171. $this->io->writeError(array(
  172. ' y - discard changes and apply the '.($update ? 'update' : 'uninstall'),
  173. ' n - abort the '.($update ? 'update' : 'uninstall').' and let you manually clean things up',
  174. ' v - view modified files',
  175. ' d - view local modifications (diff)',
  176. ));
  177. if ($update) {
  178. $this->io->writeError(' s - stash changes and try to reapply them after the update');
  179. }
  180. $this->io->writeError(' ? - print help');
  181. break;
  182. }
  183. }
  184. }
  185. /**
  186. * {@inheritDoc}
  187. */
  188. protected function reapplyChanges($path)
  189. {
  190. $path = $this->normalizePath($path);
  191. if ($this->hasStashedChanges) {
  192. $this->hasStashedChanges = false;
  193. $this->io->writeError(' <info>Re-applying stashed changes</info>');
  194. if (0 !== $this->process->execute('git stash pop', $output, $path)) {
  195. throw new \RuntimeException("Failed to apply stashed changes:\n\n".$this->process->getErrorOutput());
  196. }
  197. }
  198. }
  199. /**
  200. * Updates the given path to the given commit ref
  201. *
  202. * @param string $path
  203. * @param string $reference
  204. * @param string $branch
  205. * @param \DateTime $date
  206. * @return null|string if a string is returned, it is the commit reference that was checked out if the original could not be found
  207. *
  208. * @throws \RuntimeException
  209. */
  210. protected function updateToCommit($path, $reference, $branch, $date)
  211. {
  212. // This uses the "--" sequence to separate branch from file parameters.
  213. //
  214. // Otherwise git tries the branch name as well as file name.
  215. // If the non-existent branch is actually the name of a file, the file
  216. // is checked out.
  217. $template = 'git checkout %s -- && git reset --hard %1$s --';
  218. $branch = preg_replace('{(?:^dev-|(?:\.x)?-dev$)}i', '', $branch);
  219. $branches = null;
  220. if (0 === $this->process->execute('git branch -r', $output, $path)) {
  221. $branches = $output;
  222. }
  223. // check whether non-commitish are branches or tags, and fetch branches with the remote name
  224. $gitRef = $reference;
  225. if (!preg_match('{^[a-f0-9]{40}$}', $reference)
  226. && $branches
  227. && preg_match('{^\s+composer/'.preg_quote($reference).'$}m', $branches)
  228. ) {
  229. $command = sprintf('git checkout -B %s %s -- && git reset --hard %2$s --', ProcessExecutor::escape($branch), ProcessExecutor::escape('composer/'.$reference));
  230. if (0 === $this->process->execute($command, $output, $path)) {
  231. return;
  232. }
  233. }
  234. // try to checkout branch by name and then reset it so it's on the proper branch name
  235. if (preg_match('{^[a-f0-9]{40}$}', $reference)) {
  236. // add 'v' in front of the branch if it was stripped when generating the pretty name
  237. if (!preg_match('{^\s+composer/'.preg_quote($branch).'$}m', $branches) && preg_match('{^\s+composer/v'.preg_quote($branch).'$}m', $branches)) {
  238. $branch = 'v' . $branch;
  239. }
  240. $command = sprintf('git checkout %s --', ProcessExecutor::escape($branch));
  241. $fallbackCommand = sprintf('git checkout -B %s %s --', ProcessExecutor::escape($branch), ProcessExecutor::escape('composer/'.$branch));
  242. if (0 === $this->process->execute($command, $output, $path)
  243. || 0 === $this->process->execute($fallbackCommand, $output, $path)
  244. ) {
  245. $command = sprintf('git reset --hard %s --', ProcessExecutor::escape($reference));
  246. if (0 === $this->process->execute($command, $output, $path)) {
  247. return;
  248. }
  249. }
  250. }
  251. $command = sprintf($template, ProcessExecutor::escape($gitRef));
  252. if (0 === $this->process->execute($command, $output, $path)) {
  253. return;
  254. }
  255. // reference was not found (prints "fatal: reference is not a tree: $ref")
  256. if (false !== strpos($this->process->getErrorOutput(), $reference)) {
  257. $this->io->writeError(' <warning>'.$reference.' is gone (history was rewritten?)</warning>');
  258. }
  259. throw new \RuntimeException('Failed to execute ' . GitUtil::sanitizeUrl($command) . "\n\n" . $this->process->getErrorOutput());
  260. }
  261. protected function setPushUrl($path, $url)
  262. {
  263. // set push url for github projects
  264. if (preg_match('{^(?:https?|git)://'.GitUtil::getGitHubDomainsRegex($this->config).'/([^/]+)/([^/]+?)(?:\.git)?$}', $url, $match)) {
  265. $protocols = $this->config->get('github-protocols');
  266. $pushUrl = 'git@'.$match[1].':'.$match[2].'/'.$match[3].'.git';
  267. if ($protocols[0] !== 'git') {
  268. $pushUrl = 'https://' . $match[1] . '/'.$match[2].'/'.$match[3].'.git';
  269. }
  270. $cmd = sprintf('git remote set-url --push origin %s', ProcessExecutor::escape($pushUrl));
  271. $this->process->execute($cmd, $ignoredOutput, $path);
  272. }
  273. }
  274. /**
  275. * {@inheritDoc}
  276. */
  277. protected function getCommitLogs($fromReference, $toReference, $path)
  278. {
  279. $path = $this->normalizePath($path);
  280. $command = sprintf('git log %s..%s --pretty=format:"%%h - %%an: %%s"', $fromReference, $toReference);
  281. if (0 !== $this->process->execute($command, $output, $path)) {
  282. throw new \RuntimeException('Failed to execute ' . $command . "\n\n" . $this->process->getErrorOutput());
  283. }
  284. return $output;
  285. }
  286. /**
  287. * @param $path
  288. * @throws \RuntimeException
  289. */
  290. protected function discardChanges($path)
  291. {
  292. $path = $this->normalizePath($path);
  293. if (0 !== $this->process->execute('git reset --hard', $output, $path)) {
  294. throw new \RuntimeException("Could not reset changes\n\n:".$this->process->getErrorOutput());
  295. }
  296. }
  297. /**
  298. * @param $path
  299. * @throws \RuntimeException
  300. */
  301. protected function stashChanges($path)
  302. {
  303. $path = $this->normalizePath($path);
  304. if (0 !== $this->process->execute('git stash', $output, $path)) {
  305. throw new \RuntimeException("Could not stash changes\n\n:".$this->process->getErrorOutput());
  306. }
  307. $this->hasStashedChanges = true;
  308. }
  309. /**
  310. * @param $path
  311. * @throws \RuntimeException
  312. */
  313. protected function viewDiff($path)
  314. {
  315. $path = $this->normalizePath($path);
  316. if (0 !== $this->process->execute('git diff HEAD', $output, $path)) {
  317. throw new \RuntimeException("Could not view diff\n\n:".$this->process->getErrorOutput());
  318. }
  319. $this->io->writeError($output);
  320. }
  321. protected function normalizePath($path)
  322. {
  323. if (defined('PHP_WINDOWS_VERSION_MAJOR') && strlen($path) > 0) {
  324. $basePath = $path;
  325. $removed = array();
  326. while (!is_dir($basePath) && $basePath !== '\\') {
  327. array_unshift($removed, basename($basePath));
  328. $basePath = dirname($basePath);
  329. }
  330. if ($basePath === '\\') {
  331. return $path;
  332. }
  333. $path = rtrim(realpath($basePath) . '/' . implode('/', $removed), '/');
  334. }
  335. return $path;
  336. }
  337. }