GitDownloader.php 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  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. /**
  14. * @author Jordi Boggiano <j.boggiano@seld.be>
  15. */
  16. class GitDownloader extends VcsDownloader
  17. {
  18. /**
  19. * {@inheritDoc}
  20. */
  21. public function doDownload(PackageInterface $package, $path)
  22. {
  23. $ref = $package->getSourceReference();
  24. $command = 'git clone %s %s && cd %2$s && git remote add composer %1$s && git fetch composer';
  25. $this->io->write(" Cloning ".$ref);
  26. // added in git 1.7.1, prevents prompting the user
  27. putenv('GIT_ASKPASS=echo');
  28. $commandCallable = function($url) use ($ref, $path, $command) {
  29. return sprintf($command, escapeshellarg($url), escapeshellarg($path), escapeshellarg($ref));
  30. };
  31. $this->runCommand($commandCallable, $package->getSourceUrl(), $path);
  32. $this->setPushUrl($package, $path);
  33. $this->updateToCommit($path, $ref, $package->getPrettyVersion(), $package->getReleaseDate());
  34. }
  35. /**
  36. * {@inheritDoc}
  37. */
  38. public function doUpdate(PackageInterface $initial, PackageInterface $target, $path)
  39. {
  40. $ref = $target->getSourceReference();
  41. $this->io->write(" Checking out ".$ref);
  42. $command = 'cd %s && git remote set-url composer %s && git fetch composer && git fetch --tags composer';
  43. // capture username/password from github URL if there is one
  44. $this->process->execute(sprintf('cd %s && git remote -v', escapeshellarg($path)), $output);
  45. if (preg_match('{^composer\s+https://(.+):(.+)@github.com/}im', $output, $match)) {
  46. $this->io->setAuthorization('github.com', $match[1], $match[2]);
  47. }
  48. $commandCallable = function($url) use ($ref, $path, $command) {
  49. return sprintf($command, escapeshellarg($path), escapeshellarg($url), escapeshellarg($ref));
  50. };
  51. $this->runCommand($commandCallable, $target->getSourceUrl());
  52. $this->updateToCommit($path, $ref, $target->getPrettyVersion(), $target->getReleaseDate());
  53. }
  54. protected function updateToCommit($path, $reference, $branch, $date)
  55. {
  56. $template = 'git checkout %s && git reset --hard %1$s';
  57. $command = sprintf($template, escapeshellarg($reference));
  58. if (0 === $this->process->execute($command, $output, $path)) {
  59. return;
  60. }
  61. // reference was not found (prints "fatal: reference is not a tree: $ref")
  62. if ($date && false !== strpos($this->process->getErrorOutput(), $reference)) {
  63. $branch = preg_replace('{(?:^dev-|(?:\.x)?-dev$)}i', '', $branch);
  64. $date = $date->format('U');
  65. // guess which remote branch to look at first
  66. $command = 'git branch -r';
  67. if (0 !== $this->process->execute($command, $output, $path)) {
  68. throw new \RuntimeException('Failed to execute ' . $command . "\n\n" . $this->process->getErrorOutput());
  69. }
  70. $guessTemplate = 'git log --until=%s --date=raw -n1 --pretty=%%H %s';
  71. foreach ($this->process->splitLines($output) as $line) {
  72. if (preg_match('{^composer/'.preg_quote($branch).'(?:\.x)?$}i', trim($line))) {
  73. // find the previous commit by date in the given branch
  74. if (0 === $this->process->execute(sprintf($guessTemplate, $date, escapeshellarg(trim($line))), $output, $path)) {
  75. $newReference = trim($output);
  76. }
  77. break;
  78. }
  79. }
  80. if (empty($newReference)) {
  81. // no matching branch found, find the previous commit by date in all commits
  82. if (0 !== $this->process->execute(sprintf($guessTemplate, $date, '--all'), $output, $path)) {
  83. throw new \RuntimeException('Failed to execute ' . $command . "\n\n" . $this->process->getErrorOutput());
  84. }
  85. $newReference = trim($output);
  86. }
  87. // checkout the new recovered ref
  88. $command = sprintf($template, escapeshellarg($newReference));
  89. if (0 === $this->process->execute($command, $output, $path)) {
  90. $this->io->write(' '.$reference.' is gone (history was rewritten?), recovered by checking out '.$newReference);
  91. return;
  92. }
  93. }
  94. throw new \RuntimeException('Failed to execute ' . $command . "\n\n" . $this->process->getErrorOutput());
  95. }
  96. /**
  97. * {@inheritDoc}
  98. */
  99. protected function enforceCleanDirectory($path)
  100. {
  101. $command = sprintf('cd %s && git status --porcelain --untracked-files=no', escapeshellarg($path));
  102. if (0 !== $this->process->execute($command, $output)) {
  103. throw new \RuntimeException('Failed to execute ' . $command . "\n\n" . $this->process->getErrorOutput());
  104. }
  105. if (trim($output)) {
  106. throw new \RuntimeException('Source directory ' . $path . ' has uncommitted changes');
  107. }
  108. }
  109. /**
  110. * Runs a command doing attempts for each protocol supported by github.
  111. *
  112. * @param callable $commandCallable A callable building the command for the given url
  113. * @param string $url
  114. * @param string $path The directory to remove for each attempt (null if not needed)
  115. * @throws \RuntimeException
  116. */
  117. protected function runCommand($commandCallable, $url, $path = null)
  118. {
  119. $handler = array($this, 'outputHandler');
  120. // public github, autoswitch protocols
  121. if (preg_match('{^(?:https?|git)(://github.com/.*)}', $url, $match)) {
  122. $protocols = array('git', 'https', 'http');
  123. $messages = array();
  124. foreach ($protocols as $protocol) {
  125. $url = $protocol . $match[1];
  126. if (0 === $this->process->execute(call_user_func($commandCallable, $url), $handler)) {
  127. return;
  128. }
  129. $messages[] = '- ' . $url . "\n" . preg_replace('#^#m', ' ', $this->process->getErrorOutput());
  130. if (null !== $path) {
  131. $this->filesystem->removeDirectory($path);
  132. }
  133. }
  134. // failed to checkout, first check git accessibility
  135. $this->throwException('Failed to clone ' . $url .' via git, https and http protocols, aborting.' . "\n\n" . implode("\n", $messages), $url);
  136. }
  137. $command = call_user_func($commandCallable, $url);
  138. if (0 !== $this->process->execute($command, $handler)) {
  139. if (preg_match('{^git@github.com:(.+?)\.git$}i', $url, $match) && $this->io->isInteractive()) {
  140. // private github repository without git access, try https with auth
  141. $retries = 3;
  142. $retrying = false;
  143. do {
  144. if ($retrying) {
  145. $this->io->write('Invalid credentials');
  146. }
  147. if (!$this->io->hasAuthorization('github.com') || $retrying) {
  148. $username = $this->io->ask('Username: ');
  149. $password = $this->io->askAndHideAnswer('Password: ');
  150. $this->io->setAuthorization('github.com', $username, $password);
  151. }
  152. $auth = $this->io->getAuthorization('github.com');
  153. $url = 'https://'.$auth['username'] . ':' . $auth['password'] . '@github.com/'.$match[1].'.git';
  154. $command = call_user_func($commandCallable, $url);
  155. if (0 === $this->process->execute($command, $handler)) {
  156. return;
  157. }
  158. if (null !== $path) {
  159. $this->filesystem->removeDirectory($path);
  160. }
  161. $retrying = true;
  162. } while (--$retries);
  163. }
  164. if (null !== $path) {
  165. $this->filesystem->removeDirectory($path);
  166. }
  167. $this->throwException('Failed to execute ' . $command . "\n\n" . $this->process->getErrorOutput(), $url);
  168. }
  169. }
  170. public function outputHandler($type, $buffer)
  171. {
  172. if ($type !== 'out') {
  173. return;
  174. }
  175. if ($this->io->isVerbose()) {
  176. $this->io->write($buffer, false);
  177. }
  178. }
  179. protected function throwException($message, $url)
  180. {
  181. if (0 !== $this->process->execute('git --version', $ignoredOutput)) {
  182. throw new \RuntimeException('Failed to clone '.$url.', git was not found, check that it is installed and in your PATH env.' . "\n\n" . $this->process->getErrorOutput());
  183. }
  184. throw new \RuntimeException($message);
  185. }
  186. protected function setPushUrl(PackageInterface $package, $path)
  187. {
  188. // set push url for github projects
  189. if (preg_match('{^(?:https?|git)://github.com/([^/]+)/([^/]+?)(?:\.git)?$}', $package->getSourceUrl(), $match)) {
  190. $pushUrl = 'git@github.com:'.$match[1].'/'.$match[2].'.git';
  191. $cmd = sprintf('git remote set-url --push origin %s', escapeshellarg($pushUrl));
  192. $this->process->execute($cmd, $ignoredOutput, $path);
  193. }
  194. }
  195. }