InitCommand.php 21 KB

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