Factory.php 13 KB

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