PageRenderTime 64ms CodeModel.GetById 39ms RepoModel.GetById 0ms app.codeStats 0ms

/src/Composer/Command/InitCommand.php

https://github.com/skug/composer
PHP | 419 lines | 310 code | 76 blank | 33 comment | 42 complexity | 655b8c94b4afdcdb87675dedbbb621fb 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\Repository\CompositeRepository;
  15. use Composer\Repository\PlatformRepository;
  16. use Symfony\Component\Console\Input\InputInterface;
  17. use Symfony\Component\Console\Input\InputOption;
  18. use Symfony\Component\Console\Output\OutputInterface;
  19. use Symfony\Component\Process\Process;
  20. use Symfony\Component\Process\ExecutableFinder;
  21. /**
  22. * @author Justin Rainbow <justin.rainbow@gmail.com>
  23. * @author Jordi Boggiano <j.boggiano@seld.be>
  24. */
  25. class InitCommand extends Command
  26. {
  27. private $gitConfig;
  28. private $repos;
  29. public function parseAuthorString($author)
  30. {
  31. if (preg_match('/^(?P<name>[- \.,\w\'’]+) <(?P<email>.+?)>$/u', $author, $match)) {
  32. if (!function_exists('filter_var') || version_compare(PHP_VERSION, '5.3.3', '<') || $match['email'] === filter_var($match['email'], FILTER_VALIDATE_EMAIL)) {
  33. return array(
  34. 'name' => trim($match['name']),
  35. 'email' => $match['email']
  36. );
  37. }
  38. }
  39. throw new \InvalidArgumentException(
  40. 'Invalid author string. Must be in the format: '.
  41. 'John Smith <john@example.com>'
  42. );
  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_NONE, 'Name of the package'),
  51. new InputOption('description', null, InputOption::VALUE_NONE, 'Description of package'),
  52. new InputOption('author', null, InputOption::VALUE_NONE, 'Author name of package'),
  53. // new InputOption('version', null, InputOption::VALUE_NONE, 'Version of package'),
  54. new InputOption('homepage', null, InputOption::VALUE_NONE, 'Homepage of package'),
  55. 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"'),
  56. 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"'),
  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. protected function execute(InputInterface $input, OutputInterface $output)
  67. {
  68. $dialog = $this->getHelperSet()->get('dialog');
  69. $whitelist = array('name', 'description', 'author', 'require');
  70. $options = array_filter(array_intersect_key($input->getOptions(), array_flip($whitelist)));
  71. if (isset($options['author'])) {
  72. $options['authors'] = $this->formatAuthors($options['author']);
  73. unset($options['author']);
  74. }
  75. $options['require'] = isset($options['require']) ?
  76. $this->formatRequirements($options['require']) :
  77. new \stdClass;
  78. $file = new JsonFile('composer.json');
  79. $json = $file->encode($options);
  80. if ($input->isInteractive()) {
  81. $output->writeln(array(
  82. '',
  83. $json,
  84. ''
  85. ));
  86. if (!$dialog->askConfirmation($output, $dialog->getQuestion('Do you confirm generation', 'yes', '?'), true)) {
  87. $output->writeln('<error>Command aborted</error>');
  88. return 1;
  89. }
  90. }
  91. $file->write($options);
  92. if ($input->isInteractive()) {
  93. $ignoreFile = realpath('.gitignore');
  94. if (false === $ignoreFile) {
  95. $ignoreFile = realpath('.') . '/.gitignore';
  96. }
  97. if (!$this->hasVendorIgnore($ignoreFile)) {
  98. $question = 'Would you like the <info>vendor</info> directory added to your <info>.gitignore</info> [<comment>yes</comment>]?';
  99. if ($dialog->askConfirmation($output, $question, true)) {
  100. $this->addVendorIgnore($ignoreFile);
  101. }
  102. }
  103. }
  104. }
  105. protected function interact(InputInterface $input, OutputInterface $output)
  106. {
  107. $git = $this->getGitConfig();
  108. $dialog = $this->getHelperSet()->get('dialog');
  109. $formatter = $this->getHelperSet()->get('formatter');
  110. $output->writeln(array(
  111. '',
  112. $formatter->formatBlock('Welcome to the Composer config generator', 'bg=blue;fg=white', true),
  113. ''
  114. ));
  115. // namespace
  116. $output->writeln(array(
  117. '',
  118. 'This command will guide you through creating your composer.json config.',
  119. '',
  120. ));
  121. $cwd = realpath(".");
  122. if (false === $name = $input->getOption('name')) {
  123. $name = basename($cwd);
  124. if (isset($git['github.user'])) {
  125. $name = $git['github.user'] . '/' . $name;
  126. } elseif (!empty($_SERVER['USERNAME'])) {
  127. $name = $_SERVER['USERNAME'] . '/' . $name;
  128. } elseif (get_current_user()) {
  129. $name = get_current_user() . '/' . $name;
  130. } else {
  131. // package names must be in the format foo/bar
  132. $name = $name . '/' . $name;
  133. }
  134. }
  135. $name = $dialog->askAndValidate(
  136. $output,
  137. $dialog->getQuestion('Package name (<vendor>/<name>)', $name),
  138. function ($value) use ($name) {
  139. if (null === $value) {
  140. return $name;
  141. }
  142. if (!preg_match('{^[a-z0-9_.-]+/[a-z0-9_.-]+$}i', $value)) {
  143. throw new \InvalidArgumentException(
  144. 'The package name '.$value.' is invalid, it should have a vendor name, a forward slash, and a package name, matching: [a-z0-9_.-]+/[a-z0-9_.-]+'
  145. );
  146. }
  147. return $value;
  148. }
  149. );
  150. $input->setOption('name', $name);
  151. $description = $input->getOption('description') ?: false;
  152. $description = $dialog->ask(
  153. $output,
  154. $dialog->getQuestion('Description', $description)
  155. );
  156. $input->setOption('description', $description);
  157. if (false === $author = $input->getOption('author')) {
  158. if (isset($git['user.name']) && isset($git['user.email'])) {
  159. $author = sprintf('%s <%s>', $git['user.name'], $git['user.email']);
  160. }
  161. }
  162. $self = $this;
  163. $author = $dialog->askAndValidate(
  164. $output,
  165. $dialog->getQuestion('Author', $author),
  166. function ($value) use ($self, $author) {
  167. if (null === $value) {
  168. return $author;
  169. }
  170. $author = $self->parseAuthorString($value);
  171. return sprintf('%s <%s>', $author['name'], $author['email']);
  172. }
  173. );
  174. $input->setOption('author', $author);
  175. $output->writeln(array(
  176. '',
  177. 'Define your dependencies.',
  178. ''
  179. ));
  180. $requirements = array();
  181. if ($dialog->askConfirmation($output, $dialog->getQuestion('Would you like to define your dependencies (require) interactively', 'yes', '?'), true)) {
  182. $requirements = $this->determineRequirements($input, $output, $input->getOption('require'));
  183. }
  184. $input->setOption('require', $requirements);
  185. $devRequirements = array();
  186. if ($dialog->askConfirmation($output, $dialog->getQuestion('Would you like to define your dev dependencies (require-dev) interactively', 'yes', '?'), true)) {
  187. $devRequirements = $this->determineRequirements($input, $output, $input->getOption('require-dev'));
  188. }
  189. $input->setOption('require-dev', $devRequirements);
  190. }
  191. protected function findPackages($name)
  192. {
  193. $packages = array();
  194. // init repos
  195. if (!$this->repos) {
  196. $this->repos = new CompositeRepository(array_merge(
  197. array(new PlatformRepository),
  198. Factory::createDefaultRepositories($this->getIO())
  199. ));
  200. }
  201. $token = strtolower($name);
  202. foreach ($this->repos->getPackages() as $package) {
  203. if (false === ($pos = strpos($package->getName(), $token))) {
  204. continue;
  205. }
  206. $packages[] = $package;
  207. }
  208. return $packages;
  209. }
  210. protected function determineRequirements(InputInterface $input, OutputInterface $output, $requires = array())
  211. {
  212. $dialog = $this->getHelperSet()->get('dialog');
  213. $prompt = $dialog->getQuestion('Search for a package', false, ':');
  214. if ($requires) {
  215. foreach ($requires as $key => $requirement) {
  216. $requires[$key] = $this->normalizeRequirement($requirement);
  217. if (false === strpos($requires[$key], ' ') && $input->isInteractive()) {
  218. $question = $dialog->getQuestion('Please provide a version constraint for the '.$requirement.' requirement');
  219. if ($constraint = $dialog->ask($output, $question)) {
  220. $requires[$key] .= ' ' . $constraint;
  221. }
  222. }
  223. if (false === strpos($requires[$key], ' ')) {
  224. throw new \InvalidArgumentException('The requirement '.$requirement.' must contain a version constraint');
  225. }
  226. }
  227. return $requires;
  228. }
  229. while (null !== $package = $dialog->ask($output, $prompt)) {
  230. $matches = $this->findPackages($package);
  231. if (count($matches)) {
  232. $output->writeln(array(
  233. '',
  234. sprintf('Found <info>%s</info> packages matching <info>%s</info>', count($matches), $package),
  235. ''
  236. ));
  237. foreach ($matches as $position => $package) {
  238. $output->writeln(sprintf(' <info>%5s</info> %s <comment>%s</comment>', "[$position]", $package->getPrettyName(), $package->getPrettyVersion()));
  239. }
  240. $output->writeln('');
  241. $validator = function ($selection) use ($matches) {
  242. if ('' === $selection) {
  243. return false;
  244. }
  245. if (!is_numeric($selection) && preg_match('{^\s*(\S+) +(\S.*)\s*}', $selection, $matches)) {
  246. return $matches[1].' '.$matches[2];
  247. }
  248. if (!isset($matches[(int) $selection])) {
  249. throw new \Exception('Not a valid selection');
  250. }
  251. $package = $matches[(int) $selection];
  252. return sprintf('%s %s', $package->getName(), $package->getPrettyVersion());
  253. };
  254. $package = $dialog->askAndValidate($output, $dialog->getQuestion('Enter package # to add, or a "[package] [version]" couple if it is not listed', false, ':'), $validator, 3);
  255. if (false !== $package) {
  256. $requires[] = $package;
  257. }
  258. }
  259. }
  260. return $requires;
  261. }
  262. protected function formatAuthors($author)
  263. {
  264. return array($this->parseAuthorString($author));
  265. }
  266. protected function formatRequirements(array $requirements)
  267. {
  268. $requires = array();
  269. foreach ($requirements as $requirement) {
  270. $requirement = $this->normalizeRequirement($requirement);
  271. list($packageName, $packageVersion) = explode(" ", $requirement, 2);
  272. $requires[$packageName] = $packageVersion;
  273. }
  274. return empty($requires) ? new \stdClass : $requires;
  275. }
  276. protected function normalizeRequirement($requirement)
  277. {
  278. return preg_replace('{^([^=: ]+)[=: ](.*)$}', '$1 $2', $requirement);
  279. }
  280. protected function getGitConfig()
  281. {
  282. if (null !== $this->gitConfig) {
  283. return $this->gitConfig;
  284. }
  285. $finder = new ExecutableFinder();
  286. $gitBin = $finder->find('git');
  287. $cmd = new Process(sprintf('%s config -l', escapeshellarg($gitBin)));
  288. $cmd->run();
  289. if ($cmd->isSuccessful()) {
  290. $this->gitConfig = array();
  291. preg_match_all('{^([^=]+)=(.*)$}m', $cmd->getOutput(), $matches, PREG_SET_ORDER);
  292. foreach ($matches as $match) {
  293. $this->gitConfig[$match[1]] = $match[2];
  294. }
  295. return $this->gitConfig;
  296. }
  297. return $this->gitConfig = array();
  298. }
  299. /**
  300. * Checks the local .gitignore file for the Composer vendor directory.
  301. *
  302. * Tested patterns include:
  303. * "/$vendor"
  304. * "$vendor"
  305. * "$vendor/"
  306. * "/$vendor/"
  307. * "/$vendor/*"
  308. * "$vendor/*"
  309. *
  310. * @param string $ignoreFile
  311. * @param string $vendor
  312. *
  313. * @return bool
  314. */
  315. protected function hasVendorIgnore($ignoreFile, $vendor = 'vendor')
  316. {
  317. if (!file_exists($ignoreFile)) {
  318. return false;
  319. }
  320. $pattern = sprintf(
  321. '~^/?%s(/|/\*)?$~',
  322. preg_quote($vendor, '~')
  323. );
  324. $lines = file($ignoreFile, FILE_IGNORE_NEW_LINES);
  325. foreach ($lines as $line) {
  326. if (preg_match($pattern, $line)) {
  327. return true;
  328. }
  329. }
  330. return false;
  331. }
  332. protected function addVendorIgnore($ignoreFile, $vendor = 'vendor')
  333. {
  334. $contents = "";
  335. if (file_exists($ignoreFile)) {
  336. $contents = file_get_contents($ignoreFile);
  337. if ("\n" !== substr($contents, 0, -1)) {
  338. $contents .= "\n";
  339. }
  340. }
  341. file_put_contents($ignoreFile, $contents . $vendor. "\n");
  342. }
  343. }