SelfUpdateCommand.php 8.6 KB

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