InitCommand.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  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 Composer\Repository\ComposerRepository;
  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_NONE, 'Name of the package'),
  52. new InputOption('description', null, InputOption::VALUE_NONE, 'Description of package'),
  53. new InputOption('author', null, InputOption::VALUE_NONE, 'Author name of package'),
  54. // new InputOption('version', null, InputOption::VALUE_NONE, 'Version of package'),
  55. new InputOption('homepage', null, InputOption::VALUE_NONE, 'Homepage of package'),
  56. new InputOption('require', null, InputOption::VALUE_IS_ARRAY | InputOption::VALUE_REQUIRED, 'An array required packages'),
  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 interactively', 'yes', '?'), true)) {
  182. $requirements = $this->determineRequirements($input, $output);
  183. }
  184. $input->setOption('require', $requirements);
  185. }
  186. protected function findPackages($name)
  187. {
  188. $packages = array();
  189. // init repos
  190. if (!$this->repos) {
  191. $this->repos = new CompositeRepository(array(
  192. new PlatformRepository,
  193. new ComposerRepository(array('url' => 'http://packagist.org'), $this->getIO(), Factory::createConfig())
  194. ));
  195. }
  196. $token = strtolower($name);
  197. foreach ($this->repos->getPackages() as $package) {
  198. if (false === ($pos = strpos($package->getName(), $token))) {
  199. continue;
  200. }
  201. $packages[] = $package;
  202. }
  203. return $packages;
  204. }
  205. protected function determineRequirements(InputInterface $input, OutputInterface $output)
  206. {
  207. $dialog = $this->getHelperSet()->get('dialog');
  208. $prompt = $dialog->getQuestion('Search for a package', false, ':');
  209. $requires = $input->getOption('require') ?: array();
  210. while (null !== $package = $dialog->ask($output, $prompt)) {
  211. $matches = $this->findPackages($package);
  212. if (count($matches)) {
  213. $output->writeln(array(
  214. '',
  215. sprintf('Found <info>%s</info> packages matching <info>%s</info>', count($matches), $package),
  216. ''
  217. ));
  218. foreach ($matches as $position => $package) {
  219. $output->writeln(sprintf(' <info>%5s</info> %s <comment>%s</comment>', "[$position]", $package->getPrettyName(), $package->getPrettyVersion()));
  220. }
  221. $output->writeln('');
  222. $validator = function ($selection) use ($matches) {
  223. if ('' === $selection) {
  224. return false;
  225. }
  226. if (!is_numeric($selection) && preg_match('{^\s*(\S+) +(\S.*)\s*}', $selection, $matches)) {
  227. return $matches[1].' '.$matches[2];
  228. }
  229. if (!isset($matches[(int) $selection])) {
  230. throw new \Exception('Not a valid selection');
  231. }
  232. $package = $matches[(int) $selection];
  233. return sprintf('%s %s', $package->getName(), $package->getPrettyVersion());
  234. };
  235. $package = $dialog->askAndValidate($output, $dialog->getQuestion('Enter package # to add, or a <package> <version> couple if it is not listed', false, ':'), $validator, 3);
  236. if (false !== $package) {
  237. $requires[] = $package;
  238. }
  239. }
  240. }
  241. return $requires;
  242. }
  243. protected function formatAuthors($author)
  244. {
  245. return array($this->parseAuthorString($author));
  246. }
  247. protected function formatRequirements(array $requirements)
  248. {
  249. $requires = array();
  250. foreach ($requirements as $requirement) {
  251. list($packageName, $packageVersion) = explode(" ", $requirement, 2);
  252. $requires[$packageName] = $packageVersion;
  253. }
  254. return empty($requires) ? new \stdClass : $requires;
  255. }
  256. protected function getGitConfig()
  257. {
  258. if (null !== $this->gitConfig) {
  259. return $this->gitConfig;
  260. }
  261. $finder = new ExecutableFinder();
  262. $gitBin = $finder->find('git');
  263. $cmd = new Process(sprintf('%s config -l', escapeshellarg($gitBin)));
  264. $cmd->run();
  265. if ($cmd->isSuccessful()) {
  266. $this->gitConfig = array();
  267. preg_match_all('{^([^=]+)=(.*)$}m', $cmd->getOutput(), $matches, PREG_SET_ORDER);
  268. foreach ($matches as $match) {
  269. $this->gitConfig[$match[1]] = $match[2];
  270. }
  271. return $this->gitConfig;
  272. }
  273. return $this->gitConfig = array();
  274. }
  275. /**
  276. * Checks the local .gitignore file for the Composer vendor directory.
  277. *
  278. * Tested patterns include:
  279. * "/$vendor"
  280. * "$vendor"
  281. * "$vendor/"
  282. * "/$vendor/"
  283. * "/$vendor/*"
  284. * "$vendor/*"
  285. *
  286. * @param string $ignoreFile
  287. * @param string $vendor
  288. *
  289. * @return Boolean
  290. */
  291. protected function hasVendorIgnore($ignoreFile, $vendor = 'vendor')
  292. {
  293. if (!file_exists($ignoreFile)) {
  294. return false;
  295. }
  296. $pattern = sprintf(
  297. '~^/?%s(/|/\*)?$~',
  298. preg_quote($vendor, '~')
  299. );
  300. $lines = file($ignoreFile, FILE_IGNORE_NEW_LINES);
  301. foreach ($lines as $line) {
  302. if (preg_match($pattern, $line)) {
  303. return true;
  304. }
  305. }
  306. return false;
  307. }
  308. protected function addVendorIgnore($ignoreFile, $vendor = 'vendor')
  309. {
  310. $contents = "";
  311. if (file_exists($ignoreFile)) {
  312. $contents = file_get_contents($ignoreFile);
  313. if ("\n" !== substr($contents, 0, -1)) {
  314. $contents .= "\n";
  315. }
  316. }
  317. file_put_contents($ignoreFile, $contents . $vendor. "\n");
  318. }
  319. }