Factory.php 14 KB

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