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

eliashaeussler / version-bumper / 24362442800

13 Apr 2026 07:24PM UTC coverage: 76.092% (-11.9%) from 87.996%
24362442800

Pull #125

github

eliashaeussler
[FEATURE] Introduce actions
Pull Request #125: [FEATURE] Introduce actions

71 of 258 new or added lines in 20 files covered. (27.52%)

3 existing lines in 3 files now uncovered.

923 of 1213 relevant lines covered (76.09%)

4.14 hits per line

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

91.09
/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 CuyZ\Valinor;
29
use EliasHaeussler\TaskRunner;
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
use Throwable;
39

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

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

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

76
        parent::__construct('bump-version');
15✔
77

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

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

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

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

125
    protected function initialize(Console\Input\InputInterface $input, Console\Output\OutputInterface $output): void
15✔
126
    {
127
        $this->io = new Console\Style\SymfonyStyle($input, $output);
15✔
128
        $this->taskRunner = new TaskRunner\TaskRunner($this->io);
15✔
129
    }
130

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

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

143
            return self::INVALID;
1✔
144
        }
145

146
        if (Filesystem\Path::isRelative($configFile)) {
14✔
147
            $configFile = Filesystem\Path::makeAbsolute($configFile, $rootPath);
1✔
148
        } else {
149
            $rootPath = dirname($configFile);
13✔
150
        }
151

152
        try {
153
            $config = $this->configReader->readFromFile($configFile);
14✔
154

155
            // Override root path from config file
156
            if (null !== $config->rootPath()) {
13✔
157
                $rootPath = $config->rootPath();
13✔
158
            }
159

160
            $results = $this->bumpVersions($config, $rangeOrVersion, $rootPath, $dryRun);
13✔
161

162
            if (null === $results) {
8✔
163
                return self::FAILURE;
2✔
164
            }
165

166
            $this->decorateVersionBumpResults($results, $rootPath);
6✔
167

168
            if ($release && !$this->releaseVersion($results, $rootPath, $config->releaseOptions(), $dryRun)) {
6✔
169
                return self::FAILURE;
5✔
170
            }
171
        } catch (Valinor\Mapper\MappingError $error) {
7✔
172
            $this->decorateMappingError($error, $configFile);
1✔
173

174
            return self::FAILURE;
1✔
175
        } catch (Exception\Exception $exception) {
6✔
176
            $this->io->error($exception->getMessage());
6✔
177

178
            return self::FAILURE;
6✔
179
        } finally {
180
            if ($dryRun) {
14✔
181
                $this->io->note('No write operations were performed (dry-run mode).');
7✔
182
            }
183
        }
184

185
        if ($strict) {
5✔
186
            foreach ($results as $versionBumpResult) {
1✔
187
                if ($versionBumpResult->hasUnmatchedReports()) {
1✔
188
                    return self::FAILURE;
1✔
189
                }
190
            }
191
        }
192

193
        return self::SUCCESS;
4✔
194
    }
195

196
    /**
197
     * @return list<Result\VersionBumpResult>|null
198
     *
199
     * @throws Throwable
200
     */
201
    private function bumpVersions(
13✔
202
        Config\VersionBumperConfig $config,
203
        ?string $rangeOrVersion,
204
        string $rootPath,
205
        bool $dryRun,
206
    ): ?array {
207
        $results = [];
13✔
208

209
        // Auto-detect version range from indicators
210
        if (null !== $rangeOrVersion) {
13✔
211
            $versionRange = Enum\VersionRange::tryFromInput($rangeOrVersion) ?? $rangeOrVersion;
9✔
212
        } elseif ([] !== $config->versionRangeIndicators()) {
4✔
213
            $versionRange = $this->versionRangeDetector->detect($rootPath, $config->versionRangeIndicators());
3✔
214
        } else {
215
            $this->io->error('Please provide a version range or explicit version to bump in configured files.');
1✔
216
            $this->io->block(
1✔
217
                'You can also enable auto-detection by adding version range indicators to your configuration file.',
1✔
218
                null,
1✔
219
                'fg=cyan',
1✔
220
                '💡 ',
1✔
221
            );
1✔
222

223
            return null;
1✔
224
        }
225

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

230
            return null;
1✔
231
        }
232

233
        $this->decorateAppliedPresets($config->presets());
10✔
234

235
        // Execute pre-actions
236
        if (!$dryRun && !$this->executeActions($config, Version\Action\ActionType::PreAction, $results, $rootPath)) {
10✔
NEW
237
            return null;
×
238
        }
239

240
        // Bump versions
241
        $versionBumpResults = $this->taskRunner->run(
10✔
242
            'Bumping versions in files',
10✔
243
            fn () => $this->bumper->bump($config->filesToModify(), $rootPath, $versionRange, $dryRun),
10✔
244
        );
10✔
245

246
        // Merged results from version bump with global results
247
        $this->mergeResults($versionBumpResults, $results, $rootPath);
6✔
248

249
        // Execute post-actions
250
        if (!$dryRun && !$this->executeActions($config, Version\Action\ActionType::PostAction, $results, $rootPath)) {
6✔
NEW
251
            return null;
×
252
        }
253

254
        return $results;
6✔
255
    }
256

257
    /**
258
     * @param list<Result\VersionBumpResult> $results
259
     */
260
    private function executeActions(
3✔
261
        Config\VersionBumperConfig $config,
262
        Version\Action\ActionType $type,
263
        array &$results,
264
        string $rootPath,
265
    ): bool {
266
        if (!$config->hasActions($type)) {
3✔
267
            return true;
3✔
268
        }
269

270
        try {
271
            return $this->taskRunner->run(
1✔
272
                sprintf('Executing %s', $type->label(true)),
1✔
273
                function (TaskRunner\RunnerContext $context) use ($config, &$results, $rootPath, $type): bool {
1✔
274
                    $dispatcher = new Version\ActionDispatcher($rootPath, $this->io);
1✔
275

276
                    foreach ($config->filesToModify() as $fileToModify) {
1✔
277
                        $actionExecutionResult = $dispatcher->dispatchAll(
1✔
278
                            $fileToModify->getActionsByType($type),
1✔
279
                            $fileToModify,
1✔
280
                        );
1✔
281

282
                        if ($actionExecutionResult->failed()) {
1✔
NEW
283
                            if ($context->output->isVerbose() && $actionExecutionResult->hasOutput()) {
×
NEW
284
                                $context->output->writeln($actionExecutionResult->output());
×
285
                            }
286

NEW
287
                            throw new Exception\ActionExecutionFailed($actionExecutionResult);
×
288
                        }
289

290
                        $this->mergeResults($actionExecutionResult->results(), $results, $rootPath);
1✔
291
                    }
292

293
                    return true;
1✔
294
                },
1✔
295
            );
1✔
NEW
296
        } catch (Exception\ActionExecutionFailed) {
×
NEW
297
            $this->io->error(
×
NEW
298
                sprintf('An error occured while executing %s.', $type->label(true)),
×
NEW
299
            );
×
300

NEW
301
            return false;
×
NEW
302
        } catch (Throwable $exception) {
×
NEW
303
            $this->io->error($exception->getMessage());
×
304

NEW
305
            return false;
×
306
        }
307
    }
308

309
    /**
310
     * @param list<Result\VersionBumpResult> $results
311
     *
312
     * @throws Exception\Exception
313
     */
314
    private function releaseVersion(array $results, string $rootPath, Config\ReleaseOptions $options, bool $dryRun): bool
2✔
315
    {
316
        $this->io->title('Release');
2✔
317

318
        try {
319
            $releaseResult = $this->releaser->release($results, $rootPath, $options, $dryRun);
2✔
320

321
            $this->decorateVersionReleaseResult($releaseResult);
1✔
322

323
            return true;
1✔
324
        } catch (Exception\Exception $exception) {
1✔
325
            throw $exception;
1✔
326
        } catch (\Exception $exception) {
×
327
            $this->io->error('Git error during release: '.$exception->getMessage());
×
328
        }
329

330
        return false;
×
331
    }
332

333
    /**
334
     * @param list<Result\VersionBumpResult> $source
335
     * @param list<Result\VersionBumpResult> $target
336
     */
337
    private function mergeResults(array $source, array &$target, string $rootPath): void
6✔
338
    {
339
        foreach ($source as $sourceResult) {
6✔
340
            $finalResult = null;
6✔
341

342
            foreach ($target as $targetResult) {
6✔
343
                if ($targetResult->file()->equals($sourceResult->file(), $rootPath)) {
5✔
NEW
344
                    $finalResult = $targetResult;
×
NEW
345
                    break;
×
346
                }
347
            }
348

349
            if (null !== $finalResult) {
6✔
NEW
350
                $finalResult->merge($sourceResult);
×
351
            } else {
352
                $target[] = $sourceResult;
6✔
353
            }
354
        }
355
    }
356

357
    /**
358
     * @param list<Config\Preset\Preset> $presets
359
     */
360
    private function decorateAppliedPresets(array $presets): void
10✔
361
    {
362
        if ([] === $presets || !$this->io->isVerbose()) {
10✔
363
            return;
9✔
364
        }
365

366
        $this->io->title('Applied presets');
1✔
367

368
        $this->io->listing(
1✔
369
            array_map(
1✔
370
                static fn (Config\Preset\Preset $preset) => sprintf(
1✔
371
                    '%s <fg=gray>(%s)</>',
1✔
372
                    $preset::getDescription(),
1✔
373
                    $preset::getIdentifier(),
1✔
374
                ),
1✔
375
                $presets,
1✔
376
            ),
1✔
377
        );
1✔
378
    }
379

380
    /**
381
     * @param list<Result\VersionBumpResult> $results
382
     */
383
    private function decorateVersionBumpResults(array $results, string $rootPath): void
6✔
384
    {
385
        $titleDisplayed = false;
6✔
386

387
        usort(
6✔
388
            $results,
6✔
389
            static fn (
6✔
390
                Result\VersionBumpResult $a,
6✔
391
                Result\VersionBumpResult $b,
6✔
392
            ) => $a->file()->fullPath($rootPath) <=> $b->file()->fullPath($rootPath),
5✔
393
        );
6✔
394

395
        foreach ($results as $result) {
6✔
396
            if (!$result->hasOperations()) {
6✔
397
                continue;
4✔
398
            }
399

400
            $path = $result->file()->path();
6✔
401
            $groupedOperations = $result->groupedOperations();
6✔
402
            $hasOnlySkippedOperations = [] === array_filter(
6✔
403
                $groupedOperations,
6✔
404
                static fn (array $operations) => Enum\OperationState::Skipped !== reset($operations)->state(),
6✔
405
            );
6✔
406

407
            if (Filesystem\Path::isAbsolute($path)) {
6✔
408
                $path = Filesystem\Path::makeRelative($path, $rootPath);
1✔
409
            }
410

411
            if (!$titleDisplayed) {
6✔
412
                $this->io->title('Bumped versions');
6✔
413
                $titleDisplayed = true;
6✔
414
            }
415

416
            $this->io->section($path);
6✔
417

418
            foreach ($groupedOperations as $operations) {
6✔
419
                $operation = reset($operations);
6✔
420
                $numberOfOperations = count($operations);
6✔
421
                $state = $operation->state();
6✔
422

423
                if (Enum\OperationState::Skipped === $state && !$hasOnlySkippedOperations) {
6✔
424
                    continue;
3✔
425
                }
426

427
                $message = match ($state) {
6✔
428
                    Enum\OperationState::Modified => sprintf(
6✔
429
                        '✅ Bumped version from "%s" to "%s"',
6✔
430
                        $operation->source()?->full() ?? '',
6✔
431
                        $operation->target()?->full() ?? '',
6✔
432
                    ),
6✔
433
                    Enum\OperationState::Regenerated => '🔁 Regenerated lock file (via post-action)',
5✔
434
                    Enum\OperationState::Skipped => '⏩ Skipped file due to unmodified contents',
4✔
435
                    Enum\OperationState::Unmatched => '❓ Unmatched file pattern: '.$operation->pattern()?->original(),
4✔
436
                };
6✔
437

438
                if ($numberOfOperations > 1) {
6✔
439
                    $message .= sprintf(' (%dx)', $numberOfOperations);
3✔
440
                }
441

442
                $this->io->writeln($message);
6✔
443
            }
444
        }
445
    }
446

447
    private function decorateVersionReleaseResult(Result\VersionReleaseResult $result): void
1✔
448
    {
449
        $numberOfCommittedFiles = count($result->committedFiles());
1✔
450
        $releaseInformation = [
1✔
451
            sprintf('Added %d file%s.', $numberOfCommittedFiles, 1 !== $numberOfCommittedFiles ? 's' : ''),
1✔
452
            sprintf('Committed: <info>%s</info>', $result->commitMessage()),
1✔
453
        ];
1✔
454

455
        if (null !== $result->commitId()) {
1✔
456
            $releaseInformation[] = sprintf('Commit hash: %s', $result->commitId());
×
457
        }
458

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

461
        $this->io->listing($releaseInformation);
1✔
462
    }
463

464
    private function decorateMappingError(Valinor\Mapper\MappingError $error, string $configFile): void
1✔
465
    {
466
        $errorMessages = [];
1✔
467
        $errors = $error->messages()->errors();
1✔
468

469
        $this->io->error(
1✔
470
            sprintf('The config file "%s" is invalid.', $configFile),
1✔
471
        );
1✔
472

473
        foreach ($errors as $propertyError) {
1✔
474
            $errorMessages[] = sprintf('%s: %s', $propertyError->path(), $propertyError->toString());
1✔
475
        }
476

477
        $this->io->listing($errorMessages);
1✔
478
    }
479

480
    private function readConfigFileFromRootPackage(): ?string
15✔
481
    {
482
        $composer = $this->getComposerInstance();
15✔
483

484
        if (null === $composer) {
15✔
485
            return null;
15✔
486
        }
487

488
        $extra = $composer->getPackage()->getExtra();
1✔
489
        /* @phpstan-ignore offsetAccess.nonOffsetAccessible */
490
        $configFile = $extra['version-bumper']['config-file'] ?? null;
1✔
491

492
        if (is_string($configFile) && '' !== trim($configFile)) {
1✔
493
            return $configFile;
1✔
494
        }
495

496
        return null;
×
497
    }
498

499
    private function getComposerInstance(): ?Composer
15✔
500
    {
501
        // Composer >= 2.3
502
        if (method_exists($this, 'tryComposer')) {
15✔
503
            return $this->tryComposer();
15✔
504
        }
505

506
        // Composer < 2.3
507
        return $this->getComposer(false);
×
508
    }
509
}
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