InitCommand.php 23 KB

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