InitCommand.php 24 KB

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