• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

eliashaeussler / version-bumper / 24158885296

08 Apr 2026 09:10PM UTC coverage: 87.5% (-1.1%) from 88.577%
24158885296

Pull #122

github

eliashaeussler
[BUGFIX] Update composer.lock file after composer.json has changed
Pull Request #122: [BUGFIX] Update composer.lock file after composer.json has changed

35 of 53 new or added lines in 1 file covered. (66.04%)

5 existing lines in 1 file now uncovered.

917 of 1048 relevant lines covered (87.5%)

4.87 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

90.34
/src/Command/BumpVersionCommand.php
1
<?php
2

3
declare(strict_types=1);
4

5
/*
6
 * This file is part of the Composer package "eliashaeussler/version-bumper".
7
 *
8
 * Copyright (C) 2024-2026 Elias Häußler <elias@haeussler.dev>
9
 *
10
 * This program is free software: you can redistribute it and/or modify
11
 * it under the terms of the GNU General Public License as published by
12
 * the Free Software Foundation, either version 3 of the License, or
13
 * (at your option) any later version.
14
 *
15
 * This program is distributed in the hope that it will be useful,
16
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18
 * GNU General Public License for more details.
19
 *
20
 * You should have received a copy of the GNU General Public License
21
 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22
 */
23

24
namespace EliasHaeussler\VersionBumper\Command;
25

26
use Composer\Command;
27
use Composer\Composer;
28
use Composer\Console\Application;
29
use CuyZ\Valinor;
30
use EliasHaeussler\VersionBumper\Config;
31
use EliasHaeussler\VersionBumper\Enum;
32
use EliasHaeussler\VersionBumper\Exception;
33
use EliasHaeussler\VersionBumper\Result;
34
use EliasHaeussler\VersionBumper\Version;
35
use GitElephant\Command\Caller;
36
use Symfony\Component\Console;
37
use Symfony\Component\Filesystem;
38

39
use function array_filter;
40
use function array_map;
41
use function count;
42
use function dirname;
43
use function getcwd;
44
use function implode;
45
use function is_string;
46
use function method_exists;
47
use function reset;
48
use function sprintf;
49
use function trim;
50

51
/**
52
 * BumpVersionCommand.
53
 *
54
 * @author Elias Häußler <elias@haeussler.dev>
55
 * @license GPL-3.0-or-later
56
 */
57
final class BumpVersionCommand extends Command\BaseCommand
58
{
59
    private readonly Version\VersionBumper $bumper;
60
    private readonly Config\ConfigReader $configReader;
61
    private readonly Version\VersionRangeDetector $versionRangeDetector;
62
    private readonly Version\VersionReleaser $releaser;
63
    private Console\Style\SymfonyStyle $io;
64

65
    public function __construct(
15✔
66
        ?Composer $composer = null,
67
        ?Caller\CallerInterface $caller = null,
68
    ) {
69
        if (null !== $composer) {
15✔
70
            $this->setComposer($composer);
1✔
71
        }
72

73
        parent::__construct('bump-version');
15✔
74

75
        $this->bumper = new Version\VersionBumper();
15✔
76
        $this->configReader = new Config\ConfigReader();
15✔
77
        $this->versionRangeDetector = new Version\VersionRangeDetector($caller);
15✔
78
        $this->releaser = new Version\VersionReleaser($caller);
15✔
79
    }
80

81
    protected function configure(): void
15✔
82
    {
83
        $this->setAliases(['bv']);
15✔
84
        $this->setDescription('Bump package version in specific files during release preparations');
15✔
85

86
        $this->addArgument(
15✔
87
            'range',
15✔
88
            Console\Input\InputArgument::OPTIONAL,
15✔
89
            sprintf(
15✔
90
                'Version range (one of "%s") or explicit version to bump in configured files',
15✔
91
                implode('", "', Enum\VersionRange::all()),
15✔
92
            ),
15✔
93
        );
15✔
94

95
        $this->addOption(
15✔
96
            'config',
15✔
97
            'c',
15✔
98
            Console\Input\InputOption::VALUE_REQUIRED,
15✔
99
            'Path to configuration file (JSON, YAML or PHP) with files in which to bump new versions',
15✔
100
            $this->readConfigFileFromRootPackage(),
15✔
101
        );
15✔
102
        $this->addOption(
15✔
103
            'release',
15✔
104
            'r',
15✔
105
            Console\Input\InputOption::VALUE_NONE,
15✔
106
            'Create a new Git tag after versions are bumped',
15✔
107
        );
15✔
108
        $this->addOption(
15✔
109
            'dry-run',
15✔
110
            null,
15✔
111
            Console\Input\InputOption::VALUE_NONE,
15✔
112
            'Do not perform any write operations, just calculate version bumps',
15✔
113
        );
15✔
114
        $this->addOption(
15✔
115
            'strict',
15✔
116
            null,
15✔
117
            Console\Input\InputOption::VALUE_NONE,
15✔
118
            'Fail if any unmatched file pattern is reported',
15✔
119
        );
15✔
120
    }
121

122
    protected function initialize(Console\Input\InputInterface $input, Console\Output\OutputInterface $output): void
15✔
123
    {
124
        $this->io = new Console\Style\SymfonyStyle($input, $output);
15✔
125
    }
126

127
    protected function execute(Console\Input\InputInterface $input, Console\Output\OutputInterface $output): int
15✔
128
    {
129
        $rootPath = (string) getcwd();
15✔
130
        $rangeOrVersion = $input->getArgument('range');
15✔
131
        $configFile = $input->getOption('config') ?? $this->configReader->detectFile($rootPath);
15✔
132
        $release = $input->getOption('release');
15✔
133
        $dryRun = $input->getOption('dry-run');
15✔
134
        $strict = $input->getOption('strict');
15✔
135

136
        if (null === $configFile) {
15✔
137
            $this->io->error('Please provide a config file path using the --config option.');
1✔
138

139
            return self::INVALID;
1✔
140
        }
141

142
        if (Filesystem\Path::isRelative($configFile)) {
14✔
143
            $configFile = Filesystem\Path::makeAbsolute($configFile, $rootPath);
1✔
144
        } else {
145
            $rootPath = dirname($configFile);
13✔
146
        }
147

148
        try {
149
            $result = $this->bumpVersions($configFile, $rangeOrVersion, $rootPath, $dryRun);
14✔
150

151
            if (null === $result) {
14✔
152
                return self::FAILURE;
8✔
153
            }
154

155
            [$config, $results] = $result;
6✔
156

157
            if (!$this->updateComposerLockIfNeeded($input, $output, $rootPath, $results)) {
6✔
NEW
UNCOV
158
                return self::FAILURE;
×
159
            }
160

161
            if ($release && !$this->releaseVersion($results, $rootPath, $config->releaseOptions(), $dryRun)) {
6✔
162
                return self::FAILURE;
1✔
163
            }
164
        } finally {
165
            if ($dryRun) {
14✔
166
                $this->io->note('No write operations were performed (dry-run mode).');
7✔
167
            }
168
        }
169

170
        if ($strict) {
5✔
171
            foreach ($results as $versionBumpResult) {
1✔
172
                if ($versionBumpResult->hasUnmatchedReports()) {
1✔
173
                    return self::FAILURE;
1✔
174
                }
175
            }
176
        }
177

178
        return self::SUCCESS;
4✔
179
    }
180

181
    /**
182
     * @return array{Config\VersionBumperConfig, list<Result\VersionBumpResult>}|null
183
     */
184
    private function bumpVersions(string $configFile, ?string $rangeOrVersion, string $rootPath, bool $dryRun): ?array
14✔
185
    {
186
        try {
187
            $config = $this->configReader->readFromFile($configFile);
14✔
188
            $finalRootPath = $config->rootPath() ?? $rootPath;
13✔
189

190
            // Auto-detect version range from indicators
191
            if (null !== $rangeOrVersion) {
13✔
192
                $versionRange = Enum\VersionRange::tryFromInput($rangeOrVersion) ?? $rangeOrVersion;
9✔
193
            } elseif ([] !== $config->versionRangeIndicators()) {
4✔
194
                $versionRange = $this->versionRangeDetector->detect($finalRootPath, $config->versionRangeIndicators());
3✔
195
            } else {
196
                $this->io->error('Please provide a version range or explicit version to bump in configured files.');
1✔
197
                $this->io->block(
1✔
198
                    'You can also enable auto-detection by adding version range indicators to your configuration file.',
1✔
199
                    null,
1✔
200
                    'fg=cyan',
1✔
201
                    '💡 ',
1✔
202
                );
1✔
203

204
                return null;
1✔
205
            }
206

207
            // Exit early if version range detection fails
208
            if (null === $versionRange) {
11✔
209
                $this->io->error('Unable to auto-detect version range. Please provide a version range or explicit version instead.');
1✔
210

211
                return null;
1✔
212
            }
213

214
            $this->decorateAppliedPresets($config->presets());
10✔
215

216
            $results = $this->bumper->bump($config->filesToModify(), $finalRootPath, $versionRange, $dryRun);
10✔
217

218
            $this->decorateVersionBumpResults($results, $rootPath);
6✔
219

220
            return [$config, $results];
6✔
221
        } catch (Valinor\Mapper\MappingError $error) {
6✔
222
            $this->decorateMappingError($error, $configFile);
1✔
223
        } catch (Exception\Exception $exception) {
5✔
224
            $this->io->error($exception->getMessage());
5✔
225
        }
226

227
        return null;
6✔
228
    }
229

230
    /**
231
     * @param list<Result\VersionBumpResult> $results
232
     */
233
    private function releaseVersion(array $results, string $rootPath, Config\ReleaseOptions $options, bool $dryRun): bool
2✔
234
    {
235
        $this->io->title('Release');
2✔
236

237
        try {
238
            $releaseResult = $this->releaser->release($results, $rootPath, $options, $dryRun);
2✔
239

240
            $this->decorateVersionReleaseResult($releaseResult);
1✔
241

242
            return true;
1✔
243
        } catch (Exception\Exception $exception) {
1✔
244
            $this->io->error($exception->getMessage());
1✔
UNCOV
245
        } catch (\Exception $exception) {
×
246
            $this->io->error('Git error during release: '.$exception->getMessage());
×
247
        }
248

249
        return false;
1✔
250
    }
251

252
    /**
253
     * @param list<Config\Preset\Preset> $presets
254
     */
255
    private function decorateAppliedPresets(array $presets): void
10✔
256
    {
257
        if ([] === $presets || !$this->io->isVerbose()) {
10✔
258
            return;
8✔
259
        }
260

261
        $this->io->title('Applied presets');
2✔
262

263
        $this->io->listing(
2✔
264
            array_map(
2✔
265
                static fn (Config\Preset\Preset $preset) => sprintf(
2✔
266
                    '%s <fg=gray>(%s)</>',
2✔
267
                    $preset::getDescription(),
2✔
268
                    $preset::getIdentifier(),
2✔
269
                ),
2✔
270
                $presets,
2✔
271
            ),
2✔
272
        );
2✔
273
    }
274

275
    /**
276
     * @param list<Result\VersionBumpResult> $results
277
     */
278
    private function decorateVersionBumpResults(array $results, string $rootPath): void
6✔
279
    {
280
        $titleDisplayed = false;
6✔
281

282
        foreach ($results as $result) {
6✔
283
            if (!$result->hasOperations()) {
6✔
284
                continue;
4✔
285
            }
286

287
            $path = $result->file()->path();
6✔
288
            $groupedOperations = $result->groupedOperations();
6✔
289
            $hasOnlySkippedOperations = [] === array_filter(
6✔
290
                $groupedOperations,
6✔
291
                static fn (array $operations) => Enum\OperationState::Skipped !== reset($operations)->state(),
6✔
292
            );
6✔
293

294
            if (Filesystem\Path::isAbsolute($path)) {
6✔
UNCOV
295
                $path = Filesystem\Path::makeRelative($path, $rootPath);
×
296
            }
297

298
            if (!$titleDisplayed) {
6✔
299
                $this->io->title('Bumped versions');
6✔
300
                $titleDisplayed = true;
6✔
301
            }
302

303
            $this->io->section($path);
6✔
304

305
            foreach ($groupedOperations as $operations) {
6✔
306
                $operation = reset($operations);
6✔
307
                $numberOfOperations = count($operations);
6✔
308
                $state = $operation->state();
6✔
309

310
                if (Enum\OperationState::Skipped === $state && !$hasOnlySkippedOperations) {
6✔
311
                    continue;
3✔
312
                }
313

314
                $message = match ($state) {
6✔
315
                    Enum\OperationState::Modified => sprintf(
6✔
316
                        '✅ Bumped version from "%s" to "%s"',
6✔
317
                        $operation->source()?->full() ?? '',
6✔
318
                        $operation->target()?->full() ?? '',
6✔
319
                    ),
6✔
320
                    Enum\OperationState::Skipped => '⏩ Skipped file due to unmodified contents',
4✔
321
                    Enum\OperationState::Unmatched => '❓ Unmatched file pattern: '.$operation->pattern()->original(),
4✔
322
                };
6✔
323

324
                if ($numberOfOperations > 1) {
6✔
325
                    $message .= sprintf(' (%dx)', $numberOfOperations);
3✔
326
                }
327

328
                $this->io->writeln($message);
6✔
329
            }
330
        }
331
    }
332

333
    private function decorateVersionReleaseResult(Result\VersionReleaseResult $result): void
1✔
334
    {
335
        $numberOfCommittedFiles = count($result->committedFiles());
1✔
336
        $releaseInformation = [
1✔
337
            sprintf('Added %d file%s.', $numberOfCommittedFiles, 1 !== $numberOfCommittedFiles ? 's' : ''),
1✔
338
            sprintf('Committed: <info>%s</info>', $result->commitMessage()),
1✔
339
        ];
1✔
340

341
        if (null !== $result->commitId()) {
1✔
UNCOV
342
            $releaseInformation[] = sprintf('Commit hash: %s', $result->commitId());
×
343
        }
344

345
        $releaseInformation[] = sprintf('Tagged: <info>%s</info>', $result->tagName());
1✔
346

347
        $this->io->listing($releaseInformation);
1✔
348
    }
349

350
    private function decorateMappingError(Valinor\Mapper\MappingError $error, string $configFile): void
1✔
351
    {
352
        $errorMessages = [];
1✔
353
        $errors = $error->messages()->errors();
1✔
354

355
        $this->io->error(
1✔
356
            sprintf('The config file "%s" is invalid.', $configFile),
1✔
357
        );
1✔
358

359
        foreach ($errors as $propertyError) {
1✔
360
            $errorMessages[] = sprintf('%s: %s', $propertyError->path(), $propertyError->toString());
1✔
361
        }
362

363
        $this->io->listing($errorMessages);
1✔
364
    }
365

366
    private function readConfigFileFromRootPackage(): ?string
15✔
367
    {
368
        $composer = $this->getComposerInstance();
15✔
369

370
        if (null === $composer) {
15✔
371
            return null;
15✔
372
        }
373

374
        $extra = $composer->getPackage()->getExtra();
1✔
375
        /* @phpstan-ignore offsetAccess.nonOffsetAccessible */
376
        $configFile = $extra['version-bumper']['config-file'] ?? null;
1✔
377

378
        if (is_string($configFile) && '' !== trim($configFile)) {
1✔
379
            return $configFile;
1✔
380
        }
381

UNCOV
382
        return null;
×
383
    }
384

385
    /**
386
     * @param list<Result\VersionBumpResult> $results
387
     */
388
    private function updateComposerLockIfNeeded(
6✔
389
        Console\Input\InputInterface $input,
390
        Console\Output\OutputInterface $output,
391
        string $rootPath,
392
        array &$results,
393
    ): bool {
394
        $this->resetComposer();
6✔
395

396
        $composer = $this->getComposerInstance();
6✔
397
        $locker = $composer?->getLocker();
6✔
398

399
        if (null === $locker || !$locker->isLocked() || $locker->isFresh()) {
6✔
400
            return true;
5✔
401
        }
402

403
        $this->io->title('File integrity');
1✔
404

405
        $application = new Application();
1✔
406
        $application->setAutoExit(false);
1✔
407

408
        $commandOutput = new Console\Output\BufferedOutput(
1✔
409
            $output->getVerbosity(),
1✔
410
            $output->isDecorated(),
1✔
411
            $output->getFormatter(),
1✔
412
        );
1✔
413

414
        $parameters = [
1✔
415
            'command' => 'update',
1✔
416
            '--ignore-platform-reqs' => true,
1✔
417
            '--lock' => true,
1✔
418
            '--no-autoloader' => true,
1✔
419
            '--working-dir' => $rootPath,
1✔
420
        ];
1✔
421

422
        if ($input->hasParameterOption('--no-ansi')) {
1✔
NEW
423
            $parameters['--no-ansi'] = $input->getParameterOption('--no-ansi');
×
424
        }
425

426
        if ($input->hasParameterOption('--no-plugins')) {
1✔
NEW
427
            $parameters['--no-plugins'] = $input->getParameterOption('--no-plugins');
×
428
        }
429

430
        if ($input->hasParameterOption('--no-scripts')) {
1✔
NEW
431
            $parameters['--no-scripts'] = $input->getParameterOption('--no-scripts');
×
432
        }
433

434
        try {
435
            $result = $application->run(new Console\Input\ArrayInput($parameters), $commandOutput);
1✔
NEW
436
        } catch (\Exception $exception) {
×
NEW
437
            $this->io->write($commandOutput->fetch());
×
NEW
438
            $this->io->error($exception->getMessage());
×
439

NEW
440
            return false;
×
441
        }
442

443
        if (self::SUCCESS === $result) {
1✔
444
            $this->io->writeln('✅ Updated <info>composer.lock</info> file (content hash change)');
1✔
445

446
            // Add modified lock file to results array to include it in subsequent release operations
447
            foreach ($results as $result) {
1✔
448
                if ($result->file()->fullPath($rootPath) === $composer->getConfig()->getConfigSource()->getName()) {
1✔
NEW
449
                    $results[] = new Result\VersionBumpResult(
×
NEW
450
                        new Config\FileToModify($locker->getJsonFile()->getPath()),
×
NEW
451
                        $result->operations(),
×
NEW
452
                    );
×
453

NEW
454
                    break;
×
455
                }
456
            }
457

458
            return true;
1✔
459
        }
460

NEW
461
        if ($output->isVerbose()) {
×
NEW
462
            $this->io->write($commandOutput->fetch());
×
463
        }
464

NEW
465
        $this->io->error('An error occurred while updating the composer.lock file.');
×
466

NEW
467
        return false;
×
468
    }
469

470
    private function getComposerInstance(): ?Composer
15✔
471
    {
472
        // Composer >= 2.3
473
        if (method_exists($this, 'tryComposer')) {
15✔
474
            return $this->tryComposer();
15✔
475
        }
476

477
        // Composer < 2.3
NEW
478
        return $this->getComposer(false);
×
479
    }
480
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc