Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
139 / 139
100.00% covered (success)
100.00%
4 / 4
CRAP
100.00% covered (success)
100.00%
1 / 1
SquashCommand
100.00% covered (success)
100.00%
139 / 139
100.00% covered (success)
100.00%
4 / 4
43
100.00% covered (success)
100.00%
1 / 1
 configure
100.00% covered (success)
100.00%
18 / 18
100.00% covered (success)
100.00%
1 / 1
3
 deduplicateChanges2
100.00% covered (success)
100.00%
17 / 17
100.00% covered (success)
100.00%
1 / 1
6
 mergeChanges
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
1 / 1
4
 execute
100.00% covered (success)
100.00%
92 / 92
100.00% covered (success)
100.00%
1 / 1
30
1<?php
2/**
3 * "Squash" 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 InvalidArgumentException;
12use Symfony\Component\Console\Attribute\AsCommand;
13use Symfony\Component\Console\Input\InputInterface;
14use Symfony\Component\Console\Input\InputOption;
15use Symfony\Component\Console\Output\OutputInterface;
16
17/**
18 * "Squash" command for the changelogger tool CLI.
19 */
20#[AsCommand( 'squash', 'Squash changelog entries in the changelog file' )]
21class SquashCommand extends WriteCommand {
22
23    /**
24     * The default command name.
25     *
26     * @var string|null
27     */
28    protected static $defaultName = 'squash';
29
30    /**
31     * The default command description
32     *
33     * @var string|null
34     */
35    protected static $defaultDescription = 'Squash changelog entries in the changelog file';
36
37    /**
38     * Configures the command.
39     */
40    protected function configure() {
41        $this->setDescription( static::$defaultDescription )
42            ->addOption( 'regex', null, InputOption::VALUE_REQUIRED, 'PCRE regex to match the versions to squash, including delimiters' )
43            ->addOption( 'count', null, InputOption::VALUE_REQUIRED, 'Number of versions to squash' )
44            ->addOption( 'use-version', null, InputOption::VALUE_REQUIRED, 'Use this version instead of determining the version automatically' )
45            ->addOption( 'release-date', null, InputOption::VALUE_REQUIRED, 'Release date, as a valid PHP date or "unreleased"' )
46            ->addOption( 'prologue', null, InputOption::VALUE_REQUIRED, 'Prologue text for the new changelog entry' )
47            ->addOption( 'epilogue', null, InputOption::VALUE_REQUIRED, 'Epilogue text for the new changelog entry' )
48            ->addOption( 'link', null, InputOption::VALUE_REQUIRED, 'Link for the new changelog entry' )
49            ->addOption( '--no-deduplicate', null, InputOption::VALUE_NONE, 'Do not deduplicate the changes' )
50            ->addOption( 'yes', null, InputOption::VALUE_NONE, 'Default all questions to "yes" instead of "no". Particularly useful for non-interactive mode' )
51            ->setHelp(
52                <<<'EOF'
53The <info>squash</info> command combines multiple existing changelog entries into one.
54
55The default behavior is to combine all entries that differ from the first only by prerelease
56and/or buildinfo. If <info>--regex</info> is used, instead all entries up to the first not matching
57the regex are merged. If <info>--count</info> is used, instead that many entries are merged.
58
59The default behavior is to combine the entries under the version number, date, and link of the
60first entry, with prologue and epilogue texts concatenated. This may be overridden using
61<info>--use-version</info>, <info>--release-date</info>, <info>--link</info>, <info>--prologue</info>,
62and <info>--epilogue</info>.
63EOF
64            );
65
66        try {
67            $this->getDefinition()->addOptions( Config::formatterPlugin()->getOptions() );
68        } catch ( \Exception $ex ) { // phpcs:ignore Generic.CodeAnalysis.EmptyStatement.DetectedCatch
69            // Will handle later.
70        }
71        try {
72            $this->getDefinition()->addOptions( Config::versioningPlugin()->getOptions() );
73        } catch ( \Exception $ex ) { // phpcs:ignore Generic.CodeAnalysis.EmptyStatement.DetectedCatch
74            // Will handle later.
75        }
76    }
77
78    /**
79     * Deduplicate changes.
80     *
81     * @param InputInterface  $input InputInterface.
82     * @param OutputInterface $output OutputInterface.
83     * @param ChangeEntry[]   $changes Changes.
84     * @return int
85     */
86    protected function deduplicateChanges2( InputInterface $input, OutputInterface $output, array &$changes ) {
87        // Deduplicate changes.
88        if ( ! $changes ) {
89            $output->writeln( 'Skipping deduplication, there are no changes.', OutputInterface::VERBOSITY_DEBUG );
90            return self::OK_EXIT;
91        }
92
93        if ( $input->getOption( 'no-deduplicate' ) ) {
94            $output->writeln( 'Skipping deduplication, --no-deduplicate was specified.', OutputInterface::VERBOSITY_DEBUG );
95            return self::OK_EXIT;
96        }
97
98        $output->writeln( 'Deduplicating changes...', OutputInterface::VERBOSITY_DEBUG );
99        $seen = array();
100        foreach ( $changes as $k => $change ) {
101            list( $key, $prs ) = self::splitPrSuffixes( $change->getContent() );
102            if ( isset( $seen[ $key ] ) ) {
103                $output->writeln( "Found duplicate change '{$change->getContent()}'.", OutputInterface::VERBOSITY_DEBUG );
104                if ( $prs ) {
105                    $seen[ $key ]->setContent( $seen[ $key ]->getContent() . ' ' . implode( ' ', $prs ) );
106                }
107                unset( $changes[ $k ] );
108            } else {
109                $seen[ $key ] = $change;
110            }
111        }
112        return self::OK_EXIT;
113    }
114
115    /**
116     * Merge changes.
117     *
118     * @param ChangeEntry[] $a Changes.
119     * @param ChangeEntry[] $b Changes.
120     * @return ChangeEntry[]
121     */
122    protected function mergeChanges( array $a, array $b ) {
123        $sortConfig = array(
124            'ordering'         => Config::ordering(),
125            'knownSubheadings' => Config::types(),
126        );
127
128        $a   = $this->sortChanges( $a );
129        $b   = $this->sortChanges( $b );
130        $ret = array();
131        while ( $a && $b ) {
132            if ( ChangeEntry::compare( $a[0], $b[0], $sortConfig ) <= 0 ) {
133                $ret[] = array_shift( $a );
134            } else {
135                $ret[] = array_shift( $b );
136            }
137        }
138        return array_merge( $ret, $a, $b );
139    }
140
141    /**
142     * Executes the command.
143     *
144     * @param InputInterface  $input InputInterface.
145     * @param OutputInterface $output OutputInterface.
146     * @return int 0 If everything went fine, or an exit code.
147     */
148    protected function execute( InputInterface $input, OutputInterface $output ): int {
149        try {
150            $this->formatter = Config::formatterPlugin();
151            $this->formatter->setIO( $input, $output );
152            $this->versioning = Config::versioningPlugin();
153            $this->versioning->setIO( $input, $output );
154        } catch ( \Exception $ex ) {
155            $output->writeln( "<error>{$ex->getMessage()}</>" );
156            return self::FATAL_EXIT;
157        }
158
159        // Get the changelog.
160        $changelog = $this->loadChangelog( $input, $output );
161        if ( is_int( $changelog ) ) {
162            return $changelog;
163        }
164        $inEntries = $changelog->getEntries();
165        if ( ! $inEntries ) {
166            $output->writeln( '<error>Changelog contains no entries, cannot squash</>' );
167            return self::FATAL_EXIT;
168        }
169
170        // Extract the entries to squash.
171        $entries = array();
172        if ( $input->getOption( 'regex' ) !== null ) {
173            $regex = $input->getOption( 'regex' );
174            $output->writeln( "Looking for entries matching regex $regex", OutputInterface::VERBOSITY_DEBUG );
175            // @phan-suppress-next-line PhanInfiniteLoop -- Phan isn't realizing that the array_shift might make $inEntries falsey.
176            while ( $inEntries ) {
177                // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
178                $ret = @preg_match( $regex, $inEntries[0]->getVersion() );
179                if ( false === $ret ) {
180                    $err = error_get_last()['message'];
181                    if ( substr( $err, 0, 14 ) === 'preg_match(): ' ) {
182                        $err = substr( $err, 14 );
183                    }
184                    $output->writeln( "<error>Regex match failed: $err</>" );
185                    return self::FATAL_EXIT;
186                } elseif ( $ret ) {
187                    $output->writeln( "Will squash version {$inEntries[0]->getVersion()}", OutputInterface::VERBOSITY_DEBUG );
188                    $entries[] = array_shift( $inEntries );
189                } else {
190                    $output->writeln( "No match at {$inEntries[0]->getVersion()}, stopping there", OutputInterface::VERBOSITY_DEBUG );
191                    break;
192                }
193            }
194        } elseif ( $input->getOption( 'count' ) !== null ) {
195            $count = $input->getOption( 'count' );
196            if ( ! preg_match( '/^\d+$/', $count ) || 0 === (int) $count ) {
197                $output->writeln( '<error>Count must be a positive integer</>' );
198                return self::FATAL_EXIT;
199            }
200            $output->writeln( "Squashing first $count entries", OutputInterface::VERBOSITY_DEBUG );
201            $entries = array_splice( $inEntries, 0, $count );
202        } else {
203            $entries[] = array_shift( $inEntries );
204            try {
205                $version = $this->versioning->parseVersion( $entries[0]->getVersion() )['version'];
206            } catch ( InvalidArgumentException $ex ) {
207                $output->writeln( "<error>Cannot parse version number {$entries[0]->getVersion()}</>" );
208                return self::FATAL_EXIT;
209            }
210            $output->writeln( "Looking for entries matching version $version", OutputInterface::VERBOSITY_DEBUG );
211            $output->writeln( "Will squash version {$entries[0]->getVersion()}", OutputInterface::VERBOSITY_DEBUG );
212            // @phan-suppress-next-line PhanInfiniteLoop -- Phan isn't realizing that the array_shift might make $inEntries falsey.
213            while ( $inEntries ) {
214                try {
215                    $version2 = $this->versioning->parseVersion( $inEntries[0]->getVersion() )['version'];
216                } catch ( InvalidArgumentException $ex ) {
217                    $output->writeln( "Cannot parse version number {$inEntries[0]->getVersion()}, stopping there", OutputInterface::VERBOSITY_DEBUG );
218                    break;
219                }
220                if ( $version2 === $version ) {
221                    $output->writeln( "Will squash version {$inEntries[0]->getVersion()}", OutputInterface::VERBOSITY_DEBUG );
222                    $entries[] = array_shift( $inEntries );
223                } else {
224                    $output->writeln( "No match at {$inEntries[0]->getVersion()}, stopping there", OutputInterface::VERBOSITY_DEBUG );
225                    break;
226                }
227            }
228        }
229        if ( count( $entries ) <= 0 ) {
230            $output->writeln( '<error>No entries to squash</>' );
231            return self::NO_CHANGE_EXIT;
232        } elseif ( count( $entries ) <= 1 ) {
233            $output->writeln( '<error>Only a single entry matched, not squashing</>' );
234            return self::NO_CHANGE_EXIT;
235        }
236        $changelog->setEntries( $inEntries );
237
238        $changes   = array();
239        $prologues = array();
240        $epilogues = array();
241        foreach ( $entries as $e ) {
242            $changes = $this->mergeChanges( $changes, $e->getChanges() );
243            if ( trim( $e->getPrologue() ) !== '' ) {
244                $prologues[] = trim( $e->getPrologue() );
245            }
246            if ( trim( $e->getEpilogue() ) !== '' ) {
247                $epilogues[] = trim( $e->getEpilogue() );
248            }
249        }
250
251        $ret = $this->deduplicateChanges2( $input, $output, $changes );
252        if ( self::OK_EXIT !== $ret ) {
253            return $ret; // @codeCoverageIgnore
254        }
255        foreach ( $changes as $change ) {
256            self::cleanPrSuffix( $change );
257        }
258
259        // Determine next version.
260        if ( $input->getOption( 'use-version' ) !== null ) {
261            $version = $this->getUseVersion( $input, $output, $changelog );
262        } else {
263            $version = $entries[0]->getVersion();
264        }
265        if ( is_int( $version ) ) {
266            return $version;
267        }
268
269        if ( $input->getOption( 'release-date' ) === null ) {
270            $input->setOption( 'release-date', $entries[0]->getTimestamp()->format( 'Y-m-d\TH:i:sO' ) );
271        }
272        if ( $input->getOption( 'link' ) === null ) {
273            $input->setOption( 'link', $entries[0]->getLink() );
274        }
275        if ( $input->getOption( 'prologue' ) === null ) {
276            $input->setOption( 'prologue', implode( "\n\n", $prologues ) );
277        }
278        if ( $input->getOption( 'epilogue' ) === null ) {
279            $input->setOption( 'epilogue', implode( "\n\n", $epilogues ) );
280        }
281
282        // Add the new changelog entry.
283        $ret = $this->addEntry( $input, $output, $changelog, $version, $changes );
284        if ( self::OK_EXIT !== $ret ) {
285            return $ret;
286        }
287
288        // Write the changelog.
289        return $this->writeChangelog( $input, $output, $changelog );
290    }
291}