Debian Codegraph @

vendor/wikimedia/composer-merge-plugin/src/MergePlugin.php

raw
1 <?php
2 /**
3 * This file is part of the Composer Merge plugin.
4 *
5 * Copyright (C) 2015 Bryan Davis, Wikimedia Foundation, and contributors
6 *
7 * This software may be modified and distributed under the terms of the MIT
8 * license. See the LICENSE file for details.
9 */
10
11 namespace Wikimedia\Composer\Merge\V2;
12
13 use Composer\Composer;
14 use Composer\DependencyResolver\Operation\InstallOperation;
15 use Composer\EventDispatcher\Event as BaseEvent;
16 use Composer\EventDispatcher\EventSubscriberInterface;
17 use Composer\Factory;
18 use Composer\Installer;
19 use Composer\Installer\PackageEvent;
20 use Composer\Installer\PackageEvents;
21 use Composer\IO\IOInterface;
22 use Composer\Package\RootPackageInterface;
23 use Composer\Plugin\PluginEvents;
24 use Composer\Plugin\PluginInterface;
25 use Composer\Script\Event as ScriptEvent;
26 use Composer\Script\ScriptEvents;
27
28 /**
29 * Composer plugin that allows merging multiple composer.json files.
30 *
31 * When installed, this plugin will look for a "merge-plugin" key in the
32 * composer configuration's "extra" section. The value for this key is
33 * a set of options configuring the plugin.
34 *
35 * An "include" setting is required. The value of this setting can be either
36 * a single value or an array of values. Each value is treated as a glob()
37 * pattern identifying additional composer.json style configuration files to
38 * merge into the configuration for the current compser execution.
39 *
40 * The "autoload", "autoload-dev", "conflict", "provide", "replace",
41 * "repositories", "require", "require-dev", and "suggest" sections of the
42 * found configuration files will be merged into the root package
43 * configuration as though they were directly included in the top-level
44 * composer.json file.
45 *
46 * If included files specify conflicting package versions for "require" or
47 * "require-dev", the normal Composer dependency solver process will be used
48 * to attempt to resolve the conflict. Specifying the 'replace' key as true will
49 * change this default behaviour so that the last-defined version of a package
50 * will win, allowing for force-overrides of package defines.
51 *
52 * By default the "extra" section is not merged. This can be enabled by
53 * setitng the 'merge-extra' key to true. In normal mode, when the same key is
54 * found in both the original and the imported extra section, the version in
55 * the original config is used and the imported version is skipped. If
56 * 'replace' mode is active, this behaviour changes so the imported version of
57 * the key is used, replacing the version in the original config.
58 *
59 *
60 * @code
61 * {
62 * "require": {
63 * "wikimedia/composer-merge-plugin": "dev-master"
64 * },
65 * "extra": {
66 * "merge-plugin": {
67 * "include": [
68 * "composer.local.json"
69 * ]
70 * }
71 * }
72 * }
73 * @endcode
74 *
75 * @author Bryan Davis <[email protected]>
76 */
77 class MergePlugin implements PluginInterface, EventSubscriberInterface
78 {
79
80 /**
81 * Official package name
82 */
83 public const PACKAGE_NAME = 'wikimedia/composer-merge-plugin';
84
85 /**
86 * Priority that plugin uses to register callbacks.
87 */
88 private const CALLBACK_PRIORITY = 50000;
89
90 /**
91 * @var Composer $composer
92 */
93 protected $composer;
94
95 /**
96 * @var PluginState $state
97 */
98 protected $state;
99
100 /**
101 * @var Logger $logger
102 */
103 protected $logger;
104
105 /**
106 * Files that have already been fully processed
107 *
108 * @var array<string, bool> $loaded
109 */
110 protected $loaded = [];
111
112 /**
113 * Files that have already been partially processed
114 *
115 * @var array<string, bool> $loadedNoDev
116 */
117 protected $loadedNoDev = [];
118
119 /**
120 * Nested packages to restrict update operations.
121 *
122 * @var array<string, bool> $updateAllowList
123 */
124 protected $updateAllowList = [];
125
126 /**
127 * {@inheritdoc}
128 */
129 public function activate(Composer $composer, IOInterface $io)
130 {
131 $this->composer = $composer;
132 $this->state = new PluginState($this->composer);
133 $this->logger = new Logger('merge-plugin', $io);
134 }
135
136 /**
137 * {@inheritdoc}
138 */
139 public function deactivate(Composer $composer, IOInterface $io)
140 {
141 }
142
143 /**
144 * {@inheritdoc}
145 */
146 public function uninstall(Composer $composer, IOInterface $io)
147 {
148 }
149
150 /**
151 * {@inheritdoc}
152 */
153 public static function getSubscribedEvents()
154 {
155 return [
156 PluginEvents::INIT =>
157 ['onInit', self::CALLBACK_PRIORITY],
158 PackageEvents::POST_PACKAGE_INSTALL =>
159 ['onPostPackageInstall', self::CALLBACK_PRIORITY],
160 ScriptEvents::POST_INSTALL_CMD =>
161 ['onPostInstallOrUpdate', self::CALLBACK_PRIORITY],
162 ScriptEvents::POST_UPDATE_CMD =>
163 ['onPostInstallOrUpdate', self::CALLBACK_PRIORITY],
164 ScriptEvents::PRE_AUTOLOAD_DUMP =>
165 ['onInstallUpdateOrDump', self::CALLBACK_PRIORITY],
166 ScriptEvents::PRE_INSTALL_CMD =>
167 ['onInstallUpdateOrDump', self::CALLBACK_PRIORITY],
168 ScriptEvents::PRE_UPDATE_CMD =>
169 ['onInstallUpdateOrDump', self::CALLBACK_PRIORITY],
170 ];
171 }
172
173 /**
174 * Get list of packages to restrict update operations.
175 *
176 * @return string[]
177 * @see \Composer\Installer::setUpdateAllowList()
178 */
179 public function getUpdateAllowList()
180 {
181 return array_keys($this->updateAllowList);
182 }
183
184 /**
185 * Handle an event callback for initialization.
186 *
187 * @param BaseEvent $event
188 */
189 public function onInit(BaseEvent $event)
190 {
191 $this->state->loadSettings();
192 // It is not possible to know if the user specified --dev or --no-dev
193 // so assume it is false. The dev section will be merged later when
194 // the other events fire.
195 $this->state->setDevMode(false);
196 $this->mergeFiles($this->state->getIncludes(), false);
197 $this->mergeFiles($this->state->getRequires(), true);
198 }
199
200 /**
201 * Handle an event callback for an install, update or dump command by
202 * checking for "merge-plugin" in the "extra" data and merging package
203 * contents if found.
204 *
205 * @param ScriptEvent $event
206 */
207 public function onInstallUpdateOrDump(ScriptEvent $event)
208 {
209 $this->state->loadSettings();
210 $this->state->setDevMode($event->isDevMode());
211 $this->mergeFiles($this->state->getIncludes(), false);
212 $this->mergeFiles($this->state->getRequires(), true);
213
214 if ($event->getName() === ScriptEvents::PRE_AUTOLOAD_DUMP) {
215 $this->state->setDumpAutoloader(true);
216 $flags = $event->getFlags();
217 if (isset($flags['optimize'])) {
218 $this->state->setOptimizeAutoloader($flags['optimize']);
219 }
220 }
221 }
222
223 /**
224 * Find configuration files matching the configured glob patterns and
225 * merge their contents with the master package.
226 *
227 * @param array $patterns List of files/glob patterns
228 * @param bool $required Are the patterns required to match files?
229 * @throws MissingFileException when required and a pattern returns no
230 * results
231 */
232 protected function mergeFiles(array $patterns, $required = false)
233 {
234 $root = $this->composer->getPackage();
235
236 $files = array_map(
237 static function ($files, $pattern) use ($required) {
238 if ($required && !$files) {
239 throw new MissingFileException(
240 "merge-plugin: No files matched required '{$pattern}'"
241 );
242 }
243 return $files;
244 },
245 array_map('glob', $patterns),
246 $patterns
247 );
248
249 foreach (array_reduce($files, 'array_merge', []) as $path) {
250 $this->mergeFile($root, $path);
251 }
252 }
253
254 /**
255 * Read a JSON file and merge its contents
256 *
257 * @param RootPackageInterface $root
258 * @param string $path
259 */
260 protected function mergeFile(RootPackageInterface $root, $path)
261 {
262 if (isset($this->loaded[$path]) ||
263 (isset($this->loadedNoDev[$path]) && !$this->state->isDevMode())
264 ) {
265 $this->logger->debug(
266 "Already merged <comment>$path</comment> completely"
267 );
268 return;
269 }
270
271 $package = new ExtraPackage($path, $this->composer, $this->logger);
272
273 if (isset($this->loadedNoDev[$path])) {
274 $this->logger->info(
275 "Loading -dev sections of <comment>{$path}</comment>..."
276 );
277 $package->mergeDevInto($root, $this->state);
278 } else {
279 $this->logger->info("Loading <comment>{$path}</comment>...");
280 $package->mergeInto($root, $this->state);
281 }
282
283 $requirements = $package->getMergedRequirements();
284 if (!empty($requirements)) {
285 $this->updateAllowList = array_replace(
286 $this->updateAllowList,
287 array_fill_keys($requirements, true)
288 );
289 }
290
291 if ($this->state->isDevMode()) {
292 $this->loaded[$path] = true;
293 } else {
294 $this->loadedNoDev[$path] = true;
295 }
296
297 if ($this->state->recurseIncludes()) {
298 $this->mergeFiles($package->getIncludes(), false);
299 $this->mergeFiles($package->getRequires(), true);
300 }
301 }
302
303 /**
304 * Handle an event callback following installation of a new package by
305 * checking to see if the package that was installed was our plugin.
306 *
307 * @param PackageEvent $event
308 */
309 public function onPostPackageInstall(PackageEvent $event)
310 {
311 $op = $event->getOperation();
312 if ($op instanceof InstallOperation) {
313 $package = $op->getPackage()->getName();
314 if ($package === self::PACKAGE_NAME) {
315 $this->logger->info('composer-merge-plugin installed');
316 $this->state->setFirstInstall(true);
317 $this->state->setLocked(
318 $event->getComposer()->getLocker()->isLocked()
319 );
320 }
321 }
322 }
323
324 /**
325 * Handle an event callback following an install or update command. If our
326 * plugin was installed during the run then trigger an update command to
327 * process any merge-patterns in the current config.
328 *
329 * @param ScriptEvent $event
330 */
331 public function onPostInstallOrUpdate(ScriptEvent $event)
332 {
333 // @codeCoverageIgnoreStart
334 if ($this->state->isFirstInstall()) {
335 $this->state->setFirstInstall(false);
336
337 $requirements = $this->getUpdateAllowList();
338 if (empty($requirements)) {
339 return;
340 }
341
342 $this->logger->log("\n".'<info>Running composer update to apply merge settings</info>');
343
344 $lockBackup = null;
345 $lock = null;
346 if (!$this->state->isComposer1()) {
347 $file = Factory::getComposerFile();
348 $lock = Factory::getLockFile($file);
349 if (file_exists($lock)) {
350 $lockBackup = file_get_contents($lock);
351 }
352 }
353
354 $config = $this->composer->getConfig();
355 $preferSource = $config->get('preferred-install') === 'source';
356 $preferDist = $config->get('preferred-install') === 'dist';
357
358 $installer = Installer::create(
359 $event->getIO(),
360 // Create a new Composer instance to ensure full processing of
361 // the merged files.
362 Factory::create($event->getIO(), null, false)
363 );
364
365 $installer->setPreferSource($preferSource);
366 $installer->setPreferDist($preferDist);
367 $installer->setDevMode($event->isDevMode());
368 $installer->setDumpAutoloader($this->state->shouldDumpAutoloader());
369 $installer->setOptimizeAutoloader(
370 $this->state->shouldOptimizeAutoloader()
371 );
372
373 $installer->setUpdate(true);
374
375 if ($this->state->isComposer1()) {
376 // setUpdateWhitelist() only exists in composer 1.x. Configure as to run phan against composer 2.x
377 // @phan-suppress-next-line PhanUndeclaredMethod
378 $installer->setUpdateWhitelist($requirements);
379 } else {
380 $installer->setUpdateAllowList($requirements);
381 }
382
383 $status = $installer->run();
384 if (( $status !== 0 ) && $lockBackup && $lock && !$this->state->isComposer1()) {
385 $this->logger->log(
386 "\n".'<error>'.
387 'Update to apply merge settings failed, reverting '.$lock.' to its original content.'.
388 '</error>'
389 );
390 file_put_contents($lock, $lockBackup);
391 }
392 }
393 // @codeCoverageIgnoreEnd
394 }
395 }
396 // vim:sw=4:ts=4:sts=4:et: