Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
325 / 325
100.00% covered (success)
100.00%
16 / 16
CRAP
100.00% covered (success)
100.00%
1 / 1
WriteCommand
100.00% covered (success)
100.00%
325 / 325
100.00% covered (success)
100.00%
16 / 16
107
100.00% covered (success)
100.00%
1 / 1
 configure
100.00% covered (success)
100.00%
22 / 22
100.00% covered (success)
100.00%
1 / 1
3
 askToContinue
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
5
 loadChangelog
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
5
 addEntry
100.00% covered (success)
100.00%
17 / 17
100.00% covered (success)
100.00%
1 / 1
5
 writeChangelog
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
3
 deleteChanges
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
4
 loadChanges
100.00% covered (success)
100.00%
20 / 20
100.00% covered (success)
100.00%
1 / 1
10
 splitPrSuffixes
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
2
 cleanPrSuffix
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
2
 deduplicateChanges
100.00% covered (success)
100.00%
42 / 42
100.00% covered (success)
100.00%
1 / 1
13
 doChangesHaveContent
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
3
 doAmendChanges
100.00% covered (success)
100.00%
20 / 20
100.00% covered (success)
100.00%
1 / 1
8
 sortChanges
100.00% covered (success)
100.00%
15 / 15
100.00% covered (success)
100.00%
1 / 1
2
 getUseVersion
100.00% covered (success)
100.00%
40 / 40
100.00% covered (success)
100.00%
1 / 1
17
 nextVersion
100.00% covered (success)
100.00%
41 / 41
100.00% covered (success)
100.00%
1 / 1
11
 execute
100.00% covered (success)
100.00%
40 / 40
100.00% covered (success)
100.00%
1 / 1
14
1<?php
2/**
3 * "Write" 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 Automattic\Jetpack\Changelog\Changelog;
12use InvalidArgumentException;
13use Symfony\Component\Console\Attribute\AsCommand;
14use Symfony\Component\Console\Command\Command;
15use Symfony\Component\Console\Exception\MissingInputException;
16use Symfony\Component\Console\Helper\QuestionHelper;
17use Symfony\Component\Console\Input\InputInterface;
18use Symfony\Component\Console\Input\InputOption;
19use Symfony\Component\Console\Output\OutputInterface;
20use Symfony\Component\Console\Question\ChoiceQuestion;
21use Symfony\Component\Console\Question\ConfirmationQuestion;
22
23/**
24 * "Write" command for the changelogger tool CLI.
25 */
26#[AsCommand( 'write', 'Updates the changelog from change files' )]
27class WriteCommand extends Command {
28
29    const OK_EXIT            = 0;
30    const NO_CHANGE_EXIT     = 1;
31    const ASKED_EXIT         = 2;
32    const FATAL_EXIT         = 3;
33    const DELETE_FAILED_EXIT = 4;
34
35    /**
36     * The default command name.
37     *
38     * @var string|null
39     */
40    protected static $defaultName = 'write';
41
42    /**
43     * The default command description
44     *
45     * @var string|null
46     */
47    protected static $defaultDescription = 'Updates the changelog from change files';
48
49    /**
50     * The FormatterPlugin in use.
51     *
52     * @var FormatterPlugin
53     */
54    protected $formatter;
55
56    /**
57     * The VersioningPlugin in use.
58     *
59     * @var VersioningPlugin
60     */
61    protected $versioning;
62
63    /**
64     * Whether we already asked about there being no changes.
65     *
66     * @var bool
67     */
68    protected $askedNoChanges = false;
69
70    /**
71     * Configures the command.
72     */
73    protected function configure() {
74        $this->setDescription( static::$defaultDescription )
75            ->addOption( 'amend', null, InputOption::VALUE_NONE, 'Amend the latest version instead of creating a new one' )
76            ->addOption( 'yes', null, InputOption::VALUE_NONE, 'Default all questions to "yes" instead of "no". Particularly useful for non-interactive mode' )
77            ->addOption( 'use-version', null, InputOption::VALUE_REQUIRED, 'Use this version instead of determining the version automatically' )
78            ->addOption( 'use-significance', null, InputOption::VALUE_REQUIRED, 'When determining the new version, use this significance instead of using the actual change files' )
79            ->addOption( 'prerelease', 'p', InputOption::VALUE_REQUIRED, 'When determining the new version, include this prerelease suffix' )
80            ->addOption( 'buildinfo', 'b', InputOption::VALUE_REQUIRED, 'When fetching the next version, include this buildinfo suffix' )
81            ->addOption( 'release-date', null, InputOption::VALUE_REQUIRED, 'Release date, as a valid PHP date or "unreleased"', 'now' )
82            ->addOption( 'default-first-version', null, InputOption::VALUE_NONE, 'If the changelog is currently empty, guess a "first" version instead of erroring' )
83            ->addOption( 'deduplicate', null, InputOption::VALUE_REQUIRED, 'Deduplicate new changes against the last N versions. Set -1 to disable deduplication entirely.', 0 )
84            ->addOption( 'prologue', null, InputOption::VALUE_REQUIRED, 'Prologue text for the new changelog entry' )
85            ->addOption( 'epilogue', null, InputOption::VALUE_REQUIRED, 'Epilogue text for the new changelog entry' )
86            ->addOption( 'link', null, InputOption::VALUE_REQUIRED, 'Link for the new changelog entry' )
87            ->addOption( 'add-pr-num', null, InputOption::VALUE_NONE, 'Try to append the GH PR number to each entry. Commit subject must end like: (#123)' )
88            ->setHelp(
89                <<<'EOF'
90The <info>write</info> command adds a new changelog entry based on the changes files, and removes the changes files.
91
92Various edge cases will interactively prompt for information if possible. Use <info>--no-interaction</info> to avoid
93this, along with <info>--yes</info> if you want to proceed through all prompts instead of stopping.
94
95Exit codes are:
96
97* 0: Success.
98* 1: No changes were found, and continuing wasn't forced.
99* 2: A non-fatal error was encountered and continuing wasn't forced.
100* 3: A fatal error was encountered.
101* 4: Changelog was successfully updated, but changes files could not be removed.
102EOF
103            );
104
105        try {
106            $this->getDefinition()->addOptions( Config::formatterPlugin()->getOptions() );
107        } catch ( \Exception $ex ) { // phpcs:ignore Generic.CodeAnalysis.EmptyStatement.DetectedCatch
108            // Will handle later.
109        }
110        try {
111            $this->getDefinition()->addOptions( Config::versioningPlugin()->getOptions() );
112        } catch ( \Exception $ex ) { // phpcs:ignore Generic.CodeAnalysis.EmptyStatement.DetectedCatch
113            // Will handle later.
114        }
115    }
116
117    /**
118     * Ask to continue.
119     *
120     * @param InputInterface  $input InputInterface.
121     * @param OutputInterface $output OutputInterface.
122     * @param string          $msg Situation being asked about.
123     * @return bool
124     */
125    private function askToContinue( InputInterface $input, OutputInterface $output, $msg ) {
126        $yes = (bool) $input->getOption( 'yes' );
127
128        if ( ! $input->isInteractive() ) {
129            if ( $yes ) {
130                $output->writeln( "<warning>$msg</> Continuing anyway." );
131                return true;
132            }
133            $output->writeln( "<error>$msg</>" );
134            return false;
135        }
136        try {
137            $question = new ConfirmationQuestion( "$msg Proceed? " . ( $yes ? '[Y/n] ' : '[y/N] ' ), $yes );
138            $helper   = $this->getHelper( 'question' );
139            '@phan-var QuestionHelper $helper';
140            return $helper->ask( $input, $output, $question );
141        } catch ( MissingInputException $ex ) { // @codeCoverageIgnore
142            $output->writeln( 'Got EOF when attempting to query user, aborting.', OutputInterface::VERBOSITY_VERBOSE ); // @codeCoverageIgnore
143            return false; // @codeCoverageIgnore
144        }
145    }
146
147    /**
148     * Load the changelog.
149     *
150     * @param InputInterface  $input InputInterface.
151     * @param OutputInterface $output OutputInterface.
152     * @return Changelog|int Changelog if everything went fine, or an exit code.
153     */
154    protected function loadChangelog( InputInterface $input, OutputInterface $output ) {
155        // Load changelog.
156        $file = Config::changelogFile();
157        if ( ! file_exists( $file ) ) {
158            if ( ! $this->askToContinue( $input, $output, "Changelog file $file does not exist!" ) ) {
159                return self::ASKED_EXIT;
160            }
161            $changelog = new Changelog();
162        } else {
163            $output->writeln( "Reading changelog from $file...", OutputInterface::VERBOSITY_DEBUG );
164            error_clear_last();
165            // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
166            $contents = @file_get_contents( $file );
167            // @codeCoverageIgnoreStart
168            if ( ! is_string( $contents ) ) {
169                $err = error_get_last();
170                $output->writeln( "<error>Failed to read $file: {$err['message']}</>" );
171                return self::FATAL_EXIT;
172            }
173            // @codeCoverageIgnoreEnd
174            try {
175                $changelog = $this->formatter->parse( $contents );
176            } catch ( \Exception $ex ) {
177                $output->writeln( "<error>Failed to parse changelog: {$ex->getMessage()}</>" );
178                return self::FATAL_EXIT;
179            }
180        }
181        return $changelog;
182    }
183
184    /**
185     * Add the entry to the changelog.
186     *
187     * @param InputInterface  $input InputInterface.
188     * @param OutputInterface $output OutputInterface.
189     * @param Changelog       $changelog Changelog.
190     * @param string          $version Version.
191     * @param ChangeEntry[]   $changes Changes.
192     * @return int
193     */
194    protected function addEntry( InputInterface $input, OutputInterface $output, Changelog $changelog, $version, array $changes ) {
195        $output->writeln( 'Creating new changelog entry.', OutputInterface::VERBOSITY_DEBUG );
196        $data = array(
197            'prologue'  => (string) $input->getOption( 'prologue' ),
198            'epilogue'  => (string) $input->getOption( 'epilogue' ),
199            'link'      => $input->getOption( 'link' ),
200            'changes'   => $changes,
201            'timestamp' => (string) $input->getOption( 'release-date' ),
202        );
203        if ( null === $data['link'] && $changelog->getLatestEntry() ) {
204            $data['link'] = Config::link( $changelog->getLatestEntry()->getVersion(), $version );
205        }
206        if ( 'unreleased' === $data['timestamp'] ) {
207            $data['timestamp'] = null;
208        }
209        try {
210            $changelog->addEntry( $this->formatter->newChangelogEntry( $version, $data ) );
211        } catch ( InvalidArgumentException $ex ) {
212            $output->writeln( "<error>Failed to create changelog entry: {$ex->getMessage()}</>" );
213            return self::FATAL_EXIT;
214        }
215        return self::OK_EXIT;
216    }
217
218    /**
219     * Write the changelog.
220     *
221     * @param InputInterface  $input InputInterface.
222     * @param OutputInterface $output OutputInterface.
223     * @param Changelog       $changelog Changelog.
224     * @return int
225     */
226    protected function writeChangelog( InputInterface $input, OutputInterface $output, Changelog $changelog ) {
227        $file = Config::changelogFile();
228        $output->writeln( "Writing changelog to $file...", OutputInterface::VERBOSITY_DEBUG );
229        try {
230            $contents = $this->formatter->format( $changelog );
231        } catch ( InvalidArgumentException $ex ) {
232            $output->writeln( "<error>Failed to write the changelog: {$ex->getMessage()}</>" );
233            return self::FATAL_EXIT;
234        }
235
236        error_clear_last();
237        // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
238        $ok = @file_put_contents( $file, $contents );
239        if ( strlen( $contents ) !== $ok ) {
240            $err = error_get_last();
241            $output->writeln( "<error>Failed to write $file: {$err['message']}</>" );
242            return self::FATAL_EXIT;
243        }
244
245        return self::OK_EXIT;
246    }
247
248    /**
249     * Delete the change files.
250     *
251     * @param InputInterface  $input InputInterface.
252     * @param OutputInterface $output OutputInterface.
253     * @param array           $files Files returned from `loadChanges()`.
254     * @return int
255     */
256    protected function deleteChanges( InputInterface $input, OutputInterface $output, array $files ) {
257        $dir = Config::changesDir();
258        $ret = self::OK_EXIT;
259        foreach ( $files as $name => $flag ) {
260            if ( $flag >= 2 ) {
261                continue;
262            }
263            error_clear_last();
264            // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
265            $ok = @unlink( $dir . DIRECTORY_SEPARATOR . $name );
266            if ( $ok ) {
267                $output->writeln( "Deleted change file $name.", OutputInterface::VERBOSITY_DEBUG );
268            } else {
269                $err = error_get_last();
270                $output->writeln( "<warning>Failed to delete $name: {$err['message']}" );
271                $ret = self::DELETE_FAILED_EXIT;
272            }
273        }
274        return $ret;
275    }
276
277    /**
278     * Load the changes.
279     *
280     * @param InputInterface  $input InputInterface.
281     * @param OutputInterface $output OutputInterface.
282     * @return array Array of [ $code, $changes, $files ].
283     */
284    protected function loadChanges( InputInterface $input, OutputInterface $output ) {
285        $dir = Config::changesDir();
286        if ( ! is_dir( $dir ) ) {
287            $this->askedNoChanges = true;
288            if ( ! $this->askToContinue( $input, $output, 'Changes directory does not exist, so there are no changes to write!' ) ) {
289                return array( self::NO_CHANGE_EXIT, null, null );
290            }
291            return array( self::OK_EXIT, array(), array() );
292        }
293
294        $output->writeln( "Reading changes from $dir...", OutputInterface::VERBOSITY_DEBUG );
295        $files         = null; // Make phpcs happy.
296        $input_options = array(
297            'add-pr-num' => $input->getOption( 'add-pr-num' ),
298        );
299        $changes       = Utils::loadAllChanges( $dir, Config::types(), $this->formatter, $output, $files, $input_options );
300        $max           = $files ? max( $files ) : 0;
301        if ( $max > 0 && ! $this->askToContinue( $input, $output, ( $max > 1 ? 'Errors' : 'Warnings' ) . ' were encountered while reading changes!' ) ) {
302            return array( self::ASKED_EXIT, null, null );
303        }
304        if ( ! $changes && ! $this->askedNoChanges ) {
305            $this->askedNoChanges = true;
306            if ( ! $this->askToContinue( $input, $output, 'No changes were found!' ) ) {
307                return array( self::NO_CHANGE_EXIT, null, null );
308            }
309        }
310        return array( self::OK_EXIT, $changes, $files );
311    }
312
313    /**
314     * Extract trailing PR number links (e.g. ` [#123]`) from the change string.
315     *
316     * @param string $content Change string.
317     * @return array{string,string[]} Separated change text and PR number links.
318     */
319    protected static function splitPrSuffixes( $content ) {
320        if ( ! preg_match( '/(?: \[#\d+\])+$/', $content, $m ) ) {
321            return array( $content, array() );
322        }
323        return array(
324            substr( $content, 0, -strlen( $m[0] ) ),
325            explode( ' ', trim( $m[0] ) ),
326        );
327    }
328
329    /**
330     * Sort and deduplicate the trailing PR number suffix.
331     *
332     * @param ChangeEntry $change Change to update.
333     */
334    protected static function cleanPrSuffix( ChangeEntry $change ) {
335        list( $content, $prs ) = self::splitPrSuffixes( $change->getContent() );
336        if ( ! $prs ) {
337            return;
338        }
339
340        $prs = array_unique( $prs );
341        sort( $prs, SORT_NATURAL );
342        $content .= ' ' . implode( ' ', $prs );
343        $change->setContent( $content );
344    }
345
346    /**
347     * Deduplicate changes.
348     *
349     * @param InputInterface  $input InputInterface.
350     * @param OutputInterface $output OutputInterface.
351     * @param Changelog       $changelog Changelog.
352     * @param ChangeEntry[]   $changes Changes.
353     * @return int
354     */
355    protected function deduplicateChanges( InputInterface $input, OutputInterface $output, Changelog $changelog, array &$changes ) {
356        // Deduplicate changes.
357        if ( ! $changes ) {
358            $output->writeln( 'Skipping deduplication, there are no changes.', OutputInterface::VERBOSITY_DEBUG );
359            return self::OK_EXIT;
360        }
361
362        $depth = (int) $input->getOption( 'deduplicate' );
363        if ( $depth < 0 ) {
364            $output->writeln( "Skipping deduplication, --deduplicate is $depth.", OutputInterface::VERBOSITY_DEBUG );
365            return self::OK_EXIT;
366        }
367
368        $dedup = array();
369        if ( $depth > 0 ) {
370            $output->writeln( "Deduplicating changes from the last $depth version(s)...", OutputInterface::VERBOSITY_DEBUG );
371            foreach ( array_slice( $changelog->getEntries(), 0, $depth ) as $entry ) {
372                foreach ( $entry->getChanges() as $change ) {
373                    list( $key, $prs ) = self::splitPrSuffixes( $change->getContent() );
374                    $dedup[ $key ]     = array_merge( $dedup[ $key ] ?? array(), $prs );
375                }
376            }
377            unset( $dedup[''] );
378        } else {
379            $output->writeln( 'Deduplicating changes in the current version...', OutputInterface::VERBOSITY_DEBUG );
380        }
381        $seen    = array();
382        $changes = array_filter(
383            $changes,
384            function ( $change, $name ) use ( $dedup, &$seen, $output ) {
385                list( $key, $prs ) = self::splitPrSuffixes( $change->getContent() );
386                if ( isset( $dedup[ $key ] ) ) {
387                    // Keep only PR numbers that the previous versions don't already list.
388                    $prs = array_diff( $prs, $dedup[ $key ] );
389                    if ( ! $prs ) {
390                        $output->writeln( "Found duplicate change in $name.", OutputInterface::VERBOSITY_DEBUG );
391                        return false;
392                    }
393                    $change->setContent( $key . ' ' . implode( ' ', $prs ) );
394                }
395                if ( isset( $seen[ $key ] ) ) {
396                    $output->writeln( "Found duplicate change in $name. Merging PR numbers.", OutputInterface::VERBOSITY_DEBUG );
397                    // For now, just append the PR number to the entry; we'll clean those up at a later point.
398                    if ( $prs ) {
399                        $seen[ $key ]->setContent( $seen[ $key ]->getContent() . ' ' . implode( ' ', $prs ) );
400                    }
401                    return false;
402                }
403                $seen[ $key ] = $change;
404                return true;
405            },
406            ARRAY_FILTER_USE_BOTH
407        );
408        if ( ! $changes && ! $this->askedNoChanges ) {
409            $this->askedNoChanges = true;
410            if ( ! $this->askToContinue( $input, $output, 'All changes were duplicates.' ) ) {
411                return self::NO_CHANGE_EXIT;
412            }
413        }
414        return self::OK_EXIT;
415    }
416
417    /**
418     * Check whether any changes have content.
419     *
420     * @param InputInterface  $input InputInterface.
421     * @param OutputInterface $output OutputInterface.
422     * @param ChangeEntry[]   $changes Changes.
423     * @return bool
424     */
425    protected function doChangesHaveContent( InputInterface $input, OutputInterface $output, array $changes ) {
426        $output->writeln( 'Checking if any changes have content...', OutputInterface::VERBOSITY_DEBUG );
427        foreach ( $changes as $name => $change ) {
428            if ( $change->getContent() !== '' ) {
429                $output->writeln( "Yes, $name has content.", OutputInterface::VERBOSITY_DEBUG );
430                return true;
431            }
432        }
433        return false;
434    }
435
436    /**
437     * Apply --amend if applicable.
438     *
439     * @param InputInterface  $input InputInterface.
440     * @param OutputInterface $output OutputInterface.
441     * @param Changelog       $changelog Changelog.
442     * @param ChangeEntry[]   $changes Changes.
443     * @param string|null     $amendedVersion Set to indicate the source version of the amend, if any.
444     * @return int
445     */
446    protected function doAmendChanges( InputInterface $input, OutputInterface $output, Changelog $changelog, array &$changes, &$amendedVersion = null ) {
447        $amendedVersion = null;
448        if ( $input->getOption( 'amend' ) ) {
449            $entries = $changelog->getEntries();
450            if ( $entries ) {
451                $latest = array_shift( $entries );
452                $changelog->setEntries( $entries );
453                $amendedVersion = $latest->getVersion();
454                $changes        = array_merge( $latest->getChanges(), array_values( $changes ) );
455                $output->writeln( "Removing changes for $amendedVersion from changelog for --amend.", OutputInterface::VERBOSITY_DEBUG );
456
457                if ( $input->getOption( 'prologue' ) === null ) {
458                    $input->setOption( 'prologue', $latest->getPrologue() );
459                }
460                if ( $input->getOption( 'epilogue' ) === null ) {
461                    $input->setOption( 'epilogue', $latest->getEpilogue() );
462                }
463                if ( $input->getOption( 'link' ) === null ) {
464                    $oldLink     = $latest->getLink();
465                    $defaultLink = $changelog->getLatestEntry() ? Config::link( $changelog->getLatestEntry()->getVersion(), $latest->getVersion() ) : null;
466                    if ( $oldLink !== $defaultLink ) {
467                        $input->setOption( 'link', $latest->getLink() );
468                    }
469                }
470            } else {
471                $output->writeln( 'No version to amend, ignoring --amend.', OutputInterface::VERBOSITY_DEBUG );
472            }
473        }
474        return self::OK_EXIT;
475    }
476
477    /**
478     * Sort changes.
479     *
480     * @param ChangeEntry[] $changes Changes.
481     * @return array
482     */
483    protected function sortChanges( array $changes ) {
484        $sortConfig = array(
485            'ordering'         => Config::ordering(),
486            'knownSubheadings' => Config::types(),
487        );
488        $changes    = array_values( $changes );
489        usort(
490            $changes,
491            function ( $a, $b ) use ( $sortConfig, $changes ) {
492                $ret = ChangeEntry::compare( $a, $b, $sortConfig );
493                if ( 0 === $ret ) {
494                    // Stability.
495                    $ret = array_search( $a, $changes, true ) <=> array_search( $b, $changes, true );
496                }
497                return $ret;
498            }
499        );
500        return $changes;
501    }
502
503    /**
504     * Get the version from the command line.
505     *
506     * @param InputInterface  $input InputInterface.
507     * @param OutputInterface $output OutputInterface.
508     * @param Changelog       $changelog Changelog.
509     * @return string|int New version, or int on error.
510     */
511    protected function getUseVersion( InputInterface $input, OutputInterface $output, Changelog $changelog ) {
512        $version = $input->getOption( 'use-version' );
513        $output->writeln( "Using version $version from command line.", OutputInterface::VERBOSITY_DEBUG );
514
515        // Normalize it?
516        try {
517            $nversion = $this->versioning->normalizeVersion( $version );
518        } catch ( InvalidArgumentException $ex ) {
519            $nversion = $version;
520            $output->writeln( "<error>Invalid --use-version: {$ex->getMessage()}</>" );
521            if ( ! $this->askToContinue( $input, $output, 'The specified version is not valid. This may cause problems in the future!' ) ) {
522                return self::ASKED_EXIT;
523            }
524        }
525        if ( $version !== $nversion ) {
526            if ( ! $input->isInteractive() ) {
527                if ( ! $this->askToContinue( $input, $output, "The supplied version $version is not normalized, it should be $nversion." ) ) {
528                    return self::ASKED_EXIT;
529                }
530            } else {
531                try {
532                    $question = new ChoiceQuestion(
533                        "The supplied version $version is not normalized.",
534                        array(
535                            'proceed'   => "Proceed with $version",
536                            'normalize' => "Normalize to $nversion",
537                            'abort'     => 'Abort',
538                        ),
539                        $input->getOption( 'yes' ) ? 'proceed' : 'abort'
540                    );
541
542                    $helper = $this->getHelper( 'question' );
543                    '@phan-var QuestionHelper $helper';
544                    switch ( $helper->ask( $input, $output, $question ) ) {
545                        case 'proceed': // @codeCoverageIgnore
546                            break;
547                        case 'normalize': // @codeCoverageIgnore
548                            $output->writeln( "Normalizing $version to $nversion.", OutputInterface::VERBOSITY_DEBUG );
549                            $version = $nversion;
550                            break;
551                        default:
552                            return self::ASKED_EXIT;
553                    }
554                } catch ( MissingInputException $ex ) { // @codeCoverageIgnore
555                    $output->writeln( 'Got EOF when attempting to query user, aborting.', OutputInterface::VERBOSITY_VERBOSE ); // @codeCoverageIgnore
556                    return self::ASKED_EXIT; // @codeCoverageIgnore
557                }
558            }
559        }
560
561        // Check that it's newer than the current version.
562        $latest = $changelog->getLatestEntry();
563        if ( $latest ) {
564            $curver = $latest->getVersion();
565            try {
566                $cmp = $this->versioning->compareVersions( $version, $curver );
567            } catch ( InvalidArgumentException $ex ) {
568                $output->writeln( "Cannot compare $version with $curver: {$ex->getMessage()}", OutputInterface::VERBOSITY_DEBUG );
569                $cmp = 1;
570            }
571            if ( $cmp < 0 && ! $this->askToContinue( $input, $output, "The most recent version in the changelog is $curver, which comes after $version." ) ) {
572                return self::ASKED_EXIT;
573            }
574            if ( 0 === $cmp && ! $this->askToContinue( $input, $output, "The most recent version in the changelog is $curver, which is equivalent to $version." ) ) {
575                return self::ASKED_EXIT;
576            }
577        }
578        return $version;
579    }
580
581    /**
582     * Determine the next version.
583     *
584     * @param InputInterface  $input InputInterface.
585     * @param OutputInterface $output OutputInterface.
586     * @param Changelog       $changelog Changelog.
587     * @param ChangeEntry[]   $changes Changes.
588     * @param string|null     $amendedVersion The source version of the amend, if any.
589     * @return string|int New version, or int on error.
590     */
591    protected function nextVersion( InputInterface $input, OutputInterface $output, Changelog $changelog, array $changes, $amendedVersion ) {
592        $extra = array(
593            'prerelease' => $input->getOption( 'prerelease' ),
594            'buildinfo'  => $input->getOption( 'buildinfo' ),
595        );
596
597        // Is there a version in the changelog?
598        $latest = $changelog->getLatestEntry();
599        if ( ! $latest ) {
600            if ( null !== $amendedVersion ) {
601                $output->writeln( "Amending earliest version, reusing version $amendedVersion...", OutputInterface::VERBOSITY_DEBUG );
602                return $amendedVersion;
603            } elseif ( $input->getOption( 'default-first-version' ) ) {
604                return $this->versioning->firstVersion( $extra );
605            } else {
606                $output->writeln( '<error>Changelog file contains no entries! Use --use-version to specify the initial version.</>' );
607                return self::FATAL_EXIT;
608            }
609        }
610
611        $output->writeln( "Latest version from changelog is {$latest->getVersion()}.", OutputInterface::VERBOSITY_DEBUG );
612
613        // If they overrode the significance, use that. Otherwise use `$changes`.
614        if ( $input->getOption( 'use-significance' ) ) {
615            try {
616                $verchanges = array(
617                    $this->formatter->newChangeEntry(
618                        array(
619                            'significance' => $input->getOption( 'use-significance' ),
620                            'content'      => 'Dummy',
621                        )
622                    ),
623                );
624            } catch ( \Exception $ex ) {
625                $output->writeln( "<error>{$ex->getMessage()}</>" );
626                return self::FATAL_EXIT;
627            }
628        } else {
629            $verchanges = $changes;
630        }
631
632        // Get the next version from the versioning plugin.
633        try {
634            $version = VersionCommand::getNextVersion( $changelog->getVersions(), $verchanges, $extra );
635        } catch ( InvalidArgumentException $ex ) {
636            // Was it the version from the changelog that made it fail, or something else?
637            try {
638                $this->versioning->normalizeVersion( $latest->getVersion() );
639                $output->writeln( "<error>Failed to determine new version: {$ex->getMessage()}</>" );
640            } catch ( InvalidArgumentException $ex2 ) {
641                $output->writeln( "<error>Changelog file contains invalid version {$latest->getVersion()}! Use --use-version to specify the new version.</>" );
642            }
643            return self::FATAL_EXIT;
644        }
645        $output->writeln( "Next version is {$version}.", OutputInterface::VERBOSITY_DEBUG );
646
647        // When amending, if the next version turns out to be before the amended version, use the amended version.
648        try {
649            if ( null !== $amendedVersion && $this->versioning->compareVersions( $amendedVersion, $version ) > 0 ) {
650                $output->writeln( "Amended version $amendedVersion is later, using that instead.", OutputInterface::VERBOSITY_DEBUG );
651                $version = $amendedVersion;
652            }
653        } catch ( InvalidArgumentException $ex ) {
654            $output->writeln( "Amended version $amendedVersion is was not valid. Hope it wasn't supposed to be later.", OutputInterface::VERBOSITY_DEBUG );
655        }
656
657        return $version;
658    }
659
660    /**
661     * Executes the command.
662     *
663     * @param InputInterface  $input InputInterface.
664     * @param OutputInterface $output OutputInterface.
665     * @return int 0 If everything went fine, or an exit code.
666     */
667    protected function execute( InputInterface $input, OutputInterface $output ): int {
668        try {
669            $this->formatter = Config::formatterPlugin();
670            $this->formatter->setIO( $input, $output );
671            $this->versioning = Config::versioningPlugin();
672            $this->versioning->setIO( $input, $output );
673        } catch ( \Exception $ex ) {
674            $output->writeln( "<error>{$ex->getMessage()}</>" );
675            return self::FATAL_EXIT;
676        }
677        $this->askedNoChanges = false;
678
679        // Get the changelog.
680        $changelog = $this->loadChangelog( $input, $output );
681        if ( is_int( $changelog ) ) {
682            return $changelog;
683        }
684
685        // Get the changes.
686        list( $ret, $changes, $files ) = $this->loadChanges( $input, $output );
687        if ( self::OK_EXIT !== $ret ) {
688            return $ret;
689        }
690        $ret = $this->deduplicateChanges( $input, $output, $changelog, $changes );
691        if ( self::OK_EXIT !== $ret ) {
692            return $ret;
693        }
694        foreach ( $changes as $change ) {
695            self::cleanPrSuffix( $change );
696        }
697        $anyChangesWithContent = $this->doChangesHaveContent( $input, $output, $changes );
698        if ( ! $anyChangesWithContent && ! $this->askedNoChanges ) {
699            $this->askedNoChanges = true;
700            if ( ! $this->askToContinue( $input, $output, 'There are no changes with content for this write.' ) ) {
701                return self::NO_CHANGE_EXIT;
702            }
703        }
704        $amendedVersion = null; // Make phpcs happy.
705        $ret            = $this->doAmendChanges( $input, $output, $changelog, $changes, $amendedVersion );
706        if ( self::OK_EXIT !== $ret ) {
707            return $ret; // @codeCoverageIgnore
708        }
709        $changes = $this->sortChanges( $changes );
710
711        // Determine next version.
712        if ( $input->getOption( 'use-version' ) !== null ) {
713            $version = $this->getUseVersion( $input, $output, $changelog );
714        } else {
715            $version = $this->nextVersion( $input, $output, $changelog, $changes, $amendedVersion );
716        }
717        if ( is_int( $version ) ) {
718            return $version;
719        }
720
721        // Add the new changelog entry.
722        $ret = $this->addEntry( $input, $output, $changelog, $version, $changes );
723        if ( self::OK_EXIT !== $ret ) {
724            return $ret;
725        }
726
727        // Write the changelog.
728        $ret = $this->writeChangelog( $input, $output, $changelog );
729        if ( self::OK_EXIT !== $ret ) {
730            return $ret;
731        }
732
733        // Delete change files and return.
734        return $this->deleteChanges( $input, $output, $files );
735    }
736}