PageRenderTime 39ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 0ms

/src/Composer/Downloader/GitDownloader.php

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