Factory.php 14 KB

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