CreateProjectCommand.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  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\Package\LinkConstraint\VersionConstraint;
  20. use Composer\DependencyResolver\Pool;
  21. use Composer\DependencyResolver\Operation\InstallOperation;
  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 defaults 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. ))
  71. ->setHelp(<<<EOT
  72. The <info>create-project</info> command creates a new project from a given
  73. package into a new directory. If executed without params and in a directory
  74. with a composer.json file it installs the packages for the current project.
  75. You can use this command to bootstrap new projects or setup a clean
  76. version-controlled installation for developers of your project.
  77. <info>php composer.phar create-project vendor/project target-directory [version]</info>
  78. You can also specify the version with the package name using = or : as separator.
  79. To install unstable packages, either specify the version you want, or use the
  80. --stability=dev (where dev can be one of RC, beta, alpha or dev).
  81. To setup a developer workable version you should create the project using the source
  82. controlled code by appending the <info>'--prefer-source'</info> flag.
  83. To install a package from another repository than the default one you
  84. can pass the <info>'--repository-url=http://myrepository.org'</info> flag.
  85. EOT
  86. )
  87. ;
  88. }
  89. protected function execute(InputInterface $input, OutputInterface $output)
  90. {
  91. $config = Factory::createConfig();
  92. $preferSource = false;
  93. $preferDist = false;
  94. $this->updatePreferredOptions($config, $input, $preferSource, $preferDist);
  95. if ($input->getOption('no-custom-installers')) {
  96. $output->writeln('<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. $this->getIO(),
  101. $config,
  102. $input->getArgument('package'),
  103. $input->getArgument('directory'),
  104. $input->getArgument('version'),
  105. $input->getOption('stability'),
  106. $preferSource,
  107. $preferDist,
  108. !$input->getOption('no-dev'),
  109. $input->getOption('repository-url'),
  110. $input->getOption('no-plugins'),
  111. $input->getOption('no-scripts'),
  112. $input->getOption('keep-vcs'),
  113. $input->getOption('no-progress'),
  114. $input->getOption('no-install'),
  115. $input
  116. );
  117. }
  118. public function installProject(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, $noInstall = false, InputInterface $input)
  119. {
  120. $oldCwd = getcwd();
  121. if ($packageName !== null) {
  122. $installedFromVcs = $this->installRootPackage($io, $config, $packageName, $directory, $packageVersion, $stability, $preferSource, $preferDist, $installDevPackages, $repositoryUrl, $disablePlugins, $noScripts, $keepVcs, $noProgress);
  123. } else {
  124. $installedFromVcs = false;
  125. }
  126. $composer = Factory::create($io, null, $disablePlugins);
  127. $fs = new Filesystem();
  128. if ($noScripts === false) {
  129. // dispatch event
  130. $composer->getEventDispatcher()->dispatchCommandEvent(ScriptEvents::POST_ROOT_PACKAGE_INSTALL, $installDevPackages);
  131. }
  132. $rootPackageConfig = $composer->getConfig();
  133. $this->updatePreferredOptions($rootPackageConfig, $input, $preferSource, $preferDist);
  134. // install dependencies of the created project
  135. if ($noInstall === false) {
  136. $installer = Installer::create($io, $composer);
  137. $installer->setPreferSource($preferSource)
  138. ->setPreferDist($preferDist)
  139. ->setDevMode($installDevPackages)
  140. ->setRunScripts( ! $noScripts);
  141. if ($disablePlugins) {
  142. $installer->disablePlugins();
  143. }
  144. $status = $installer->run();
  145. if (0 !== $status) {
  146. return $status;
  147. }
  148. }
  149. $hasVcs = $installedFromVcs;
  150. if (!$keepVcs && $installedFromVcs
  151. && (
  152. !$io->isInteractive()
  153. || $io->askConfirmation('<info>Do you want to remove the existing VCS (.git, .svn..) history?</info> [<comment>Y,n</comment>]? ', true)
  154. )
  155. ) {
  156. $finder = new Finder();
  157. $finder->depth(0)->directories()->in(getcwd())->ignoreVCS(false)->ignoreDotFiles(false);
  158. foreach (array('.svn', '_svn', 'CVS', '_darcs', '.arch-params', '.monotone', '.bzr', '.git', '.hg') as $vcsName) {
  159. $finder->name($vcsName);
  160. }
  161. try {
  162. $dirs = iterator_to_array($finder);
  163. unset($finder);
  164. foreach ($dirs as $dir) {
  165. if (!$fs->removeDirectory($dir)) {
  166. throw new \RuntimeException('Could not remove '.$dir);
  167. }
  168. }
  169. } catch (\Exception $e) {
  170. $io->write('<error>An error occurred while removing the VCS metadata: '.$e->getMessage().'</error>');
  171. }
  172. $hasVcs = false;
  173. }
  174. // rewriting self.version dependencies with explicit version numbers if the package's vcs metadata is gone
  175. if (!$hasVcs) {
  176. $package = $composer->getPackage();
  177. $configSource = new JsonConfigSource(new JsonFile('composer.json'));
  178. foreach (BasePackage::$supportedLinkTypes as $type => $meta) {
  179. foreach ($package->{'get'.$meta['method']}() as $link) {
  180. if ($link->getPrettyConstraint() === 'self.version') {
  181. $configSource->addLink($type, $link->getTarget(), $package->getPrettyVersion());
  182. }
  183. }
  184. }
  185. }
  186. if ($noScripts === false) {
  187. // dispatch event
  188. $composer->getEventDispatcher()->dispatchCommandEvent(ScriptEvents::POST_CREATE_PROJECT_CMD, $installDevPackages);
  189. }
  190. chdir($oldCwd);
  191. $vendorComposerDir = $composer->getConfig()->get('vendor-dir').'/composer';
  192. if (is_dir($vendorComposerDir) && $fs->isDirEmpty($vendorComposerDir)) {
  193. @rmdir($vendorComposerDir);
  194. $vendorDir = $composer->getConfig()->get('vendor-dir');
  195. if (is_dir($vendorDir) && $fs->isDirEmpty($vendorDir)) {
  196. @rmdir($vendorDir);
  197. }
  198. }
  199. return 0;
  200. }
  201. 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)
  202. {
  203. if (null === $repositoryUrl) {
  204. $sourceRepo = new CompositeRepository(Factory::createDefaultRepositories($io, $config));
  205. } elseif ("json" === pathinfo($repositoryUrl, PATHINFO_EXTENSION)) {
  206. $sourceRepo = new FilesystemRepository(new JsonFile($repositoryUrl, new RemoteFilesystem($io)));
  207. } elseif (0 === strpos($repositoryUrl, 'http')) {
  208. $sourceRepo = new ComposerRepository(array('url' => $repositoryUrl), $io, $config);
  209. } else {
  210. throw new \InvalidArgumentException("Invalid repository url given. Has to be a .json file or an http url.");
  211. }
  212. $parser = new VersionParser();
  213. $candidates = array();
  214. $requirements = $parser->parseNameVersionPairs(array($packageName));
  215. $name = strtolower($requirements[0]['name']);
  216. if (!$packageVersion && isset($requirements[0]['version'])) {
  217. $packageVersion = $requirements[0]['version'];
  218. }
  219. if (null === $stability) {
  220. if (preg_match('{^[^,\s]*?@('.implode('|', array_keys(BasePackage::$stabilities)).')$}i', $packageVersion, $match)) {
  221. $stability = $match[1];
  222. } else {
  223. $stability = VersionParser::parseStability($packageVersion);
  224. }
  225. }
  226. $stability = VersionParser::normalizeStability($stability);
  227. if (!isset(BasePackage::$stabilities[$stability])) {
  228. throw new \InvalidArgumentException('Invalid stability provided ('.$stability.'), must be one of: '.implode(', ', array_keys(BasePackage::$stabilities)));
  229. }
  230. $pool = new Pool($stability);
  231. $pool->addRepository($sourceRepo);
  232. $constraint = $packageVersion ? $parser->parseConstraints($packageVersion) : null;
  233. $candidates = $pool->whatProvides($name, $constraint);
  234. foreach ($candidates as $key => $candidate) {
  235. if ($candidate->getName() !== $name) {
  236. unset($candidates[$key]);
  237. }
  238. }
  239. if (!$candidates) {
  240. throw new \InvalidArgumentException("Could not find package $name" . ($packageVersion ? " with version $packageVersion." : " with stability $stability."));
  241. }
  242. if (null === $directory) {
  243. $parts = explode("/", $name, 2);
  244. $directory = getcwd() . DIRECTORY_SEPARATOR . array_pop($parts);
  245. }
  246. // select highest version if we have many
  247. $package = reset($candidates);
  248. foreach ($candidates as $candidate) {
  249. if (version_compare($package->getVersion(), $candidate->getVersion(), '<')) {
  250. $package = $candidate;
  251. }
  252. }
  253. unset($candidates);
  254. $io->write('<info>Installing ' . $package->getName() . ' (' . VersionParser::formatVersion($package, false) . ')</info>');
  255. if ($disablePlugins) {
  256. $io->write('<info>Plugins have been disabled.</info>');
  257. }
  258. if (0 === strpos($package->getPrettyVersion(), 'dev-') && in_array($package->getSourceType(), array('git', 'hg'))) {
  259. $package->setSourceReference(substr($package->getPrettyVersion(), 4));
  260. }
  261. $dm = $this->createDownloadManager($io, $config);
  262. $dm->setPreferSource($preferSource)
  263. ->setPreferDist($preferDist)
  264. ->setOutputProgress(!$noProgress);
  265. $projectInstaller = new ProjectInstaller($directory, $dm);
  266. $im = $this->createInstallationManager();
  267. $im->addInstaller($projectInstaller);
  268. $im->install(new InstalledFilesystemRepository(new JsonFile('php://memory')), new InstallOperation($package));
  269. $im->notifyInstalls();
  270. $installedFromVcs = 'source' === $package->getInstallationSource();
  271. $io->write('<info>Created project in ' . $directory . '</info>');
  272. chdir($directory);
  273. putenv('COMPOSER_ROOT_VERSION='.$package->getPrettyVersion());
  274. return $installedFromVcs;
  275. }
  276. protected function createDownloadManager(IOInterface $io, Config $config)
  277. {
  278. $factory = new Factory();
  279. return $factory->createDownloadManager($io, $config);
  280. }
  281. protected function createInstallationManager()
  282. {
  283. return new InstallationManager();
  284. }
  285. /**
  286. * Updated preferSource or preferDist based on the preferredInstall config option
  287. * @param Config $config
  288. * @param InputInterface $input
  289. * @param boolean $preferSource
  290. * @param boolean $preferDist
  291. */
  292. protected function updatePreferredOptions(Config $config, InputInterface $input, &$preferSource, &$preferDist)
  293. {
  294. switch ($config->get('preferred-install')) {
  295. case 'source':
  296. $preferSource = true;
  297. $preferDist = false;
  298. break;
  299. case 'dist':
  300. $preferSource = false;
  301. $preferDist = true;
  302. break;
  303. case 'auto':
  304. default:
  305. // noop
  306. break;
  307. }
  308. if ($input->getOption('prefer-source') || $input->getOption('prefer-dist')) {
  309. $preferSource = $input->getOption('prefer-source');
  310. $preferDist = $input->getOption('prefer-dist');
  311. }
  312. }
  313. }