PageRenderTime 58ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 0ms

/src/Composer/Command/InitCommand.php

https://github.com/ramondelafuente/composer
PHP | 505 lines | 379 code | 89 blank | 37 comment | 55 complexity | d90504e0a21de4a8a27372f0c5ae3385 MD5 | raw file
  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\Json\JsonFile;
  13. use Composer\Factory;
  14. use Composer\Package\BasePackage;
  15. use Composer\Repository\CompositeRepository;
  16. use Composer\Repository\PlatformRepository;
  17. use Composer\Package\Version\VersionParser;
  18. use Symfony\Component\Console\Input\InputInterface;
  19. use Symfony\Component\Console\Input\InputOption;
  20. use Symfony\Component\Console\Output\OutputInterface;
  21. use Symfony\Component\Process\Process;
  22. use Symfony\Component\Process\ExecutableFinder;
  23. /**
  24. * @author Justin Rainbow <justin.rainbow@gmail.com>
  25. * @author Jordi Boggiano <j.boggiano@seld.be>
  26. */
  27. class InitCommand extends Command
  28. {
  29. private $gitConfig;
  30. private $repos;
  31. public function parseAuthorString($author)
  32. {
  33. if (preg_match('/^(?P<name>[- \.,\p{L}\'’]+) <(?P<email>.+?)>$/u', $author, $match)) {
  34. if ($this->isValidEmail($match['email'])) {
  35. return array(
  36. 'name' => trim($match['name']),
  37. 'email' => $match['email']
  38. );
  39. }
  40. }
  41. throw new \InvalidArgumentException(
  42. 'Invalid author string. Must be in the format: '.
  43. 'John Smith <john@example.com>'
  44. );
  45. }
  46. protected function configure()
  47. {
  48. $this
  49. ->setName('init')
  50. ->setDescription('Creates a basic composer.json file in current directory.')
  51. ->setDefinition(array(
  52. new InputOption('name', null, InputOption::VALUE_REQUIRED, 'Name of the package'),
  53. new InputOption('description', null, InputOption::VALUE_REQUIRED, 'Description of package'),
  54. new InputOption('author', null, InputOption::VALUE_REQUIRED, 'Author name of package'),
  55. // new InputOption('version', null, InputOption::VALUE_NONE, 'Version of package'),
  56. new InputOption('homepage', null, InputOption::VALUE_REQUIRED, 'Homepage of package'),
  57. 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"'),
  58. 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"'),
  59. new InputOption('stability', 's', InputOption::VALUE_REQUIRED, 'Minimum stability (empty or one of: '.implode(', ', array_keys(BasePackage::$stabilities)).')'),
  60. new InputOption('license', 'l', InputOption::VALUE_REQUIRED, 'License of package'),
  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. protected function execute(InputInterface $input, OutputInterface $output)
  71. {
  72. $dialog = $this->getHelperSet()->get('dialog');
  73. $whitelist = array('name', 'description', 'author', 'homepage', 'require', 'require-dev', 'stability', 'license');
  74. $options = array_filter(array_intersect_key($input->getOptions(), array_flip($whitelist)));
  75. if (isset($options['author'])) {
  76. $options['authors'] = $this->formatAuthors($options['author']);
  77. unset($options['author']);
  78. }
  79. if (isset($options['stability'])) {
  80. $options['minimum-stability'] = $options['stability'];
  81. unset($options['stability']);
  82. }
  83. $options['require'] = isset($options['require']) ? $this->formatRequirements($options['require']) : new \stdClass;
  84. if (array() === $options['require']) {
  85. $options['require'] = new \stdClass;
  86. }
  87. if (isset($options['require-dev'])) {
  88. $options['require-dev'] = $this->formatRequirements($options['require-dev']) ;
  89. if (array() === $options['require-dev']) {
  90. $options['require-dev'] = new \stdClass;
  91. }
  92. }
  93. $file = new JsonFile('composer.json');
  94. $json = $file->encode($options);
  95. if ($input->isInteractive()) {
  96. $output->writeln(array(
  97. '',
  98. $json,
  99. ''
  100. ));
  101. if (!$dialog->askConfirmation($output, $dialog->getQuestion('Do you confirm generation', 'yes', '?'), true)) {
  102. $output->writeln('<error>Command aborted</error>');
  103. return 1;
  104. }
  105. }
  106. $file->write($options);
  107. if ($input->isInteractive() && is_dir('.git')) {
  108. $ignoreFile = realpath('.gitignore');
  109. if (false === $ignoreFile) {
  110. $ignoreFile = realpath('.') . '/.gitignore';
  111. }
  112. if (!$this->hasVendorIgnore($ignoreFile)) {
  113. $question = 'Would you like the <info>vendor</info> directory added to your <info>.gitignore</info> [<comment>yes</comment>]?';
  114. if ($dialog->askConfirmation($output, $question, true)) {
  115. $this->addVendorIgnore($ignoreFile);
  116. }
  117. }
  118. }
  119. }
  120. protected function interact(InputInterface $input, OutputInterface $output)
  121. {
  122. $git = $this->getGitConfig();
  123. $dialog = $this->getHelperSet()->get('dialog');
  124. $formatter = $this->getHelperSet()->get('formatter');
  125. $output->writeln(array(
  126. '',
  127. $formatter->formatBlock('Welcome to the Composer config generator', 'bg=blue;fg=white', true),
  128. ''
  129. ));
  130. // namespace
  131. $output->writeln(array(
  132. '',
  133. 'This command will guide you through creating your composer.json config.',
  134. '',
  135. ));
  136. $cwd = realpath(".");
  137. if (!$name = $input->getOption('name')) {
  138. $name = basename($cwd);
  139. $name = preg_replace('{(?:([a-z])([A-Z])|([A-Z])([A-Z][a-z]))}', '\\1\\3-\\2\\4', $name);
  140. $name = strtolower($name);
  141. if (isset($git['github.user'])) {
  142. $name = $git['github.user'] . '/' . $name;
  143. } elseif (!empty($_SERVER['USERNAME'])) {
  144. $name = $_SERVER['USERNAME'] . '/' . $name;
  145. } elseif (get_current_user()) {
  146. $name = get_current_user() . '/' . $name;
  147. } else {
  148. // package names must be in the format foo/bar
  149. $name = $name . '/' . $name;
  150. }
  151. } else {
  152. if (!preg_match('{^[a-z0-9_.-]+/[a-z0-9_.-]+$}', $name)) {
  153. throw new \InvalidArgumentException(
  154. '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_.-]+'
  155. );
  156. }
  157. }
  158. $name = $dialog->askAndValidate(
  159. $output,
  160. $dialog->getQuestion('Package name (<vendor>/<name>)', $name),
  161. function ($value) use ($name) {
  162. if (null === $value) {
  163. return $name;
  164. }
  165. if (!preg_match('{^[a-z0-9_.-]+/[a-z0-9_.-]+$}', $value)) {
  166. throw new \InvalidArgumentException(
  167. '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_.-]+'
  168. );
  169. }
  170. return $value;
  171. }
  172. );
  173. $input->setOption('name', $name);
  174. $description = $input->getOption('description') ?: false;
  175. $description = $dialog->ask(
  176. $output,
  177. $dialog->getQuestion('Description', $description)
  178. );
  179. $input->setOption('description', $description);
  180. if (null === $author = $input->getOption('author')) {
  181. if (isset($git['user.name']) && isset($git['user.email'])) {
  182. $author = sprintf('%s <%s>', $git['user.name'], $git['user.email']);
  183. }
  184. }
  185. $self = $this;
  186. $author = $dialog->askAndValidate(
  187. $output,
  188. $dialog->getQuestion('Author', $author),
  189. function ($value) use ($self, $author) {
  190. if (null === $value) {
  191. return $author;
  192. }
  193. $author = $self->parseAuthorString($value);
  194. return sprintf('%s <%s>', $author['name'], $author['email']);
  195. }
  196. );
  197. $input->setOption('author', $author);
  198. $minimumStability = $input->getOption('stability') ?: '';
  199. $minimumStability = $dialog->askAndValidate(
  200. $output,
  201. $dialog->getQuestion('Minimum Stability', $minimumStability),
  202. function ($value) use ($self, $minimumStability) {
  203. if (null === $value) {
  204. return $minimumStability;
  205. }
  206. if (!isset(BasePackage::$stabilities[$value])) {
  207. throw new \InvalidArgumentException(
  208. 'Invalid minimum stability "'.$value.'". Must be empty or one of: '.
  209. implode(', ', array_keys(BasePackage::$stabilities))
  210. );
  211. }
  212. return $value;
  213. }
  214. );
  215. $input->setOption('stability', $minimumStability);
  216. $license = $input->getOption('license') ?: false;
  217. $license = $dialog->ask(
  218. $output,
  219. $dialog->getQuestion('License', $license)
  220. );
  221. $input->setOption('license', $license);
  222. $output->writeln(array(
  223. '',
  224. 'Define your dependencies.',
  225. ''
  226. ));
  227. $requirements = array();
  228. if ($dialog->askConfirmation($output, $dialog->getQuestion('Would you like to define your dependencies (require) interactively', 'yes', '?'), true)) {
  229. $requirements = $this->determineRequirements($input, $output, $input->getOption('require'));
  230. }
  231. $input->setOption('require', $requirements);
  232. $devRequirements = array();
  233. if ($dialog->askConfirmation($output, $dialog->getQuestion('Would you like to define your dev dependencies (require-dev) interactively', 'yes', '?'), true)) {
  234. $devRequirements = $this->determineRequirements($input, $output, $input->getOption('require-dev'));
  235. }
  236. $input->setOption('require-dev', $devRequirements);
  237. }
  238. protected function findPackages($name)
  239. {
  240. $packages = array();
  241. // init repos
  242. if (!$this->repos) {
  243. $this->repos = new CompositeRepository(array_merge(
  244. array(new PlatformRepository),
  245. Factory::createDefaultRepositories($this->getIO())
  246. ));
  247. }
  248. return $this->repos->search($name);
  249. }
  250. protected function determineRequirements(InputInterface $input, OutputInterface $output, $requires = array())
  251. {
  252. $dialog = $this->getHelperSet()->get('dialog');
  253. $prompt = $dialog->getQuestion('Search for a package', false, ':');
  254. if ($requires) {
  255. $requires = $this->normalizeRequirements($requires);
  256. $result = array();
  257. foreach ($requires as $key => $requirement) {
  258. if (!isset($requirement['version']) && $input->isInteractive()) {
  259. $question = $dialog->getQuestion('Please provide a version constraint for the '.$requirement['name'].' requirement');
  260. if ($constraint = $dialog->ask($output, $question)) {
  261. $requirement['version'] = $constraint;
  262. }
  263. }
  264. if (!isset($requirement['version'])) {
  265. throw new \InvalidArgumentException('The requirement '.$requirement['name'].' must contain a version constraint');
  266. }
  267. $result[] = $requirement['name'] . ' ' . $requirement['version'];
  268. }
  269. return $result;
  270. }
  271. while (null !== $package = $dialog->ask($output, $prompt)) {
  272. $matches = $this->findPackages($package);
  273. if (count($matches)) {
  274. $output->writeln(array(
  275. '',
  276. sprintf('Found <info>%s</info> packages matching <info>%s</info>', count($matches), $package),
  277. ''
  278. ));
  279. $exactMatch = null;
  280. $choices = array();
  281. foreach ($matches as $position => $package) {
  282. $choices[] = sprintf(' <info>%5s</info> %s', "[$position]", $package['name']);
  283. if ($package['name'] === $package) {
  284. $exactMatch = true;
  285. break;
  286. }
  287. }
  288. // no match, prompt which to pick
  289. if (!$exactMatch) {
  290. $output->writeln($choices);
  291. $output->writeln('');
  292. $validator = function ($selection) use ($matches) {
  293. if ('' === $selection) {
  294. return false;
  295. }
  296. if (!is_numeric($selection) && preg_match('{^\s*(\S+)\s+(\S.*)\s*$}', $selection, $matches)) {
  297. return $matches[1].' '.$matches[2];
  298. }
  299. if (!isset($matches[(int) $selection])) {
  300. throw new \Exception('Not a valid selection');
  301. }
  302. $package = $matches[(int) $selection];
  303. return $package['name'];
  304. };
  305. $package = $dialog->askAndValidate($output, $dialog->getQuestion('Enter package # to add, or the complete package name if it is not listed', false, ':'), $validator, 3);
  306. }
  307. // no constraint yet, prompt user
  308. if (false !== $package && false === strpos($package, ' ')) {
  309. $validator = function ($input) {
  310. $input = trim($input);
  311. return $input ?: false;
  312. };
  313. $constraint = $dialog->askAndValidate($output, $dialog->getQuestion('Enter the version constraint to require', false, ':'), $validator, 3);
  314. if (false === $constraint) {
  315. continue;
  316. }
  317. $package .= ' '.$constraint;
  318. }
  319. if (false !== $package) {
  320. $requires[] = $package;
  321. }
  322. }
  323. }
  324. return $requires;
  325. }
  326. protected function formatAuthors($author)
  327. {
  328. return array($this->parseAuthorString($author));
  329. }
  330. protected function formatRequirements(array $requirements)
  331. {
  332. $requires = array();
  333. $requirements = $this->normalizeRequirements($requirements);
  334. foreach ($requirements as $requirement) {
  335. $requires[$requirement['name']] = $requirement['version'];
  336. }
  337. return $requires;
  338. }
  339. protected function getGitConfig()
  340. {
  341. if (null !== $this->gitConfig) {
  342. return $this->gitConfig;
  343. }
  344. $finder = new ExecutableFinder();
  345. $gitBin = $finder->find('git');
  346. $cmd = new Process(sprintf('%s config -l', escapeshellarg($gitBin)));
  347. $cmd->run();
  348. if ($cmd->isSuccessful()) {
  349. $this->gitConfig = array();
  350. preg_match_all('{^([^=]+)=(.*)$}m', $cmd->getOutput(), $matches, PREG_SET_ORDER);
  351. foreach ($matches as $match) {
  352. $this->gitConfig[$match[1]] = $match[2];
  353. }
  354. return $this->gitConfig;
  355. }
  356. return $this->gitConfig = array();
  357. }
  358. /**
  359. * Checks the local .gitignore file for the Composer vendor directory.
  360. *
  361. * Tested patterns include:
  362. * "/$vendor"
  363. * "$vendor"
  364. * "$vendor/"
  365. * "/$vendor/"
  366. * "/$vendor/*"
  367. * "$vendor/*"
  368. *
  369. * @param string $ignoreFile
  370. * @param string $vendor
  371. *
  372. * @return bool
  373. */
  374. protected function hasVendorIgnore($ignoreFile, $vendor = 'vendor')
  375. {
  376. if (!file_exists($ignoreFile)) {
  377. return false;
  378. }
  379. $pattern = sprintf('{^/?%s(/\*?)?$}', preg_quote($vendor));
  380. $lines = file($ignoreFile, FILE_IGNORE_NEW_LINES);
  381. foreach ($lines as $line) {
  382. if (preg_match($pattern, $line)) {
  383. return true;
  384. }
  385. }
  386. return false;
  387. }
  388. protected function normalizeRequirements(array $requirements)
  389. {
  390. $parser = new VersionParser();
  391. return $parser->parseNameVersionPairs($requirements);
  392. }
  393. protected function addVendorIgnore($ignoreFile, $vendor = '/vendor/')
  394. {
  395. $contents = "";
  396. if (file_exists($ignoreFile)) {
  397. $contents = file_get_contents($ignoreFile);
  398. if ("\n" !== substr($contents, 0, -1)) {
  399. $contents .= "\n";
  400. }
  401. }
  402. file_put_contents($ignoreFile, $contents . $vendor. "\n");
  403. }
  404. protected function isValidEmail($email)
  405. {
  406. // assume it's valid if we can't validate it
  407. if (!function_exists('filter_var')) {
  408. return true;
  409. }
  410. // php <5.3.3 has a very broken email validator, so bypass checks
  411. if (version_compare(PHP_VERSION, '5.3.3', '<')) {
  412. return true;
  413. }
  414. return false !== filter_var($email, FILTER_VALIDATE_EMAIL);
  415. }
  416. }