SelfUpdateCommand.php 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  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\Command;
  12. use Composer\Composer;
  13. use Composer\Factory;
  14. use Composer\Util\Filesystem;
  15. use Composer\Util\RemoteFilesystem;
  16. use Composer\Downloader\FilesystemException;
  17. use Symfony\Component\Console\Input\InputInterface;
  18. use Symfony\Component\Console\Input\InputOption;
  19. use Symfony\Component\Console\Input\InputArgument;
  20. use Symfony\Component\Console\Output\OutputInterface;
  21. use Symfony\Component\Finder\Finder;
  22. /**
  23. * @author Igor Wiedler <igor@wiedler.ch>
  24. * @author Kevin Ran <kran@adobe.com>
  25. * @author Jordi Boggiano <j.boggiano@seld.be>
  26. */
  27. class SelfUpdateCommand extends Command
  28. {
  29. const HOMEPAGE = 'getcomposer.org';
  30. const OLD_INSTALL_EXT = '-old.phar';
  31. protected function configure()
  32. {
  33. $this
  34. ->setName('self-update')
  35. ->setAliases(array('selfupdate'))
  36. ->setDescription('Updates composer.phar to the latest version.')
  37. ->setDefinition(array(
  38. new InputOption('rollback', 'r', InputOption::VALUE_NONE, 'Revert to an older installation of composer'),
  39. new InputOption('clean-backups', null, InputOption::VALUE_NONE, 'Delete old backups during an update. This makes the current version of composer the only backup available after the update'),
  40. new InputArgument('version', InputArgument::OPTIONAL, 'The version to update to'),
  41. ))
  42. ->setHelp(<<<EOT
  43. The <info>self-update</info> command checks getcomposer.org for newer
  44. versions of composer and if found, installs the latest.
  45. <info>php composer.phar self-update</info>
  46. EOT
  47. )
  48. ;
  49. }
  50. protected function execute(InputInterface $input, OutputInterface $output)
  51. {
  52. $baseUrl = (extension_loaded('openssl') ? 'https' : 'http') . '://' . self::HOMEPAGE;
  53. $config = Factory::createConfig();
  54. $remoteFilesystem = new RemoteFilesystem($this->getIO(), $config);
  55. $cacheDir = $config->get('cache-dir');
  56. $rollbackDir = $config->get('data-dir');
  57. $localFilename = realpath($_SERVER['argv'][0]) ?: $_SERVER['argv'][0];
  58. // check if current dir is writable and if not try the cache dir from settings
  59. $tmpDir = is_writable(dirname($localFilename)) ? dirname($localFilename) : $cacheDir;
  60. // check for permissions in local filesystem before start connection process
  61. if (!is_writable($tmpDir)) {
  62. throw new FilesystemException('Composer update failed: the "'.$tmpDir.'" directory used to download the temp file could not be written');
  63. }
  64. if (!is_writable($localFilename)) {
  65. throw new FilesystemException('Composer update failed: the "'.$localFilename.'" file could not be written');
  66. }
  67. if ($input->getOption('rollback')) {
  68. return $this->rollback($output, $rollbackDir, $localFilename);
  69. }
  70. $latestVersion = trim($remoteFilesystem->getContents(self::HOMEPAGE, $baseUrl. '/version', false));
  71. $updateVersion = $input->getArgument('version') ?: $latestVersion;
  72. if (preg_match('{^[0-9a-f]{40}$}', $updateVersion) && $updateVersion !== $latestVersion) {
  73. $output->writeln('<error>You can not update to a specific SHA-1 as those phars are not available for download</error>');
  74. return 1;
  75. }
  76. if (Composer::VERSION === $updateVersion) {
  77. $output->writeln('<info>You are already using composer version '.$updateVersion.'.</info>');
  78. return 0;
  79. }
  80. $tempFilename = $tmpDir . '/' . basename($localFilename, '.phar').'-temp.phar';
  81. $backupFile = sprintf(
  82. '%s/%s-%s%s',
  83. $rollbackDir,
  84. strtr(Composer::RELEASE_DATE, ' :', '_-'),
  85. preg_replace('{^([0-9a-f]{7})[0-9a-f]{33}$}', '$1', Composer::VERSION),
  86. self::OLD_INSTALL_EXT
  87. );
  88. $output->writeln(sprintf("Updating to version <info>%s</info>.", $updateVersion));
  89. $remoteFilename = $baseUrl . (preg_match('{^[0-9a-f]{40}$}', $updateVersion) ? '/composer.phar' : "/download/{$updateVersion}/composer.phar");
  90. $remoteFilesystem->copy(self::HOMEPAGE, $remoteFilename, $tempFilename);
  91. if (!file_exists($tempFilename)) {
  92. $output->writeln('<error>The download of the new composer version failed for an unexpected reason</error>');
  93. return 1;
  94. }
  95. // remove saved installations of composer
  96. if ($input->getOption('clean-backups')) {
  97. $finder = $this->getOldInstallationFinder($rollbackDir);
  98. $fs = new Filesystem;
  99. foreach ($finder as $file) {
  100. $file = (string) $file;
  101. $output->writeln('<info>Removing: '.$file.'</info>');
  102. $fs->remove($file);
  103. }
  104. }
  105. if ($err = $this->setLocalPhar($localFilename, $tempFilename, $backupFile)) {
  106. $output->writeln('<error>The file is corrupted ('.$err->getMessage().').</error>');
  107. $output->writeln('<error>Please re-run the self-update command to try again.</error>');
  108. return 1;
  109. }
  110. if (file_exists($backupFile)) {
  111. $output->writeln('Use <info>composer self-update --rollback</info> to return to version '.Composer::VERSION);
  112. } else {
  113. $output->writeln('<warning>A backup of the current version could not be written to '.$backupFile.', no rollback possible</warning>');
  114. }
  115. }
  116. protected function rollback(OutputInterface $output, $rollbackDir, $localFilename)
  117. {
  118. $rollbackVersion = $this->getLastBackupVersion($rollbackDir);
  119. if (!$rollbackVersion) {
  120. throw new \UnexpectedValueException('Composer rollback failed: no installation to roll back to in "'.$rollbackDir.'"');
  121. }
  122. if (!is_writable($rollbackDir)) {
  123. throw new FilesystemException('Composer rollback failed: the "'.$rollbackDir.'" dir could not be written to');
  124. }
  125. $old = $rollbackDir . '/' . $rollbackVersion . self::OLD_INSTALL_EXT;
  126. if (!is_file($old)) {
  127. throw new FilesystemException('Composer rollback failed: "'.$old.'" could not be found');
  128. }
  129. if (!is_readable($old)) {
  130. throw new FilesystemException('Composer rollback failed: "'.$old.'" could not be read');
  131. }
  132. $oldFile = $rollbackDir . "/{$rollbackVersion}" . self::OLD_INSTALL_EXT;
  133. $output->writeln(sprintf("Rolling back to version <info>%s</info>.", $rollbackVersion));
  134. if ($err = $this->setLocalPhar($localFilename, $oldFile)) {
  135. $output->writeln('<error>The backup file was corrupted ('.$err->getMessage().') and has been removed.</error>');
  136. return 1;
  137. }
  138. return 0;
  139. }
  140. protected function setLocalPhar($localFilename, $newFilename, $backupTarget = null)
  141. {
  142. try {
  143. @chmod($newFilename, 0777 & ~umask());
  144. if (!ini_get('phar.readonly')) {
  145. // test the phar validity
  146. $phar = new \Phar($newFilename);
  147. // free the variable to unlock the file
  148. unset($phar);
  149. }
  150. // copy current file into installations dir
  151. if ($backupTarget && file_exists($localFilename)) {
  152. @copy($localFilename, $backupTarget);
  153. }
  154. rename($newFilename, $localFilename);
  155. } catch (\Exception $e) {
  156. if ($backupTarget) {
  157. @unlink($newFilename);
  158. }
  159. if (!$e instanceof \UnexpectedValueException && !$e instanceof \PharException) {
  160. throw $e;
  161. }
  162. return $e;
  163. }
  164. }
  165. protected function getLastBackupVersion($rollbackDir)
  166. {
  167. $finder = $this->getOldInstallationFinder($rollbackDir);
  168. $finder->sortByName();
  169. $files = iterator_to_array($finder);
  170. if (count($files)) {
  171. return basename(end($files), self::OLD_INSTALL_EXT);
  172. }
  173. return false;
  174. }
  175. protected function getOldInstallationFinder($rollbackDir)
  176. {
  177. $finder = Finder::create()
  178. ->depth(0)
  179. ->files()
  180. ->name('*' . self::OLD_INSTALL_EXT)
  181. ->in($rollbackDir);
  182. return $finder;
  183. }
  184. }