Locker.php 14 KB

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