InitCommand.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  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\Repository\CompositeRepository;
  14. use Composer\Repository\PlatformRepository;
  15. use Composer\Repository\ComposerRepository;
  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>[- \.,a-z0-9]+) <(?P<email>.+?)>$/i', $author, $match)) {
  32. if (!function_exists('filter_var') || $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, 'An array required packages'),
  56. ))
  57. ->setHelp(<<<EOT
  58. The <info>init</info> command creates a basic composer.json file
  59. in the current directory.
  60. <info>php composer.phar init</info>
  61. EOT
  62. )
  63. ;
  64. }
  65. protected function execute(InputInterface $input, OutputInterface $output)
  66. {
  67. $dialog = $this->getHelperSet()->get('dialog');
  68. $whitelist = array('name', 'description', 'author', 'require');
  69. $options = array_filter(array_intersect_key($input->getOptions(), array_flip($whitelist)));
  70. if (isset($options['author'])) {
  71. $options['authors'] = $this->formatAuthors($options['author']);
  72. unset($options['author']);
  73. }
  74. $options['require'] = isset($options['require']) ?
  75. $this->formatRequirements($options['require']) :
  76. new \stdClass;
  77. $file = new JsonFile('composer.json');
  78. $json = $file->encode($options);
  79. if ($input->isInteractive()) {
  80. $output->writeln(array(
  81. '',
  82. $json,
  83. ''
  84. ));
  85. if (!$dialog->askConfirmation($output, $dialog->getQuestion('Do you confirm generation', 'yes', '?'), true)) {
  86. $output->writeln('<error>Command aborted</error>');
  87. return 1;
  88. }
  89. }
  90. $file->write($options);
  91. if ($input->isInteractive()) {
  92. $ignoreFile = realpath('.gitignore');
  93. if (false === $ignoreFile) {
  94. $ignoreFile = realpath('.') . '/.gitignore';
  95. }
  96. if (!$this->hasVendorIgnore($ignoreFile)) {
  97. $question = 'Would you like the <info>vendor</info> directory added to your <info>.gitignore</info> [<comment>yes</comment>]?';
  98. if ($dialog->askConfirmation($output, $question, true)) {
  99. $this->addVendorIgnore($ignoreFile);
  100. }
  101. }
  102. }
  103. }
  104. protected function interact(InputInterface $input, OutputInterface $output)
  105. {
  106. $git = $this->getGitConfig();
  107. $dialog = $this->getHelperSet()->get('dialog');
  108. $formatter = $this->getHelperSet()->get('formatter');
  109. $output->writeln(array(
  110. '',
  111. $formatter->formatBlock('Welcome to the Composer config generator', 'bg=blue;fg=white', true),
  112. ''
  113. ));
  114. // namespace
  115. $output->writeln(array(
  116. '',
  117. 'This command will guide you through creating your composer.json config.',
  118. '',
  119. ));
  120. $cwd = realpath(".");
  121. if (false === $name = $input->getOption('name')) {
  122. $name = basename($cwd);
  123. if (isset($git['github.user'])) {
  124. $name = $git['github.user'] . '/' . $name;
  125. } elseif (!empty($_SERVER['USERNAME'])) {
  126. $name = $_SERVER['USERNAME'] . '/' . $name;
  127. } elseif (get_current_user()) {
  128. $name = get_current_user() . '/' . $name;
  129. } else {
  130. // package names must be in the format foo/bar
  131. $name = $name . '/' . $name;
  132. }
  133. }
  134. $name = $dialog->askAndValidate(
  135. $output,
  136. $dialog->getQuestion('Package name (<vendor>/<name>)', $name),
  137. function ($value) use ($name) {
  138. if (null === $value) {
  139. return $name;
  140. }
  141. if (!preg_match('{^[a-z0-9_.-]+/[a-z0-9_.-]+$}i', $value)) {
  142. throw new \InvalidArgumentException(
  143. '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_.-]+'
  144. );
  145. }
  146. return $value;
  147. }
  148. );
  149. $input->setOption('name', $name);
  150. $description = $input->getOption('description') ?: false;
  151. $description = $dialog->ask(
  152. $output,
  153. $dialog->getQuestion('Description', $description)
  154. );
  155. $input->setOption('description', $description);
  156. if (false === $author = $input->getOption('author')) {
  157. if (isset($git['user.name']) && isset($git['user.email'])) {
  158. $author = sprintf('%s <%s>', $git['user.name'], $git['user.email']);
  159. }
  160. }
  161. $self = $this;
  162. $author = $dialog->askAndValidate(
  163. $output,
  164. $dialog->getQuestion('Author', $author),
  165. function ($value) use ($self, $author) {
  166. if (null === $value) {
  167. return $author;
  168. }
  169. $author = $self->parseAuthorString($value);
  170. return sprintf('%s <%s>', $author['name'], $author['email']);
  171. }
  172. );
  173. $input->setOption('author', $author);
  174. $output->writeln(array(
  175. '',
  176. 'Define your dependencies.',
  177. ''
  178. ));
  179. $requirements = array();
  180. if ($dialog->askConfirmation($output, $dialog->getQuestion('Would you like to define your dependencies interactively', 'yes', '?'), true)) {
  181. $requirements = $this->determineRequirements($input, $output);
  182. }
  183. $input->setOption('require', $requirements);
  184. }
  185. protected function findPackages($name)
  186. {
  187. $packages = array();
  188. // init repos
  189. if (!$this->repos) {
  190. $this->repos = new CompositeRepository(array(
  191. new PlatformRepository,
  192. new ComposerRepository(array('url' => 'http://packagist.org'))
  193. ));
  194. }
  195. $token = strtolower($name);
  196. foreach ($this->repos->getPackages() as $package) {
  197. if (false === ($pos = strpos($package->getName(), $token))) {
  198. continue;
  199. }
  200. $packages[] = $package;
  201. }
  202. return $packages;
  203. }
  204. protected function determineRequirements(InputInterface $input, OutputInterface $output)
  205. {
  206. $dialog = $this->getHelperSet()->get('dialog');
  207. $prompt = $dialog->getQuestion('Search for a package', false, ':');
  208. $requires = $input->getOption('require') ?: array();
  209. while (null !== $package = $dialog->ask($output, $prompt)) {
  210. $matches = $this->findPackages($package);
  211. if (count($matches)) {
  212. $output->writeln(array(
  213. '',
  214. sprintf('Found <info>%s</info> packages matching <info>%s</info>', count($matches), $package),
  215. ''
  216. ));
  217. foreach ($matches as $position => $package) {
  218. $output->writeln(sprintf(' <info>%5s</info> %s <comment>%s</comment>', "[$position]", $package->getPrettyName(), $package->getPrettyVersion()));
  219. }
  220. $output->writeln('');
  221. $validator = function ($selection) use ($matches) {
  222. if ('' === $selection) {
  223. return false;
  224. }
  225. if (!is_numeric($selection) && preg_match('{^\s*(\S+) +(\S.*)\s*}', $selection, $matches)) {
  226. return $matches[1].' '.$matches[2];
  227. }
  228. if (!isset($matches[(int) $selection])) {
  229. throw new \Exception('Not a valid selection');
  230. }
  231. $package = $matches[(int) $selection];
  232. return sprintf('%s %s', $package->getName(), $package->getPrettyVersion());
  233. };
  234. $package = $dialog->askAndValidate($output, $dialog->getQuestion('Enter package # to add, or a <package> <version> couple if it is not listed', false, ':'), $validator, 3);
  235. if (false !== $package) {
  236. $requires[] = $package;
  237. }
  238. }
  239. }
  240. return $requires;
  241. }
  242. protected function formatAuthors($author)
  243. {
  244. return array($this->parseAuthorString($author));
  245. }
  246. protected function formatRequirements(array $requirements)
  247. {
  248. $requires = array();
  249. foreach ($requirements as $requirement) {
  250. list($packageName, $packageVersion) = explode(" ", $requirement, 2);
  251. $requires[$packageName] = $packageVersion;
  252. }
  253. return empty($requires) ? new \stdClass : $requires;
  254. }
  255. protected function getGitConfig()
  256. {
  257. if (null !== $this->gitConfig) {
  258. return $this->gitConfig;
  259. }
  260. $finder = new ExecutableFinder();
  261. $gitBin = $finder->find('git');
  262. $cmd = new Process(sprintf('%s config -l', $gitBin));
  263. $cmd->run();
  264. if ($cmd->isSuccessful()) {
  265. return $this->gitConfig = parse_ini_string($cmd->getOutput(), false, INI_SCANNER_RAW);
  266. }
  267. return $this->gitConfig = array();
  268. }
  269. /**
  270. * Checks the local .gitignore file for the Composer vendor directory.
  271. *
  272. * Tested patterns include:
  273. * "/$vendor"
  274. * "$vendor"
  275. * "$vendor/"
  276. * "/$vendor/"
  277. * "/$vendor/*"
  278. * "$vendor/*"
  279. *
  280. * @param string $ignoreFile
  281. * @param string $vendor
  282. *
  283. * @return Boolean
  284. */
  285. protected function hasVendorIgnore($ignoreFile, $vendor = 'vendor')
  286. {
  287. if (!file_exists($ignoreFile)) {
  288. return false;
  289. }
  290. $pattern = sprintf(
  291. '~^/?%s(/|/\*)?$~',
  292. preg_quote($vendor, '~')
  293. );
  294. $lines = file($ignoreFile, FILE_IGNORE_NEW_LINES);
  295. foreach ($lines as $line) {
  296. if (preg_match($pattern, $line)) {
  297. return true;
  298. }
  299. }
  300. return false;
  301. }
  302. protected function addVendorIgnore($ignoreFile, $vendor = 'vendor')
  303. {
  304. $contents = "";
  305. if (file_exists($ignoreFile)) {
  306. $contents = file_get_contents($ignoreFile);
  307. if ("\n" !== substr($contents, 0, -1)) {
  308. $contents .= "\n";
  309. }
  310. }
  311. file_put_contents($ignoreFile, $contents . $vendor. "\n");
  312. }
  313. }