CreateProjectCommand.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  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\Config;
  13. use Composer\Factory;
  14. use Composer\Installer;
  15. use Composer\Installer\ProjectInstaller;
  16. use Composer\Installer\InstallationManager;
  17. use Composer\IO\IOInterface;
  18. use Composer\Package\BasePackage;
  19. use Composer\DependencyResolver\Pool;
  20. use Composer\DependencyResolver\Operation\InstallOperation;
  21. use Composer\Package\Version\VersionSelector;
  22. use Composer\Repository\ComposerRepository;
  23. use Composer\Repository\CompositeRepository;
  24. use Composer\Repository\FilesystemRepository;
  25. use Composer\Repository\InstalledFilesystemRepository;
  26. use Composer\Script\ScriptEvents;
  27. use Symfony\Component\Console\Input\InputArgument;
  28. use Symfony\Component\Console\Input\InputInterface;
  29. use Symfony\Component\Console\Input\InputOption;
  30. use Symfony\Component\Console\Output\OutputInterface;
  31. use Symfony\Component\Finder\Finder;
  32. use Composer\Json\JsonFile;
  33. use Composer\Config\JsonConfigSource;
  34. use Composer\Util\Filesystem;
  35. use Composer\Util\RemoteFilesystem;
  36. use Composer\Package\Version\VersionParser;
  37. /**
  38. * Install a package as new project into new directory.
  39. *
  40. * @author Benjamin Eberlei <kontakt@beberlei.de>
  41. * @author Jordi Boggiano <j.boggiano@seld.be>
  42. * @author Tobias Munk <schmunk@usrbin.de>
  43. * @author Nils Adermann <naderman@naderman.de>
  44. */
  45. class CreateProjectCommand extends Command
  46. {
  47. protected function configure()
  48. {
  49. $this
  50. ->setName('create-project')
  51. ->setDescription('Create new project from a package into given directory.')
  52. ->setDefinition(array(
  53. new InputArgument('package', InputArgument::OPTIONAL, 'Package name to be installed'),
  54. new InputArgument('directory', InputArgument::OPTIONAL, 'Directory where the files should be created'),
  55. new InputArgument('version', InputArgument::OPTIONAL, 'Version, will default to latest'),
  56. new InputOption('stability', 's', InputOption::VALUE_REQUIRED, 'Minimum-stability allowed (unless a version is specified).'),
  57. new InputOption('prefer-source', null, InputOption::VALUE_NONE, 'Forces installation from package sources when possible, including VCS information.'),
  58. new InputOption('prefer-dist', null, InputOption::VALUE_NONE, 'Forces installation from package dist even for dev versions.'),
  59. new InputOption('repository-url', null, InputOption::VALUE_REQUIRED, 'Pick a different repository url to look for the package.'),
  60. new InputOption('dev', null, InputOption::VALUE_NONE, 'Enables installation of require-dev packages (enabled by default, only present for BC).'),
  61. new InputOption('no-dev', null, InputOption::VALUE_NONE, 'Disables installation of require-dev packages.'),
  62. new InputOption('no-plugins', null, InputOption::VALUE_NONE, 'Whether to disable plugins.'),
  63. new InputOption('no-custom-installers', null, InputOption::VALUE_NONE, 'DEPRECATED: Use no-plugins instead.'),
  64. new InputOption('no-scripts', null, InputOption::VALUE_NONE, 'Whether to prevent execution of all defined scripts in the root package.'),
  65. new InputOption('no-progress', null, InputOption::VALUE_NONE, 'Do not output download progress.'),
  66. new InputOption('keep-vcs', null, InputOption::VALUE_NONE, 'Whether to prevent deletion vcs folder.'),
  67. new InputOption('no-install', null, InputOption::VALUE_NONE, 'Whether to skip installation of the package dependencies.'),
  68. new InputOption('disable-tls', null, InputOption::VALUE_NONE, 'Disable SSL/TLS protection for HTTPS requests'),
  69. new InputOption('cafile', null, InputOption::VALUE_REQUIRED, 'The path to a valid CA certificate file for SSL/TLS certificate verification'),
  70. new InputOption('ignore-platform-reqs', null, InputOption::VALUE_NONE, 'Ignore platform requirements (php & ext- packages).'),
  71. ))
  72. ->setHelp(<<<EOT
  73. The <info>create-project</info> command creates a new project from a given
  74. package into a new directory. If executed without params and in a directory
  75. with a composer.json file it installs the packages for the current project.
  76. You can use this command to bootstrap new projects or setup a clean
  77. version-controlled installation for developers of your project.
  78. <info>php composer.phar create-project vendor/project target-directory [version]</info>
  79. You can also specify the version with the package name using = or : as separator.
  80. To install unstable packages, either specify the version you want, or use the
  81. --stability=dev (where dev can be one of RC, beta, alpha or dev).
  82. To setup a developer workable version you should create the project using the source
  83. controlled code by appending the <info>'--prefer-source'</info> flag.
  84. To install a package from another repository than the default one you
  85. can pass the <info>'--repository-url=http://myrepository.org'</info> flag.
  86. EOT
  87. )
  88. ;
  89. }
  90. protected function execute(InputInterface $input, OutputInterface $output)
  91. {
  92. $config = Factory::createConfig();
  93. $io = $this->getIO();
  94. $this->updatePreferredOptions($config, $input, $preferSource, $preferDist, true);
  95. if ($input->getOption('no-custom-installers')) {
  96. $io->writeError('<warning>You are using the deprecated option "no-custom-installers". Use "no-plugins" instead.</warning>');
  97. $input->setOption('no-plugins', true);
  98. }
  99. return $this->installProject(
  100. $io,
  101. $config,
  102. $input,
  103. $input->getArgument('package'),
  104. $input->getArgument('directory'),
  105. $input->getArgument('version'),
  106. $input->getOption('stability'),
  107. $preferSource,
  108. $preferDist,
  109. !$input->getOption('no-dev'),
  110. $input->getOption('repository-url'),
  111. $input->getOption('no-plugins'),
  112. $input->getOption('no-scripts'),
  113. $input->getOption('keep-vcs'),
  114. $input->getOption('no-progress'),
  115. $input->getOption('no-install'),
  116. $input->getOption('ignore-platform-reqs')
  117. );
  118. }
  119. public function installProject(IOInterface $io, Config $config, InputInterface $input, $packageName, $directory = null, $packageVersion = null, $stability = 'stable', $preferSource = false, $preferDist = false, $installDevPackages = false, $repositoryUrl = null, $disablePlugins = false, $noScripts = false, $keepVcs = false, $noProgress = false, $noInstall = false, $ignorePlatformReqs = false)
  120. {
  121. $oldCwd = getcwd();
  122. // we need to manually load the configuration to pass the auth credentials to the io interface!
  123. $io->loadConfiguration($config);
  124. if ($packageName !== null) {
  125. $installedFromVcs = $this->installRootPackage($io, $config, $packageName, $directory, $packageVersion, $stability, $preferSource, $preferDist, $installDevPackages, $repositoryUrl, $disablePlugins, $noScripts, $keepVcs, $noProgress);
  126. } else {
  127. $installedFromVcs = false;
  128. }
  129. $composer = Factory::create($io, null, $disablePlugins);
  130. $composer->getDownloadManager()->setOutputProgress(!$noProgress);
  131. $fs = new Filesystem();
  132. if ($noScripts === false) {
  133. // dispatch event
  134. $composer->getEventDispatcher()->dispatchScript(ScriptEvents::POST_ROOT_PACKAGE_INSTALL, $installDevPackages);
  135. }
  136. $rootPackageConfig = $composer->getConfig();
  137. $this->updatePreferredOptions($rootPackageConfig, $input, $preferSource, $preferDist);
  138. // install dependencies of the created project
  139. if ($noInstall === false) {
  140. $installer = Installer::create($io, $composer);
  141. $installer->setPreferSource($preferSource)
  142. ->setPreferDist($preferDist)
  143. ->setDevMode($installDevPackages)
  144. ->setRunScripts(!$noScripts)
  145. ->setIgnorePlatformRequirements($ignorePlatformReqs);
  146. if ($disablePlugins) {
  147. $installer->disablePlugins();
  148. }
  149. $status = $installer->run();
  150. if (0 !== $status) {
  151. return $status;
  152. }
  153. }
  154. $hasVcs = $installedFromVcs;
  155. if (!$keepVcs && $installedFromVcs
  156. && (
  157. !$io->isInteractive()
  158. || $io->askConfirmation('<info>Do you want to remove the existing VCS (.git, .svn..) history?</info> [<comment>Y,n</comment>]? ', true)
  159. )
  160. ) {
  161. $finder = new Finder();
  162. $finder->depth(0)->directories()->in(getcwd())->ignoreVCS(false)->ignoreDotFiles(false);
  163. foreach (array('.svn', '_svn', 'CVS', '_darcs', '.arch-params', '.monotone', '.bzr', '.git', '.hg') as $vcsName) {
  164. $finder->name($vcsName);
  165. }
  166. try {
  167. $dirs = iterator_to_array($finder);
  168. unset($finder);
  169. foreach ($dirs as $dir) {
  170. if (!$fs->removeDirectory($dir)) {
  171. throw new \RuntimeException('Could not remove '.$dir);
  172. }
  173. }
  174. } catch (\Exception $e) {
  175. $io->writeError('<error>An error occurred while removing the VCS metadata: '.$e->getMessage().'</error>');
  176. }
  177. $hasVcs = false;
  178. }
  179. // rewriting self.version dependencies with explicit version numbers if the package's vcs metadata is gone
  180. if (!$hasVcs) {
  181. $package = $composer->getPackage();
  182. $configSource = new JsonConfigSource(new JsonFile('composer.json'));
  183. foreach (BasePackage::$supportedLinkTypes as $type => $meta) {
  184. foreach ($package->{'get'.$meta['method']}() as $link) {
  185. if ($link->getPrettyConstraint() === 'self.version') {
  186. $configSource->addLink($type, $link->getTarget(), $package->getPrettyVersion());
  187. }
  188. }
  189. }
  190. }
  191. if ($noScripts === false) {
  192. // dispatch event
  193. $composer->getEventDispatcher()->dispatchScript(ScriptEvents::POST_CREATE_PROJECT_CMD, $installDevPackages);
  194. }
  195. chdir($oldCwd);
  196. $vendorComposerDir = $composer->getConfig()->get('vendor-dir').'/composer';
  197. if (is_dir($vendorComposerDir) && $fs->isDirEmpty($vendorComposerDir)) {
  198. @rmdir($vendorComposerDir);
  199. $vendorDir = $composer->getConfig()->get('vendor-dir');
  200. if (is_dir($vendorDir) && $fs->isDirEmpty($vendorDir)) {
  201. @rmdir($vendorDir);
  202. }
  203. }
  204. return 0;
  205. }
  206. protected function installRootPackage(IOInterface $io, Config $config, $packageName, $directory = null, $packageVersion = null, $stability = 'stable', $preferSource = false, $preferDist = false, $installDevPackages = false, $repositoryUrl = null, $disablePlugins = false, $noScripts = false, $keepVcs = false, $noProgress = false)
  207. {
  208. if (null === $repositoryUrl) {
  209. $sourceRepo = new CompositeRepository(Factory::createDefaultRepositories($io, $config));
  210. } elseif ("json" === pathinfo($repositoryUrl, PATHINFO_EXTENSION) && file_exists($repositoryUrl)) {
  211. $json = new JsonFile($repositoryUrl, Factory::createRemoteFilesystem($io, $config));
  212. $data = $json->read();
  213. if (!empty($data['packages']) || !empty($data['includes']) || !empty($data['provider-includes'])) {
  214. $sourceRepo = new ComposerRepository(array('url' => 'file://' . strtr(realpath($repositoryUrl), '\\', '/')), $io, $config);
  215. } else {
  216. $sourceRepo = new FilesystemRepository($json);
  217. }
  218. } elseif (0 === strpos($repositoryUrl, 'http')) {
  219. $sourceRepo = new ComposerRepository(array('url' => $repositoryUrl), $io, $config);
  220. } else {
  221. throw new \InvalidArgumentException("Invalid repository url given. Has to be a .json file or an http url.");
  222. }
  223. $parser = new VersionParser();
  224. $requirements = $parser->parseNameVersionPairs(array($packageName));
  225. $name = strtolower($requirements[0]['name']);
  226. if (!$packageVersion && isset($requirements[0]['version'])) {
  227. $packageVersion = $requirements[0]['version'];
  228. }
  229. if (null === $stability) {
  230. if (preg_match('{^[^,\s]*?@('.implode('|', array_keys(BasePackage::$stabilities)).')$}i', $packageVersion, $match)) {
  231. $stability = $match[1];
  232. } else {
  233. $stability = VersionParser::parseStability($packageVersion);
  234. }
  235. }
  236. $stability = VersionParser::normalizeStability($stability);
  237. if (!isset(BasePackage::$stabilities[$stability])) {
  238. throw new \InvalidArgumentException('Invalid stability provided ('.$stability.'), must be one of: '.implode(', ', array_keys(BasePackage::$stabilities)));
  239. }
  240. $pool = new Pool($stability);
  241. $pool->addRepository($sourceRepo);
  242. // using those 3 constants to build a version without the 'extra' bit that can contain garbage
  243. $phpVersion = PHP_MAJOR_VERSION.'.'.PHP_MINOR_VERSION.'.'.PHP_RELEASE_VERSION;
  244. // find the latest version if there are multiple
  245. $versionSelector = new VersionSelector($pool);
  246. $package = $versionSelector->findBestCandidate($name, $packageVersion, $phpVersion, $stability);
  247. if (!$package) {
  248. throw new \InvalidArgumentException("Could not find package $name" . ($packageVersion ? " with version $packageVersion." : " with stability $stability."));
  249. }
  250. if (null === $directory) {
  251. $parts = explode("/", $name, 2);
  252. $directory = getcwd() . DIRECTORY_SEPARATOR . array_pop($parts);
  253. }
  254. // handler Ctrl+C for unix-like systems
  255. if (function_exists('pcntl_signal')) {
  256. declare (ticks = 100);
  257. pcntl_signal(SIGINT, function () use ($directory) {
  258. $fs = new Filesystem();
  259. $fs->removeDirectory($directory);
  260. exit(130);
  261. });
  262. }
  263. $io->writeError('<info>Installing ' . $package->getName() . ' (' . $package->getFullPrettyVersion(false) . ')</info>');
  264. if ($disablePlugins) {
  265. $io->writeError('<info>Plugins have been disabled.</info>');
  266. }
  267. if (0 === strpos($package->getPrettyVersion(), 'dev-') && in_array($package->getSourceType(), array('git', 'hg'))) {
  268. $package->setSourceReference(substr($package->getPrettyVersion(), 4));
  269. }
  270. $dm = $this->createDownloadManager($io, $config);
  271. $dm->setPreferSource($preferSource)
  272. ->setPreferDist($preferDist)
  273. ->setOutputProgress(!$noProgress);
  274. $projectInstaller = new ProjectInstaller($directory, $dm);
  275. $im = $this->createInstallationManager();
  276. $im->addInstaller($projectInstaller);
  277. $im->install(new InstalledFilesystemRepository(new JsonFile('php://memory')), new InstallOperation($package));
  278. $im->notifyInstalls($io);
  279. $installedFromVcs = 'source' === $package->getInstallationSource();
  280. $io->writeError('<info>Created project in ' . $directory . '</info>');
  281. chdir($directory);
  282. $_SERVER['COMPOSER_ROOT_VERSION'] = $package->getPrettyVersion();
  283. putenv('COMPOSER_ROOT_VERSION='.$_SERVER['COMPOSER_ROOT_VERSION']);
  284. return $installedFromVcs;
  285. }
  286. protected function createDownloadManager(IOInterface $io, Config $config)
  287. {
  288. $factory = new Factory();
  289. return $factory->createDownloadManager($io, $config);
  290. }
  291. protected function createInstallationManager()
  292. {
  293. return new InstallationManager();
  294. }
  295. /**
  296. * Updated preferSource or preferDist based on the preferredInstall config option
  297. * @param Config $config
  298. * @param InputInterface $input
  299. * @param bool $preferSource
  300. * @param bool $preferDist
  301. */
  302. protected function updatePreferredOptions(Config $config, InputInterface $input, &$preferSource, &$preferDist, $keepVcsRequiresPreferSource = false)
  303. {
  304. $preferSource = false;
  305. $preferDist = false;
  306. switch ($config->get('preferred-install')) {
  307. case 'source':
  308. $preferSource = true;
  309. break;
  310. case 'dist':
  311. $preferDist = true;
  312. break;
  313. case 'auto':
  314. default:
  315. // noop
  316. break;
  317. }
  318. if ($input->getOption('prefer-source') || $input->getOption('prefer-dist') || ($keepVcsRequiresPreferSource && $input->getOption('keep-vcs'))) {
  319. $preferSource = $input->getOption('prefer-source') || ($keepVcsRequiresPreferSource && $input->getOption('keep-vcs'));
  320. $preferDist = $input->getOption('prefer-dist');
  321. }
  322. }
  323. }