Locker.php 14 KB

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