GitDownloader.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  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\GitHub;
  14. use Composer\Util\Git as GitUtil;
  15. /**
  16. * @author Jordi Boggiano <j.boggiano@seld.be>
  17. */
  18. class GitDownloader extends VcsDownloader
  19. {
  20. private $hasStashedChanges = false;
  21. /**
  22. * {@inheritDoc}
  23. */
  24. public function doDownload(PackageInterface $package, $path)
  25. {
  26. $this->cleanEnv();
  27. $path = $this->normalizePath($path);
  28. $ref = $package->getSourceReference();
  29. $flag = defined('PHP_WINDOWS_VERSION_MAJOR') ? '/D ' : '';
  30. $command = 'git clone %s %s && cd '.$flag.'%2$s && git remote add composer %1$s && git fetch composer';
  31. $this->io->write(" Cloning ".$ref);
  32. $commandCallable = function($url) use ($ref, $path, $command) {
  33. return sprintf($command, escapeshellarg($url), escapeshellarg($path), escapeshellarg($ref));
  34. };
  35. $this->runCommand($commandCallable, $package->getSourceUrl(), $path, true);
  36. $this->setPushUrl($package, $path);
  37. $this->updateToCommit($path, $ref, $package->getPrettyVersion(), $package->getReleaseDate());
  38. }
  39. /**
  40. * {@inheritDoc}
  41. */
  42. public function doUpdate(PackageInterface $initial, PackageInterface $target, $path)
  43. {
  44. $this->cleanEnv();
  45. $path = $this->normalizePath($path);
  46. if (!is_dir($path.'/.git')) {
  47. throw new \RuntimeException('The .git directory is missing from '.$path.', see http://getcomposer.org/commit-deps for more information');
  48. }
  49. $ref = $target->getSourceReference();
  50. $this->io->write(" Checking out ".$ref);
  51. $command = 'git remote set-url composer %s && git fetch composer && git fetch --tags composer';
  52. // capture username/password from URL if there is one
  53. $this->process->execute('git remote -v', $output, $path);
  54. if (preg_match('{^(?:composer|origin)\s+https?://(.+):(.+)@([^/]+)}im', $output, $match)) {
  55. $this->io->setAuthentication($match[3], urldecode($match[1]), urldecode($match[2]));
  56. }
  57. $commandCallable = function($url) use ($command) {
  58. return sprintf($command, escapeshellarg($url));
  59. };
  60. $this->runCommand($commandCallable, $target->getSourceUrl(), $path);
  61. $this->updateToCommit($path, $ref, $target->getPrettyVersion(), $target->getReleaseDate());
  62. }
  63. /**
  64. * {@inheritDoc}
  65. */
  66. public function getLocalChanges($path)
  67. {
  68. $this->cleanEnv();
  69. $path = $this->normalizePath($path);
  70. if (!is_dir($path.'/.git')) {
  71. return;
  72. }
  73. $command = 'git status --porcelain --untracked-files=no';
  74. if (0 !== $this->process->execute($command, $output, $path)) {
  75. throw new \RuntimeException('Failed to execute ' . $command . "\n\n" . $this->process->getErrorOutput());
  76. }
  77. return trim($output) ?: null;
  78. }
  79. /**
  80. * {@inheritDoc}
  81. */
  82. protected function cleanChanges($path, $update)
  83. {
  84. $this->cleanEnv();
  85. $path = $this->normalizePath($path);
  86. if (!$changes = $this->getLocalChanges($path)) {
  87. return;
  88. }
  89. if (!$this->io->isInteractive()) {
  90. $discardChanges = $this->config->get('discard-changes');
  91. if (true === $discardChanges) {
  92. return $this->discardChanges($path);
  93. }
  94. if ('stash' === $discardChanges) {
  95. if (!$update) {
  96. return parent::cleanChanges($path, $update);
  97. }
  98. return $this->stashChanges($path);
  99. }
  100. return parent::cleanChanges($path, $update);
  101. }
  102. $changes = array_map(function ($elem) {
  103. return ' '.$elem;
  104. }, preg_split('{\s*\r?\n\s*}', $changes));
  105. $this->io->write(' <error>The package has modified files:</error>');
  106. $this->io->write(array_slice($changes, 0, 10));
  107. if (count($changes) > 10) {
  108. $this->io->write(' <info>'.count($changes) - 10 . ' more files modified, choose "v" to view the full list</info>');
  109. }
  110. while (true) {
  111. switch ($this->io->ask(' <info>Discard changes [y,n,v,'.($update ? 's,' : '').'?]?</info> ', '?')) {
  112. case 'y':
  113. $this->discardChanges($path);
  114. break 2;
  115. case 's':
  116. if (!$update) {
  117. goto help;
  118. }
  119. $this->stashChanges($path);
  120. break 2;
  121. case 'n':
  122. throw new \RuntimeException('Update aborted');
  123. case 'v':
  124. $this->io->write($changes);
  125. break;
  126. case '?':
  127. default:
  128. help:
  129. $this->io->write(array(
  130. ' y - discard changes and apply the '.($update ? 'update' : 'uninstall'),
  131. ' n - abort the '.($update ? 'update' : 'uninstall').' and let you manually clean things up',
  132. ' v - view modified files',
  133. ));
  134. if ($update) {
  135. $this->io->write(' s - stash changes and try to reapply them after the update');
  136. }
  137. $this->io->write(' ? - print help');
  138. break;
  139. }
  140. }
  141. }
  142. /**
  143. * {@inheritDoc}
  144. */
  145. protected function reapplyChanges($path)
  146. {
  147. $path = $this->normalizePath($path);
  148. if ($this->hasStashedChanges) {
  149. $this->hasStashedChanges = false;
  150. $this->io->write(' <info>Re-applying stashed changes');
  151. if (0 !== $this->process->execute('git stash pop', $output, $path)) {
  152. throw new \RuntimeException("Failed to apply stashed changes:\n\n".$this->process->getErrorOutput());
  153. }
  154. }
  155. }
  156. protected function updateToCommit($path, $reference, $branch, $date)
  157. {
  158. $template = 'git checkout %s && git reset --hard %1$s';
  159. $branch = preg_replace('{(?:^dev-|(?:\.x)?-dev$)}i', '', $branch);
  160. $branches = null;
  161. if (0 === $this->process->execute('git branch -r', $output, $path)) {
  162. $branches = $output;
  163. }
  164. // check whether non-commitish are branches or tags, and fetch branches with the remote name
  165. $gitRef = $reference;
  166. if (!preg_match('{^[a-f0-9]{40}$}', $reference)
  167. && $branches
  168. && preg_match('{^\s+composer/'.preg_quote($reference).'$}m', $output)
  169. ) {
  170. $command = sprintf('git checkout -B %s %s && git reset --hard %2$s', escapeshellarg($branch), escapeshellarg('composer/'.$reference));
  171. if (0 === $this->process->execute($command, $output, $path)) {
  172. return;
  173. }
  174. }
  175. // try to checkout branch by name and then reset it so it's on the proper branch name
  176. if (preg_match('{^[a-f0-9]{40}$}', $reference)) {
  177. // add 'v' in front of the branch if it was stripped when generating the pretty name
  178. if (!preg_match('{^\s+composer/'.preg_quote($branch).'$}m', $branches) && preg_match('{^\s+composer/v'.preg_quote($branch).'$}m', $branches)) {
  179. $branch = 'v' . $branch;
  180. }
  181. $command = sprintf('git checkout %s', escapeshellarg($branch));
  182. $fallbackCommand = sprintf('git checkout -B %s %s', escapeshellarg($branch), escapeshellarg('composer/'.$branch));
  183. if (0 === $this->process->execute($command, $output, $path)
  184. || 0 === $this->process->execute($fallbackCommand, $output, $path)
  185. ) {
  186. $command = sprintf('git reset --hard %s', escapeshellarg($reference));
  187. if (0 === $this->process->execute($command, $output, $path)) {
  188. return;
  189. }
  190. }
  191. }
  192. $command = sprintf($template, escapeshellarg($gitRef));
  193. if (0 === $this->process->execute($command, $output, $path)) {
  194. return;
  195. }
  196. // reference was not found (prints "fatal: reference is not a tree: $ref")
  197. if ($date && false !== strpos($this->process->getErrorOutput(), $reference)) {
  198. $date = $date->format('U');
  199. // guess which remote branch to look at first
  200. $command = 'git branch -r';
  201. if (0 !== $this->process->execute($command, $output, $path)) {
  202. throw new \RuntimeException('Failed to execute ' . $command . "\n\n" . $this->process->getErrorOutput());
  203. }
  204. $guessTemplate = 'git log --until=%s --date=raw -n1 --pretty=%%H %s';
  205. foreach ($this->process->splitLines($output) as $line) {
  206. if (preg_match('{^composer/'.preg_quote($branch).'(?:\.x)?$}i', trim($line))) {
  207. // find the previous commit by date in the given branch
  208. if (0 === $this->process->execute(sprintf($guessTemplate, $date, escapeshellarg(trim($line))), $output, $path)) {
  209. $newReference = trim($output);
  210. }
  211. break;
  212. }
  213. }
  214. if (empty($newReference)) {
  215. // no matching branch found, find the previous commit by date in all commits
  216. if (0 !== $this->process->execute(sprintf($guessTemplate, $date, '--all'), $output, $path)) {
  217. throw new \RuntimeException('Failed to execute ' . $this->sanitizeUrl($command) . "\n\n" . $this->process->getErrorOutput());
  218. }
  219. $newReference = trim($output);
  220. }
  221. // checkout the new recovered ref
  222. $command = sprintf($template, escapeshellarg($reference));
  223. if (0 === $this->process->execute($command, $output, $path)) {
  224. $this->io->write(' '.$reference.' is gone (history was rewritten?), recovered by checking out '.$newReference);
  225. return;
  226. }
  227. }
  228. throw new \RuntimeException('Failed to execute ' . $this->sanitizeUrl($command) . "\n\n" . $this->process->getErrorOutput());
  229. }
  230. /**
  231. * Runs a command doing attempts for each protocol supported by github.
  232. *
  233. * @param callable $commandCallable A callable building the command for the given url
  234. * @param string $url
  235. * @param string $cwd
  236. * @param bool $initialClone If true, the directory if cleared between every attempt
  237. * @throws \InvalidArgumentException
  238. * @throws \RuntimeException
  239. */
  240. protected function runCommand($commandCallable, $url, $cwd, $initialClone = false)
  241. {
  242. if ($initialClone) {
  243. $origCwd = $cwd;
  244. $cwd = null;
  245. }
  246. if (preg_match('{^ssh://[^@]+@[^:]+:[^0-9]+}', $url)) {
  247. throw new \InvalidArgumentException('The source URL '.$url.' is invalid, ssh URLs should have a port number after ":".'."\n".'Use ssh://git@example.com:22/path or just git@example.com:path if you do not want to provide a password or custom port.');
  248. }
  249. // public github, autoswitch protocols
  250. if (preg_match('{^(?:https?|git)(://github.com/.*)}', $url, $match)) {
  251. $protocols = $this->config->get('github-protocols');
  252. if (!is_array($protocols)) {
  253. throw new \RuntimeException('Config value "github-protocols" must be an array, got '.gettype($protocols));
  254. }
  255. $messages = array();
  256. foreach ($protocols as $protocol) {
  257. $url = $protocol . $match[1];
  258. if (0 === $this->process->execute(call_user_func($commandCallable, $url), $ignoredOutput, $cwd)) {
  259. return;
  260. }
  261. $messages[] = '- ' . $url . "\n" . preg_replace('#^#m', ' ', $this->process->getErrorOutput());
  262. if ($initialClone) {
  263. $this->filesystem->removeDirectory($origCwd);
  264. }
  265. }
  266. // failed to checkout, first check git accessibility
  267. $this->throwException('Failed to clone ' . $this->sanitizeUrl($url) .' via '.implode(', ', $protocols).' protocols, aborting.' . "\n\n" . implode("\n", $messages), $url);
  268. }
  269. $command = call_user_func($commandCallable, $url);
  270. if (0 !== $this->process->execute($command, $ignoredOutput, $cwd)) {
  271. // private github repository without git access, try https with auth
  272. if (preg_match('{^git@(github.com):(.+?)\.git$}i', $url, $match)) {
  273. if (!$this->io->hasAuthentication($match[1])) {
  274. $gitHubUtil = new GitHub($this->io, $this->config, $this->process);
  275. $message = 'Cloning failed using an ssh key for authentication, enter your GitHub credentials to access private repos';
  276. if (!$gitHubUtil->authorizeOAuth($match[1]) && $this->io->isInteractive()) {
  277. $gitHubUtil->authorizeOAuthInteractively($match[1], $message);
  278. }
  279. }
  280. if ($this->io->hasAuthentication($match[1])) {
  281. $auth = $this->io->getAuthentication($match[1]);
  282. $url = 'https://'.urlencode($auth['username']) . ':' . urlencode($auth['password']) . '@'.$match[1].'/'.$match[2].'.git';
  283. $command = call_user_func($commandCallable, $url);
  284. if (0 === $this->process->execute($command, $ignoredOutput, $cwd)) {
  285. return;
  286. }
  287. }
  288. } elseif ( // private non-github repo that failed to authenticate
  289. $this->io->isInteractive() &&
  290. preg_match('{(https?://)([^/]+)(.*)$}i', $url, $match) &&
  291. strpos($this->process->getErrorOutput(), 'fatal: Authentication failed') !== false
  292. ) {
  293. if ($this->io->hasAuthentication($match[2])) {
  294. $auth = $this->io->getAuthentication($match[2]);
  295. } else {
  296. $this->io->write($url.' requires Authentication');
  297. $auth = array(
  298. 'username' => $this->io->ask('Username: '),
  299. 'password' => $this->io->askAndHideAnswer('Password: '),
  300. );
  301. }
  302. $url = $match[1].urlencode($auth['username']).':'.urlencode($auth['password']).'@'.$match[2].$match[3];
  303. $command = call_user_func($commandCallable, $url);
  304. if (0 === $this->process->execute($command, $ignoredOutput, $cwd)) {
  305. $this->io->setAuthentication($match[2], $auth['username'], $auth['password']);
  306. return;
  307. }
  308. }
  309. if ($initialClone) {
  310. $this->filesystem->removeDirectory($origCwd);
  311. }
  312. $this->throwException('Failed to execute ' . $this->sanitizeUrl($command) . "\n\n" . $this->process->getErrorOutput(), $url);
  313. }
  314. }
  315. protected function throwException($message, $url)
  316. {
  317. if (0 !== $this->process->execute('git --version', $ignoredOutput)) {
  318. throw new \RuntimeException('Failed to clone '.$this->sanitizeUrl($url).', git was not found, check that it is installed and in your PATH env.' . "\n\n" . $this->process->getErrorOutput());
  319. }
  320. throw new \RuntimeException($message);
  321. }
  322. protected function sanitizeUrl($message)
  323. {
  324. return preg_replace('{://(.+?):.+?@}', '://$1:***@', $message);
  325. }
  326. protected function setPushUrl(PackageInterface $package, $path)
  327. {
  328. // set push url for github projects
  329. if (preg_match('{^(?:https?|git)://github.com/([^/]+)/([^/]+?)(?:\.git)?$}', $package->getSourceUrl(), $match)) {
  330. $protocols = $this->config->get('github-protocols');
  331. $pushUrl = 'git@github.com:'.$match[1].'/'.$match[2].'.git';
  332. if ($protocols[0] !== 'git') {
  333. $pushUrl = 'https://github.com/'.$match[1].'/'.$match[2].'.git';
  334. }
  335. $cmd = sprintf('git remote set-url --push origin %s', escapeshellarg($pushUrl));
  336. $this->process->execute($cmd, $ignoredOutput, $path);
  337. }
  338. }
  339. /**
  340. * {@inheritDoc}
  341. */
  342. protected function getCommitLogs($fromReference, $toReference, $path)
  343. {
  344. $path = $this->normalizePath($path);
  345. $command = sprintf('git log %s..%s --pretty=format:"%%h - %%an: %%s"', $fromReference, $toReference);
  346. if (0 !== $this->process->execute($command, $output, $path)) {
  347. throw new \RuntimeException('Failed to execute ' . $command . "\n\n" . $this->process->getErrorOutput());
  348. }
  349. return $output;
  350. }
  351. /**
  352. * @param $path
  353. * @throws \RuntimeException
  354. */
  355. protected function discardChanges($path)
  356. {
  357. $path = $this->normalizePath($path);
  358. if (0 !== $this->process->execute('git reset --hard', $output, $path)) {
  359. throw new \RuntimeException("Could not reset changes\n\n:".$this->process->getErrorOutput());
  360. }
  361. }
  362. /**
  363. * @param $path
  364. * @throws \RuntimeException
  365. */
  366. protected function stashChanges($path)
  367. {
  368. $path = $this->normalizePath($path);
  369. if (0 !== $this->process->execute('git stash', $output, $path)) {
  370. throw new \RuntimeException("Could not stash changes\n\n:".$this->process->getErrorOutput());
  371. }
  372. $this->hasStashedChanges = true;
  373. }
  374. protected function cleanEnv()
  375. {
  376. $util = new GitUtil;
  377. $util->cleanEnv();
  378. }
  379. protected function normalizePath($path)
  380. {
  381. if (defined('PHP_WINDOWS_VERSION_MAJOR') && strlen($path) > 0) {
  382. $basePath = $path;
  383. $removed = array();
  384. while (!is_dir($basePath) && $basePath !== '\\') {
  385. array_unshift($removed, basename($basePath));
  386. $basePath = dirname($basePath);
  387. }
  388. if ($basePath === '\\') {
  389. return $path;
  390. }
  391. $path = rtrim(realpath($basePath) . '/' . implode('/', $removed), '/');
  392. }
  393. return $path;
  394. }
  395. }