Factory.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  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. @rmdir($oldPath);
  113. }
  114. }
  115. }
  116. return $config;
  117. }
  118. public static function getComposerFile()
  119. {
  120. return trim(getenv('COMPOSER')) ?: './composer.json';
  121. }
  122. public static function createAdditionalStyles()
  123. {
  124. return array(
  125. 'highlight' => new OutputFormatterStyle('red'),
  126. 'warning' => new OutputFormatterStyle('black', 'yellow'),
  127. );
  128. }
  129. public static function createDefaultRepositories(IOInterface $io = null, Config $config = null, RepositoryManager $rm = null)
  130. {
  131. $repos = array();
  132. if (!$config) {
  133. $config = static::createConfig();
  134. }
  135. if (!$rm) {
  136. if (!$io) {
  137. throw new \InvalidArgumentException('This function requires either an IOInterface or a RepositoryManager');
  138. }
  139. $factory = new static;
  140. $rm = $factory->createRepositoryManager($io, $config);
  141. }
  142. foreach ($config->getRepositories() as $index => $repo) {
  143. if (!is_array($repo)) {
  144. throw new \UnexpectedValueException('Repository '.$index.' ('.json_encode($repo).') should be an array, '.gettype($repo).' given');
  145. }
  146. if (!isset($repo['type'])) {
  147. throw new \UnexpectedValueException('Repository '.$index.' ('.json_encode($repo).') must have a type defined');
  148. }
  149. $name = is_int($index) && isset($repo['url']) ? preg_replace('{^https?://}i', '', $repo['url']) : $index;
  150. while (isset($repos[$name])) {
  151. $name .= '2';
  152. }
  153. $repos[$name] = $rm->createRepository($repo['type'], $repo);
  154. }
  155. return $repos;
  156. }
  157. /**
  158. * Creates a Composer instance
  159. *
  160. * @param IOInterface $io IO instance
  161. * @param array|string|null $localConfig either a configuration array or a filename to read from, if null it will
  162. * read from the default filename
  163. * @param bool $disablePlugins Whether plugins should not be loaded
  164. * @throws \InvalidArgumentException
  165. * @throws \UnexpectedValueException
  166. * @return Composer
  167. */
  168. public function createComposer(IOInterface $io, $localConfig = null, $disablePlugins = false)
  169. {
  170. // load Composer configuration
  171. if (null === $localConfig) {
  172. $localConfig = static::getComposerFile();
  173. }
  174. if (is_string($localConfig)) {
  175. $composerFile = $localConfig;
  176. $file = new JsonFile($localConfig, new RemoteFilesystem($io));
  177. if (!$file->exists()) {
  178. if ($localConfig === './composer.json' || $localConfig === 'composer.json') {
  179. $message = 'Composer could not find a composer.json file in '.getcwd();
  180. } else {
  181. $message = 'Composer could not find the config file: '.$localConfig;
  182. }
  183. $instructions = 'To initialize a project, please create a composer.json file as described in the http://getcomposer.org/ "Getting Started" section';
  184. throw new \InvalidArgumentException($message.PHP_EOL.$instructions);
  185. }
  186. $file->validateSchema(JsonFile::LAX_SCHEMA);
  187. $localConfig = $file->read();
  188. }
  189. // Configuration defaults
  190. $config = static::createConfig();
  191. $config->merge($localConfig);
  192. $io->loadConfiguration($config);
  193. $vendorDir = $config->get('vendor-dir');
  194. $binDir = $config->get('bin-dir');
  195. // setup process timeout
  196. ProcessExecutor::setTimeout((int) $config->get('process-timeout'));
  197. // initialize repository manager
  198. $rm = $this->createRepositoryManager($io, $config);
  199. // load local repository
  200. $this->addLocalRepository($rm, $vendorDir);
  201. // load package
  202. $parser = new VersionParser;
  203. $loader = new Package\Loader\RootPackageLoader($rm, $config, $parser, new ProcessExecutor($io));
  204. $package = $loader->load($localConfig);
  205. // initialize installation manager
  206. $im = $this->createInstallationManager();
  207. // initialize composer
  208. $composer = new Composer();
  209. $composer->setConfig($config);
  210. $composer->setPackage($package);
  211. $composer->setRepositoryManager($rm);
  212. $composer->setInstallationManager($im);
  213. // initialize event dispatcher
  214. $dispatcher = new EventDispatcher($composer, $io);
  215. // initialize download manager
  216. $dm = $this->createDownloadManager($io, $config, $dispatcher);
  217. $composer->setDownloadManager($dm);
  218. $composer->setEventDispatcher($dispatcher);
  219. // initialize autoload generator
  220. $generator = new AutoloadGenerator($dispatcher);
  221. $composer->setAutoloadGenerator($generator);
  222. // add installers to the manager
  223. $this->createDefaultInstallers($im, $composer, $io);
  224. $globalRepository = $this->createGlobalRepository($config, $vendorDir);
  225. $pm = $this->createPluginManager($composer, $io, $globalRepository);
  226. $composer->setPluginManager($pm);
  227. if (!$disablePlugins) {
  228. $pm->loadInstalledPlugins();
  229. }
  230. // purge packages if they have been deleted on the filesystem
  231. $this->purgePackages($rm, $im);
  232. // init locker if possible
  233. if (isset($composerFile)) {
  234. $lockFile = "json" === pathinfo($composerFile, PATHINFO_EXTENSION)
  235. ? substr($composerFile, 0, -4).'lock'
  236. : $composerFile . '.lock';
  237. $locker = new Package\Locker($io, new JsonFile($lockFile, new RemoteFilesystem($io)), $rm, $im, md5_file($composerFile));
  238. $composer->setLocker($locker);
  239. }
  240. return $composer;
  241. }
  242. /**
  243. * @param IOInterface $io
  244. * @param Config $config
  245. * @return Repository\RepositoryManager
  246. */
  247. protected function createRepositoryManager(IOInterface $io, Config $config)
  248. {
  249. $rm = new RepositoryManager($io, $config);
  250. $rm->setRepositoryClass('composer', 'Composer\Repository\ComposerRepository');
  251. $rm->setRepositoryClass('vcs', 'Composer\Repository\VcsRepository');
  252. $rm->setRepositoryClass('package', 'Composer\Repository\PackageRepository');
  253. $rm->setRepositoryClass('pear', 'Composer\Repository\PearRepository');
  254. $rm->setRepositoryClass('git', 'Composer\Repository\VcsRepository');
  255. $rm->setRepositoryClass('svn', 'Composer\Repository\VcsRepository');
  256. $rm->setRepositoryClass('hg', 'Composer\Repository\VcsRepository');
  257. $rm->setRepositoryClass('artifact', 'Composer\Repository\ArtifactRepository');
  258. return $rm;
  259. }
  260. /**
  261. * @param Repository\RepositoryManager $rm
  262. * @param string $vendorDir
  263. */
  264. protected function addLocalRepository(RepositoryManager $rm, $vendorDir)
  265. {
  266. $rm->setLocalRepository(new Repository\InstalledFilesystemRepository(new JsonFile($vendorDir.'/composer/installed.json')));
  267. }
  268. /**
  269. * @param Config $config
  270. * @param string $vendorDir
  271. */
  272. protected function createGlobalRepository(Config $config, $vendorDir)
  273. {
  274. if ($config->get('home') == $vendorDir) {
  275. return null;
  276. }
  277. $path = $config->get('home').'/vendor/composer/installed.json';
  278. if (!file_exists($path)) {
  279. return null;
  280. }
  281. return new Repository\InstalledFilesystemRepository(new JsonFile($path));
  282. }
  283. /**
  284. * @param IO\IOInterface $io
  285. * @param Config $config
  286. * @param EventDispatcher $eventDispatcher
  287. * @return Downloader\DownloadManager
  288. */
  289. public function createDownloadManager(IOInterface $io, Config $config, EventDispatcher $eventDispatcher = null)
  290. {
  291. $cache = null;
  292. if ($config->get('cache-files-ttl') > 0) {
  293. $cache = new Cache($io, $config->get('cache-files-dir'), 'a-z0-9_./');
  294. }
  295. $dm = new Downloader\DownloadManager();
  296. switch ($config->get('preferred-install')) {
  297. case 'dist':
  298. $dm->setPreferDist(true);
  299. break;
  300. case 'source':
  301. $dm->setPreferSource(true);
  302. break;
  303. case 'auto':
  304. default:
  305. // noop
  306. break;
  307. }
  308. $dm->setDownloader('git', new Downloader\GitDownloader($io, $config));
  309. $dm->setDownloader('svn', new Downloader\SvnDownloader($io, $config));
  310. $dm->setDownloader('hg', new Downloader\HgDownloader($io, $config));
  311. $dm->setDownloader('perforce', new Downloader\PerforceDownloader($io, $config));
  312. $dm->setDownloader('zip', new Downloader\ZipDownloader($io, $config, $eventDispatcher, $cache));
  313. $dm->setDownloader('rar', new Downloader\RarDownloader($io, $config, $eventDispatcher, $cache));
  314. $dm->setDownloader('tar', new Downloader\TarDownloader($io, $config, $eventDispatcher, $cache));
  315. $dm->setDownloader('phar', new Downloader\PharDownloader($io, $config, $eventDispatcher, $cache));
  316. $dm->setDownloader('file', new Downloader\FileDownloader($io, $config, $eventDispatcher, $cache));
  317. return $dm;
  318. }
  319. /**
  320. * @param Config $config The configuration
  321. * @param Downloader\DownloadManager $dm Manager use to download sources
  322. *
  323. * @return Archiver\ArchiveManager
  324. */
  325. public function createArchiveManager(Config $config, Downloader\DownloadManager $dm = null)
  326. {
  327. if (null === $dm) {
  328. $io = new IO\NullIO();
  329. $io->loadConfiguration($config);
  330. $dm = $this->createDownloadManager($io, $config);
  331. }
  332. $am = new Archiver\ArchiveManager($dm);
  333. $am->addArchiver(new Archiver\PharArchiver);
  334. return $am;
  335. }
  336. /**
  337. * @return Plugin\PluginManager
  338. */
  339. protected function createPluginManager(Composer $composer, IOInterface $io, RepositoryInterface $globalRepository = null)
  340. {
  341. return new Plugin\PluginManager($composer, $io, $globalRepository);
  342. }
  343. /**
  344. * @return Installer\InstallationManager
  345. */
  346. protected function createInstallationManager()
  347. {
  348. return new Installer\InstallationManager();
  349. }
  350. /**
  351. * @param Installer\InstallationManager $im
  352. * @param Composer $composer
  353. * @param IO\IOInterface $io
  354. */
  355. protected function createDefaultInstallers(Installer\InstallationManager $im, Composer $composer, IOInterface $io)
  356. {
  357. $im->addInstaller(new Installer\LibraryInstaller($io, $composer, null));
  358. $im->addInstaller(new Installer\PearInstaller($io, $composer, 'pear-library'));
  359. $im->addInstaller(new Installer\PluginInstaller($io, $composer));
  360. $im->addInstaller(new Installer\MetapackageInstaller($io));
  361. }
  362. /**
  363. * @param Repository\RepositoryManager $rm
  364. * @param Installer\InstallationManager $im
  365. */
  366. protected function purgePackages(Repository\RepositoryManager $rm, Installer\InstallationManager $im)
  367. {
  368. $repo = $rm->getLocalRepository();
  369. foreach ($repo->getPackages() as $package) {
  370. if (!$im->isPackageInstalled($repo, $package)) {
  371. $repo->removePackage($package);
  372. }
  373. }
  374. }
  375. /**
  376. * @param IOInterface $io IO instance
  377. * @param mixed $config either a configuration array or a filename to read from, if null it will read from
  378. * the default filename
  379. * @param bool $disablePlugins Whether plugins should not be loaded
  380. * @return Composer
  381. */
  382. public static function create(IOInterface $io, $config = null, $disablePlugins = false)
  383. {
  384. $factory = new static();
  385. return $factory->createComposer($io, $config, $disablePlugins);
  386. }
  387. }