InitCommand.php 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684
  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\Factory;
  14. use Composer\Json\JsonFile;
  15. use Composer\Package\BasePackage;
  16. use Composer\Package\Version\VersionParser;
  17. use Composer\Package\Version\VersionSelector;
  18. use Composer\Repository\CompositeRepository;
  19. use Composer\Repository\PlatformRepository;
  20. use Composer\Repository\RepositoryFactory;
  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\ExecutableFinder;
  26. use Symfony\Component\Process\Process;
  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. // initialize repos if configured
  133. $repositories = $input->getOption('repository');
  134. if ($repositories) {
  135. $config = Factory::createConfig($io);
  136. $repos = array(new PlatformRepository);
  137. foreach ($repositories as $repo) {
  138. $repos[] = RepositoryFactory::fromString($io, $config, $repo);
  139. }
  140. $repos[] = RepositoryFactory::createRepo($io, $config, array(
  141. 'type' => 'composer',
  142. 'url' => 'https://packagist.org',
  143. ));
  144. $this->repos = new CompositeRepository($repos);
  145. unset($repos, $config, $repositories);
  146. }
  147. $io->writeError(array(
  148. '',
  149. $formatter->formatBlock('Welcome to the Composer config generator', 'bg=blue;fg=white', true),
  150. '',
  151. ));
  152. // namespace
  153. $io->writeError(array(
  154. '',
  155. 'This command will guide you through creating your composer.json config.',
  156. '',
  157. ));
  158. $cwd = realpath(".");
  159. if (!$name = $input->getOption('name')) {
  160. $name = basename($cwd);
  161. $name = preg_replace('{(?:([a-z])([A-Z])|([A-Z])([A-Z][a-z]))}', '\\1\\3-\\2\\4', $name);
  162. $name = strtolower($name);
  163. if (isset($git['github.user'])) {
  164. $name = $git['github.user'] . '/' . $name;
  165. } elseif (!empty($_SERVER['USERNAME'])) {
  166. $name = $_SERVER['USERNAME'] . '/' . $name;
  167. } elseif (!empty($_SERVER['USER'])) {
  168. $name = $_SERVER['USER'] . '/' . $name;
  169. } elseif (get_current_user()) {
  170. $name = get_current_user() . '/' . $name;
  171. } else {
  172. // package names must be in the format foo/bar
  173. $name = $name . '/' . $name;
  174. }
  175. $name = strtolower($name);
  176. } else {
  177. if (!preg_match('{^[a-z0-9_.-]+/[a-z0-9_.-]+$}', $name)) {
  178. throw new \InvalidArgumentException(
  179. '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_.-]+'
  180. );
  181. }
  182. }
  183. $name = $io->askAndValidate(
  184. 'Package name (<vendor>/<name>) [<comment>'.$name.'</comment>]: ',
  185. function ($value) use ($name) {
  186. if (null === $value) {
  187. return $name;
  188. }
  189. if (!preg_match('{^[a-z0-9_.-]+/[a-z0-9_.-]+$}', $value)) {
  190. throw new \InvalidArgumentException(
  191. '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_.-]+'
  192. );
  193. }
  194. return $value;
  195. },
  196. null,
  197. $name
  198. );
  199. $input->setOption('name', $name);
  200. $description = $input->getOption('description') ?: false;
  201. $description = $io->ask(
  202. 'Description [<comment>'.$description.'</comment>]: ',
  203. $description
  204. );
  205. $input->setOption('description', $description);
  206. if (null === $author = $input->getOption('author')) {
  207. if (isset($git['user.name']) && isset($git['user.email'])) {
  208. $author = sprintf('%s <%s>', $git['user.name'], $git['user.email']);
  209. }
  210. }
  211. $self = $this;
  212. $author = $io->askAndValidate(
  213. 'Author [<comment>'.$author.'</comment>, n to skip]: ',
  214. function ($value) use ($self, $author) {
  215. if ($value === 'n' || $value === 'no') {
  216. return;
  217. }
  218. $value = $value ?: $author;
  219. $author = $self->parseAuthorString($value);
  220. return sprintf('%s <%s>', $author['name'], $author['email']);
  221. },
  222. null,
  223. $author
  224. );
  225. $input->setOption('author', $author);
  226. $minimumStability = $input->getOption('stability') ?: null;
  227. $minimumStability = $io->askAndValidate(
  228. 'Minimum Stability [<comment>'.$minimumStability.'</comment>]: ',
  229. function ($value) use ($self, $minimumStability) {
  230. if (null === $value) {
  231. return $minimumStability;
  232. }
  233. if (!isset(BasePackage::$stabilities[$value])) {
  234. throw new \InvalidArgumentException(
  235. 'Invalid minimum stability "'.$value.'". Must be empty or one of: '.
  236. implode(', ', array_keys(BasePackage::$stabilities))
  237. );
  238. }
  239. return $value;
  240. },
  241. null,
  242. $minimumStability
  243. );
  244. $input->setOption('stability', $minimumStability);
  245. $type = $input->getOption('type') ?: false;
  246. $type = $io->ask(
  247. 'Package Type (e.g. library, project, metapackage, composer-plugin) [<comment>'.$type.'</comment>]: ',
  248. $type
  249. );
  250. $input->setOption('type', $type);
  251. $license = $input->getOption('license') ?: false;
  252. $license = $io->ask(
  253. 'License [<comment>'.$license.'</comment>]: ',
  254. $license
  255. );
  256. $input->setOption('license', $license);
  257. $io->writeError(array('', 'Define your dependencies.', ''));
  258. $question = 'Would you like to define your dependencies (require) interactively [<comment>yes</comment>]? ';
  259. $require = $input->getOption('require');
  260. $requirements = array();
  261. if ($require || $io->askConfirmation($question, true)) {
  262. $requirements = $this->determineRequirements($input, $output, $require);
  263. }
  264. $input->setOption('require', $requirements);
  265. $question = 'Would you like to define your dev dependencies (require-dev) interactively [<comment>yes</comment>]? ';
  266. $requireDev = $input->getOption('require-dev');
  267. $devRequirements = array();
  268. if ($requireDev || $io->askConfirmation($question, true)) {
  269. $devRequirements = $this->determineRequirements($input, $output, $requireDev);
  270. }
  271. $input->setOption('require-dev', $devRequirements);
  272. }
  273. /**
  274. * @private
  275. * @param string $author
  276. * @return array
  277. */
  278. public function parseAuthorString($author)
  279. {
  280. if (preg_match('/^(?P<name>[- .,\p{L}\p{N}\p{Mn}\'’"()]+) <(?P<email>.+?)>$/u', $author, $match)) {
  281. if ($this->isValidEmail($match['email'])) {
  282. return array(
  283. 'name' => trim($match['name']),
  284. 'email' => $match['email'],
  285. );
  286. }
  287. }
  288. throw new \InvalidArgumentException(
  289. 'Invalid author string. Must be in the format: '.
  290. 'John Smith <john@example.com>'
  291. );
  292. }
  293. protected function findPackages($name)
  294. {
  295. return $this->getRepos()->search($name);
  296. }
  297. protected function getRepos()
  298. {
  299. if (!$this->repos) {
  300. $this->repos = new CompositeRepository(array_merge(
  301. array(new PlatformRepository),
  302. RepositoryFactory::defaultRepos($this->getIO())
  303. ));
  304. }
  305. return $this->repos;
  306. }
  307. protected function determineRequirements(InputInterface $input, OutputInterface $output, $requires = array(), $phpVersion = null, $preferredStability = 'stable')
  308. {
  309. if ($requires) {
  310. $requires = $this->normalizeRequirements($requires);
  311. $result = array();
  312. $io = $this->getIO();
  313. foreach ($requires as $requirement) {
  314. if (!isset($requirement['version'])) {
  315. // determine the best version automatically
  316. $version = $this->findBestVersionForPackage($input, $requirement['name'], $phpVersion, $preferredStability);
  317. $requirement['version'] = $version;
  318. $io->writeError(sprintf(
  319. 'Using version <info>%s</info> for <info>%s</info>',
  320. $requirement['version'],
  321. $requirement['name']
  322. ));
  323. }
  324. $result[] = $requirement['name'] . ' ' . $requirement['version'];
  325. }
  326. return $result;
  327. }
  328. $versionParser = new VersionParser();
  329. $io = $this->getIO();
  330. while (null !== $package = $io->ask('Search for a package: ')) {
  331. $matches = $this->findPackages($package);
  332. if (count($matches)) {
  333. $exactMatch = null;
  334. $choices = array();
  335. foreach ($matches as $position => $foundPackage) {
  336. $choices[] = sprintf(' <info>%5s</info> %s', "[$position]", $foundPackage['name']);
  337. if ($foundPackage['name'] === $package) {
  338. $exactMatch = true;
  339. break;
  340. }
  341. }
  342. // no match, prompt which to pick
  343. if (!$exactMatch) {
  344. $io->writeError(array(
  345. '',
  346. sprintf('Found <info>%s</info> packages matching <info>%s</info>', count($matches), $package),
  347. '',
  348. ));
  349. $io->writeError($choices);
  350. $io->writeError('');
  351. $validator = function ($selection) use ($matches, $versionParser) {
  352. if ('' === $selection) {
  353. return false;
  354. }
  355. if (is_numeric($selection) && isset($matches[(int) $selection])) {
  356. $package = $matches[(int) $selection];
  357. return $package['name'];
  358. }
  359. if (preg_match('{^\s*(?P<name>[\S/]+)(?:\s+(?P<version>\S+))?\s*$}', $selection, $packageMatches)) {
  360. if (isset($packageMatches['version'])) {
  361. // parsing `acme/example ~2.3`
  362. // validate version constraint
  363. $versionParser->parseConstraints($packageMatches['version']);
  364. return $packageMatches['name'].' '.$packageMatches['version'];
  365. }
  366. // parsing `acme/example`
  367. return $packageMatches['name'];
  368. }
  369. throw new \Exception('Not a valid selection');
  370. };
  371. $package = $io->askAndValidate(
  372. 'Enter package # to add, or the complete package name if it is not listed: ',
  373. $validator,
  374. 3,
  375. false
  376. );
  377. }
  378. // no constraint yet, determine the best version automatically
  379. if (false !== $package && false === strpos($package, ' ')) {
  380. $validator = function ($input) {
  381. $input = trim($input);
  382. return $input ?: false;
  383. };
  384. $constraint = $io->askAndValidate(
  385. 'Enter the version constraint to require (or leave blank to use the latest version): ',
  386. $validator,
  387. 3,
  388. false
  389. );
  390. if (false === $constraint) {
  391. $constraint = $this->findBestVersionForPackage($input, $package, $phpVersion, $preferredStability);
  392. $io->writeError(sprintf(
  393. 'Using version <info>%s</info> for <info>%s</info>',
  394. $constraint,
  395. $package
  396. ));
  397. }
  398. $package .= ' '.$constraint;
  399. }
  400. if (false !== $package) {
  401. $requires[] = $package;
  402. }
  403. }
  404. }
  405. return $requires;
  406. }
  407. protected function formatAuthors($author)
  408. {
  409. return array($this->parseAuthorString($author));
  410. }
  411. protected function formatRequirements(array $requirements)
  412. {
  413. $requires = array();
  414. $requirements = $this->normalizeRequirements($requirements);
  415. foreach ($requirements as $requirement) {
  416. $requires[$requirement['name']] = $requirement['version'];
  417. }
  418. return $requires;
  419. }
  420. protected function getGitConfig()
  421. {
  422. if (null !== $this->gitConfig) {
  423. return $this->gitConfig;
  424. }
  425. $finder = new ExecutableFinder();
  426. $gitBin = $finder->find('git');
  427. $cmd = new Process(sprintf('%s config -l', ProcessExecutor::escape($gitBin)));
  428. $cmd->run();
  429. if ($cmd->isSuccessful()) {
  430. $this->gitConfig = array();
  431. preg_match_all('{^([^=]+)=(.*)$}m', $cmd->getOutput(), $matches, PREG_SET_ORDER);
  432. foreach ($matches as $match) {
  433. $this->gitConfig[$match[1]] = $match[2];
  434. }
  435. return $this->gitConfig;
  436. }
  437. return $this->gitConfig = array();
  438. }
  439. /**
  440. * Checks the local .gitignore file for the Composer vendor directory.
  441. *
  442. * Tested patterns include:
  443. * "/$vendor"
  444. * "$vendor"
  445. * "$vendor/"
  446. * "/$vendor/"
  447. * "/$vendor/*"
  448. * "$vendor/*"
  449. *
  450. * @param string $ignoreFile
  451. * @param string $vendor
  452. *
  453. * @return bool
  454. */
  455. protected function hasVendorIgnore($ignoreFile, $vendor = 'vendor')
  456. {
  457. if (!file_exists($ignoreFile)) {
  458. return false;
  459. }
  460. $pattern = sprintf('{^/?%s(/\*?)?$}', preg_quote($vendor));
  461. $lines = file($ignoreFile, FILE_IGNORE_NEW_LINES);
  462. foreach ($lines as $line) {
  463. if (preg_match($pattern, $line)) {
  464. return true;
  465. }
  466. }
  467. return false;
  468. }
  469. protected function normalizeRequirements(array $requirements)
  470. {
  471. $parser = new VersionParser();
  472. return $parser->parseNameVersionPairs($requirements);
  473. }
  474. protected function addVendorIgnore($ignoreFile, $vendor = '/vendor/')
  475. {
  476. $contents = "";
  477. if (file_exists($ignoreFile)) {
  478. $contents = file_get_contents($ignoreFile);
  479. if ("\n" !== substr($contents, 0, -1)) {
  480. $contents .= "\n";
  481. }
  482. }
  483. file_put_contents($ignoreFile, $contents . $vendor. "\n");
  484. }
  485. protected function isValidEmail($email)
  486. {
  487. // assume it's valid if we can't validate it
  488. if (!function_exists('filter_var')) {
  489. return true;
  490. }
  491. // php <5.3.3 has a very broken email validator, so bypass checks
  492. if (PHP_VERSION_ID < 50303) {
  493. return true;
  494. }
  495. return false !== filter_var($email, FILTER_VALIDATE_EMAIL);
  496. }
  497. private function getPool(InputInterface $input)
  498. {
  499. if (!$this->pool) {
  500. $this->pool = new Pool($this->getMinimumStability($input));
  501. $this->pool->addRepository($this->getRepos());
  502. }
  503. return $this->pool;
  504. }
  505. private function getMinimumStability(InputInterface $input)
  506. {
  507. if ($input->hasOption('stability')) {
  508. return $input->getOption('stability') ?: 'stable';
  509. }
  510. $file = Factory::getComposerFile();
  511. if (is_file($file) && is_readable($file) && is_array($composer = json_decode(file_get_contents($file), true))) {
  512. if (!empty($composer['minimum-stability'])) {
  513. return $composer['minimum-stability'];
  514. }
  515. }
  516. return 'stable';
  517. }
  518. /**
  519. * Given a package name, this determines the best version to use in the require key.
  520. *
  521. * This returns a version with the ~ operator prefixed when possible.
  522. *
  523. * @param InputInterface $input
  524. * @param string $name
  525. * @param string $phpVersion
  526. * @param string $preferredStability
  527. * @throws \InvalidArgumentException
  528. * @return string
  529. */
  530. private function findBestVersionForPackage(InputInterface $input, $name, $phpVersion, $preferredStability = 'stable')
  531. {
  532. // find the latest version allowed in this pool
  533. $versionSelector = new VersionSelector($this->getPool($input));
  534. $package = $versionSelector->findBestCandidate($name, null, $phpVersion, $preferredStability);
  535. if (!$package) {
  536. // Check whether the PHP version was the problem
  537. if ($phpVersion && $versionSelector->findBestCandidate($name)) {
  538. throw new \InvalidArgumentException(sprintf(
  539. 'Could not find package %s at any version matching your PHP version %s', $name, $phpVersion
  540. ));
  541. }
  542. $similar = $this->findSimilar($name);
  543. if ($similar) {
  544. throw new \InvalidArgumentException(sprintf(
  545. "Could not find package %s.\n\nDid you mean " . (count($similar) > 1 ? 'one of these' : 'this') . "?\n %s",
  546. $name,
  547. implode("\n ", $similar)
  548. ));
  549. }
  550. throw new \InvalidArgumentException(sprintf(
  551. 'Could not find package %s at any version for your minimum-stability (%s). Check the package spelling or your minimum-stability',
  552. $name,
  553. $this->getMinimumStability($input)
  554. ));
  555. }
  556. return $versionSelector->findRecommendedRequireVersion($package);
  557. }
  558. private function findSimilar($package)
  559. {
  560. try {
  561. $results = $this->repos->search($package);
  562. } catch (\Exception $e) {
  563. // ignore search errors
  564. return array();
  565. }
  566. $similarPackages = array();
  567. foreach ($results as $result) {
  568. $similarPackages[$result['name']] = levenshtein($package, $result['name']);
  569. }
  570. asort($similarPackages);
  571. return array_keys(array_slice($similarPackages, 0, 5));
  572. }
  573. }