InitCommand.php 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860
  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\Factory;
  13. use Composer\Json\JsonFile;
  14. use Composer\Package\BasePackage;
  15. use Composer\Package\Package;
  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\Repository\RepositorySet;
  22. use Composer\Util\ProcessExecutor;
  23. use Symfony\Component\Console\Input\ArrayInput;
  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 RepositorySet[] */
  40. private $repositorySets;
  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(
  63. <<<EOT
  64. The <info>init</info> command creates a basic composer.json file
  65. in the current directory.
  66. <info>php composer.phar init</info>
  67. Read more at https://getcomposer.org/doc/03-cli.md#init
  68. EOT
  69. )
  70. ;
  71. }
  72. /**
  73. * {@inheritdoc}
  74. */
  75. protected function execute(InputInterface $input, OutputInterface $output)
  76. {
  77. $io = $this->getIO();
  78. $allowlist = array('name', 'description', 'author', 'type', 'homepage', 'require', 'require-dev', 'stability', 'license');
  79. $options = array_filter(array_intersect_key($input->getOptions(), array_flip($allowlist)));
  80. if (isset($options['author'])) {
  81. $options['authors'] = $this->formatAuthors($options['author']);
  82. unset($options['author']);
  83. }
  84. $repositories = $input->getOption('repository');
  85. if ($repositories) {
  86. $config = Factory::createConfig($io);
  87. foreach ($repositories as $repo) {
  88. $options['repositories'][] = RepositoryFactory::configFromString($io, $config, $repo);
  89. }
  90. }
  91. if (isset($options['stability'])) {
  92. $options['minimum-stability'] = $options['stability'];
  93. unset($options['stability']);
  94. }
  95. $options['require'] = isset($options['require']) ? $this->formatRequirements($options['require']) : new \stdClass;
  96. if (array() === $options['require']) {
  97. $options['require'] = new \stdClass;
  98. }
  99. if (isset($options['require-dev'])) {
  100. $options['require-dev'] = $this->formatRequirements($options['require-dev']);
  101. if (array() === $options['require-dev']) {
  102. $options['require-dev'] = new \stdClass;
  103. }
  104. }
  105. $file = new JsonFile(Factory::getComposerFile());
  106. $json = $file->encode($options);
  107. if ($input->isInteractive()) {
  108. $io->writeError(array('', $json, ''));
  109. if (!$io->askConfirmation('Do you confirm generation [<comment>yes</comment>]? ', true)) {
  110. $io->writeError('<error>Command aborted</error>');
  111. return 1;
  112. }
  113. }
  114. $file->write($options);
  115. if ($input->isInteractive() && is_dir('.git')) {
  116. $ignoreFile = realpath('.gitignore');
  117. if (false === $ignoreFile) {
  118. $ignoreFile = realpath('.') . '/.gitignore';
  119. }
  120. if (!$this->hasVendorIgnore($ignoreFile)) {
  121. $question = 'Would you like the <info>vendor</info> directory added to your <info>.gitignore</info> [<comment>yes</comment>]? ';
  122. if ($io->askConfirmation($question, true)) {
  123. $this->addVendorIgnore($ignoreFile);
  124. }
  125. }
  126. }
  127. $question = 'Would you like to install dependencies now [<comment>yes</comment>]? ';
  128. if ($input->isInteractive() && $this->hasDependencies($options) && $io->askConfirmation($question, true)) {
  129. $this->installDependencies($output);
  130. }
  131. return 0;
  132. }
  133. /**
  134. * {@inheritdoc}
  135. */
  136. protected function interact(InputInterface $input, OutputInterface $output)
  137. {
  138. $git = $this->getGitConfig();
  139. $io = $this->getIO();
  140. $formatter = $this->getHelperSet()->get('formatter');
  141. // initialize repos if configured
  142. $repositories = $input->getOption('repository');
  143. if ($repositories) {
  144. $config = Factory::createConfig($io);
  145. $repos = array(new PlatformRepository);
  146. $createDefaultPackagistRepo = true;
  147. foreach ($repositories as $repo) {
  148. $repoConfig = RepositoryFactory::configFromString($io, $config, $repo);
  149. if (
  150. (isset($repoConfig['packagist']) && $repoConfig === array('packagist' => false))
  151. || (isset($repoConfig['packagist.org']) && $repoConfig === array('packagist.org' => false))
  152. ) {
  153. $createDefaultPackagistRepo = false;
  154. continue;
  155. }
  156. $repos[] = RepositoryFactory::createRepo($io, $config, $repoConfig);
  157. }
  158. if ($createDefaultPackagistRepo) {
  159. $repos[] = RepositoryFactory::createRepo($io, $config, array(
  160. 'type' => 'composer',
  161. 'url' => 'https://repo.packagist.org',
  162. ));
  163. }
  164. $this->repos = new CompositeRepository($repos);
  165. unset($repos, $config, $repositories);
  166. }
  167. $io->writeError(array(
  168. '',
  169. $formatter->formatBlock('Welcome to the Composer config generator', 'bg=blue;fg=white', true),
  170. '',
  171. ));
  172. // namespace
  173. $io->writeError(array(
  174. '',
  175. 'This command will guide you through creating your composer.json config.',
  176. '',
  177. ));
  178. $cwd = realpath(".");
  179. if (!$name = $input->getOption('name')) {
  180. $name = basename($cwd);
  181. $name = preg_replace('{(?:([a-z])([A-Z])|([A-Z])([A-Z][a-z]))}', '\\1\\3-\\2\\4', $name);
  182. $name = strtolower($name);
  183. if (!empty($_SERVER['COMPOSER_DEFAULT_VENDOR'])) {
  184. $name = $_SERVER['COMPOSER_DEFAULT_VENDOR'] . '/' . $name;
  185. } elseif (isset($git['github.user'])) {
  186. $name = $git['github.user'] . '/' . $name;
  187. } elseif (!empty($_SERVER['USERNAME'])) {
  188. $name = $_SERVER['USERNAME'] . '/' . $name;
  189. } elseif (!empty($_SERVER['USER'])) {
  190. $name = $_SERVER['USER'] . '/' . $name;
  191. } elseif (get_current_user()) {
  192. $name = get_current_user() . '/' . $name;
  193. } else {
  194. // package names must be in the format foo/bar
  195. $name .= '/' . $name;
  196. }
  197. $name = strtolower($name);
  198. } else {
  199. if (!preg_match('{^[a-z0-9_.-]+/[a-z0-9_.-]+$}D', $name)) {
  200. throw new \InvalidArgumentException(
  201. '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_.-]+'
  202. );
  203. }
  204. }
  205. $name = $io->askAndValidate(
  206. 'Package name (<vendor>/<name>) [<comment>'.$name.'</comment>]: ',
  207. function ($value) use ($name) {
  208. if (null === $value) {
  209. return $name;
  210. }
  211. if (!preg_match('{^[a-z0-9_.-]+/[a-z0-9_.-]+$}D', $value)) {
  212. throw new \InvalidArgumentException(
  213. '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_.-]+'
  214. );
  215. }
  216. return $value;
  217. },
  218. null,
  219. $name
  220. );
  221. $input->setOption('name', $name);
  222. $description = $input->getOption('description') ?: false;
  223. $description = $io->ask(
  224. 'Description [<comment>'.$description.'</comment>]: ',
  225. $description
  226. );
  227. $input->setOption('description', $description);
  228. if (null === $author = $input->getOption('author')) {
  229. if (!empty($_SERVER['COMPOSER_DEFAULT_AUTHOR'])) {
  230. $author_name = $_SERVER['COMPOSER_DEFAULT_AUTHOR'];
  231. } elseif (isset($git['user.name'])) {
  232. $author_name = $git['user.name'];
  233. }
  234. if (!empty($_SERVER['COMPOSER_DEFAULT_EMAIL'])) {
  235. $author_email = $_SERVER['COMPOSER_DEFAULT_EMAIL'];
  236. } elseif (isset($git['user.email'])) {
  237. $author_email = $git['user.email'];
  238. }
  239. if (isset($author_name) && isset($author_email)) {
  240. $author = sprintf('%s <%s>', $author_name, $author_email);
  241. }
  242. }
  243. $self = $this;
  244. $author = $io->askAndValidate(
  245. 'Author [<comment>'.$author.'</comment>, n to skip]: ',
  246. function ($value) use ($self, $author) {
  247. if ($value === 'n' || $value === 'no') {
  248. return;
  249. }
  250. $value = $value ?: $author;
  251. $author = $self->parseAuthorString($value);
  252. return sprintf('%s <%s>', $author['name'], $author['email']);
  253. },
  254. null,
  255. $author
  256. );
  257. $input->setOption('author', $author);
  258. $minimumStability = $input->getOption('stability') ?: null;
  259. $minimumStability = $io->askAndValidate(
  260. 'Minimum Stability [<comment>'.$minimumStability.'</comment>]: ',
  261. function ($value) use ($minimumStability) {
  262. if (null === $value) {
  263. return $minimumStability;
  264. }
  265. if (!isset(BasePackage::$stabilities[$value])) {
  266. throw new \InvalidArgumentException(
  267. 'Invalid minimum stability "'.$value.'". Must be empty or one of: '.
  268. implode(', ', array_keys(BasePackage::$stabilities))
  269. );
  270. }
  271. return $value;
  272. },
  273. null,
  274. $minimumStability
  275. );
  276. $input->setOption('stability', $minimumStability);
  277. $type = $input->getOption('type') ?: false;
  278. $type = $io->ask(
  279. 'Package Type (e.g. library, project, metapackage, composer-plugin) [<comment>'.$type.'</comment>]: ',
  280. $type
  281. );
  282. $input->setOption('type', $type);
  283. if (null === $license = $input->getOption('license')) {
  284. if (!empty($_SERVER['COMPOSER_DEFAULT_LICENSE'])) {
  285. $license = $_SERVER['COMPOSER_DEFAULT_LICENSE'];
  286. }
  287. }
  288. $license = $io->ask(
  289. 'License [<comment>'.$license.'</comment>]: ',
  290. $license
  291. );
  292. $input->setOption('license', $license);
  293. $io->writeError(array('', 'Define your dependencies.', ''));
  294. // prepare to resolve dependencies
  295. $repos = $this->getRepos();
  296. $preferredStability = $minimumStability ?: 'stable';
  297. $platformRepo = null;
  298. if ($repos instanceof CompositeRepository) {
  299. foreach ($repos->getRepositories() as $candidateRepo) {
  300. if ($candidateRepo instanceof PlatformRepository) {
  301. $platformRepo = $candidateRepo;
  302. break;
  303. }
  304. }
  305. }
  306. $question = 'Would you like to define your dependencies (require) interactively [<comment>yes</comment>]? ';
  307. $require = $input->getOption('require');
  308. $requirements = array();
  309. if ($require || $io->askConfirmation($question, true)) {
  310. $requirements = $this->determineRequirements($input, $output, $require, $platformRepo, $preferredStability);
  311. }
  312. $input->setOption('require', $requirements);
  313. $question = 'Would you like to define your dev dependencies (require-dev) interactively [<comment>yes</comment>]? ';
  314. $requireDev = $input->getOption('require-dev');
  315. $devRequirements = array();
  316. if ($requireDev || $io->askConfirmation($question, true)) {
  317. $devRequirements = $this->determineRequirements($input, $output, $requireDev, $platformRepo, $preferredStability);
  318. }
  319. $input->setOption('require-dev', $devRequirements);
  320. }
  321. /**
  322. * @private
  323. * @param string $author
  324. * @return array
  325. */
  326. public function parseAuthorString($author)
  327. {
  328. if (preg_match('/^(?P<name>[- .,\p{L}\p{N}\p{Mn}\'’"()]+) <(?P<email>.+?)>$/u', $author, $match)) {
  329. if ($this->isValidEmail($match['email'])) {
  330. return array(
  331. 'name' => trim($match['name']),
  332. 'email' => $match['email'],
  333. );
  334. }
  335. }
  336. throw new \InvalidArgumentException(
  337. 'Invalid author string. Must be in the format: '.
  338. 'John Smith <john@example.com>'
  339. );
  340. }
  341. protected function findPackages($name)
  342. {
  343. return $this->getRepos()->search($name);
  344. }
  345. protected function getRepos()
  346. {
  347. if (!$this->repos) {
  348. $this->repos = new CompositeRepository(array_merge(
  349. array(new PlatformRepository),
  350. RepositoryFactory::defaultRepos($this->getIO())
  351. ));
  352. }
  353. return $this->repos;
  354. }
  355. final protected function determineRequirements(InputInterface $input, OutputInterface $output, $requires = array(), PlatformRepository $platformRepo = null, $preferredStability = 'stable', $checkProvidedVersions = true, $fixed = false)
  356. {
  357. if ($requires) {
  358. $requires = $this->normalizeRequirements($requires);
  359. $result = array();
  360. $io = $this->getIO();
  361. foreach ($requires as $requirement) {
  362. if (!isset($requirement['version'])) {
  363. // determine the best version automatically
  364. list($name, $version) = $this->findBestVersionAndNameForPackage($input, $requirement['name'], $platformRepo, $preferredStability, null, null, $fixed);
  365. $requirement['version'] = $version;
  366. // replace package name from packagist.org
  367. $requirement['name'] = $name;
  368. $io->writeError(sprintf(
  369. 'Using version <info>%s</info> for <info>%s</info>',
  370. $requirement['version'],
  371. $requirement['name']
  372. ));
  373. } else {
  374. // check that the specified version/constraint exists before we proceed
  375. list($name, $version) = $this->findBestVersionAndNameForPackage($input, $requirement['name'], $platformRepo, $preferredStability, $checkProvidedVersions ? $requirement['version'] : null, 'dev', $fixed);
  376. // replace package name from packagist.org
  377. $requirement['name'] = $name;
  378. }
  379. $result[] = $requirement['name'] . ' ' . $requirement['version'];
  380. }
  381. return $result;
  382. }
  383. $versionParser = new VersionParser();
  384. // Collect existing packages
  385. $composer = $this->getComposer(false);
  386. $installedRepo = $composer ? $composer->getRepositoryManager()->getLocalRepository() : null;
  387. $existingPackages = array();
  388. if ($installedRepo) {
  389. foreach ($installedRepo->getPackages() as $package) {
  390. $existingPackages[] = $package->getName();
  391. }
  392. }
  393. foreach ($requires as $requiredPackage) {
  394. $existingPackages[] = substr($requiredPackage, 0, strpos($requiredPackage, ' '));
  395. }
  396. unset($composer, $installedRepo, $requiredPackage);
  397. $io = $this->getIO();
  398. while (null !== $package = $io->ask('Search for a package: ')) {
  399. $matches = $this->findPackages($package);
  400. if (count($matches)) {
  401. // Remove existing packages from search results.
  402. foreach ($matches as $position => $foundPackage) {
  403. if (in_array($foundPackage['name'], $existingPackages, true)) {
  404. unset($matches[$position]);
  405. }
  406. }
  407. $matches = array_values($matches);
  408. $exactMatch = null;
  409. $choices = array();
  410. foreach ($matches as $position => $foundPackage) {
  411. $abandoned = '';
  412. if (isset($foundPackage['abandoned'])) {
  413. if (is_string($foundPackage['abandoned'])) {
  414. $replacement = sprintf('Use %s instead', $foundPackage['abandoned']);
  415. } else {
  416. $replacement = 'No replacement was suggested';
  417. }
  418. $abandoned = sprintf('<warning>Abandoned. %s.</warning>', $replacement);
  419. }
  420. $choices[] = sprintf(' <info>%5s</info> %s %s', "[$position]", $foundPackage['name'], $abandoned);
  421. if ($foundPackage['name'] === $package) {
  422. $exactMatch = true;
  423. break;
  424. }
  425. }
  426. // no match, prompt which to pick
  427. if (!$exactMatch) {
  428. $io->writeError(array(
  429. '',
  430. sprintf('Found <info>%s</info> packages matching <info>%s</info>', count($matches), $package),
  431. '',
  432. ));
  433. $io->writeError($choices);
  434. $io->writeError('');
  435. $validator = function ($selection) use ($matches, $versionParser) {
  436. if ('' === $selection) {
  437. return false;
  438. }
  439. if (is_numeric($selection) && isset($matches[(int) $selection])) {
  440. $package = $matches[(int) $selection];
  441. return $package['name'];
  442. }
  443. if (preg_match('{^\s*(?P<name>[\S/]+)(?:\s+(?P<version>\S+))?\s*$}', $selection, $packageMatches)) {
  444. if (isset($packageMatches['version'])) {
  445. // parsing `acme/example ~2.3`
  446. // validate version constraint
  447. $versionParser->parseConstraints($packageMatches['version']);
  448. return $packageMatches['name'].' '.$packageMatches['version'];
  449. }
  450. // parsing `acme/example`
  451. return $packageMatches['name'];
  452. }
  453. throw new \Exception('Not a valid selection');
  454. };
  455. $package = $io->askAndValidate(
  456. 'Enter package # to add, or the complete package name if it is not listed: ',
  457. $validator,
  458. 3,
  459. false
  460. );
  461. }
  462. // no constraint yet, determine the best version automatically
  463. if (false !== $package && false === strpos($package, ' ')) {
  464. $validator = function ($input) {
  465. $input = trim($input);
  466. return $input ?: false;
  467. };
  468. $constraint = $io->askAndValidate(
  469. 'Enter the version constraint to require (or leave blank to use the latest version): ',
  470. $validator,
  471. 3,
  472. false
  473. );
  474. if (false === $constraint) {
  475. list($name, $constraint) = $this->findBestVersionAndNameForPackage($input, $package, $platformRepo, $preferredStability);
  476. $io->writeError(sprintf(
  477. 'Using version <info>%s</info> for <info>%s</info>',
  478. $constraint,
  479. $package
  480. ));
  481. }
  482. $package .= ' '.$constraint;
  483. }
  484. if (false !== $package) {
  485. $requires[] = $package;
  486. $existingPackages[] = substr($package, 0, strpos($package, ' '));
  487. }
  488. }
  489. }
  490. return $requires;
  491. }
  492. protected function formatAuthors($author)
  493. {
  494. return array($this->parseAuthorString($author));
  495. }
  496. protected function formatRequirements(array $requirements)
  497. {
  498. $requires = array();
  499. $requirements = $this->normalizeRequirements($requirements);
  500. foreach ($requirements as $requirement) {
  501. $requires[$requirement['name']] = $requirement['version'];
  502. }
  503. return $requires;
  504. }
  505. protected function getGitConfig()
  506. {
  507. if (null !== $this->gitConfig) {
  508. return $this->gitConfig;
  509. }
  510. $finder = new ExecutableFinder();
  511. $gitBin = $finder->find('git');
  512. // TODO in v3 always call with an array
  513. if (method_exists('Symfony\Component\Process\Process', 'fromShellCommandline')) {
  514. $cmd = new Process(array($gitBin, 'config', '-l'));
  515. } else {
  516. $cmd = new Process(sprintf('%s config -l', ProcessExecutor::escape($gitBin)));
  517. }
  518. $cmd->run();
  519. if ($cmd->isSuccessful()) {
  520. $this->gitConfig = array();
  521. preg_match_all('{^([^=]+)=(.*)$}m', $cmd->getOutput(), $matches, PREG_SET_ORDER);
  522. foreach ($matches as $match) {
  523. $this->gitConfig[$match[1]] = $match[2];
  524. }
  525. return $this->gitConfig;
  526. }
  527. return $this->gitConfig = array();
  528. }
  529. /**
  530. * Checks the local .gitignore file for the Composer vendor directory.
  531. *
  532. * Tested patterns include:
  533. * "/$vendor"
  534. * "$vendor"
  535. * "$vendor/"
  536. * "/$vendor/"
  537. * "/$vendor/*"
  538. * "$vendor/*"
  539. *
  540. * @param string $ignoreFile
  541. * @param string $vendor
  542. *
  543. * @return bool
  544. */
  545. protected function hasVendorIgnore($ignoreFile, $vendor = 'vendor')
  546. {
  547. if (!file_exists($ignoreFile)) {
  548. return false;
  549. }
  550. $pattern = sprintf('{^/?%s(/\*?)?$}', preg_quote($vendor));
  551. $lines = file($ignoreFile, FILE_IGNORE_NEW_LINES);
  552. foreach ($lines as $line) {
  553. if (preg_match($pattern, $line)) {
  554. return true;
  555. }
  556. }
  557. return false;
  558. }
  559. protected function normalizeRequirements(array $requirements)
  560. {
  561. $parser = new VersionParser();
  562. return $parser->parseNameVersionPairs($requirements);
  563. }
  564. protected function addVendorIgnore($ignoreFile, $vendor = '/vendor/')
  565. {
  566. $contents = "";
  567. if (file_exists($ignoreFile)) {
  568. $contents = file_get_contents($ignoreFile);
  569. if ("\n" !== substr($contents, 0, -1)) {
  570. $contents .= "\n";
  571. }
  572. }
  573. file_put_contents($ignoreFile, $contents . $vendor. "\n");
  574. }
  575. protected function isValidEmail($email)
  576. {
  577. // assume it's valid if we can't validate it
  578. if (!function_exists('filter_var')) {
  579. return true;
  580. }
  581. // php <5.3.3 has a very broken email validator, so bypass checks
  582. if (PHP_VERSION_ID < 50303) {
  583. return true;
  584. }
  585. return false !== filter_var($email, FILTER_VALIDATE_EMAIL);
  586. }
  587. private function getRepositorySet(InputInterface $input, $minimumStability = null)
  588. {
  589. $key = $minimumStability ?: 'default';
  590. if (!isset($this->repositorySets[$key])) {
  591. $this->repositorySets[$key] = $repositorySet = new RepositorySet($minimumStability ?: $this->getMinimumStability($input));
  592. $repositorySet->addRepository($this->getRepos());
  593. }
  594. return $this->repositorySets[$key];
  595. }
  596. private function getMinimumStability(InputInterface $input)
  597. {
  598. if ($input->hasOption('stability')) {
  599. return VersionParser::normalizeStability($input->getOption('stability') ?: 'stable');
  600. }
  601. $file = Factory::getComposerFile();
  602. if (is_file($file) && is_readable($file) && is_array($composer = json_decode(file_get_contents($file), true))) {
  603. if (!empty($composer['minimum-stability'])) {
  604. return VersionParser::normalizeStability($composer['minimum-stability']);
  605. }
  606. }
  607. return 'stable';
  608. }
  609. /**
  610. * Given a package name, this determines the best version to use in the require key.
  611. *
  612. * This returns a version with the ~ operator prefixed when possible.
  613. *
  614. * @param InputInterface $input
  615. * @param string $name
  616. * @param PlatformRepository|null $platformRepo
  617. * @param string $preferredStability
  618. * @param string|null $requiredVersion
  619. * @param string $minimumStability
  620. * @param bool $fixed
  621. * @throws \InvalidArgumentException
  622. * @return array name version
  623. */
  624. private function findBestVersionAndNameForPackage(InputInterface $input, $name, PlatformRepository $platformRepo = null, $preferredStability = 'stable', $requiredVersion = null, $minimumStability = null, $fixed = null)
  625. {
  626. // ignore platform repo if platform requirements are ignored
  627. $ignorePlatformReqs = $input->hasOption('ignore-platform-reqs') && $input->getOption('ignore-platform-reqs');
  628. if ($ignorePlatformReqs) {
  629. $platformRepo = null;
  630. }
  631. // find the latest version allowed in this repo set
  632. $versionSelector = new VersionSelector($this->getRepositorySet($input, $minimumStability), $platformRepo);
  633. $package = $versionSelector->findBestCandidate($name, $requiredVersion, $preferredStability);
  634. if (!$package) {
  635. // platform packages can not be found in the pool in versions other than the local platform's has
  636. // so if platform reqs are ignored we just take the user's word for it
  637. if ($ignorePlatformReqs && preg_match(PlatformRepository::PLATFORM_PACKAGE_REGEX, $name)) {
  638. return array($name, $requiredVersion ?: '*');
  639. }
  640. // Check whether the PHP version was the problem
  641. if ($platformRepo && $versionSelector->findBestCandidate($name, $requiredVersion, $preferredStability, true)) {
  642. throw new \InvalidArgumentException(sprintf(
  643. 'Package %s at version %s has a PHP requirement incompatible with your PHP version, PHP extensions and Composer version',
  644. $name,
  645. $requiredVersion
  646. ));
  647. }
  648. // Check whether the required version was the problem
  649. if ($requiredVersion && $versionSelector->findBestCandidate($name, null, $preferredStability)) {
  650. throw new \InvalidArgumentException(sprintf(
  651. 'Could not find package %s in a version matching %s',
  652. $name,
  653. $requiredVersion
  654. ));
  655. }
  656. // Check whether the PHP version was the problem for all versions
  657. if ($platformRepo && $versionSelector->findBestCandidate($name, null, $preferredStability, true)) {
  658. throw new \InvalidArgumentException(sprintf(
  659. 'Could not find package %s in any version matching your PHP version, PHP extensions and Composer version',
  660. $name
  661. ));
  662. }
  663. // Check for similar names/typos
  664. $similar = $this->findSimilar($name);
  665. if ($similar) {
  666. // Check whether the minimum stability was the problem but the package exists
  667. if ($requiredVersion === null && in_array($name, $similar, true)) {
  668. throw new \InvalidArgumentException(sprintf(
  669. 'Could not find a version of package %s matching your minimum-stability (%s). Require it with an explicit version constraint allowing its desired stability.',
  670. $name,
  671. $this->getMinimumStability($input)
  672. ));
  673. }
  674. throw new \InvalidArgumentException(sprintf(
  675. "Could not find package %s.\n\nDid you mean " . (count($similar) > 1 ? 'one of these' : 'this') . "?\n %s",
  676. $name,
  677. implode("\n ", $similar)
  678. ));
  679. }
  680. throw new \InvalidArgumentException(sprintf(
  681. 'Could not find a matching version of package %s. Check the package spelling, your version constraint and that the package is available in a stability which matches your minimum-stability (%s).',
  682. $name,
  683. $this->getMinimumStability($input)
  684. ));
  685. }
  686. return array(
  687. $package->getPrettyName(),
  688. $fixed ? $package->getPrettyVersion() : $versionSelector->findRecommendedRequireVersion($package),
  689. );
  690. }
  691. private function findSimilar($package)
  692. {
  693. try {
  694. $results = $this->repos->search($package);
  695. } catch (\Exception $e) {
  696. // ignore search errors
  697. return array();
  698. }
  699. $similarPackages = array();
  700. $installedRepo = $this->getComposer()->getRepositoryManager()->getLocalRepository();
  701. foreach ($results as $result) {
  702. if ($installedRepo->findPackage($result['name'], '*')) {
  703. // Ignore installed package
  704. continue;
  705. }
  706. $similarPackages[$result['name']] = levenshtein($package, $result['name']);
  707. }
  708. asort($similarPackages);
  709. return array_keys(array_slice($similarPackages, 0, 5));
  710. }
  711. private function installDependencies($output)
  712. {
  713. try {
  714. $installCommand = $this->getApplication()->find('install');
  715. $installCommand->run(new ArrayInput(array()), $output);
  716. } catch (\Exception $e) {
  717. $this->getIO()->writeError('Could not install dependencies. Run `composer install` to see more information.');
  718. }
  719. }
  720. private function hasDependencies($options)
  721. {
  722. $requires = (array) $options['require'];
  723. $devRequires = isset($options['require-dev']) ? (array) $options['require-dev'] : array();
  724. return !empty($requires) || !empty($devRequires);
  725. }
  726. }