PageRenderTime 55ms CodeModel.GetById 25ms RepoModel.GetById 1ms app.codeStats 0ms

/src/Composer/Command/InitCommand.php

https://github.com/theshadow/composer
PHP | 464 lines | 348 code | 83 blank | 33 comment | 51 complexity | 21661f96dd1bd16ec6354ffd868c7680 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>[- \.,\w\'’]+) <(?P<email>.+?)>$/u', $author, $match)) {
  34. if (!function_exists('filter_var') || version_compare(PHP_VERSION, '5.3.3', '<') || $match['email'] === filter_var($match['email'], FILTER_VALIDATE_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. ))
  61. ->setHelp(<<<EOT
  62. The <info>init</info> command creates a basic composer.json file
  63. in the current directory.
  64. <info>php composer.phar init</info>
  65. EOT
  66. )
  67. ;
  68. }
  69. protected function execute(InputInterface $input, OutputInterface $output)
  70. {
  71. $dialog = $this->getHelperSet()->get('dialog');
  72. $whitelist = array('name', 'description', 'author', 'homepage', 'require', 'require-dev', 'stability');
  73. $options = array_filter(array_intersect_key($input->getOptions(), array_flip($whitelist)));
  74. if (isset($options['author'])) {
  75. $options['authors'] = $this->formatAuthors($options['author']);
  76. unset($options['author']);
  77. }
  78. if (isset($options['stability'])) {
  79. $options['minimum-stability'] = $options['stability'];
  80. unset($options['stability']);
  81. }
  82. $options['require'] = isset($options['require']) ? $this->formatRequirements($options['require']) : new \stdClass;
  83. if (array() === $options['require']) {
  84. $options['require'] = new \stdClass;
  85. }
  86. if (isset($options['require-dev'])) {
  87. $options['require-dev'] = $this->formatRequirements($options['require-dev']) ;
  88. if (array() === $options['require-dev']) {
  89. $options['require-dev'] = new \stdClass;
  90. }
  91. }
  92. $file = new JsonFile('composer.json');
  93. $json = $file->encode($options);
  94. if ($input->isInteractive()) {
  95. $output->writeln(array(
  96. '',
  97. $json,
  98. ''
  99. ));
  100. if (!$dialog->askConfirmation($output, $dialog->getQuestion('Do you confirm generation', 'yes', '?'), true)) {
  101. $output->writeln('<error>Command aborted</error>');
  102. return 1;
  103. }
  104. }
  105. $file->write($options);
  106. if ($input->isInteractive() && is_dir('.git')) {
  107. $ignoreFile = realpath('.gitignore');
  108. if (false === $ignoreFile) {
  109. $ignoreFile = realpath('.') . '/.gitignore';
  110. }
  111. if (!$this->hasVendorIgnore($ignoreFile)) {
  112. $question = 'Would you like the <info>vendor</info> directory added to your <info>.gitignore</info> [<comment>yes</comment>]?';
  113. if ($dialog->askConfirmation($output, $question, true)) {
  114. $this->addVendorIgnore($ignoreFile);
  115. }
  116. }
  117. }
  118. }
  119. protected function interact(InputInterface $input, OutputInterface $output)
  120. {
  121. $git = $this->getGitConfig();
  122. $dialog = $this->getHelperSet()->get('dialog');
  123. $formatter = $this->getHelperSet()->get('formatter');
  124. $output->writeln(array(
  125. '',
  126. $formatter->formatBlock('Welcome to the Composer config generator', 'bg=blue;fg=white', true),
  127. ''
  128. ));
  129. // namespace
  130. $output->writeln(array(
  131. '',
  132. 'This command will guide you through creating your composer.json config.',
  133. '',
  134. ));
  135. $cwd = realpath(".");
  136. if (!$name = $input->getOption('name')) {
  137. $name = basename($cwd);
  138. $name = preg_replace('{(?:([a-z])([A-Z])|([A-Z])([A-Z][a-z]))}', '\\1\\3-\\2\\4', $name);
  139. $name = strtolower($name);
  140. if (isset($git['github.user'])) {
  141. $name = $git['github.user'] . '/' . $name;
  142. } elseif (!empty($_SERVER['USERNAME'])) {
  143. $name = $_SERVER['USERNAME'] . '/' . $name;
  144. } elseif (get_current_user()) {
  145. $name = get_current_user() . '/' . $name;
  146. } else {
  147. // package names must be in the format foo/bar
  148. $name = $name . '/' . $name;
  149. }
  150. } else {
  151. if (!preg_match('{^[a-z0-9_.-]+/[a-z0-9_.-]+$}', $name)) {
  152. throw new \InvalidArgumentException(
  153. '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_.-]+'
  154. );
  155. }
  156. }
  157. $name = $dialog->askAndValidate(
  158. $output,
  159. $dialog->getQuestion('Package name (<vendor>/<name>)', $name),
  160. function ($value) use ($name) {
  161. if (null === $value) {
  162. return $name;
  163. }
  164. if (!preg_match('{^[a-z0-9_.-]+/[a-z0-9_.-]+$}', $value)) {
  165. throw new \InvalidArgumentException(
  166. '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_.-]+'
  167. );
  168. }
  169. return $value;
  170. }
  171. );
  172. $input->setOption('name', $name);
  173. $description = $input->getOption('description') ?: false;
  174. $description = $dialog->ask(
  175. $output,
  176. $dialog->getQuestion('Description', $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 = $dialog->askAndValidate(
  186. $output,
  187. $dialog->getQuestion('Author', $author),
  188. function ($value) use ($self, $author) {
  189. if (null === $value) {
  190. return $author;
  191. }
  192. $author = $self->parseAuthorString($value);
  193. return sprintf('%s <%s>', $author['name'], $author['email']);
  194. }
  195. );
  196. $input->setOption('author', $author);
  197. $minimumStability = $input->getOption('stability') ?: '';
  198. $minimumStability = $dialog->askAndValidate(
  199. $output,
  200. $dialog->getQuestion('Minimum Stability', $minimumStability),
  201. function ($value) use ($self, $minimumStability) {
  202. if (null === $value) {
  203. return $minimumStability;
  204. }
  205. if (!isset(BasePackage::$stabilities[$value])) {
  206. throw new \InvalidArgumentException(
  207. 'Invalid minimum stability "'.$value.'". Must be empty or one of: '.
  208. implode(', ', array_keys(BasePackage::$stabilities))
  209. );
  210. }
  211. return $value;
  212. }
  213. );
  214. $input->setOption('stability', $minimumStability);
  215. $output->writeln(array(
  216. '',
  217. 'Define your dependencies.',
  218. ''
  219. ));
  220. $requirements = array();
  221. if ($dialog->askConfirmation($output, $dialog->getQuestion('Would you like to define your dependencies (require) interactively', 'yes', '?'), true)) {
  222. $requirements = $this->determineRequirements($input, $output, $input->getOption('require'));
  223. }
  224. $input->setOption('require', $requirements);
  225. $devRequirements = array();
  226. if ($dialog->askConfirmation($output, $dialog->getQuestion('Would you like to define your dev dependencies (require-dev) interactively', 'yes', '?'), true)) {
  227. $devRequirements = $this->determineRequirements($input, $output, $input->getOption('require-dev'));
  228. }
  229. $input->setOption('require-dev', $devRequirements);
  230. }
  231. protected function findPackages($name)
  232. {
  233. $packages = array();
  234. // init repos
  235. if (!$this->repos) {
  236. $this->repos = new CompositeRepository(array_merge(
  237. array(new PlatformRepository),
  238. Factory::createDefaultRepositories($this->getIO())
  239. ));
  240. }
  241. $token = strtolower($name);
  242. $this->repos->filterPackages(function ($package) use ($token, &$packages) {
  243. if (false !== strpos($package->getName(), $token)) {
  244. $packages[] = $package;
  245. }
  246. });
  247. return $packages;
  248. }
  249. protected function determineRequirements(InputInterface $input, OutputInterface $output, $requires = array())
  250. {
  251. $dialog = $this->getHelperSet()->get('dialog');
  252. $prompt = $dialog->getQuestion('Search for a package', false, ':');
  253. if ($requires) {
  254. $requires = $this->normalizeRequirements($requires);
  255. $result = array();
  256. foreach ($requires as $key => $requirement) {
  257. if (!isset($requirement['version']) && $input->isInteractive()) {
  258. $question = $dialog->getQuestion('Please provide a version constraint for the '.$requirement['name'].' requirement');
  259. if ($constraint = $dialog->ask($output, $question)) {
  260. $requirement['version'] = $constraint;
  261. }
  262. }
  263. if (!isset($requirement['version'])) {
  264. throw new \InvalidArgumentException('The requirement '.$requirement['name'].' must contain a version constraint');
  265. }
  266. $result[] = $requirement['name'] . ' ' . $requirement['version'];
  267. }
  268. return $result;
  269. }
  270. while (null !== $package = $dialog->ask($output, $prompt)) {
  271. $matches = $this->findPackages($package);
  272. if (count($matches)) {
  273. $output->writeln(array(
  274. '',
  275. sprintf('Found <info>%s</info> packages matching <info>%s</info>', count($matches), $package),
  276. ''
  277. ));
  278. foreach ($matches as $position => $package) {
  279. $output->writeln(sprintf(' <info>%5s</info> %s <comment>%s</comment>', "[$position]", $package->getPrettyName(), $package->getPrettyVersion()));
  280. }
  281. $output->writeln('');
  282. $validator = function ($selection) use ($matches) {
  283. if ('' === $selection) {
  284. return false;
  285. }
  286. if (!is_numeric($selection) && preg_match('{^\s*(\S+) +(\S.*)\s*}', $selection, $matches)) {
  287. return $matches[1].' '.$matches[2];
  288. }
  289. if (!isset($matches[(int) $selection])) {
  290. throw new \Exception('Not a valid selection');
  291. }
  292. $package = $matches[(int) $selection];
  293. return sprintf('%s %s', $package->getName(), $package->getPrettyVersion());
  294. };
  295. $package = $dialog->askAndValidate($output, $dialog->getQuestion('Enter package # to add, or a "[package] [version]" couple if it is not listed', false, ':'), $validator, 3);
  296. if (false !== $package) {
  297. $requires[] = $package;
  298. }
  299. }
  300. }
  301. return $requires;
  302. }
  303. protected function formatAuthors($author)
  304. {
  305. return array($this->parseAuthorString($author));
  306. }
  307. protected function formatRequirements(array $requirements)
  308. {
  309. $requires = array();
  310. $requirements = $this->normalizeRequirements($requirements);
  311. foreach ($requirements as $requirement) {
  312. $requires[$requirement['name']] = $requirement['version'];
  313. }
  314. return $requires;
  315. }
  316. protected function getGitConfig()
  317. {
  318. if (null !== $this->gitConfig) {
  319. return $this->gitConfig;
  320. }
  321. $finder = new ExecutableFinder();
  322. $gitBin = $finder->find('git');
  323. $cmd = new Process(sprintf('%s config -l', escapeshellarg($gitBin)));
  324. $cmd->run();
  325. if ($cmd->isSuccessful()) {
  326. $this->gitConfig = array();
  327. preg_match_all('{^([^=]+)=(.*)$}m', $cmd->getOutput(), $matches, PREG_SET_ORDER);
  328. foreach ($matches as $match) {
  329. $this->gitConfig[$match[1]] = $match[2];
  330. }
  331. return $this->gitConfig;
  332. }
  333. return $this->gitConfig = array();
  334. }
  335. /**
  336. * Checks the local .gitignore file for the Composer vendor directory.
  337. *
  338. * Tested patterns include:
  339. * "/$vendor"
  340. * "$vendor"
  341. * "$vendor/"
  342. * "/$vendor/"
  343. * "/$vendor/*"
  344. * "$vendor/*"
  345. *
  346. * @param string $ignoreFile
  347. * @param string $vendor
  348. *
  349. * @return bool
  350. */
  351. protected function hasVendorIgnore($ignoreFile, $vendor = 'vendor')
  352. {
  353. if (!file_exists($ignoreFile)) {
  354. return false;
  355. }
  356. $pattern = sprintf('{^/?%s(/\*?)?$}', preg_quote($vendor));
  357. $lines = file($ignoreFile, FILE_IGNORE_NEW_LINES);
  358. foreach ($lines as $line) {
  359. if (preg_match($pattern, $line)) {
  360. return true;
  361. }
  362. }
  363. return false;
  364. }
  365. protected function normalizeRequirements(array $requirements)
  366. {
  367. $parser = new VersionParser();
  368. return $parser->parseNameVersionPairs($requirements);
  369. }
  370. protected function addVendorIgnore($ignoreFile, $vendor = '/vendor/')
  371. {
  372. $contents = "";
  373. if (file_exists($ignoreFile)) {
  374. $contents = file_get_contents($ignoreFile);
  375. if ("\n" !== substr($contents, 0, -1)) {
  376. $contents .= "\n";
  377. }
  378. }
  379. file_put_contents($ignoreFile, $contents . $vendor. "\n");
  380. }
  381. }