Locker.php 13 KB

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