Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
153 / 153
100.00% covered (success)
100.00%
5 / 5
CRAP
100.00% covered (success)
100.00%
1 / 1
AddCommand
100.00% covered (success)
100.00%
153 / 153
100.00% covered (success)
100.00%
5 / 5
55
100.00% covered (success)
100.00%
1 / 1
 configure
100.00% covered (success)
100.00%
23 / 23
100.00% covered (success)
100.00%
1 / 1
2
 validateFilename
100.00% covered (success)
100.00%
17 / 17
100.00% covered (success)
100.00%
1 / 1
9
 getDefaultFilename
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
4
 getQuestionHelper
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 execute
100.00% covered (success)
100.00%
103 / 103
100.00% covered (success)
100.00%
1 / 1
39
1<?php
2/**
3 * "Add" command for the changelogger tool CLI.
4 *
5 * @package automattic/jetpack-changelogger
6 */
7
8namespace Automattic\Jetpack\Changelogger;
9
10use Symfony\Component\Console\Attribute\AsCommand;
11use Symfony\Component\Console\Command\Command;
12use Symfony\Component\Console\Exception\MissingInputException;
13use Symfony\Component\Console\Helper\QuestionHelper;
14use Symfony\Component\Console\Input\InputInterface;
15use Symfony\Component\Console\Input\InputOption;
16use Symfony\Component\Console\Output\OutputInterface;
17use Symfony\Component\Console\Question\ChoiceQuestion;
18use Symfony\Component\Console\Question\Question;
19
20/**
21 * "Add" command for the changelogger tool CLI.
22 */
23#[AsCommand( 'add', 'Adds a change file' )]
24class AddCommand extends Command {
25
26    /**
27     * Bad characters for filenames.
28     *
29     * @var array
30     */
31    private static $badChars = array(
32        '<'  => 'angle brackets',
33        '>'  => 'angle brackets',
34        ':'  => 'colons',
35        '"'  => 'double quotes',
36        '/'  => 'slashes',
37        '\\' => 'backslashes',
38        '|'  => 'pipes',
39        '?'  => 'question marks',
40        '*'  => 'asterisks',
41    );
42
43    /**
44     * Significance values and descriptions.
45     *
46     * @var array
47     */
48    private static $significances = array(
49        'patch' => 'Backwards-compatible bug fixes.',
50        'minor' => 'Added (or deprecated) functionality in a backwards-compatible manner.',
51        'major' => 'Broke backwards compatibility in some way.',
52    );
53
54    /**
55     * The default command name
56     *
57     * @var string|null
58     */
59    protected static $defaultName = 'add';
60
61    /**
62     * The default command description
63     *
64     * @var string|null
65     */
66    protected static $defaultDescription = 'Adds a change file';
67
68    /**
69     * Configures the command.
70     */
71    protected function configure() {
72        $joiner = function ( $arr ) {
73            return implode(
74                "\n",
75                array_map(
76                    function ( $k, $v ) {
77                        return " - $k: $v";
78                    },
79                    array_keys( $arr ),
80                    $arr
81                )
82            );
83        };
84
85        $this->setDescription( static::$defaultDescription )
86            ->addOption( 'filename', 'f', InputOption::VALUE_REQUIRED, 'Name for the change file. If not provided, a default will be determined from the current timestamp or git branch name.' )
87            ->addOption( 'filename-auto-suffix', null, InputOption::VALUE_NONE, 'If the specified file already exists in non-interactive mode, add a numeric suffix so the new entry can be created.' )
88            ->addOption( 'significance', 's', InputOption::VALUE_REQUIRED, "Significance of the change, in the style of semantic versioning. One of the following:\n" . $joiner( self::$significances ) )
89            ->addOption( 'type', 't', InputOption::VALUE_REQUIRED, Config::types() ? "Type of change. One of the following:\n" . $joiner( Config::types() ) : 'Normally this would be used to indicate the type of change, but this project does not use types. Do not use.' )
90            ->addOption( 'comment', 'c', InputOption::VALUE_REQUIRED, 'Optional comment to include in the file.' )
91            ->addOption( 'entry', 'e', InputOption::VALUE_REQUIRED, 'Changelog entry. May be empty if the significance is "patch".' )
92            ->setHelp(
93                <<<'EOF'
94The <info>add</info> command adds a new change file to the changelog directory.
95
96By default this is an interactive process: the user will be queried for the necessary
97information, with command line arguments supplying default values. Use <info>--no-interaction</info>
98to create an entry non-interactively.
99EOF
100            );
101    }
102
103    /**
104     * Validate a filename.
105     *
106     * @param string $filename Filename.
107     * @return string $filename
108     * @throws \RuntimeException On error.
109     */
110    public function validateFilename( $filename ) {
111        if ( '' === $filename ) {
112            throw new \RuntimeException( 'Filename may not be empty.' );
113        }
114
115        if ( '.' === $filename[0] ) {
116            throw new \RuntimeException( 'Filename may not begin with a dot.' );
117        }
118
119        $bad = array();
120        foreach ( self::$badChars as $c => $name ) {
121            if ( strpos( $filename, $c ) !== false ) {
122                $bad[ $name ] = true;
123            }
124        }
125        if ( $bad ) {
126            $bad = array_keys( $bad );
127            if ( count( $bad ) > 1 ) {
128                $bad[ count( $bad ) - 1 ] = 'or ' . $bad[ count( $bad ) - 1 ];
129            }
130            throw new \RuntimeException( 'Filename may not contain ' . implode( count( $bad ) > 2 ? ', ' : ' ', $bad ) . '.' );
131        }
132
133        $path = Config::changesDir() . "/$filename";
134        if ( file_exists( $path ) ) {
135            throw new \RuntimeException( "File \"$path\" already exists. If you want to replace it, delete it manually." );
136        }
137
138        return $filename;
139    }
140
141    /**
142     * Get the default filename.
143     *
144     * @param OutputInterface $output OutputInterface.
145     * @return string
146     */
147    protected function getDefaultFilename( OutputInterface $output ) {
148        static $non_feature_branches = array( 'current', 'default', 'develop', 'latest', 'main', 'master', 'next', 'production', 'support', 'tip', 'trunk' );
149
150        try {
151            $debugHelper = $this->getHelper( 'debug_formatter' );
152            '@phan-var \Symfony\Component\Console\Helper\DebugFormatterHelper $debugHelper';
153            $process = Utils::runCommand( array( 'git', 'rev-parse', '--abbrev-ref', 'HEAD' ), $output, $debugHelper );
154            if ( $process->isSuccessful() ) {
155                $ret = trim( $process->getOutput() );
156                if ( ! in_array( $ret, $non_feature_branches, true ) ) {
157                    return strtr( $ret, array_fill_keys( array_keys( self::$badChars ), '-' ) );
158                }
159            }
160        } catch ( \Exception $ex ) { // @codeCoverageIgnore
161            $output->writeln( "Command failed: {$ex->getMessage()}", OutputInterface::VERBOSITY_DEBUG ); // @codeCoverageIgnore
162        }
163
164        $date = new \DateTime( 'now', new \DateTimeZone( 'UTC' ) );
165        return $date->format( 'Y-m-d-H-i-s-u' );
166    }
167
168    /**
169     * Get a QuestionHelper.
170     *
171     * @return QuestionHelper
172     */
173    private function getQuestionHelper() {
174        // @phan-suppress-next-line PhanTypeMismatchReturnSuperType -- That's how ->getHelper() works.
175        return $this->getHelper( 'question' );
176    }
177
178    /**
179     * Executes the command.
180     *
181     * @param InputInterface  $input InputInterface.
182     * @param OutputInterface $output OutputInterface.
183     * @return int 0 if everything went fine, or an exit code.
184     */
185    protected function execute( InputInterface $input, OutputInterface $output ): int {
186        try {
187            $dir = Config::changesDir();
188            if ( ! is_dir( $dir ) ) {
189                error_clear_last();
190                // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
191                if ( ! @mkdir( $dir, 0775, true ) ) {
192                    $err = error_get_last();
193                    $output->writeln( "<error>Could not create directory $dir: {$err['message']}</>" );
194                    return 1;
195                }
196            }
197
198            $isInteractive = $input->isInteractive();
199
200            // Determine the changelog entry filename.
201            $filename = $input->getOption( 'filename' );
202            if ( null === $filename ) {
203                $filename = $this->getDefaultFilename( $output );
204            }
205            if ( $isInteractive ) {
206                $question = new Question( "Name your changelog file <info>[default: $filename]</> > ", $filename );
207                $question->setValidator( array( $this, 'validateFilename' ) );
208                $filename = $this->getQuestionHelper()->ask( $input, $output, $question );
209                if ( null === $filename ) { // non-interactive.
210                    $output->writeln( 'Got EOF when attempting to query user, aborting.', OutputInterface::VERBOSITY_VERBOSE ); // @codeCoverageIgnore
211                    return 1; // @codeCoverageIgnore
212                }
213            } else {
214                if ( null === $input->getOption( 'filename' ) ) {
215                    $output->writeln( "Using default filename \"$filename\".", OutputInterface::VERBOSITY_VERBOSE );
216                }
217                if ( file_exists( "$dir/$filename" ) && $input->getOption( 'filename-auto-suffix' ) ) {
218                    $i = 2;
219                    while ( file_exists( "$dir/$filename#$i" ) ) {
220                        ++$i;
221                    }
222                    $output->writeln( "File \"$filename\" already exists. Creating \"$filename#$i\" instead.", OutputInterface::VERBOSITY_VERBOSE );
223                    $filename = "$filename#$i";
224                }
225                try {
226                    $this->validateFilename( $filename );
227                } catch ( \RuntimeException $ex ) {
228                    $output->writeln( "<error>{$ex->getMessage()}</>" );
229                    return 1;
230                }
231            }
232
233            $contents = '';
234
235            // Determine the change significance and add to the file contents.
236            $significance = $input->getOption( 'significance' );
237            if ( null !== $significance ) {
238                $significance = strtolower( $significance );
239            }
240            if ( $isInteractive ) {
241                $question     = new ChoiceQuestion( 'Significance of the change, in the style of semantic versioning.', self::$significances, $significance );
242                $significance = $this->getQuestionHelper()->ask( $input, $output, $question );
243                if ( null === $significance ) { // non-interactive.
244                    $output->writeln( 'Got EOF when attempting to query user, aborting.', OutputInterface::VERBOSITY_VERBOSE ); // @codeCoverageIgnore
245                    return 1; // @codeCoverageIgnore
246                }
247            } else {
248                if ( null === $significance ) {
249                    $output->writeln( '<error>Significance must be specified in non-interactive mode.</>' );
250                    return 1;
251                }
252                if ( ! isset( self::$significances[ $significance ] ) ) {
253                    $output->writeln( "<error>Significance value \"$significance\" is not valid.</>" );
254                    return 1;
255                }
256            }
257            $contents .= "Significance: $significance\n";
258
259            // Determine the change type and add to the file contents, if applicable.
260            $types = Config::types();
261            if ( $types ) {
262                $type = $input->getOption( 'type' );
263                if ( null !== $type ) {
264                    $type = strtolower( $type );
265                }
266                if ( $isInteractive ) {
267                    $question = new ChoiceQuestion( 'Type of change.', $types, $type );
268                    $type     = $this->getQuestionHelper()->ask( $input, $output, $question );
269                    if ( null === $type ) { // non-interactive.
270                        $output->writeln( 'Got EOF when attempting to query user, aborting.', OutputInterface::VERBOSITY_VERBOSE ); // @codeCoverageIgnore
271                        return 1; // @codeCoverageIgnore
272                    }
273                } else {
274                    if ( null === $type ) {
275                        $output->writeln( '<error>Type must be specified in non-interactive mode.</>' );
276                        return 1;
277                    }
278                    if ( ! isset( $types[ $type ] ) ) {
279                        $output->writeln( "<error>Type \"$type\" is not valid.</>" );
280                        return 1;
281                    }
282                }
283                $contents .= "Type: $type\n";
284            } elseif ( null !== $input->getOption( 'type' ) ) {
285                $output->writeln( '<warning>This project does not use types. Do not specify --type.</>' );
286            }
287
288            // Determine the changelog entry and add to the file contents.
289            $entry = $input->getOption( 'entry' );
290            if ( $isInteractive ) {
291                if ( 'patch' === $significance ) {
292                    $question = new Question( "Changelog entry. May be left empty if this change is particularly insignificant.\n > ", (string) $entry );
293                } else {
294                    $question = new Question( "Changelog entry. May not be empty.\n > ", $entry );
295                    $question->setValidator(
296                        function ( $v ) {
297                            if ( trim( (string) $v ) === '' ) {
298                                throw new \RuntimeException( 'An empty changelog entry is only allowed when the significance is "patch".' );
299                            }
300                            return $v;
301                        }
302                    );
303                }
304                $entry = $this->getQuestionHelper()->ask( $input, $output, $question );
305                if ( null === $entry ) {
306                    $output->writeln( 'Got EOF when attempting to query user, aborting.', OutputInterface::VERBOSITY_VERBOSE ); // @codeCoverageIgnore
307                    return 1; // @codeCoverageIgnore
308                }
309            } else {
310                if ( null === $entry ) {
311                    $output->writeln( '<error>Entry must be specified in non-interactive mode.</>' );
312                    if ( 'patch' === $significance ) {
313                        $output->writeln( '<info>If you want to have an empty entry for this change, pass the empty string as the entry (like <comment>--entry=</>) and also please provide a comment (using <comment>--comment</>).</>' );
314                    }
315                    return 1;
316                }
317                if ( 'patch' !== $significance && '' === $entry ) {
318                    $output->writeln( '<error>An empty changelog entry is only allowed when the significance is "patch".</>' );
319                    return 1;
320                }
321            }
322
323            // Ask if a change comment is desired, if they left the change entry itself empty.
324            $comment = (string) $input->getOption( 'comment' );
325            if ( $isInteractive && '' === $entry ) {
326                $question = new Question( "You omitted the changelog entry, which is fine. But please comment as to why no entry is needed.\n > ", $comment );
327                $comment  = $this->getQuestionHelper()->ask( $input, $output, $question );
328                if ( null === $comment ) {
329                    $output->writeln( 'Got EOF when attempting to query user, aborting.', OutputInterface::VERBOSITY_VERBOSE ); // @codeCoverageIgnore
330                    return 1; // @codeCoverageIgnore
331                }
332            }
333            $comment = trim( preg_replace( '/\s+/', ' ', $comment ) );
334            if ( '' !== $comment ) {
335                $contents .= "Comment: $comment\n";
336            }
337
338            $contents .= "\n$entry";
339
340            // Ok! Write the file.
341            // Use fopen/fwrite/fclose instead of file_put_contents because the latter doesn't support 'x'.
342            $output->writeln(
343                "<info>Creating changelog entry $dir/$filename:\n" . preg_replace( '/^/m', '  ', $contents ) . '</>',
344                OutputInterface::VERBOSITY_DEBUG
345            );
346            $contents .= "\n";
347            error_clear_last();
348            // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
349            $fp = @fopen( "$dir/$filename", 'x' );
350            if ( ! $fp ||
351                // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
352                @fwrite( $fp, $contents ) !== strlen( $contents ) ||
353                ! fclose( $fp )
354            ) {
355                // @codeCoverageIgnoreStart
356                $err = error_get_last();
357                $output->writeln( "<error>Failed to write file \"$dir/$filename\": {$err['message']}.</>" );
358                // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
359                @fclose( $fp );
360                // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
361                @unlink( "$dir/$filename" );
362                return 1;
363                // @codeCoverageIgnoreEnd
364            }
365
366            return 0;
367        } catch ( MissingInputException $ex ) { // @codeCoverageIgnore
368            $output->writeln( 'Got EOF when attempting to query user, aborting.', OutputInterface::VERBOSITY_VERBOSE ); // @codeCoverageIgnore
369            return 1; // @codeCoverageIgnore
370        }
371    }
372}