InitCommand.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  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. $description
  179. );
  180. $input->setOption('description', $description);
  181. if (null === $author = $input->getOption('author')) {
  182. if (isset($git['user.name']) && isset($git['user.email'])) {
  183. $author = sprintf('%s <%s>', $git['user.name'], $git['user.email']);
  184. }
  185. }
  186. $self = $this;
  187. $author = $dialog->askAndValidate(
  188. $output,
  189. $dialog->getQuestion('Author', $author),
  190. function ($value) use ($self, $author) {
  191. if (null === $value) {
  192. return $author;
  193. }
  194. $author = $self->parseAuthorString($value);
  195. return sprintf('%s <%s>', $author['name'], $author['email']);
  196. }
  197. );
  198. $input->setOption('author', $author);
  199. $minimumStability = $input->getOption('stability') ?: '';
  200. $minimumStability = $dialog->askAndValidate(
  201. $output,
  202. $dialog->getQuestion('Minimum Stability', $minimumStability),
  203. function ($value) use ($self, $minimumStability) {
  204. if (null === $value) {
  205. return $minimumStability;
  206. }
  207. if (!isset(BasePackage::$stabilities[$value])) {
  208. throw new \InvalidArgumentException(
  209. 'Invalid minimum stability "'.$value.'". Must be empty or one of: '.
  210. implode(', ', array_keys(BasePackage::$stabilities))
  211. );
  212. }
  213. return $value;
  214. }
  215. );
  216. $input->setOption('stability', $minimumStability);
  217. $license = $input->getOption('license') ?: false;
  218. $license = $dialog->ask(
  219. $output,
  220. $dialog->getQuestion('License', $license),
  221. $license
  222. );
  223. $input->setOption('license', $license);
  224. $output->writeln(array(
  225. '',
  226. 'Define your dependencies.',
  227. ''
  228. ));
  229. $requirements = array();
  230. if ($dialog->askConfirmation($output, $dialog->getQuestion('Would you like to define your dependencies (require) interactively', 'yes', '?'), true)) {
  231. $requirements = $this->determineRequirements($input, $output, $input->getOption('require'));
  232. }
  233. $input->setOption('require', $requirements);
  234. $devRequirements = array();
  235. if ($dialog->askConfirmation($output, $dialog->getQuestion('Would you like to define your dev dependencies (require-dev) interactively', 'yes', '?'), true)) {
  236. $devRequirements = $this->determineRequirements($input, $output, $input->getOption('require-dev'));
  237. }
  238. $input->setOption('require-dev', $devRequirements);
  239. }
  240. protected function findPackages($name)
  241. {
  242. $packages = array();
  243. // init repos
  244. if (!$this->repos) {
  245. $this->repos = new CompositeRepository(array_merge(
  246. array(new PlatformRepository),
  247. Factory::createDefaultRepositories($this->getIO())
  248. ));
  249. }
  250. return $this->repos->search($name);
  251. }
  252. protected function determineRequirements(InputInterface $input, OutputInterface $output, $requires = array())
  253. {
  254. $dialog = $this->getHelperSet()->get('dialog');
  255. $prompt = $dialog->getQuestion('Search for a package', false, ':');
  256. if ($requires) {
  257. $requires = $this->normalizeRequirements($requires);
  258. $result = array();
  259. foreach ($requires as $key => $requirement) {
  260. if (!isset($requirement['version']) && $input->isInteractive()) {
  261. $question = $dialog->getQuestion('Please provide a version constraint for the '.$requirement['name'].' requirement');
  262. if ($constraint = $dialog->ask($output, $question)) {
  263. $requirement['version'] = $constraint;
  264. }
  265. }
  266. if (!isset($requirement['version'])) {
  267. throw new \InvalidArgumentException('The requirement '.$requirement['name'].' must contain a version constraint');
  268. }
  269. $result[] = $requirement['name'] . ' ' . $requirement['version'];
  270. }
  271. return $result;
  272. }
  273. while (null !== $package = $dialog->ask($output, $prompt)) {
  274. $matches = $this->findPackages($package);
  275. if (count($matches)) {
  276. $output->writeln(array(
  277. '',
  278. sprintf('Found <info>%s</info> packages matching <info>%s</info>', count($matches), $package),
  279. ''
  280. ));
  281. $exactMatch = null;
  282. $choices = array();
  283. foreach ($matches as $position => $package) {
  284. $choices[] = sprintf(' <info>%5s</info> %s', "[$position]", $package['name']);
  285. if ($package['name'] === $package) {
  286. $exactMatch = true;
  287. break;
  288. }
  289. }
  290. // no match, prompt which to pick
  291. if (!$exactMatch) {
  292. $output->writeln($choices);
  293. $output->writeln('');
  294. $validator = function ($selection) use ($matches) {
  295. if ('' === $selection) {
  296. return false;
  297. }
  298. if (!is_numeric($selection) && preg_match('{^\s*(\S+)\s+(\S.*)\s*$}', $selection, $matches)) {
  299. return $matches[1].' '.$matches[2];
  300. }
  301. if (!isset($matches[(int) $selection])) {
  302. throw new \Exception('Not a valid selection');
  303. }
  304. $package = $matches[(int) $selection];
  305. return $package['name'];
  306. };
  307. $package = $dialog->askAndValidate($output, $dialog->getQuestion('Enter package # to add, or the complete package name if it is not listed', false, ':'), $validator, 3);
  308. }
  309. // no constraint yet, prompt user
  310. if (false !== $package && false === strpos($package, ' ')) {
  311. $validator = function ($input) {
  312. $input = trim($input);
  313. return $input ?: false;
  314. };
  315. $constraint = $dialog->askAndValidate($output, $dialog->getQuestion('Enter the version constraint to require', false, ':'), $validator, 3);
  316. if (false === $constraint) {
  317. continue;
  318. }
  319. $package .= ' '.$constraint;
  320. }
  321. if (false !== $package) {
  322. $requires[] = $package;
  323. }
  324. }
  325. }
  326. return $requires;
  327. }
  328. protected function formatAuthors($author)
  329. {
  330. return array($this->parseAuthorString($author));
  331. }
  332. protected function formatRequirements(array $requirements)
  333. {
  334. $requires = array();
  335. $requirements = $this->normalizeRequirements($requirements);
  336. foreach ($requirements as $requirement) {
  337. $requires[$requirement['name']] = $requirement['version'];
  338. }
  339. return $requires;
  340. }
  341. protected function getGitConfig()
  342. {
  343. if (null !== $this->gitConfig) {
  344. return $this->gitConfig;
  345. }
  346. $finder = new ExecutableFinder();
  347. $gitBin = $finder->find('git');
  348. $cmd = new Process(sprintf('%s config -l', escapeshellarg($gitBin)));
  349. $cmd->run();
  350. if ($cmd->isSuccessful()) {
  351. $this->gitConfig = array();
  352. preg_match_all('{^([^=]+)=(.*)$}m', $cmd->getOutput(), $matches, PREG_SET_ORDER);
  353. foreach ($matches as $match) {
  354. $this->gitConfig[$match[1]] = $match[2];
  355. }
  356. return $this->gitConfig;
  357. }
  358. return $this->gitConfig = array();
  359. }
  360. /**
  361. * Checks the local .gitignore file for the Composer vendor directory.
  362. *
  363. * Tested patterns include:
  364. * "/$vendor"
  365. * "$vendor"
  366. * "$vendor/"
  367. * "/$vendor/"
  368. * "/$vendor/*"
  369. * "$vendor/*"
  370. *
  371. * @param string $ignoreFile
  372. * @param string $vendor
  373. *
  374. * @return bool
  375. */
  376. protected function hasVendorIgnore($ignoreFile, $vendor = 'vendor')
  377. {
  378. if (!file_exists($ignoreFile)) {
  379. return false;
  380. }
  381. $pattern = sprintf('{^/?%s(/\*?)?$}', preg_quote($vendor));
  382. $lines = file($ignoreFile, FILE_IGNORE_NEW_LINES);
  383. foreach ($lines as $line) {
  384. if (preg_match($pattern, $line)) {
  385. return true;
  386. }
  387. }
  388. return false;
  389. }
  390. protected function normalizeRequirements(array $requirements)
  391. {
  392. $parser = new VersionParser();
  393. return $parser->parseNameVersionPairs($requirements);
  394. }
  395. protected function addVendorIgnore($ignoreFile, $vendor = '/vendor/')
  396. {
  397. $contents = "";
  398. if (file_exists($ignoreFile)) {
  399. $contents = file_get_contents($ignoreFile);
  400. if ("\n" !== substr($contents, 0, -1)) {
  401. $contents .= "\n";
  402. }
  403. }
  404. file_put_contents($ignoreFile, $contents . $vendor. "\n");
  405. }
  406. protected function isValidEmail($email)
  407. {
  408. // assume it's valid if we can't validate it
  409. if (!function_exists('filter_var')) {
  410. return true;
  411. }
  412. // php <5.3.3 has a very broken email validator, so bypass checks
  413. if (version_compare(PHP_VERSION, '5.3.3', '<')) {
  414. return true;
  415. }
  416. return false !== filter_var($email, FILTER_VALIDATE_EMAIL);
  417. }
  418. }