CreateProjectCommand.php 16 KB

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