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

eliashaeussler / version-bumper / 19470488180

18 Nov 2025 02:55PM UTC coverage: 88.577% (-0.1%) from 88.7%
19470488180

push

github

web-flow
Merge pull request #104 from eliashaeussler/task/codeclimate

[TASK] Drop CodeClimate integration

884 of 998 relevant lines covered (88.58%)

4.9 hits per line

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

96.81
/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-2025 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\VersionBumper\Config;
30
use EliasHaeussler\VersionBumper\Enum;
31
use EliasHaeussler\VersionBumper\Exception;
32
use EliasHaeussler\VersionBumper\Result;
33
use EliasHaeussler\VersionBumper\Version;
34
use GitElephant\Command\Caller;
35
use Symfony\Component\Console;
36
use Symfony\Component\Filesystem;
37

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

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

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

72
        parent::__construct('bump-version');
14✔
73

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

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

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

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

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

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

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

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

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

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

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

154
            [$config, $results] = $result;
5✔
155

156
            if ($release && !$this->releaseVersion($results, $rootPath, $config->releaseOptions(), $dryRun)) {
5✔
157
                return self::FAILURE;
1✔
158
            }
159
        } finally {
160
            if ($dryRun) {
13✔
161
                $this->io->note('No write operations were performed (dry-run mode).');
7✔
162
            }
163
        }
164

165
        if ($strict) {
4✔
166
            foreach ($results as $versionBumpResult) {
1✔
167
                if ($versionBumpResult->hasUnmatchedReports()) {
1✔
168
                    return self::FAILURE;
1✔
169
                }
170
            }
171
        }
172

173
        return self::SUCCESS;
3✔
174
    }
175

176
    /**
177
     * @return array{Config\VersionBumperConfig, list<Result\VersionBumpResult>}|null
178
     */
179
    private function bumpVersions(string $configFile, ?string $rangeOrVersion, string $rootPath, bool $dryRun): ?array
13✔
180
    {
181
        try {
182
            $config = $this->configReader->readFromFile($configFile);
13✔
183
            $finalRootPath = $config->rootPath() ?? $rootPath;
12✔
184

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

199
                return null;
1✔
200
            }
201

202
            // Exit early if version range detection fails
203
            if (null === $versionRange) {
10✔
204
                $this->io->error('Unable to auto-detect version range. Please provide a version range or explicit version instead.');
1✔
205

206
                return null;
1✔
207
            }
208

209
            $this->decorateAppliedPresets($config->presets());
9✔
210

211
            $results = $this->bumper->bump($config->filesToModify(), $finalRootPath, $versionRange, $dryRun);
9✔
212

213
            $this->decorateVersionBumpResults($results, $rootPath);
5✔
214

215
            return [$config, $results];
5✔
216
        } catch (Valinor\Mapper\MappingError $error) {
6✔
217
            $this->decorateMappingError($error, $configFile);
1✔
218
        } catch (Exception\Exception $exception) {
5✔
219
            $this->io->error($exception->getMessage());
5✔
220
        }
221

222
        return null;
6✔
223
    }
224

225
    /**
226
     * @param list<Result\VersionBumpResult> $results
227
     */
228
    private function releaseVersion(array $results, string $rootPath, Config\ReleaseOptions $options, bool $dryRun): bool
2✔
229
    {
230
        $this->io->title('Release');
2✔
231

232
        try {
233
            $releaseResult = $this->releaser->release($results, $rootPath, $options, $dryRun);
2✔
234

235
            $this->decorateVersionReleaseResult($releaseResult);
1✔
236

237
            return true;
1✔
238
        } catch (Exception\Exception $exception) {
1✔
239
            $this->io->error($exception->getMessage());
1✔
240
        } catch (\Exception $exception) {
×
241
            $this->io->error('Git error during release: '.$exception->getMessage());
×
242
        }
243

244
        return false;
1✔
245
    }
246

247
    /**
248
     * @param list<Config\Preset\Preset> $presets
249
     */
250
    private function decorateAppliedPresets(array $presets): void
9✔
251
    {
252
        if ([] === $presets || !$this->io->isVerbose()) {
9✔
253
            return;
8✔
254
        }
255

256
        $this->io->title('Applied presets');
1✔
257

258
        $this->io->listing(
1✔
259
            array_map(
1✔
260
                static fn (Config\Preset\Preset $preset) => sprintf(
1✔
261
                    '%s <fg=gray>(%s)</>',
1✔
262
                    $preset::getDescription(),
1✔
263
                    $preset::getIdentifier(),
1✔
264
                ),
1✔
265
                $presets,
1✔
266
            ),
1✔
267
        );
1✔
268
    }
269

270
    /**
271
     * @param list<Result\VersionBumpResult> $results
272
     */
273
    private function decorateVersionBumpResults(array $results, string $rootPath): void
5✔
274
    {
275
        $titleDisplayed = false;
5✔
276

277
        foreach ($results as $result) {
5✔
278
            if (!$result->hasOperations()) {
5✔
279
                continue;
4✔
280
            }
281

282
            $path = $result->file()->path();
5✔
283
            $groupedOperations = $result->groupedOperations();
5✔
284
            $hasOnlySkippedOperations = [] === array_filter(
5✔
285
                $groupedOperations,
5✔
286
                static fn (array $operations) => Enum\OperationState::Skipped !== reset($operations)->state(),
5✔
287
            );
5✔
288

289
            if (Filesystem\Path::isAbsolute($path)) {
5✔
290
                $path = Filesystem\Path::makeRelative($path, $rootPath);
×
291
            }
292

293
            if (!$titleDisplayed) {
5✔
294
                $this->io->title('Bumped versions');
5✔
295
                $titleDisplayed = true;
5✔
296
            }
297

298
            $this->io->section($path);
5✔
299

300
            foreach ($groupedOperations as $operations) {
5✔
301
                $operation = reset($operations);
5✔
302
                $numberOfOperations = count($operations);
5✔
303
                $state = $operation->state();
5✔
304

305
                if (Enum\OperationState::Skipped === $state && !$hasOnlySkippedOperations) {
5✔
306
                    continue;
3✔
307
                }
308

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

319
                if ($numberOfOperations > 1) {
5✔
320
                    $message .= sprintf(' (%dx)', $numberOfOperations);
3✔
321
                }
322

323
                $this->io->writeln($message);
5✔
324
            }
325
        }
326
    }
327

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

336
        if (null !== $result->commitId()) {
1✔
337
            $releaseInformation[] = sprintf('Commit hash: %s', $result->commitId());
×
338
        }
339

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

342
        $this->io->listing($releaseInformation);
1✔
343
    }
344

345
    private function decorateMappingError(Valinor\Mapper\MappingError $error, string $configFile): void
1✔
346
    {
347
        $errorMessages = [];
1✔
348
        $errors = $error->messages()->errors();
1✔
349

350
        $this->io->error(
1✔
351
            sprintf('The config file "%s" is invalid.', $configFile),
1✔
352
        );
1✔
353

354
        foreach ($errors as $propertyError) {
1✔
355
            $errorMessages[] = sprintf('%s: %s', $propertyError->path(), $propertyError->toString());
1✔
356
        }
357

358
        $this->io->listing($errorMessages);
1✔
359
    }
360

361
    private function readConfigFileFromRootPackage(): ?string
14✔
362
    {
363
        if (method_exists($this, 'tryComposer')) {
14✔
364
            // Composer >= 2.3
365
            $composer = $this->tryComposer();
14✔
366
        } else {
367
            // Composer < 2.3
368
            $composer = $this->getComposer(false);
×
369
        }
370

371
        if (null === $composer) {
14✔
372
            return null;
14✔
373
        }
374

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

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

383
        return null;
×
384
    }
385
}
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