CreateProjectCommand.php 16 KB

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