Factory.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  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;
  12. use Composer\Config\JsonConfigSource;
  13. use Composer\Json\JsonFile;
  14. use Composer\IO\IOInterface;
  15. use Composer\Package\Archiver;
  16. use Composer\Package\Version\VersionGuesser;
  17. use Composer\Repository\RepositoryManager;
  18. use Composer\Repository\WritableRepositoryInterface;
  19. use Composer\Util\ProcessExecutor;
  20. use Composer\Util\RemoteFilesystem;
  21. use Symfony\Component\Console\Formatter\OutputFormatterStyle;
  22. use Composer\EventDispatcher\EventDispatcher;
  23. use Composer\Autoload\AutoloadGenerator;
  24. use Composer\Semver\VersionParser;
  25. use Seld\JsonLint\JsonParser;
  26. /**
  27. * Creates a configured instance of composer.
  28. *
  29. * @author Ryan Weaver <ryan@knplabs.com>
  30. * @author Jordi Boggiano <j.boggiano@seld.be>
  31. * @author Igor Wiedler <igor@wiedler.ch>
  32. * @author Nils Adermann <naderman@naderman.de>
  33. */
  34. class Factory
  35. {
  36. /**
  37. * @throws \RuntimeException
  38. * @return string
  39. */
  40. protected static function getHomeDir()
  41. {
  42. $home = getenv('COMPOSER_HOME');
  43. if (!$home) {
  44. if (defined('PHP_WINDOWS_VERSION_MAJOR')) {
  45. if (!getenv('APPDATA')) {
  46. throw new \RuntimeException('The APPDATA or COMPOSER_HOME environment variable must be set for composer to run correctly');
  47. }
  48. $home = strtr(getenv('APPDATA'), '\\', '/') . '/Composer';
  49. } else {
  50. if (!getenv('HOME')) {
  51. throw new \RuntimeException('The HOME or COMPOSER_HOME environment variable must be set for composer to run correctly');
  52. }
  53. $home = rtrim(getenv('HOME'), '/') . '/.composer';
  54. }
  55. }
  56. return $home;
  57. }
  58. /**
  59. * @param string $home
  60. * @return string
  61. */
  62. protected static function getCacheDir($home)
  63. {
  64. $cacheDir = getenv('COMPOSER_CACHE_DIR');
  65. if (!$cacheDir) {
  66. if (defined('PHP_WINDOWS_VERSION_MAJOR')) {
  67. if ($cacheDir = getenv('LOCALAPPDATA')) {
  68. $cacheDir .= '/Composer';
  69. } else {
  70. $cacheDir = $home . '/cache';
  71. }
  72. $cacheDir = strtr($cacheDir, '\\', '/');
  73. } else {
  74. $cacheDir = $home.'/cache';
  75. }
  76. }
  77. return $cacheDir;
  78. }
  79. /**
  80. * @param IOInterface|null $io
  81. * @return Config
  82. */
  83. public static function createConfig(IOInterface $io = null, $cwd = null)
  84. {
  85. $cwd = $cwd ?: getcwd();
  86. // determine home and cache dirs
  87. $home = self::getHomeDir();
  88. $cacheDir = self::getCacheDir($home);
  89. // Protect directory against web access. Since HOME could be
  90. // the www-data's user home and be web-accessible it is a
  91. // potential security risk
  92. foreach (array($home, $cacheDir) as $dir) {
  93. if (!file_exists($dir . '/.htaccess')) {
  94. if (!is_dir($dir)) {
  95. @mkdir($dir, 0777, true);
  96. }
  97. @file_put_contents($dir . '/.htaccess', 'Deny from all');
  98. }
  99. }
  100. $config = new Config(true, $cwd);
  101. // add dirs to the config
  102. $config->merge(array('config' => array('home' => $home, 'cache-dir' => $cacheDir)));
  103. // load global config
  104. $file = new JsonFile($config->get('home').'/config.json');
  105. if ($file->exists()) {
  106. if ($io && $io->isDebug()) {
  107. $io->writeError('Loading config file ' . $file->getPath());
  108. }
  109. $config->merge($file->read());
  110. }
  111. $config->setConfigSource(new JsonConfigSource($file));
  112. // load global auth file
  113. $file = new JsonFile($config->get('home').'/auth.json');
  114. if ($file->exists()) {
  115. if ($io && $io->isDebug()) {
  116. $io->writeError('Loading config file ' . $file->getPath());
  117. }
  118. $config->merge(array('config' => $file->read()));
  119. }
  120. $config->setAuthConfigSource(new JsonConfigSource($file, true));
  121. return $config;
  122. }
  123. public static function getComposerFile()
  124. {
  125. return trim(getenv('COMPOSER')) ?: './composer.json';
  126. }
  127. public static function createAdditionalStyles()
  128. {
  129. return array(
  130. 'highlight' => new OutputFormatterStyle('red'),
  131. 'warning' => new OutputFormatterStyle('black', 'yellow'),
  132. );
  133. }
  134. public static function createDefaultRepositories(IOInterface $io = null, Config $config = null, RepositoryManager $rm = null)
  135. {
  136. $repos = array();
  137. if (!$config) {
  138. $config = static::createConfig($io);
  139. }
  140. if (!$rm) {
  141. if (!$io) {
  142. throw new \InvalidArgumentException('This function requires either an IOInterface or a RepositoryManager');
  143. }
  144. $factory = new static;
  145. $rm = $factory->createRepositoryManager($io, $config);
  146. }
  147. foreach ($config->getRepositories() as $index => $repo) {
  148. if (is_string($repo)) {
  149. throw new \UnexpectedValueException('"repositories" should be an array of repository definitions, only a single repository was given');
  150. }
  151. if (!is_array($repo)) {
  152. throw new \UnexpectedValueException('Repository "'.$index.'" ('.json_encode($repo).') should be an array, '.gettype($repo).' given');
  153. }
  154. if (!isset($repo['type'])) {
  155. throw new \UnexpectedValueException('Repository "'.$index.'" ('.json_encode($repo).') must have a type defined');
  156. }
  157. $name = is_int($index) && isset($repo['url']) ? preg_replace('{^https?://}i', '', $repo['url']) : $index;
  158. while (isset($repos[$name])) {
  159. $name .= '2';
  160. }
  161. $repos[$name] = $rm->createRepository($repo['type'], $repo);
  162. }
  163. return $repos;
  164. }
  165. /**
  166. * Creates a Composer instance
  167. *
  168. * @param IOInterface $io IO instance
  169. * @param array|string|null $localConfig either a configuration array or a filename to read from, if null it will
  170. * read from the default filename
  171. * @param bool $disablePlugins Whether plugins should not be loaded
  172. * @param bool $fullLoad Whether to initialize everything or only main project stuff (used when loading the global composer)
  173. * @throws \InvalidArgumentException
  174. * @throws \UnexpectedValueException
  175. * @return Composer
  176. */
  177. public function createComposer(IOInterface $io, $localConfig = null, $disablePlugins = false, $cwd = null, $fullLoad = true)
  178. {
  179. $cwd = $cwd ?: getcwd();
  180. // load Composer configuration
  181. if (null === $localConfig) {
  182. $localConfig = static::getComposerFile();
  183. }
  184. if (is_string($localConfig)) {
  185. $composerFile = $localConfig;
  186. $file = new JsonFile($localConfig, new RemoteFilesystem($io));
  187. if (!$file->exists()) {
  188. if ($localConfig === './composer.json' || $localConfig === 'composer.json') {
  189. $message = 'Composer could not find a composer.json file in '.$cwd;
  190. } else {
  191. $message = 'Composer could not find the config file: '.$localConfig;
  192. }
  193. $instructions = 'To initialize a project, please create a composer.json file as described in the https://getcomposer.org/ "Getting Started" section';
  194. throw new \InvalidArgumentException($message.PHP_EOL.$instructions);
  195. }
  196. $file->validateSchema(JsonFile::LAX_SCHEMA);
  197. $jsonParser = new JsonParser;
  198. try {
  199. $jsonParser->parse(file_get_contents($localConfig), JsonParser::DETECT_KEY_CONFLICTS);
  200. } catch (\Seld\JsonLint\DuplicateKeyException $e) {
  201. $details = $e->getDetails();
  202. $io->writeError('<warning>Key '.$details['key'].' is a duplicate in '.$localConfig.' at line '.$details['line'].'</warning>');
  203. }
  204. $localConfig = $file->read();
  205. }
  206. // Load config and override with local config/auth config
  207. $config = static::createConfig($io, $cwd);
  208. $config->merge($localConfig);
  209. if (isset($composerFile)) {
  210. if ($io && $io->isDebug()) {
  211. $io->writeError('Loading config file ' . $composerFile);
  212. }
  213. $localAuthFile = new JsonFile(dirname(realpath($composerFile)) . '/auth.json');
  214. if ($localAuthFile->exists()) {
  215. if ($io && $io->isDebug()) {
  216. $io->writeError('Loading config file ' . $localAuthFile->getPath());
  217. }
  218. $config->merge(array('config' => $localAuthFile->read()));
  219. $config->setAuthConfigSource(new JsonConfigSource($localAuthFile, true));
  220. }
  221. }
  222. $vendorDir = $config->get('vendor-dir');
  223. $binDir = $config->get('bin-dir');
  224. // initialize composer
  225. $composer = new Composer();
  226. $composer->setConfig($config);
  227. if ($fullLoad) {
  228. // load auth configs into the IO instance
  229. $io->loadConfiguration($config);
  230. }
  231. // initialize event dispatcher
  232. $dispatcher = new EventDispatcher($composer, $io);
  233. $composer->setEventDispatcher($dispatcher);
  234. // initialize repository manager
  235. $rm = $this->createRepositoryManager($io, $config, $dispatcher);
  236. $composer->setRepositoryManager($rm);
  237. // load local repository
  238. $this->addLocalRepository($rm, $vendorDir);
  239. // force-set the version of the global package if not defined as
  240. // guessing it adds no value and only takes time
  241. if (!$fullLoad && !isset($localConfig['version'])) {
  242. $localConfig['version'] = '1.0.0';
  243. }
  244. // load package
  245. $parser = new VersionParser;
  246. $guesser = new VersionGuesser($config, new ProcessExecutor($io), $parser);
  247. $loader = new Package\Loader\RootPackageLoader($rm, $config, $parser, $guesser);
  248. $package = $loader->load($localConfig, 'Composer\Package\RootPackage', $cwd);
  249. $composer->setPackage($package);
  250. // initialize installation manager
  251. $im = $this->createInstallationManager();
  252. $composer->setInstallationManager($im);
  253. if ($fullLoad) {
  254. // initialize download manager
  255. $dm = $this->createDownloadManager($io, $config, $dispatcher);
  256. $composer->setDownloadManager($dm);
  257. // initialize autoload generator
  258. $generator = new AutoloadGenerator($dispatcher, $io);
  259. $composer->setAutoloadGenerator($generator);
  260. }
  261. // add installers to the manager (must happen after download manager is created since they read it out of $composer)
  262. $this->createDefaultInstallers($im, $composer, $io);
  263. if ($fullLoad) {
  264. $globalComposer = $this->createGlobalComposer($io, $config, $disablePlugins);
  265. $pm = $this->createPluginManager($io, $composer, $globalComposer, $disablePlugins);
  266. $composer->setPluginManager($pm);
  267. $pm->loadInstalledPlugins();
  268. // once we have plugins and custom installers we can
  269. // purge packages from local repos if they have been deleted on the filesystem
  270. if ($rm->getLocalRepository()) {
  271. $this->purgePackages($rm->getLocalRepository(), $im);
  272. }
  273. }
  274. // init locker if possible
  275. if ($fullLoad && isset($composerFile)) {
  276. $lockFile = "json" === pathinfo($composerFile, PATHINFO_EXTENSION)
  277. ? substr($composerFile, 0, -4).'lock'
  278. : $composerFile . '.lock';
  279. $locker = new Package\Locker($io, new JsonFile($lockFile, new RemoteFilesystem($io, $config)), $rm, $im, file_get_contents($composerFile));
  280. $composer->setLocker($locker);
  281. }
  282. return $composer;
  283. }
  284. /**
  285. * @param IOInterface $io
  286. * @param Config $config
  287. * @param EventDispatcher $eventDispatcher
  288. * @return Repository\RepositoryManager
  289. */
  290. protected function createRepositoryManager(IOInterface $io, Config $config, EventDispatcher $eventDispatcher = null)
  291. {
  292. $rm = new RepositoryManager($io, $config, $eventDispatcher);
  293. $rm->setRepositoryClass('composer', 'Composer\Repository\ComposerRepository');
  294. $rm->setRepositoryClass('vcs', 'Composer\Repository\VcsRepository');
  295. $rm->setRepositoryClass('package', 'Composer\Repository\PackageRepository');
  296. $rm->setRepositoryClass('pear', 'Composer\Repository\PearRepository');
  297. $rm->setRepositoryClass('git', 'Composer\Repository\VcsRepository');
  298. $rm->setRepositoryClass('gitlab', 'Composer\Repository\VcsRepository');
  299. $rm->setRepositoryClass('svn', 'Composer\Repository\VcsRepository');
  300. $rm->setRepositoryClass('perforce', 'Composer\Repository\VcsRepository');
  301. $rm->setRepositoryClass('hg', 'Composer\Repository\VcsRepository');
  302. $rm->setRepositoryClass('artifact', 'Composer\Repository\ArtifactRepository');
  303. $rm->setRepositoryClass('path', 'Composer\Repository\PathRepository');
  304. return $rm;
  305. }
  306. /**
  307. * @param Repository\RepositoryManager $rm
  308. * @param string $vendorDir
  309. */
  310. protected function addLocalRepository(RepositoryManager $rm, $vendorDir)
  311. {
  312. $rm->setLocalRepository(new Repository\InstalledFilesystemRepository(new JsonFile($vendorDir.'/composer/installed.json')));
  313. }
  314. /**
  315. * @param Config $config
  316. * @return Composer|null
  317. */
  318. protected function createGlobalComposer(IOInterface $io, Config $config, $disablePlugins)
  319. {
  320. if (realpath($config->get('home')) === getcwd()) {
  321. return;
  322. }
  323. $composer = null;
  324. try {
  325. $composer = self::createComposer($io, $config->get('home') . '/composer.json', $disablePlugins, $config->get('home'), false);
  326. } catch (\Exception $e) {
  327. if ($io->isDebug()) {
  328. $io->writeError('Failed to initialize global composer: '.$e->getMessage());
  329. }
  330. }
  331. return $composer;
  332. }
  333. /**
  334. * @param IO\IOInterface $io
  335. * @param Config $config
  336. * @param EventDispatcher $eventDispatcher
  337. * @return Downloader\DownloadManager
  338. */
  339. public function createDownloadManager(IOInterface $io, Config $config, EventDispatcher $eventDispatcher = null)
  340. {
  341. $cache = null;
  342. if ($config->get('cache-files-ttl') > 0) {
  343. $cache = new Cache($io, $config->get('cache-files-dir'), 'a-z0-9_./');
  344. }
  345. $dm = new Downloader\DownloadManager($io);
  346. switch ($config->get('preferred-install')) {
  347. case 'dist':
  348. $dm->setPreferDist(true);
  349. break;
  350. case 'source':
  351. $dm->setPreferSource(true);
  352. break;
  353. case 'auto':
  354. default:
  355. // noop
  356. break;
  357. }
  358. $dm->setDownloader('git', new Downloader\GitDownloader($io, $config));
  359. $dm->setDownloader('svn', new Downloader\SvnDownloader($io, $config));
  360. $dm->setDownloader('hg', new Downloader\HgDownloader($io, $config));
  361. $dm->setDownloader('perforce', new Downloader\PerforceDownloader($io, $config));
  362. $dm->setDownloader('zip', new Downloader\ZipDownloader($io, $config, $eventDispatcher, $cache));
  363. $dm->setDownloader('rar', new Downloader\RarDownloader($io, $config, $eventDispatcher, $cache));
  364. $dm->setDownloader('tar', new Downloader\TarDownloader($io, $config, $eventDispatcher, $cache));
  365. $dm->setDownloader('gzip', new Downloader\GzipDownloader($io, $config, $eventDispatcher, $cache));
  366. $dm->setDownloader('xz', new Downloader\XzDownloader($io, $config, $eventDispatcher, $cache));
  367. $dm->setDownloader('phar', new Downloader\PharDownloader($io, $config, $eventDispatcher, $cache));
  368. $dm->setDownloader('file', new Downloader\FileDownloader($io, $config, $eventDispatcher, $cache));
  369. $dm->setDownloader('path', new Downloader\PathDownloader($io, $config, $eventDispatcher, $cache));
  370. return $dm;
  371. }
  372. /**
  373. * @param Config $config The configuration
  374. * @param Downloader\DownloadManager $dm Manager use to download sources
  375. * @return Archiver\ArchiveManager
  376. */
  377. public function createArchiveManager(Config $config, Downloader\DownloadManager $dm = null)
  378. {
  379. if (null === $dm) {
  380. $io = new IO\NullIO();
  381. $io->loadConfiguration($config);
  382. $dm = $this->createDownloadManager($io, $config);
  383. }
  384. $am = new Archiver\ArchiveManager($dm);
  385. $am->addArchiver(new Archiver\PharArchiver);
  386. return $am;
  387. }
  388. /**
  389. * @param IOInterface $io
  390. * @param Composer $composer
  391. * @param Composer $globalComposer
  392. * @param bool $disablePlugins
  393. * @return Plugin\PluginManager
  394. */
  395. protected function createPluginManager(IOInterface $io, Composer $composer, Composer $globalComposer = null, $disablePlugins = false)
  396. {
  397. return new Plugin\PluginManager($io, $composer, $globalComposer, $disablePlugins);
  398. }
  399. /**
  400. * @return Installer\InstallationManager
  401. */
  402. protected function createInstallationManager()
  403. {
  404. return new Installer\InstallationManager();
  405. }
  406. /**
  407. * @param Installer\InstallationManager $im
  408. * @param Composer $composer
  409. * @param IO\IOInterface $io
  410. */
  411. protected function createDefaultInstallers(Installer\InstallationManager $im, Composer $composer, IOInterface $io)
  412. {
  413. $im->addInstaller(new Installer\LibraryInstaller($io, $composer, null));
  414. $im->addInstaller(new Installer\PearInstaller($io, $composer, 'pear-library'));
  415. $im->addInstaller(new Installer\PluginInstaller($io, $composer));
  416. $im->addInstaller(new Installer\MetapackageInstaller($io));
  417. }
  418. /**
  419. * @param WritableRepositoryInterface $repo repository to purge packages from
  420. * @param Installer\InstallationManager $im manager to check whether packages are still installed
  421. */
  422. protected function purgePackages(WritableRepositoryInterface $repo, Installer\InstallationManager $im)
  423. {
  424. foreach ($repo->getPackages() as $package) {
  425. if (!$im->isPackageInstalled($repo, $package)) {
  426. $repo->removePackage($package);
  427. }
  428. }
  429. }
  430. /**
  431. * @param IOInterface $io IO instance
  432. * @param mixed $config either a configuration array or a filename to read from, if null it will read from
  433. * the default filename
  434. * @param bool $disablePlugins Whether plugins should not be loaded
  435. * @return Composer
  436. */
  437. public static function create(IOInterface $io, $config = null, $disablePlugins = false)
  438. {
  439. $factory = new static();
  440. return $factory->createComposer($io, $config, $disablePlugins);
  441. }
  442. }