InitCommand.php 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666
  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\DependencyResolver\Pool;
  13. use Composer\Json\JsonFile;
  14. use Composer\Factory;
  15. use Composer\Repository\RepositoryFactory;
  16. use Composer\Package\BasePackage;
  17. use Composer\Package\Version\VersionParser;
  18. use Composer\Package\Version\VersionSelector;
  19. use Composer\Repository\CompositeRepository;
  20. use Composer\Repository\PlatformRepository;
  21. use Composer\Util\ProcessExecutor;
  22. use Symfony\Component\Console\Input\InputInterface;
  23. use Symfony\Component\Console\Input\InputOption;
  24. use Symfony\Component\Console\Output\OutputInterface;
  25. use Symfony\Component\Process\Process;
  26. use Symfony\Component\Process\ExecutableFinder;
  27. /**
  28. * @author Justin Rainbow <justin.rainbow@gmail.com>
  29. * @author Jordi Boggiano <j.boggiano@seld.be>
  30. */
  31. class InitCommand extends BaseCommand
  32. {
  33. /** @var CompositeRepository */
  34. protected $repos;
  35. /** @var array */
  36. private $gitConfig;
  37. /** @var Pool */
  38. private $pool;
  39. /**
  40. * {@inheritdoc}
  41. */
  42. protected function configure()
  43. {
  44. $this
  45. ->setName('init')
  46. ->setDescription('Creates a basic composer.json file in current directory.')
  47. ->setDefinition(array(
  48. new InputOption('name', null, InputOption::VALUE_REQUIRED, 'Name of the package'),
  49. new InputOption('description', null, InputOption::VALUE_REQUIRED, 'Description of package'),
  50. new InputOption('author', null, InputOption::VALUE_REQUIRED, 'Author name of package'),
  51. // new InputOption('version', null, InputOption::VALUE_NONE, 'Version of package'),
  52. new InputOption('type', null, InputOption::VALUE_OPTIONAL, 'Type of package (e.g. library, project, metapackage, composer-plugin)'),
  53. new InputOption('homepage', null, InputOption::VALUE_REQUIRED, 'Homepage of package'),
  54. new InputOption('require', null, InputOption::VALUE_IS_ARRAY | InputOption::VALUE_REQUIRED, 'Package to require with a version constraint, e.g. foo/bar:1.0.0 or foo/bar=1.0.0 or "foo/bar 1.0.0"'),
  55. new InputOption('require-dev', null, InputOption::VALUE_IS_ARRAY | InputOption::VALUE_REQUIRED, 'Package to require for development with a version constraint, e.g. foo/bar:1.0.0 or foo/bar=1.0.0 or "foo/bar 1.0.0"'),
  56. new InputOption('stability', 's', InputOption::VALUE_REQUIRED, 'Minimum stability (empty or one of: '.implode(', ', array_keys(BasePackage::$stabilities)).')'),
  57. new InputOption('license', 'l', InputOption::VALUE_REQUIRED, 'License of package'),
  58. new InputOption('repository', null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'Add custom repositories, either by URL or using JSON arrays'),
  59. ))
  60. ->setHelp(<<<EOT
  61. The <info>init</info> command creates a basic composer.json file
  62. in the current directory.
  63. <info>php composer.phar init</info>
  64. EOT
  65. )
  66. ;
  67. }
  68. /**
  69. * {@inheritdoc}
  70. */
  71. protected function execute(InputInterface $input, OutputInterface $output)
  72. {
  73. $io = $this->getIO();
  74. $whitelist = array('name', 'description', 'author', 'type', 'homepage', 'require', 'require-dev', 'stability', 'license');
  75. $options = array_filter(array_intersect_key($input->getOptions(), array_flip($whitelist)));
  76. if (isset($options['author'])) {
  77. $options['authors'] = $this->formatAuthors($options['author']);
  78. unset($options['author']);
  79. }
  80. $repositories = $input->getOption('repository');
  81. if ($repositories) {
  82. $config = Factory::createConfig($io);
  83. foreach ($repositories as $repo) {
  84. $options['repositories'][] = RepositoryFactory::configFromString($io, $config, $repo);
  85. }
  86. }
  87. if (isset($options['stability'])) {
  88. $options['minimum-stability'] = $options['stability'];
  89. unset($options['stability']);
  90. }
  91. $options['require'] = isset($options['require']) ? $this->formatRequirements($options['require']) : new \stdClass;
  92. if (array() === $options['require']) {
  93. $options['require'] = new \stdClass;
  94. }
  95. if (isset($options['require-dev'])) {
  96. $options['require-dev'] = $this->formatRequirements($options['require-dev']);
  97. if (array() === $options['require-dev']) {
  98. $options['require-dev'] = new \stdClass;
  99. }
  100. }
  101. $file = new JsonFile(Factory::getComposerFile());
  102. $json = $file->encode($options);
  103. if ($input->isInteractive()) {
  104. $io->writeError(array('', $json, ''));
  105. if (!$io->askConfirmation('Do you confirm generation [<comment>yes</comment>]? ', true)) {
  106. $io->writeError('<error>Command aborted</error>');
  107. return 1;
  108. }
  109. }
  110. $file->write($options);
  111. if ($input->isInteractive() && is_dir('.git')) {
  112. $ignoreFile = realpath('.gitignore');
  113. if (false === $ignoreFile) {
  114. $ignoreFile = realpath('.') . '/.gitignore';
  115. }
  116. if (!$this->hasVendorIgnore($ignoreFile)) {
  117. $question = 'Would you like the <info>vendor</info> directory added to your <info>.gitignore</info> [<comment>yes</comment>]? ';
  118. if ($io->askConfirmation($question, true)) {
  119. $this->addVendorIgnore($ignoreFile);
  120. }
  121. }
  122. }
  123. }
  124. /**
  125. * {@inheritdoc}
  126. */
  127. protected function interact(InputInterface $input, OutputInterface $output)
  128. {
  129. $git = $this->getGitConfig();
  130. $io = $this->getIO();
  131. $formatter = $this->getHelperSet()->get('formatter');
  132. $config = Factory::createConfig($io);
  133. $defaults = $config->get('defaults');
  134. // initialize repos if configured
  135. $repositories = $input->getOption('repository');
  136. if ($repositories) {
  137. $repos = array(new PlatformRepository);
  138. foreach ($repositories as $repo) {
  139. $repos[] = RepositoryFactory::fromString($io, $config, $repo);
  140. }
  141. $repos[] = RepositoryFactory::createRepo($io, $config, array(
  142. 'type' => 'composer',
  143. 'url' => 'https://packagist.org',
  144. ));
  145. $this->repos = new CompositeRepository($repos);
  146. unset($repos, $config, $repositories);
  147. }
  148. $io->writeError(array(
  149. '',
  150. $formatter->formatBlock('Welcome to the Composer config generator', 'bg=blue;fg=white', true),
  151. '',
  152. ));
  153. // namespace
  154. $io->writeError(array(
  155. '',
  156. 'This command will guide you through creating your composer.json config.',
  157. '',
  158. ));
  159. $cwd = realpath(".");
  160. if (!$name = $input->getOption('name')) {
  161. $name = basename($cwd);
  162. $name = preg_replace('{(?:([a-z])([A-Z])|([A-Z])([A-Z][a-z]))}', '\\1\\3-\\2\\4', $name);
  163. $name = strtolower($name);
  164. if ( isset($defaults['vendor']) ) {
  165. $name = $defaults['vendor'] . '/' . $name;
  166. } elseif (isset($git['github.user'])) {
  167. $name = $git['github.user'] . '/' . $name;
  168. } elseif (!empty($_SERVER['USERNAME'])) {
  169. $name = $_SERVER['USERNAME'] . '/' . $name;
  170. } elseif (!empty($_SERVER['USER'])) {
  171. $name = $_SERVER['USER'] . '/' . $name;
  172. } elseif (get_current_user()) {
  173. $name = get_current_user() . '/' . $name;
  174. } else {
  175. // package names must be in the format foo/bar
  176. $name = $name . '/' . $name;
  177. }
  178. $name = strtolower($name);
  179. } else {
  180. if (!preg_match('{^[a-z0-9_.-]+/[a-z0-9_.-]+$}', $name)) {
  181. throw new \InvalidArgumentException(
  182. 'The package name '.$name.' is invalid, it should be lowercase and have a vendor name, a forward slash, and a package name, matching: [a-z0-9_.-]+/[a-z0-9_.-]+'
  183. );
  184. }
  185. }
  186. $name = $io->askAndValidate(
  187. 'Package name (<vendor>/<name>) [<comment>'.$name.'</comment>]: ',
  188. function ($value) use ($name) {
  189. if (null === $value) {
  190. return $name;
  191. }
  192. if (!preg_match('{^[a-z0-9_.-]+/[a-z0-9_.-]+$}', $value)) {
  193. throw new \InvalidArgumentException(
  194. 'The package name '.$value.' is invalid, it should be lowercase and have a vendor name, a forward slash, and a package name, matching: [a-z0-9_.-]+/[a-z0-9_.-]+'
  195. );
  196. }
  197. return $value;
  198. },
  199. null,
  200. $name
  201. );
  202. $input->setOption('name', $name);
  203. $description = $input->getOption('description') ?: false;
  204. $description = $io->ask(
  205. 'Description [<comment>'.$description.'</comment>]: ',
  206. $description
  207. );
  208. $input->setOption('description', $description);
  209. if (null === $author = $input->getOption('author')) {
  210. if ( isset($defaults['author']) && isset($defaults['author']['name']) && isset($defaults['author']['email']) ) {
  211. $author = sprintf('%s <%s>', $defaults['author']['name'], $defaults['author']['email']);
  212. } elseif (isset($git['user.name']) && isset($git['user.email'])) {
  213. $author = sprintf('%s <%s>', $git['user.name'], $git['user.email']);
  214. }
  215. }
  216. $self = $this;
  217. $author = $io->askAndValidate(
  218. 'Author [<comment>'.$author.'</comment>, n to skip]: ',
  219. function ($value) use ($self, $author) {
  220. if ($value === 'n' || $value === 'no') {
  221. return;
  222. }
  223. $value = $value ?: $author;
  224. $author = $self->parseAuthorString($value);
  225. return sprintf('%s <%s>', $author['name'], $author['email']);
  226. },
  227. null,
  228. $author
  229. );
  230. $input->setOption('author', $author);
  231. $minimumStability = $input->getOption('stability') ?: null;
  232. $minimumStability = $io->askAndValidate(
  233. 'Minimum Stability [<comment>'.$minimumStability.'</comment>]: ',
  234. function ($value) use ($self, $minimumStability) {
  235. if (null === $value) {
  236. return $minimumStability;
  237. }
  238. if (!isset(BasePackage::$stabilities[$value])) {
  239. throw new \InvalidArgumentException(
  240. 'Invalid minimum stability "'.$value.'". Must be empty or one of: '.
  241. implode(', ', array_keys(BasePackage::$stabilities))
  242. );
  243. }
  244. return $value;
  245. },
  246. null,
  247. $minimumStability
  248. );
  249. $input->setOption('stability', $minimumStability);
  250. $type = $input->getOption('type') ?: false;
  251. $type = $io->ask(
  252. 'Package Type (e.g. library, project, metapackage, composer-plugin) [<comment>'.$type.'</comment>]: ',
  253. $type
  254. );
  255. $input->setOption('type', $type);
  256. if (null === $license = $input->getOption('license')) {
  257. if ( isset($defaults['license']) ) {
  258. $license = $defaults['license'];
  259. }
  260. }
  261. $license = $io->ask(
  262. 'License [<comment>'.$license.'</comment>]: ',
  263. $license
  264. );
  265. $input->setOption('license', $license);
  266. $io->writeError(array('', 'Define your dependencies.', ''));
  267. $question = 'Would you like to define your dependencies (require) interactively [<comment>yes</comment>]? ';
  268. $require = $input->getOption('require');
  269. $requirements = array();
  270. if ($require || $io->askConfirmation($question, true)) {
  271. $requirements = $this->determineRequirements($input, $output, $require);
  272. }
  273. $input->setOption('require', $requirements);
  274. $question = 'Would you like to define your dev dependencies (require-dev) interactively [<comment>yes</comment>]? ';
  275. $requireDev = $input->getOption('require-dev');
  276. $devRequirements = array();
  277. if ($requireDev || $io->askConfirmation($question, true)) {
  278. $devRequirements = $this->determineRequirements($input, $output, $requireDev);
  279. }
  280. $input->setOption('require-dev', $devRequirements);
  281. }
  282. /**
  283. * @private
  284. * @param string $author
  285. * @return array
  286. */
  287. public function parseAuthorString($author)
  288. {
  289. if (preg_match('/^(?P<name>[- .,\p{L}\p{N}\p{Mn}\'’"()]+) <(?P<email>.+?)>$/u', $author, $match)) {
  290. if ($this->isValidEmail($match['email'])) {
  291. return array(
  292. 'name' => trim($match['name']),
  293. 'email' => $match['email'],
  294. );
  295. }
  296. }
  297. throw new \InvalidArgumentException(
  298. 'Invalid author string. Must be in the format: '.
  299. 'John Smith <john@example.com>'
  300. );
  301. }
  302. protected function findPackages($name)
  303. {
  304. return $this->getRepos()->search($name);
  305. }
  306. protected function getRepos()
  307. {
  308. if (!$this->repos) {
  309. $this->repos = new CompositeRepository(array_merge(
  310. array(new PlatformRepository),
  311. RepositoryFactory::defaultRepos($this->getIO())
  312. ));
  313. }
  314. return $this->repos;
  315. }
  316. protected function determineRequirements(InputInterface $input, OutputInterface $output, $requires = array(), $phpVersion = null, $preferredStability = 'stable')
  317. {
  318. if ($requires) {
  319. $requires = $this->normalizeRequirements($requires);
  320. $result = array();
  321. $io = $this->getIO();
  322. foreach ($requires as $requirement) {
  323. if (!isset($requirement['version'])) {
  324. // determine the best version automatically
  325. $version = $this->findBestVersionForPackage($input, $requirement['name'], $phpVersion, $preferredStability);
  326. $requirement['version'] = $version;
  327. $io->writeError(sprintf(
  328. 'Using version <info>%s</info> for <info>%s</info>',
  329. $requirement['version'],
  330. $requirement['name']
  331. ));
  332. }
  333. $result[] = $requirement['name'] . ' ' . $requirement['version'];
  334. }
  335. return $result;
  336. }
  337. $versionParser = new VersionParser();
  338. $io = $this->getIO();
  339. while (null !== $package = $io->ask('Search for a package: ')) {
  340. $matches = $this->findPackages($package);
  341. if (count($matches)) {
  342. $exactMatch = null;
  343. $choices = array();
  344. foreach ($matches as $position => $foundPackage) {
  345. $choices[] = sprintf(' <info>%5s</info> %s', "[$position]", $foundPackage['name']);
  346. if ($foundPackage['name'] === $package) {
  347. $exactMatch = true;
  348. break;
  349. }
  350. }
  351. // no match, prompt which to pick
  352. if (!$exactMatch) {
  353. $io->writeError(array(
  354. '',
  355. sprintf('Found <info>%s</info> packages matching <info>%s</info>', count($matches), $package),
  356. '',
  357. ));
  358. $io->writeError($choices);
  359. $io->writeError('');
  360. $validator = function ($selection) use ($matches, $versionParser) {
  361. if ('' === $selection) {
  362. return false;
  363. }
  364. if (is_numeric($selection) && isset($matches[(int) $selection])) {
  365. $package = $matches[(int) $selection];
  366. return $package['name'];
  367. }
  368. if (preg_match('{^\s*(?P<name>[\S/]+)(?:\s+(?P<version>\S+))?\s*$}', $selection, $packageMatches)) {
  369. if (isset($packageMatches['version'])) {
  370. // parsing `acme/example ~2.3`
  371. // validate version constraint
  372. $versionParser->parseConstraints($packageMatches['version']);
  373. return $packageMatches['name'].' '.$packageMatches['version'];
  374. }
  375. // parsing `acme/example`
  376. return $packageMatches['name'];
  377. }
  378. throw new \Exception('Not a valid selection');
  379. };
  380. $package = $io->askAndValidate(
  381. 'Enter package # to add, or the complete package name if it is not listed: ',
  382. $validator,
  383. 3,
  384. false
  385. );
  386. }
  387. // no constraint yet, determine the best version automatically
  388. if (false !== $package && false === strpos($package, ' ')) {
  389. $validator = function ($input) {
  390. $input = trim($input);
  391. return $input ?: false;
  392. };
  393. $constraint = $io->askAndValidate(
  394. 'Enter the version constraint to require (or leave blank to use the latest version): ',
  395. $validator,
  396. 3,
  397. false
  398. );
  399. if (false === $constraint) {
  400. $constraint = $this->findBestVersionForPackage($input, $package, $phpVersion, $preferredStability);
  401. $io->writeError(sprintf(
  402. 'Using version <info>%s</info> for <info>%s</info>',
  403. $constraint,
  404. $package
  405. ));
  406. }
  407. $package .= ' '.$constraint;
  408. }
  409. if (false !== $package) {
  410. $requires[] = $package;
  411. }
  412. }
  413. }
  414. return $requires;
  415. }
  416. protected function formatAuthors($author)
  417. {
  418. return array($this->parseAuthorString($author));
  419. }
  420. protected function formatRequirements(array $requirements)
  421. {
  422. $requires = array();
  423. $requirements = $this->normalizeRequirements($requirements);
  424. foreach ($requirements as $requirement) {
  425. $requires[$requirement['name']] = $requirement['version'];
  426. }
  427. return $requires;
  428. }
  429. protected function getGitConfig()
  430. {
  431. if (null !== $this->gitConfig) {
  432. return $this->gitConfig;
  433. }
  434. $finder = new ExecutableFinder();
  435. $gitBin = $finder->find('git');
  436. $cmd = new Process(sprintf('%s config -l', ProcessExecutor::escape($gitBin)));
  437. $cmd->run();
  438. if ($cmd->isSuccessful()) {
  439. $this->gitConfig = array();
  440. preg_match_all('{^([^=]+)=(.*)$}m', $cmd->getOutput(), $matches, PREG_SET_ORDER);
  441. foreach ($matches as $match) {
  442. $this->gitConfig[$match[1]] = $match[2];
  443. }
  444. return $this->gitConfig;
  445. }
  446. return $this->gitConfig = array();
  447. }
  448. /**
  449. * Checks the local .gitignore file for the Composer vendor directory.
  450. *
  451. * Tested patterns include:
  452. * "/$vendor"
  453. * "$vendor"
  454. * "$vendor/"
  455. * "/$vendor/"
  456. * "/$vendor/*"
  457. * "$vendor/*"
  458. *
  459. * @param string $ignoreFile
  460. * @param string $vendor
  461. *
  462. * @return bool
  463. */
  464. protected function hasVendorIgnore($ignoreFile, $vendor = 'vendor')
  465. {
  466. if (!file_exists($ignoreFile)) {
  467. return false;
  468. }
  469. $pattern = sprintf('{^/?%s(/\*?)?$}', preg_quote($vendor));
  470. $lines = file($ignoreFile, FILE_IGNORE_NEW_LINES);
  471. foreach ($lines as $line) {
  472. if (preg_match($pattern, $line)) {
  473. return true;
  474. }
  475. }
  476. return false;
  477. }
  478. protected function normalizeRequirements(array $requirements)
  479. {
  480. $parser = new VersionParser();
  481. return $parser->parseNameVersionPairs($requirements);
  482. }
  483. protected function addVendorIgnore($ignoreFile, $vendor = '/vendor/')
  484. {
  485. $contents = "";
  486. if (file_exists($ignoreFile)) {
  487. $contents = file_get_contents($ignoreFile);
  488. if ("\n" !== substr($contents, 0, -1)) {
  489. $contents .= "\n";
  490. }
  491. }
  492. file_put_contents($ignoreFile, $contents . $vendor. "\n");
  493. }
  494. protected function isValidEmail($email)
  495. {
  496. // assume it's valid if we can't validate it
  497. if (!function_exists('filter_var')) {
  498. return true;
  499. }
  500. // php <5.3.3 has a very broken email validator, so bypass checks
  501. if (PHP_VERSION_ID < 50303) {
  502. return true;
  503. }
  504. return false !== filter_var($email, FILTER_VALIDATE_EMAIL);
  505. }
  506. private function getPool(InputInterface $input)
  507. {
  508. if (!$this->pool) {
  509. $this->pool = new Pool($this->getMinimumStability($input));
  510. $this->pool->addRepository($this->getRepos());
  511. }
  512. return $this->pool;
  513. }
  514. private function getMinimumStability(InputInterface $input)
  515. {
  516. if ($input->hasOption('stability')) {
  517. return $input->getOption('stability') ?: 'stable';
  518. }
  519. $file = Factory::getComposerFile();
  520. if (is_file($file) && is_readable($file) && is_array($composer = json_decode(file_get_contents($file), true))) {
  521. if (!empty($composer['minimum-stability'])) {
  522. return $composer['minimum-stability'];
  523. }
  524. }
  525. return 'stable';
  526. }
  527. /**
  528. * Given a package name, this determines the best version to use in the require key.
  529. *
  530. * This returns a version with the ~ operator prefixed when possible.
  531. *
  532. * @param InputInterface $input
  533. * @param string $name
  534. * @param string $phpVersion
  535. * @param string $preferredStability
  536. * @throws \InvalidArgumentException
  537. * @return string
  538. */
  539. private function findBestVersionForPackage(InputInterface $input, $name, $phpVersion, $preferredStability = 'stable')
  540. {
  541. // find the latest version allowed in this pool
  542. $versionSelector = new VersionSelector($this->getPool($input));
  543. $package = $versionSelector->findBestCandidate($name, null, $phpVersion, $preferredStability);
  544. if (!$package) {
  545. // Check whether the PHP version was the problem
  546. if ($phpVersion && $versionSelector->findBestCandidate($name)) {
  547. throw new \InvalidArgumentException(sprintf(
  548. 'Could not find package %s at any version matching your PHP version %s', $name, $phpVersion
  549. ));
  550. }
  551. throw new \InvalidArgumentException(sprintf(
  552. 'Could not find package %s at any version for your minimum-stability (%s). Check the package spelling or your minimum-stability',
  553. $name,
  554. $this->getMinimumStability($input)
  555. ));
  556. }
  557. return $versionSelector->findRecommendedRequireVersion($package);
  558. }
  559. }