Locker.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  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\Package;
  12. use Composer\Json\JsonFile;
  13. use Composer\Installer\InstallationManager;
  14. use Composer\Repository\RepositoryManager;
  15. use Composer\Util\ProcessExecutor;
  16. use Composer\Repository\ArrayRepository;
  17. use Composer\Package\Dumper\ArrayDumper;
  18. use Composer\Package\Loader\ArrayLoader;
  19. use Composer\Plugin\PluginInterface;
  20. use Composer\Util\Git as GitUtil;
  21. use Composer\IO\IOInterface;
  22. use Seld\JsonLint\ParsingException;
  23. /**
  24. * Reads/writes project lockfile (composer.lock).
  25. *
  26. * @author Konstantin Kudryashiv <ever.zet@gmail.com>
  27. * @author Jordi Boggiano <j.boggiano@seld.be>
  28. */
  29. class Locker
  30. {
  31. private $lockFile;
  32. private $repositoryManager;
  33. private $installationManager;
  34. private $hash;
  35. private $contentHash;
  36. private $loader;
  37. private $dumper;
  38. private $process;
  39. private $lockDataCache;
  40. /**
  41. * Initializes packages locker.
  42. *
  43. * @param IOInterface $io
  44. * @param JsonFile $lockFile lockfile loader
  45. * @param RepositoryManager $repositoryManager repository manager instance
  46. * @param InstallationManager $installationManager installation manager instance
  47. * @param string $composerFileContents The contents of the composer file
  48. */
  49. public function __construct(IOInterface $io, JsonFile $lockFile, RepositoryManager $repositoryManager, InstallationManager $installationManager, $composerFileContents)
  50. {
  51. $this->lockFile = $lockFile;
  52. $this->repositoryManager = $repositoryManager;
  53. $this->installationManager = $installationManager;
  54. $this->hash = md5($composerFileContents);
  55. $this->contentHash = self::getContentHash($composerFileContents);
  56. $this->loader = new ArrayLoader(null, true);
  57. $this->dumper = new ArrayDumper();
  58. $this->process = new ProcessExecutor($io);
  59. }
  60. /**
  61. * Returns the md5 hash of the sorted content of the composer file.
  62. *
  63. * @param string $composerFileContents The contents of the composer file.
  64. *
  65. * @return string
  66. */
  67. public static function getContentHash($composerFileContents)
  68. {
  69. $content = json_decode($composerFileContents, true);
  70. $relevantKeys = array(
  71. 'name',
  72. 'version',
  73. 'require',
  74. 'require-dev',
  75. 'conflict',
  76. 'replace',
  77. 'provide',
  78. 'minimum-stability',
  79. 'prefer-stable',
  80. 'repositories',
  81. 'extra',
  82. );
  83. $relevantContent = array();
  84. foreach (array_intersect($relevantKeys, array_keys($content)) as $key) {
  85. $relevantContent[$key] = $content[$key];
  86. }
  87. if (isset($content['config']['platform'])) {
  88. $relevantContent['config']['platform'] = $content['config']['platform'];
  89. }
  90. ksort($relevantContent);
  91. return md5(json_encode($relevantContent));
  92. }
  93. /**
  94. * Checks whether locker has been locked (lockfile found).
  95. *
  96. * @return bool
  97. */
  98. public function isLocked()
  99. {
  100. if (!$this->lockFile->exists()) {
  101. return false;
  102. }
  103. $data = $this->getLockData();
  104. return isset($data['packages']);
  105. }
  106. /**
  107. * Checks whether the lock file is still up to date with the current hash
  108. *
  109. * @return bool
  110. */
  111. public function isFresh()
  112. {
  113. $lock = $this->lockFile->read();
  114. if (!empty($lock['content-hash'])) {
  115. // There is a content hash key, use that instead of the file hash
  116. return $this->contentHash === $lock['content-hash'];
  117. }
  118. // BC support for old lock files without content-hash
  119. if (!empty($lock['hash'])) {
  120. return $this->hash === $lock['hash'];
  121. }
  122. // should not be reached unless the lock file is corrupted, so assume it's out of date
  123. return false;
  124. }
  125. /**
  126. * Searches and returns an array of locked packages, retrieved from registered repositories.
  127. *
  128. * @param bool $withDevReqs true to retrieve the locked dev packages
  129. * @throws \RuntimeException
  130. * @return \Composer\Repository\RepositoryInterface
  131. */
  132. public function getLockedRepository($withDevReqs = false)
  133. {
  134. $lockData = $this->getLockData();
  135. $packages = new ArrayRepository();
  136. $lockedPackages = $lockData['packages'];
  137. if ($withDevReqs) {
  138. if (isset($lockData['packages-dev'])) {
  139. $lockedPackages = array_merge($lockedPackages, $lockData['packages-dev']);
  140. } else {
  141. throw new \RuntimeException('The lock file does not contain require-dev information, run install with the --no-dev option or run update to install those packages.');
  142. }
  143. }
  144. if (empty($lockedPackages)) {
  145. return $packages;
  146. }
  147. if (isset($lockedPackages[0]['name'])) {
  148. foreach ($lockedPackages as $info) {
  149. $packages->addPackage($this->loader->load($info));
  150. }
  151. return $packages;
  152. }
  153. throw new \RuntimeException('Your composer.lock was created before 2012-09-15, and is not supported anymore. Run "composer update" to generate a new one.');
  154. }
  155. /**
  156. * Returns the platform requirements stored in the lock file
  157. *
  158. * @param bool $withDevReqs if true, the platform requirements from the require-dev block are also returned
  159. * @return \Composer\Package\Link[]
  160. */
  161. public function getPlatformRequirements($withDevReqs = false)
  162. {
  163. $lockData = $this->getLockData();
  164. $requirements = array();
  165. if (!empty($lockData['platform'])) {
  166. $requirements = $this->loader->parseLinks(
  167. '__ROOT__',
  168. '1.0.0',
  169. 'requires',
  170. isset($lockData['platform']) ? $lockData['platform'] : array()
  171. );
  172. }
  173. if ($withDevReqs && !empty($lockData['platform-dev'])) {
  174. $devRequirements = $this->loader->parseLinks(
  175. '__ROOT__',
  176. '1.0.0',
  177. 'requires',
  178. isset($lockData['platform-dev']) ? $lockData['platform-dev'] : array()
  179. );
  180. $requirements = array_merge($requirements, $devRequirements);
  181. }
  182. return $requirements;
  183. }
  184. public function getMinimumStability()
  185. {
  186. $lockData = $this->getLockData();
  187. return isset($lockData['minimum-stability']) ? $lockData['minimum-stability'] : 'stable';
  188. }
  189. public function getStabilityFlags()
  190. {
  191. $lockData = $this->getLockData();
  192. return isset($lockData['stability-flags']) ? $lockData['stability-flags'] : array();
  193. }
  194. public function getPreferStable()
  195. {
  196. $lockData = $this->getLockData();
  197. // return null if not set to allow caller logic to choose the
  198. // right behavior since old lock files have no prefer-stable
  199. return isset($lockData['prefer-stable']) ? $lockData['prefer-stable'] : null;
  200. }
  201. public function getPreferLowest()
  202. {
  203. $lockData = $this->getLockData();
  204. // return null if not set to allow caller logic to choose the
  205. // right behavior since old lock files have no prefer-lowest
  206. return isset($lockData['prefer-lowest']) ? $lockData['prefer-lowest'] : null;
  207. }
  208. public function getPlatformOverrides()
  209. {
  210. $lockData = $this->getLockData();
  211. return isset($lockData['platform-overrides']) ? $lockData['platform-overrides'] : array();
  212. }
  213. public function getAliases()
  214. {
  215. $lockData = $this->getLockData();
  216. return isset($lockData['aliases']) ? $lockData['aliases'] : array();
  217. }
  218. public function getLockData()
  219. {
  220. if (null !== $this->lockDataCache) {
  221. return $this->lockDataCache;
  222. }
  223. if (!$this->lockFile->exists()) {
  224. throw new \LogicException('No lockfile found. Unable to read locked packages');
  225. }
  226. return $this->lockDataCache = $this->lockFile->read();
  227. }
  228. /**
  229. * Locks provided data into lockfile.
  230. *
  231. * @param array $packages array of packages
  232. * @param mixed $devPackages array of dev packages or null if installed without --dev
  233. * @param array $platformReqs array of package name => constraint for required platform packages
  234. * @param mixed $platformDevReqs array of package name => constraint for dev-required platform packages
  235. * @param array $aliases array of aliases
  236. * @param string $minimumStability
  237. * @param array $stabilityFlags
  238. * @param bool $preferStable
  239. * @param bool $preferLowest
  240. * @param array $platformOverrides
  241. *
  242. * @return bool
  243. */
  244. public function setLockData(array $packages, $devPackages, array $platformReqs, $platformDevReqs, array $aliases, $minimumStability, array $stabilityFlags, $preferStable, $preferLowest, array $platformOverrides)
  245. {
  246. $lock = array(
  247. '_readme' => array('This file locks the dependencies of your project to a known state',
  248. 'Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies',
  249. 'This file is @gener'.'ated automatically', ),
  250. 'content-hash' => $this->contentHash,
  251. 'packages' => null,
  252. 'packages-dev' => null,
  253. 'aliases' => array(),
  254. 'minimum-stability' => $minimumStability,
  255. 'stability-flags' => $stabilityFlags,
  256. 'prefer-stable' => $preferStable,
  257. 'prefer-lowest' => $preferLowest,
  258. );
  259. foreach ($aliases as $package => $versions) {
  260. foreach ($versions as $version => $alias) {
  261. $lock['aliases'][] = array(
  262. 'alias' => $alias['alias'],
  263. 'alias_normalized' => $alias['alias_normalized'],
  264. 'version' => $version,
  265. 'package' => $package,
  266. );
  267. }
  268. }
  269. $lock['packages'] = $this->lockPackages($packages);
  270. if (null !== $devPackages) {
  271. $lock['packages-dev'] = $this->lockPackages($devPackages);
  272. }
  273. $lock['platform'] = $platformReqs;
  274. $lock['platform-dev'] = $platformDevReqs;
  275. if ($platformOverrides) {
  276. $lock['platform-overrides'] = $platformOverrides;
  277. }
  278. $lock['plugin-api-version'] = PluginInterface::PLUGIN_API_VERSION;
  279. if (empty($lock['packages']) && empty($lock['packages-dev']) && empty($lock['platform']) && empty($lock['platform-dev'])) {
  280. if ($this->lockFile->exists()) {
  281. unlink($this->lockFile->getPath());
  282. }
  283. return false;
  284. }
  285. try {
  286. $isLocked = $this->isLocked();
  287. } catch (ParsingException $e) {
  288. $isLocked = false;
  289. }
  290. if (!$isLocked || $lock !== $this->getLockData()) {
  291. $this->lockFile->write($lock);
  292. $this->lockDataCache = null;
  293. return true;
  294. }
  295. return false;
  296. }
  297. private function lockPackages(array $packages)
  298. {
  299. $locked = array();
  300. foreach ($packages as $package) {
  301. if ($package instanceof AliasPackage) {
  302. continue;
  303. }
  304. $name = $package->getPrettyName();
  305. $version = $package->getPrettyVersion();
  306. if (!$name || !$version) {
  307. throw new \LogicException(sprintf(
  308. 'Package "%s" has no version or name and can not be locked',
  309. $package
  310. ));
  311. }
  312. $spec = $this->dumper->dump($package);
  313. unset($spec['version_normalized']);
  314. // always move time to the end of the package definition
  315. $time = isset($spec['time']) ? $spec['time'] : null;
  316. unset($spec['time']);
  317. if ($package->isDev() && $package->getInstallationSource() === 'source') {
  318. // use the exact commit time of the current reference if it's a dev package
  319. $time = $this->getPackageTime($package) ?: $time;
  320. }
  321. if (null !== $time) {
  322. $spec['time'] = $time;
  323. }
  324. unset($spec['installation-source']);
  325. $locked[] = $spec;
  326. }
  327. usort($locked, function ($a, $b) {
  328. $comparison = strcmp($a['name'], $b['name']);
  329. if (0 !== $comparison) {
  330. return $comparison;
  331. }
  332. // If it is the same package, compare the versions to make the order deterministic
  333. return strcmp($a['version'], $b['version']);
  334. });
  335. return $locked;
  336. }
  337. /**
  338. * Returns the packages's datetime for its source reference.
  339. *
  340. * @param PackageInterface $package The package to scan.
  341. * @return string|null The formatted datetime or null if none was found.
  342. */
  343. private function getPackageTime(PackageInterface $package)
  344. {
  345. if (!function_exists('proc_open')) {
  346. return null;
  347. }
  348. $path = realpath($this->installationManager->getInstallPath($package));
  349. $sourceType = $package->getSourceType();
  350. $datetime = null;
  351. if ($path && in_array($sourceType, array('git', 'hg'))) {
  352. $sourceRef = $package->getSourceReference() ?: $package->getDistReference();
  353. switch ($sourceType) {
  354. case 'git':
  355. GitUtil::cleanEnv();
  356. if (0 === $this->process->execute('git log -n1 --pretty=%ct '.ProcessExecutor::escape($sourceRef), $output, $path) && preg_match('{^\s*\d+\s*$}', $output)) {
  357. $datetime = new \DateTime('@'.trim($output), new \DateTimeZone('UTC'));
  358. }
  359. break;
  360. case 'hg':
  361. if (0 === $this->process->execute('hg log --template "{date|hgdate}" -r '.ProcessExecutor::escape($sourceRef), $output, $path) && preg_match('{^\s*(\d+)\s*}', $output, $match)) {
  362. $datetime = new \DateTime('@'.$match[1], new \DateTimeZone('UTC'));
  363. }
  364. break;
  365. }
  366. }
  367. return $datetime ? $datetime->format(DATE_RFC3339) : null;
  368. }
  369. }