Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
109 / 109
100.00% covered (success)
100.00%
3 / 3
CRAP
100.00% covered (success)
100.00%
1 / 1
VersionCommand
100.00% covered (success)
100.00%
109 / 109
100.00% covered (success)
100.00%
3 / 3
33
100.00% covered (success)
100.00%
1 / 1
 configure
100.00% covered (success)
100.00%
15 / 15
100.00% covered (success)
100.00%
1 / 1
3
 getNextVersion
100.00% covered (success)
100.00%
20 / 20
100.00% covered (success)
100.00%
1 / 1
8
 execute
100.00% covered (success)
100.00%
74 / 74
100.00% covered (success)
100.00%
1 / 1
22
1<?php
2/**
3 * "Version" command for the changelogger tool CLI.
4 *
5 * @package automattic/jetpack-changelogger
6 */
7
8namespace Automattic\Jetpack\Changelogger;
9
10use Automattic\Jetpack\Changelog\ChangeEntry;
11use Symfony\Component\Console\Attribute\AsCommand;
12use Symfony\Component\Console\Command\Command;
13use Symfony\Component\Console\Input\InputArgument;
14use Symfony\Component\Console\Input\InputInterface;
15use Symfony\Component\Console\Input\InputOption;
16use Symfony\Component\Console\Output\OutputInterface;
17
18/**
19 * "Version" command for the changelogger tool CLI.
20 */
21#[AsCommand( 'version', 'Displays versions from the changelog and change files' )]
22class VersionCommand extends Command {
23
24    /**
25     * The default command name
26     *
27     * @var string|null
28     */
29    protected static $defaultName = 'version';
30
31    /**
32     * The default command description
33     *
34     * @var string|null
35     */
36    protected static $defaultDescription = 'Displays versions from the changelog and change files';
37
38    /**
39     * Configures the command.
40     */
41    protected function configure() {
42        $this->setDescription( static::$defaultDescription )
43            ->addArgument( 'which', InputArgument::REQUIRED, 'Version to fetch: <info>previous</>, <info>current</>, or <info>next</>' )
44            ->addOption( 'use-version', null, InputOption::VALUE_REQUIRED, 'When fetching the next version, use this instead of the current version in the changelog' )
45            ->addOption( 'use-significance', null, InputOption::VALUE_REQUIRED, 'When fetching the next version, use this significance instead of using the actual change files' )
46            ->addOption( 'prerelease', 'p', InputOption::VALUE_REQUIRED, 'When fetching the next version, include this prerelease suffix' )
47            ->addOption( 'buildinfo', 'b', InputOption::VALUE_REQUIRED, 'When fetching the next version, include this buildinfo suffix' )
48            ->addOption( 'default-first-version', null, InputOption::VALUE_NONE, 'If the changelog is currently empty, guess a "first" version instead of erroring. When used with <info>current</>, makes it work as <info>next</> in that situation.' )
49            ->setHelp(
50                <<<'EOF'
51The <info>version</info> command reads the versions from the changelog, and outputs the previous, current, or next version based on the change files.
52EOF
53            );
54
55        try {
56            $this->getDefinition()->addOptions( Config::formatterPlugin()->getOptions() );
57        } catch ( \Exception $ex ) { // phpcs:ignore Generic.CodeAnalysis.EmptyStatement.DetectedCatch
58            // Will handle later.
59        }
60        try {
61            $this->getDefinition()->addOptions( Config::versioningPlugin()->getOptions() );
62        } catch ( \Exception $ex ) { // phpcs:ignore Generic.CodeAnalysis.EmptyStatement.DetectedCatch
63            // Will handle later.
64        }
65    }
66
67    /**
68     * Get the next version based on the changelog.
69     *
70     * @param string[]      $versions Existing versions from the changelog.
71     * @param ChangeEntry[] $changes Changes.
72     * @param array         $extra Extra components for the version.
73     * @return string $version
74     * @throws \InvalidArgumentException If something is wrong.
75     */
76    public static function getNextVersion( array $versions, array $changes, array $extra ) {
77        $versioning = Config::versioningPlugin();
78
79        $curversion     = $versions[0];
80        $releaseversion = null;
81        foreach ( $versions as $v ) {
82            try {
83                $parsed = $versioning->parseVersion( $v );
84            } catch ( \Exception $ex ) {
85                break;
86            }
87            if ( null === $parsed['prerelease'] ) {
88                $releaseversion = $parsed['version'];
89                break;
90            }
91        }
92
93        // Simple case, current version is a release version.
94        if ( $curversion === $releaseversion ) {
95            return $versioning->nextVersion( $curversion, $changes, $extra );
96        }
97
98        // Some DWIM going on here, when the current version is a prerelease:
99        // 1. First, find the most recent non-prerelease version and calculate "next" based on that.
100        // 2. If the above returned a version earlier than the most recent version, re-normalize with the new $extra.
101        // This handles the situation where you're going from 1.2.3-alpha to 1.2.3-beta.
102        // 3. If that returned an earlier version too, bump to the next version from the most recent version.
103        // This handles the situation where you have 1.2.3-beta to eventually make 1.2.3 while meanwhile you're looking at the following -alpha version.
104        if ( null !== $releaseversion ) {
105            $newversion = $versioning->nextVersion( $releaseversion, $changes, $extra );
106            if ( $versioning->compareVersions( $curversion, $newversion ) < 0 ) {
107                return $newversion;
108            }
109        }
110        $newversion = $versioning->normalizeVersion( $curversion, $extra );
111        if ( $versioning->compareVersions( $curversion, $newversion ) < 0 ) {
112            return $newversion;
113        }
114        return $versioning->nextVersion( $curversion, $changes, $extra );
115    }
116
117    /**
118     * Executes the command.
119     *
120     * @param InputInterface  $input InputInterface.
121     * @param OutputInterface $output OutputInterface.
122     * @return int 0 if everything went fine, or an exit code.
123     */
124    protected function execute( InputInterface $input, OutputInterface $output ): int {
125        try {
126            $formatter = Config::formatterPlugin();
127            $formatter->setIO( $input, $output );
128            $versioning = Config::versioningPlugin();
129            $versioning->setIO( $input, $output );
130        } catch ( \Exception $ex ) {
131            $output->writeln( "<error>{$ex->getMessage()}</>" );
132            return 1;
133        }
134
135        $which = (string) $input->getArgument( 'which' );
136        $l     = '' === $which ? 1 : strlen( $which );
137        $ok    = false;
138        foreach ( array( 'previous', 'current', 'next' ) as $w ) {
139            if ( substr( $w, 0, $l ) === $which ) {
140                $which = $w;
141                $ok    = true;
142            }
143        }
144        if ( ! $ok ) {
145            $output->writeln( "<error>Don't know how to fetch the \"$which\" version</>" );
146            return 1;
147        }
148
149        // Read current versions, either from command line or changelog.
150        if ( 'next' === $which && $input->getOption( 'use-version' ) !== null ) {
151            $versions = array( (string) $input->getOption( 'use-version' ) );
152        } else {
153            $file = Config::changelogFile();
154            if ( ! file_exists( $file ) ) {
155                $output->writeln( "<error>Changelog file $file does not exist</>" );
156                return 1;
157            }
158
159            error_clear_last();
160            // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
161            $contents = @file_get_contents( $file );
162            // @codeCoverageIgnoreStart
163            if ( ! is_string( $contents ) ) {
164                $err = error_get_last();
165                $output->writeln( "<error>Failed to read $file: {$err['message']}</>" );
166                return 1;
167            }
168            // @codeCoverageIgnoreEnd
169
170            try {
171                $versions = $formatter->parse( $contents )->getVersions();
172            } catch ( \Exception $ex ) {
173                $output->writeln( "<error>Failed to parse changelog: {$ex->getMessage()}</>" );
174                return 1;
175            }
176
177            if ( count( $versions ) === 0 && ! $input->getOption( 'default-first-version' ) ) {
178                $output->writeln( '<error>Changelog file contains no entries</>' );
179                return 1;
180            }
181        }
182
183        // If we want the previous, return it from the changelog.
184        if ( 'previous' === $which ) {
185            if ( count( $versions ) < 2 ) {
186                $output->writeln( '<error>Changelog file contains no previous version</>' );
187                return 1;
188            }
189            $output->writeln( $versions[1], OutputInterface::VERBOSITY_QUIET );
190            return 0;
191        }
192
193        // For current and next, if the changelog was empty of versions (and it didn't error out
194        // earlier) then guess the first version.
195        $extra = array(
196            'prerelease' => $input->getOption( 'prerelease' ),
197            'buildinfo'  => $input->getOption( 'buildinfo' ),
198        );
199        if ( ! $versions ) {
200            try {
201                $output->writeln( $versioning->firstVersion( $extra ), OutputInterface::VERBOSITY_QUIET );
202                return 0;
203            } catch ( \Exception $ex ) {
204                $output->writeln( "<error>{$ex->getMessage()}</>" );
205                return 1;
206            }
207        }
208
209        // Otherwise, for current, return the current version.
210        if ( 'current' === $which ) {
211            $output->writeln( $versions[0], OutputInterface::VERBOSITY_QUIET );
212            return 0;
213        }
214
215        // We want the next version. Determine it based on changes or command line.
216        if ( $input->getOption( 'use-significance' ) ) {
217            try {
218                $changes = array(
219                    $formatter->newChangeEntry(
220                        array(
221                            'significance' => $input->getOption( 'use-significance' ),
222                            'content'      => 'Dummy',
223                        )
224                    ),
225                );
226            } catch ( \Exception $ex ) {
227                $output->writeln( "<error>{$ex->getMessage()}</>" );
228                return 1;
229            }
230        } else {
231            $dir = Config::changesDir();
232            if ( is_dir( $dir ) ) {
233                $dummy   = null;
234                $changes = Utils::loadAllChanges( Config::changesDir(), Config::types(), $formatter, $output, $dummy, array( 'skip-data' => true ) );
235            } else {
236                $output->writeln( '<warning>Changes directory does not exist</>' );
237                $changes = array();
238            }
239        }
240        try {
241            $output->writeln( self::getNextVersion( $versions, $changes, $extra ), OutputInterface::VERBOSITY_QUIET );
242            return 0;
243        } catch ( \Exception $ex ) {
244            $output->writeln( "<error>{$ex->getMessage()}</>" );
245            return 1;
246        }
247    }
248}