Factory.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  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\Repository\RepositoryManager;
  17. use Composer\Repository\RepositoryInterface;
  18. use Composer\Util\ProcessExecutor;
  19. use Composer\Util\RemoteFilesystem;
  20. use Symfony\Component\Console\Formatter\OutputFormatterStyle;
  21. use Composer\EventDispatcher\EventDispatcher;
  22. use Composer\Autoload\AutoloadGenerator;
  23. use Composer\Package\Version\VersionParser;
  24. /**
  25. * Creates a configured instance of composer.
  26. *
  27. * @author Ryan Weaver <ryan@knplabs.com>
  28. * @author Jordi Boggiano <j.boggiano@seld.be>
  29. * @author Igor Wiedler <igor@wiedler.ch>
  30. * @author Nils Adermann <naderman@naderman.de>
  31. */
  32. class Factory
  33. {
  34. /**
  35. * @throws \RuntimeException
  36. * @return Config
  37. */
  38. public static function createConfig()
  39. {
  40. // determine home and cache dirs
  41. $home = getenv('COMPOSER_HOME');
  42. $cacheDir = getenv('COMPOSER_CACHE_DIR');
  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. if (!$cacheDir) {
  57. if (defined('PHP_WINDOWS_VERSION_MAJOR')) {
  58. if ($cacheDir = getenv('LOCALAPPDATA')) {
  59. $cacheDir .= '/Composer';
  60. } else {
  61. $cacheDir = $home . '/cache';
  62. }
  63. $cacheDir = strtr($cacheDir, '\\', '/');
  64. } else {
  65. $cacheDir = $home.'/cache';
  66. }
  67. }
  68. // Protect directory against web access. Since HOME could be
  69. // the www-data's user home and be web-accessible it is a
  70. // potential security risk
  71. foreach (array($home, $cacheDir) as $dir) {
  72. if (!file_exists($dir . '/.htaccess')) {
  73. if (!is_dir($dir)) {
  74. @mkdir($dir, 0777, true);
  75. }
  76. @file_put_contents($dir . '/.htaccess', 'Deny from all');
  77. }
  78. }
  79. $config = new Config();
  80. // add dirs to the config
  81. $config->merge(array('config' => array('home' => $home, 'cache-dir' => $cacheDir)));
  82. $file = new JsonFile($home.'/config.json');
  83. if ($file->exists()) {
  84. $config->merge($file->read());
  85. }
  86. $config->setConfigSource(new JsonConfigSource($file));
  87. // move old cache dirs to the new locations
  88. $legacyPaths = array(
  89. 'cache-repo-dir' => array('/cache' => '/http*', '/cache.svn' => '/*', '/cache.github' => '/*'),
  90. 'cache-vcs-dir' => array('/cache.git' => '/*', '/cache.hg' => '/*'),
  91. 'cache-files-dir' => array('/cache.files' => '/*'),
  92. );
  93. foreach ($legacyPaths as $key => $oldPaths) {
  94. foreach ($oldPaths as $oldPath => $match) {
  95. $dir = $config->get($key);
  96. if ('/cache.github' === $oldPath) {
  97. $dir .= '/github.com';
  98. }
  99. $oldPath = $config->get('home').$oldPath;
  100. $oldPathMatch = $oldPath . $match;
  101. if (is_dir($oldPath) && $dir !== $oldPath) {
  102. if (!is_dir($dir)) {
  103. if (!@mkdir($dir, 0777, true)) {
  104. continue;
  105. }
  106. }
  107. if (is_array($children = glob($oldPathMatch))) {
  108. foreach ($children as $child) {
  109. @rename($child, $dir.'/'.basename($child));
  110. }
  111. }
  112. if ($config->get('cache-dir') != $oldPath) {
  113. @rmdir($oldPath);
  114. }
  115. }
  116. }
  117. }
  118. return $config;
  119. }
  120. public static function getComposerFile()
  121. {
  122. return trim(getenv('COMPOSER')) ?: './composer.json';
  123. }
  124. public static function createAdditionalStyles()
  125. {
  126. return array(
  127. 'highlight' => new OutputFormatterStyle('red'),
  128. 'warning' => new OutputFormatterStyle('black', 'yellow'),
  129. );
  130. }
  131. public static function createDefaultRepositories(IOInterface $io = null, Config $config = null, RepositoryManager $rm = null)
  132. {
  133. $repos = array();
  134. if (!$config) {
  135. $config = static::createConfig();
  136. }
  137. if (!$rm) {
  138. if (!$io) {
  139. throw new \InvalidArgumentException('This function requires either an IOInterface or a RepositoryManager');
  140. }
  141. $factory = new static;
  142. $rm = $factory->createRepositoryManager($io, $config);
  143. }
  144. foreach ($config->getRepositories() as $index => $repo) {
  145. if (!is_array($repo)) {
  146. throw new \UnexpectedValueException('Repository '.$index.' ('.json_encode($repo).') should be an array, '.gettype($repo).' given');
  147. }
  148. if (!isset($repo['type'])) {
  149. throw new \UnexpectedValueException('Repository '.$index.' ('.json_encode($repo).') must have a type defined');
  150. }
  151. $name = is_int($index) && isset($repo['url']) ? preg_replace('{^https?://}i', '', $repo['url']) : $index;
  152. while (isset($repos[$name])) {
  153. $name .= '2';
  154. }
  155. $repos[$name] = $rm->createRepository($repo['type'], $repo);
  156. }
  157. return $repos;
  158. }
  159. /**
  160. * Creates a Composer instance
  161. *
  162. * @param IOInterface $io IO instance
  163. * @param array|string|null $localConfig either a configuration array or a filename to read from, if null it will
  164. * read from the default filename
  165. * @param bool $disablePlugins Whether plugins should not be loaded
  166. * @throws \InvalidArgumentException
  167. * @throws \UnexpectedValueException
  168. * @return Composer
  169. */
  170. public function createComposer(IOInterface $io, $localConfig = null, $disablePlugins = false)
  171. {
  172. // load Composer configuration
  173. if (null === $localConfig) {
  174. $localConfig = static::getComposerFile();
  175. }
  176. if (is_string($localConfig)) {
  177. $composerFile = $localConfig;
  178. $file = new JsonFile($localConfig, new RemoteFilesystem($io));
  179. if (!$file->exists()) {
  180. if ($localConfig === './composer.json' || $localConfig === 'composer.json') {
  181. $message = 'Composer could not find a composer.json file in '.getcwd();
  182. } else {
  183. $message = 'Composer could not find the config file: '.$localConfig;
  184. }
  185. $instructions = 'To initialize a project, please create a composer.json file as described in the http://getcomposer.org/ "Getting Started" section';
  186. throw new \InvalidArgumentException($message.PHP_EOL.$instructions);
  187. }
  188. $file->validateSchema(JsonFile::LAX_SCHEMA);
  189. $localConfig = $file->read();
  190. }
  191. // Configuration defaults
  192. $config = static::createConfig();
  193. $config->merge($localConfig);
  194. $io->loadConfiguration($config);
  195. $vendorDir = $config->get('vendor-dir');
  196. $binDir = $config->get('bin-dir');
  197. // setup process timeout
  198. ProcessExecutor::setTimeout((int) $config->get('process-timeout'));
  199. // initialize composer
  200. $composer = new Composer();
  201. $composer->setConfig($config);
  202. // initialize event dispatcher
  203. $dispatcher = new EventDispatcher($composer, $io);
  204. // initialize repository manager
  205. $rm = $this->createRepositoryManager($io, $config, $dispatcher);
  206. // load local repository
  207. $this->addLocalRepository($rm, $vendorDir);
  208. // load package
  209. $parser = new VersionParser;
  210. $loader = new Package\Loader\RootPackageLoader($rm, $config, $parser, new ProcessExecutor($io));
  211. $package = $loader->load($localConfig);
  212. // initialize installation manager
  213. $im = $this->createInstallationManager();
  214. // Composer composition
  215. $composer->setPackage($package);
  216. $composer->setRepositoryManager($rm);
  217. $composer->setInstallationManager($im);
  218. // initialize download manager
  219. $dm = $this->createDownloadManager($io, $config, $dispatcher);
  220. $composer->setDownloadManager($dm);
  221. $composer->setEventDispatcher($dispatcher);
  222. // initialize autoload generator
  223. $generator = new AutoloadGenerator($dispatcher);
  224. $composer->setAutoloadGenerator($generator);
  225. // add installers to the manager
  226. $this->createDefaultInstallers($im, $composer, $io);
  227. $globalRepository = $this->createGlobalRepository($config, $vendorDir);
  228. $pm = $this->createPluginManager($composer, $io, $globalRepository);
  229. $composer->setPluginManager($pm);
  230. if (!$disablePlugins) {
  231. $pm->loadInstalledPlugins();
  232. }
  233. // purge packages if they have been deleted on the filesystem
  234. $this->purgePackages($rm, $im);
  235. // init locker if possible
  236. if (isset($composerFile)) {
  237. $lockFile = "json" === pathinfo($composerFile, PATHINFO_EXTENSION)
  238. ? substr($composerFile, 0, -4).'lock'
  239. : $composerFile . '.lock';
  240. $locker = new Package\Locker($io, new JsonFile($lockFile, new RemoteFilesystem($io)), $rm, $im, md5_file($composerFile));
  241. $composer->setLocker($locker);
  242. }
  243. return $composer;
  244. }
  245. /**
  246. * @param IOInterface $io
  247. * @param Config $config
  248. * @return Repository\RepositoryManager
  249. */
  250. protected function createRepositoryManager(IOInterface $io, Config $config, EventDispatcher $eventDispatcher = null)
  251. {
  252. $rm = new RepositoryManager($io, $config, $eventDispatcher);
  253. $rm->setRepositoryClass('composer', 'Composer\Repository\ComposerRepository');
  254. $rm->setRepositoryClass('vcs', 'Composer\Repository\VcsRepository');
  255. $rm->setRepositoryClass('package', 'Composer\Repository\PackageRepository');
  256. $rm->setRepositoryClass('pear', 'Composer\Repository\PearRepository');
  257. $rm->setRepositoryClass('git', 'Composer\Repository\VcsRepository');
  258. $rm->setRepositoryClass('svn', 'Composer\Repository\VcsRepository');
  259. $rm->setRepositoryClass('perforce', 'Composer\Repository\VcsRepository');
  260. $rm->setRepositoryClass('hg', 'Composer\Repository\VcsRepository');
  261. $rm->setRepositoryClass('artifact', 'Composer\Repository\ArtifactRepository');
  262. return $rm;
  263. }
  264. /**
  265. * @param Repository\RepositoryManager $rm
  266. * @param string $vendorDir
  267. */
  268. protected function addLocalRepository(RepositoryManager $rm, $vendorDir)
  269. {
  270. $rm->setLocalRepository(new Repository\InstalledFilesystemRepository(new JsonFile($vendorDir.'/composer/installed.json')));
  271. }
  272. /**
  273. * @param Config $config
  274. * @param string $vendorDir
  275. */
  276. protected function createGlobalRepository(Config $config, $vendorDir)
  277. {
  278. if ($config->get('home') == $vendorDir) {
  279. return null;
  280. }
  281. $path = $config->get('home').'/vendor/composer/installed.json';
  282. if (!file_exists($path)) {
  283. return null;
  284. }
  285. return new Repository\InstalledFilesystemRepository(new JsonFile($path));
  286. }
  287. /**
  288. * @param IO\IOInterface $io
  289. * @param Config $config
  290. * @param EventDispatcher $eventDispatcher
  291. * @return Downloader\DownloadManager
  292. */
  293. public function createDownloadManager(IOInterface $io, Config $config, EventDispatcher $eventDispatcher = null)
  294. {
  295. $cache = null;
  296. if ($config->get('cache-files-ttl') > 0) {
  297. $cache = new Cache($io, $config->get('cache-files-dir'), 'a-z0-9_./');
  298. }
  299. $dm = new Downloader\DownloadManager();
  300. switch ($config->get('preferred-install')) {
  301. case 'dist':
  302. $dm->setPreferDist(true);
  303. break;
  304. case 'source':
  305. $dm->setPreferSource(true);
  306. break;
  307. case 'auto':
  308. default:
  309. // noop
  310. break;
  311. }
  312. $dm->setDownloader('git', new Downloader\GitDownloader($io, $config));
  313. $dm->setDownloader('svn', new Downloader\SvnDownloader($io, $config));
  314. $dm->setDownloader('hg', new Downloader\HgDownloader($io, $config));
  315. $dm->setDownloader('perforce', new Downloader\PerforceDownloader($io, $config));
  316. $dm->setDownloader('zip', new Downloader\ZipDownloader($io, $config, $eventDispatcher, $cache));
  317. $dm->setDownloader('rar', new Downloader\RarDownloader($io, $config, $eventDispatcher, $cache));
  318. $dm->setDownloader('tar', new Downloader\TarDownloader($io, $config, $eventDispatcher, $cache));
  319. $dm->setDownloader('phar', new Downloader\PharDownloader($io, $config, $eventDispatcher, $cache));
  320. $dm->setDownloader('file', new Downloader\FileDownloader($io, $config, $eventDispatcher, $cache));
  321. return $dm;
  322. }
  323. /**
  324. * @param Config $config The configuration
  325. * @param Downloader\DownloadManager $dm Manager use to download sources
  326. *
  327. * @return Archiver\ArchiveManager
  328. */
  329. public function createArchiveManager(Config $config, Downloader\DownloadManager $dm = null)
  330. {
  331. if (null === $dm) {
  332. $io = new IO\NullIO();
  333. $io->loadConfiguration($config);
  334. $dm = $this->createDownloadManager($io, $config);
  335. }
  336. $am = new Archiver\ArchiveManager($dm);
  337. $am->addArchiver(new Archiver\PharArchiver);
  338. return $am;
  339. }
  340. /**
  341. * @return Plugin\PluginManager
  342. */
  343. protected function createPluginManager(Composer $composer, IOInterface $io, RepositoryInterface $globalRepository = null)
  344. {
  345. return new Plugin\PluginManager($composer, $io, $globalRepository);
  346. }
  347. /**
  348. * @return Installer\InstallationManager
  349. */
  350. protected function createInstallationManager()
  351. {
  352. return new Installer\InstallationManager();
  353. }
  354. /**
  355. * @param Installer\InstallationManager $im
  356. * @param Composer $composer
  357. * @param IO\IOInterface $io
  358. */
  359. protected function createDefaultInstallers(Installer\InstallationManager $im, Composer $composer, IOInterface $io)
  360. {
  361. $im->addInstaller(new Installer\LibraryInstaller($io, $composer, null));
  362. $im->addInstaller(new Installer\PearInstaller($io, $composer, 'pear-library'));
  363. $im->addInstaller(new Installer\PluginInstaller($io, $composer));
  364. $im->addInstaller(new Installer\MetapackageInstaller($io));
  365. }
  366. /**
  367. * @param Repository\RepositoryManager $rm
  368. * @param Installer\InstallationManager $im
  369. */
  370. protected function purgePackages(Repository\RepositoryManager $rm, Installer\InstallationManager $im)
  371. {
  372. $repo = $rm->getLocalRepository();
  373. foreach ($repo->getPackages() as $package) {
  374. if (!$im->isPackageInstalled($repo, $package)) {
  375. $repo->removePackage($package);
  376. }
  377. }
  378. }
  379. /**
  380. * @param IOInterface $io IO instance
  381. * @param mixed $config either a configuration array or a filename to read from, if null it will read from
  382. * the default filename
  383. * @param bool $disablePlugins Whether plugins should not be loaded
  384. * @return Composer
  385. */
  386. public static function create(IOInterface $io, $config = null, $disablePlugins = false)
  387. {
  388. $factory = new static();
  389. return $factory->createComposer($io, $config, $disablePlugins);
  390. }
  391. }