Locker.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  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\Package\AliasPackage;
  17. use Composer\Repository\ArrayRepository;
  18. use Composer\Package\Dumper\ArrayDumper;
  19. use Composer\Package\Loader\ArrayLoader;
  20. use Composer\Package\Version\VersionParser;
  21. /**
  22. * Reads/writes project lockfile (composer.lock).
  23. *
  24. * @author Konstantin Kudryashiv <ever.zet@gmail.com>
  25. * @author Jordi Boggiano <j.boggiano@seld.be>
  26. */
  27. class Locker
  28. {
  29. private $lockFile;
  30. private $repositoryManager;
  31. private $installationManager;
  32. private $hash;
  33. private $loader;
  34. private $dumper;
  35. private $lockDataCache;
  36. /**
  37. * Initializes packages locker.
  38. *
  39. * @param JsonFile $lockFile lockfile loader
  40. * @param RepositoryManager $repositoryManager repository manager instance
  41. * @param InstallationManager $installationManager installation manager instance
  42. * @param string $hash unique hash of the current composer configuration
  43. */
  44. public function __construct(JsonFile $lockFile, RepositoryManager $repositoryManager, InstallationManager $installationManager, $hash)
  45. {
  46. $this->lockFile = $lockFile;
  47. $this->repositoryManager = $repositoryManager;
  48. $this->installationManager = $installationManager;
  49. $this->hash = $hash;
  50. $this->loader = new ArrayLoader();
  51. $this->dumper = new ArrayDumper();
  52. }
  53. /**
  54. * Checks whether locker were been locked (lockfile found).
  55. *
  56. * @return bool
  57. */
  58. public function isLocked()
  59. {
  60. if (!$this->lockFile->exists()) {
  61. return false;
  62. }
  63. $data = $this->getLockData();
  64. return isset($data['packages']);
  65. }
  66. /**
  67. * Checks whether the lock file is still up to date with the current hash
  68. *
  69. * @return bool
  70. */
  71. public function isFresh()
  72. {
  73. $lock = $this->lockFile->read();
  74. return $this->hash === $lock['hash'];
  75. }
  76. /**
  77. * Searches and returns an array of locked packages, retrieved from registered repositories.
  78. *
  79. * @param bool $withDevReqs true to retrieve the locked dev packages
  80. * @return \Composer\Repository\RepositoryInterface
  81. */
  82. public function getLockedRepository($withDevReqs = false)
  83. {
  84. $lockData = $this->getLockData();
  85. $packages = new ArrayRepository();
  86. $lockedPackages = $lockData['packages'];
  87. if ($withDevReqs) {
  88. if (isset($lockData['packages-dev'])) {
  89. $lockedPackages = array_merge($lockedPackages, $lockData['packages-dev']);
  90. } else {
  91. 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.');
  92. }
  93. }
  94. if (empty($lockedPackages)) {
  95. return $packages;
  96. }
  97. if (isset($lockedPackages[0]['name'])) {
  98. foreach ($lockedPackages as $info) {
  99. $packages->addPackage($this->loader->load($info));
  100. }
  101. return $packages;
  102. }
  103. 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.');
  104. }
  105. /**
  106. * Returns the platform requirements stored in the lock file
  107. *
  108. * @param bool $withDevReqs if true, the platform requirements from the require-dev block are also returned
  109. * @return \Composer\Package\Link[]
  110. */
  111. public function getPlatformRequirements($withDevReqs = false)
  112. {
  113. $lockData = $this->getLockData();
  114. $versionParser = new VersionParser();
  115. $requirements = array();
  116. if (!empty($lockData['platform'])) {
  117. $requirements = $versionParser->parseLinks(
  118. '__ROOT__',
  119. '1.0.0',
  120. 'requires',
  121. isset($lockData['platform']) ? $lockData['platform'] : array()
  122. );
  123. }
  124. if ($withDevReqs && !empty($lockData['platform-dev'])) {
  125. $devRequirements = $versionParser->parseLinks(
  126. '__ROOT__',
  127. '1.0.0',
  128. 'requires',
  129. isset($lockData['platform-dev']) ? $lockData['platform-dev'] : array()
  130. );
  131. $requirements = array_merge($requirements, $devRequirements);
  132. }
  133. return $requirements;
  134. }
  135. public function getMinimumStability()
  136. {
  137. $lockData = $this->getLockData();
  138. return isset($lockData['minimum-stability']) ? $lockData['minimum-stability'] : 'stable';
  139. }
  140. public function getStabilityFlags()
  141. {
  142. $lockData = $this->getLockData();
  143. return isset($lockData['stability-flags']) ? $lockData['stability-flags'] : array();
  144. }
  145. public function getAliases()
  146. {
  147. $lockData = $this->getLockData();
  148. return isset($lockData['aliases']) ? $lockData['aliases'] : array();
  149. }
  150. public function getLockData()
  151. {
  152. if (null !== $this->lockDataCache) {
  153. return $this->lockDataCache;
  154. }
  155. if (!$this->lockFile->exists()) {
  156. throw new \LogicException('No lockfile found. Unable to read locked packages');
  157. }
  158. return $this->lockDataCache = $this->lockFile->read();
  159. }
  160. /**
  161. * Locks provided data into lockfile.
  162. *
  163. * @param array $packages array of packages
  164. * @param mixed $devPackages array of dev packages or null if installed without --dev
  165. * @param array $platformReqs array of package name => constraint for required platform packages
  166. * @param mixed $platformDevReqs array of package name => constraint for dev-required platform packages
  167. * @param array $aliases array of aliases
  168. * @param string $minimumStability
  169. * @param array $stabilityFlags
  170. *
  171. * @return bool
  172. */
  173. public function setLockData(array $packages, $devPackages, array $platformReqs, $platformDevReqs, array $aliases, $minimumStability, array $stabilityFlags)
  174. {
  175. $lock = array(
  176. '_readme' => array('This file locks the dependencies of your project to a known state', 'Read more about it at http://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file'),
  177. 'hash' => $this->hash,
  178. 'packages' => null,
  179. 'packages-dev' => null,
  180. 'aliases' => array(),
  181. 'minimum-stability' => $minimumStability,
  182. 'stability-flags' => $stabilityFlags,
  183. );
  184. foreach ($aliases as $package => $versions) {
  185. foreach ($versions as $version => $alias) {
  186. $lock['aliases'][] = array(
  187. 'alias' => $alias['alias'],
  188. 'alias_normalized' => $alias['alias_normalized'],
  189. 'version' => $version,
  190. 'package' => $package,
  191. );
  192. }
  193. }
  194. $lock['packages'] = $this->lockPackages($packages);
  195. if (null !== $devPackages) {
  196. $lock['packages-dev'] = $this->lockPackages($devPackages);
  197. }
  198. if (empty($lock['packages']) && empty($lock['packages-dev'])) {
  199. if ($this->lockFile->exists()) {
  200. unlink($this->lockFile->getPath());
  201. }
  202. return false;
  203. }
  204. $lock['platform'] = $platformReqs;
  205. $lock['platform-dev'] = $platformDevReqs;
  206. if (!$this->isLocked() || $lock !== $this->getLockData()) {
  207. $this->lockFile->write($lock);
  208. $this->lockDataCache = null;
  209. return true;
  210. }
  211. return false;
  212. }
  213. private function lockPackages(array $packages)
  214. {
  215. $locked = array();
  216. foreach ($packages as $package) {
  217. if ($package instanceof AliasPackage) {
  218. continue;
  219. }
  220. $name = $package->getPrettyName();
  221. $version = $package->getPrettyVersion();
  222. if (!$name || !$version) {
  223. throw new \LogicException(sprintf(
  224. 'Package "%s" has no version or name and can not be locked', $package
  225. ));
  226. }
  227. $spec = $this->dumper->dump($package);
  228. unset($spec['version_normalized']);
  229. // always move time to the end of the package definition
  230. $time = isset($spec['time']) ? $spec['time'] : null;
  231. unset($spec['time']);
  232. if ($package->isDev()) {
  233. // use the exact commit time of the current reference if it's a dev package
  234. $time = $this->getPackageTime($package) ?: $time;
  235. }
  236. if (null !== $time) {
  237. $spec['time'] = $time;
  238. }
  239. unset($spec['installation-source']);
  240. $locked[] = $spec;
  241. }
  242. usort($locked, function ($a, $b) {
  243. $comparison = strcmp($a['name'], $b['name']);
  244. if (0 !== $comparison) {
  245. return $comparison;
  246. }
  247. // If it is the same package, compare the versions to make the order deterministic
  248. return strcmp($a['version'], $b['version']);
  249. });
  250. return $locked;
  251. }
  252. /**
  253. * Returns the packages's datetime for its source reference.
  254. *
  255. * @param PackageInterface $package The package to scan.
  256. * @return string|null The formatted datetime or null if none was found.
  257. */
  258. private function getPackageTime(PackageInterface $package)
  259. {
  260. if (!function_exists('proc_open')) {
  261. return null;
  262. }
  263. $path = $this->installationManager->getInstallPath($package);
  264. $sourceType = $package->getSourceType();
  265. $datetime = null;
  266. if ($path && in_array($sourceType, array('git', 'hg'))) {
  267. $sourceRef = $package->getSourceReference() ?: $package->getDistReference();
  268. $process = new ProcessExecutor();
  269. switch ($sourceType) {
  270. case 'git':
  271. if (0 === $process->execute('git log -n1 --pretty=%ct '.escapeshellarg($sourceRef), $output, $path) && preg_match('{^\s*\d+\s*$}', $output)) {
  272. $datetime = new \DateTime('@'.trim($output), new \DateTimeZone('UTC'));
  273. }
  274. break;
  275. case 'hg':
  276. if (0 === $process->execute('hg log --template "{date|hgdate}" -r '.escapeshellarg($sourceRef), $output, $path) && preg_match('{^\s*(\d+)\s*}', $output, $match)) {
  277. $datetime = new \DateTime('@'.$match[1], new \DateTimeZone('UTC'));
  278. }
  279. break;
  280. }
  281. }
  282. return $datetime ? $datetime->format('Y-m-d H:i:s') : null;
  283. }
  284. }