InitCommand.php 16 KB

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