Debian Codegraph @

vendor/wikimedia/parsoid/tools/OptsProcessor.php

raw
1 <?php
2 /**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
17 */
18
19 namespace Wikimedia\Parsoid\Tools;
20
21 /**
22 * Class for processing CLI args
23 *
24 * This code has been extracted from Core's Maintenance.php class
25 * by removing all non-CLI arg processing state and code.
26 */
27 class OptsProcessor {
28
29 /**
30 * Array of desired params
31 * @var array
32 */
33 public $params = [];
34
35 /**
36 * Array of mapping short parameters to long ones
37 * @var array
38 */
39 public $shortParamsMap = [];
40
41 /**
42 * Array of desired args
43 * @var array
44 */
45 public $argList = [];
46
47 /**
48 * This is the array of options that were actually passed
49 * @var array
50 */
51 protected $options = [];
52
53 /**
54 * This is the array of arguments that were actually passed
55 * @var array
56 */
57 public $args = [];
58
59 /**
60 * Allow arbitrary options to be passed, or only specified ones?
61 * @var bool
62 */
63 public $allowUnregisteredOptions = false;
64
65 /**
66 * Name of the script currently running
67 * @var string
68 */
69 private $self;
70
71 /**
72 * Is the script running in quiet mode?
73 * @var bool
74 */
75 private $quiet = false;
76
77 /**
78 * Add a description of the script
79 * @var string
80 */
81 private $description = '';
82
83 /**
84 * Generic options added by addDefaultParams()
85 * Generic options which might or not be supported by the script
86 * @var array
87 */
88 private $genericParameters = [];
89
90 /**
91 * Generic options which might or not be supported by the script
92 * @var array
93 */
94 private $dependentParameters = [];
95
96 /**
97 * Used to read the options in the order they were passed.
98 * Useful for option chaining (Ex. dumpBackup.php). It will
99 * be an empty array if the options are passed in through
100 * loadParamsAndArgs( $self, $opts, $args ).
101 *
102 * This is an array of arrays where
103 * 0 => the option and 1 => parameter value.
104 *
105 * @var array
106 */
107 public $orderedOptions = [];
108
109 /**
110 * Adds default args (--help, --quiet right now)
111 */
112 public function __construct() {
113 $this->addDefaultParams();
114 global $argv;
115 $this->self = $argv[0];
116 }
117
118 /**
119 * Set the description text.
120 * @param string $text The text of the description
121 */
122 public function addDescription( string $text ): void {
123 $this->description = $text;
124 }
125
126 /**
127 * Get the script's name
128 * @return string
129 */
130 public function getName(): string {
131 return $this->self;
132 }
133
134 /**
135 * Checks to see if a particular option is supported. Normally this means
136 * it has been registered by the script via addOption.
137 * @param string $name The name of the option
138 * @return bool true if the option exists, false otherwise
139 */
140 public function supportsOption( string $name ): bool {
141 return isset( $this->params[$name] );
142 }
143
144 /**
145 * Add a parameter to the script. Will be displayed on --help
146 * with the associated description
147 *
148 * @param string $name The name of the param (help, version, etc)
149 * @param string $description The description of the param to show on --help
150 * @param bool $required Is the param required?
151 * @param bool $withArg Is an argument required with this option?
152 * @param string|bool $shortName Character to use as short name
153 * @param bool $multiOccurrence Can this option be passed multiple times?
154 */
155 public function addOption(
156 string $name, string $description, bool $required = false,
157 bool $withArg = false, $shortName = false,
158 bool $multiOccurrence = false
159 ): void {
160 $this->params[$name] = [
161 'desc' => $description,
162 'require' => $required,
163 'withArg' => $withArg,
164 'shortName' => $shortName,
165 'multiOccurrence' => $multiOccurrence,
166 ];
167
168 if ( $shortName !== false ) {
169 $this->shortParamsMap[$shortName] = $name;
170 }
171 }
172
173 /**
174 * Checks to see if a particular option exists.
175 * @param string $name The name of the option
176 * @return bool
177 */
178 public function hasOption( string $name ): bool {
179 return isset( $this->options[$name] );
180 }
181
182 /**
183 * Get an option, or return the default.
184 *
185 * If the option was added to support multiple occurrences,
186 * this will return an array.
187 *
188 * @param string $name The name of the param
189 * @param mixed $default Anything you want, default null
190 * @return mixed
191 */
192 public function getOption( $name, $default = null ) {
193 if ( $this->hasOption( $name ) ) {
194 return $this->options[$name];
195 } else {
196 // Set it so we don't have to provide the default again
197 $this->options[$name] = $default;
198
199 return $this->options[$name];
200 }
201 }
202
203 /**
204 * Add some args that are needed
205 * @param string $arg Name of the arg, like 'start'
206 * @param string $description Short description of the arg
207 * @param bool $required Is this required?
208 */
209 public function addArg( string $arg, string $description, bool $required = true ) {
210 $this->argList[] = [
211 'name' => $arg,
212 'desc' => $description,
213 'require' => $required
214 ];
215 }
216
217 /**
218 * Remove an option. Useful for removing options that won't be used in your script.
219 * @param string $name The option to remove.
220 */
221 public function deleteOption( string $name ): void {
222 unset( $this->params[$name] );
223 }
224
225 /**
226 * Sets whether to allow unregistered options, which are options passed to
227 * a script that do not match an expected parameter.
228 * @param bool $allow Should we allow?
229 */
230 public function setAllowUnregisteredOptions( bool $allow ): void {
231 $this->allowUnregisteredOptions = $allow;
232 }
233
234 /**
235 * Does a given argument exist?
236 * @param int $argId The integer value (from zero) for the arg
237 * @return bool
238 */
239 public function hasArg( int $argId = 0 ): bool {
240 return isset( $this->args[$argId] );
241 }
242
243 /**
244 * Get an argument.
245 * @param int $argId The integer value (from zero) for the arg
246 * @param mixed $default The default if it doesn't exist
247 * @return mixed
248 */
249 public function getArg( int $argId = 0, $default = null ) {
250 return $this->hasArg( $argId ) ? $this->args[$argId] : $default;
251 }
252
253 public function isQuiet(): bool {
254 return $this->quiet;
255 }
256
257 /**
258 * Add the default parameters to the scripts
259 */
260 public function addDefaultParams(): void {
261 # Generic (non script dependent) options:
262
263 $this->addOption( 'help', 'Display this help message', false, false, 'h' );
264 $this->addOption( 'quiet', 'Whether to suppress non-error output', false, false, 'q' );
265
266 # Save generic options to display them separately in help
267 $this->genericParameters = $this->params;
268
269 # Save additional script dependent options to display
270 # them separately in help
271 $this->dependentParameters = array_diff_key( $this->params, $this->genericParameters );
272 }
273
274 /**
275 * Clear all params and arguments.
276 */
277 public function clearParamsAndArgs(): void {
278 $this->options = [];
279 $this->args = [];
280 }
281
282 /**
283 * Load params and arguments from a given array
284 * of command-line arguments
285 *
286 * @param array $argv
287 */
288 public function loadWithArgv( array $argv ): void {
289 $options = [];
290 $args = [];
291 $this->orderedOptions = [];
292
293 # Parse arguments
294 for ( $arg = reset( $argv ); $arg !== false; $arg = next( $argv ) ) {
295 if ( $arg == '--' ) {
296 # End of options, remainder should be considered arguments
297 $arg = next( $argv );
298 while ( $arg !== false ) {
299 $args[] = $arg;
300 $arg = next( $argv );
301 }
302 break;
303 } elseif ( substr( $arg, 0, 2 ) == '--' ) {
304 # Long options
305 $option = substr( $arg, 2 );
306 if ( isset( $this->params[$option] ) && $this->params[$option]['withArg'] ) {
307 $param = next( $argv );
308 if ( $param === false ) {
309 $this->error( "\nERROR: $option parameter needs a value after it\n" );
310 $this->maybeHelp( true );
311 }
312
313 $this->setParam( $options, $option, $param );
314 } else {
315 $bits = explode( '=', $option, 2 );
316 $this->setParam( $options, $bits[0], $bits[1] ?? 1 );
317 }
318 } elseif ( $arg == '-' ) {
319 # Lonely "-", often used to indicate stdin or stdout.
320 $args[] = $arg;
321 } elseif ( substr( $arg, 0, 1 ) == '-' ) {
322 # Short options
323 $argLength = strlen( $arg );
324 for ( $p = 1; $p < $argLength; $p++ ) {
325 $option = $arg[$p];
326 if ( !isset( $this->params[$option] ) && isset( $this->shortParamsMap[$option] ) ) {
327 $option = $this->shortParamsMap[$option];
328 }
329
330 if ( isset( $this->params[$option]['withArg'] ) && $this->params[$option]['withArg'] ) {
331 $param = next( $argv );
332 if ( $param === false ) {
333 $this->error( "\nERROR: $option parameter needs a value after it\n" );
334 $this->maybeHelp( true );
335 }
336 $this->setParam( $options, $option, $param );
337 } else {
338 $this->setParam( $options, $option, 1 );
339 }
340 }
341 } else {
342 $args[] = $arg;
343 }
344 }
345
346 $this->options = $options;
347 $this->args = $args;
348 }
349
350 /**
351 * Helper function used solely by loadParamsAndArgs
352 * to prevent code duplication
353 *
354 * This sets the param in the options array based on
355 * whether or not it can be specified multiple times.
356 *
357 * @param array &$options
358 * @param string $option
359 * @param mixed $value
360 */
361 private function setParam( array &$options, string $option, $value ): void {
362 $this->orderedOptions[] = [ $option, $value ];
363
364 if ( isset( $this->params[$option] ) ) {
365 $multi = $this->params[$option]['multiOccurrence'];
366 } else {
367 $multi = false;
368 }
369 $exists = array_key_exists( $option, $options );
370 if ( $multi && $exists ) {
371 $options[$option][] = $value;
372 } elseif ( $multi ) {
373 $options[$option] = [ $value ];
374 } elseif ( !$exists ) {
375 $options[$option] = $value;
376 } else {
377 $this->error( "\nERROR: $option parameter given twice\n" );
378 $this->maybeHelp( true );
379 }
380 }
381
382 /**
383 * Process command line arguments
384 * $options becomes an array with keys set to the option names
385 * $args becomes a zero-based array containing the non-option arguments
386 *
387 * @param ?string $self The name of the script, if any
388 * @param ?array $opts An array of options, in form of key=>value
389 * @param ?array $args An array of command line arguments
390 */
391 public function loadParamsAndArgs(
392 ?string $self = null, ?array $opts = null, ?array $args = null
393 ): void {
394 # If we were given opts or args, set those and return early
395 if ( $self ) {
396 $this->self = $self;
397 }
398 if ( $opts ) {
399 $this->options = $opts;
400 }
401 if ( $args ) {
402 $this->args = $args;
403 }
404
405 global $argv;
406 $this->self = $argv[0];
407 $this->loadWithArgv( array_slice( $argv, 1 ) );
408 }
409
410 /**
411 * Run some validation checks on the params, etc
412 */
413 public function validateParamsAndArgs(): void {
414 $die = false;
415 # Check to make sure we've got all the required options
416 foreach ( $this->params as $opt => $info ) {
417 if ( $info['require'] && !$this->hasOption( $opt ) ) {
418 $this->error( "Param $opt required!" );
419 $die = true;
420 }
421 }
422 # Check arg list too
423 foreach ( $this->argList as $k => $info ) {
424 if ( $info['require'] && !$this->hasArg( $k ) ) {
425 $this->error( 'Argument <' . $info['name'] . '> required!' );
426 $die = true;
427 }
428 }
429 if ( !$this->allowUnregisteredOptions ) {
430 # Check for unexpected options
431 foreach ( $this->options as $opt => $val ) {
432 if ( !$this->supportsOption( $opt ) ) {
433 $this->error( "Unexpected option $opt!" );
434 $die = true;
435 }
436 }
437 }
438
439 if ( $die ) {
440 $this->maybeHelp( true );
441 }
442 }
443
444 /**
445 * Maybe show the help.
446 * @param bool $force Whether to force the help to show, default false
447 */
448 public function maybeHelp( bool $force = false ): void {
449 if ( !$force && !$this->hasOption( 'help' ) ) {
450 return;
451 }
452
453 $screenWidth = 80; // TODO: Calculate this!
454 $tab = " ";
455 $descWidth = $screenWidth - ( 2 * strlen( $tab ) );
456
457 ksort( $this->params );
458
459 // Description ...
460 if ( $this->description ) {
461 print "\n" . wordwrap( $this->description, $screenWidth ) . "\n";
462 }
463 $output = "\nUsage: php " . basename( $this->self );
464
465 // ... append parameters ...
466 if ( $this->params ) {
467 $output .= " [--" . implode( "|--", array_keys( $this->params ) ) . "]";
468 }
469
470 // ... and append arguments.
471 if ( $this->argList ) {
472 $output .= ' ';
473 foreach ( $this->argList as $k => $arg ) {
474 if ( $arg['require'] ) {
475 $output .= '<' . $arg['name'] . '>';
476 } else {
477 $output .= '[' . $arg['name'] . ']';
478 }
479 if ( $k < count( $this->argList ) - 1 ) {
480 $output .= ' ';
481 }
482 }
483 }
484 print "$output\n\n";
485
486 # TODO abstract some repetitive code below
487
488 // Generic parameters
489 foreach ( $this->genericParameters as $par => $info ) {
490 if ( $info['shortName'] !== false ) {
491 $par .= " (-{$info['shortName']})";
492 }
493 $this->output(
494 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
495 "\n$tab$tab" ) . "\n"
496 );
497 }
498 print "\n";
499
500 $scriptDependantParams = $this->dependentParameters;
501 if ( count( $scriptDependantParams ) > 0 ) {
502 print "Script dependent parameters:\n";
503 // Parameters description
504 foreach ( $scriptDependantParams as $par => $info ) {
505 if ( $info['shortName'] !== false ) {
506 $par .= " (-{$info['shortName']})";
507 }
508 $this->output(
509 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
510 "\n$tab$tab" ) . "\n"
511 );
512 }
513 print "\n";
514 }
515
516 // Script specific parameters not defined on construction by
517 // addDefaultParams()
518 $scriptSpecificParams = array_diff_key(
519 # all script parameters:
520 $this->params,
521 # remove the default parameters:
522 $this->genericParameters,
523 $this->dependentParameters
524 );
525 if ( count( $scriptSpecificParams ) > 0 ) {
526 print "Script specific parameters:\n";
527 // Parameters description
528 foreach ( $scriptSpecificParams as $par => $info ) {
529 if ( $info['shortName'] !== false ) {
530 $par .= " (-{$info['shortName']})";
531 }
532 $this->output(
533 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
534 "\n$tab$tab" ) . "\n"
535 );
536 }
537 print "\n";
538 }
539
540 // Print arguments
541 if ( count( $this->argList ) > 0 ) {
542 print "Arguments:\n";
543 // Arguments description
544 foreach ( $this->argList as $info ) {
545 $openChar = $info['require'] ? '<' : '[';
546 $closeChar = $info['require'] ? '>' : ']';
547 $this->output(
548 wordwrap( "$tab$openChar" . $info['name'] . "$closeChar: " .
549 $info['desc'], $descWidth, "\n$tab$tab" ) . "\n"
550 );
551 }
552 print "\n";
553 }
554
555 die( 1 );
556 }
557
558 /**
559 * Override to redirect opts processor error messages.
560 *
561 * @param string $err
562 */
563 protected function error( string $err ): void {
564 error_log( $err );
565 }
566
567 /**
568 * Override to redirect opts processor output.
569 *
570 * @param string $out
571 */
572 protected function output( string $out ): void {
573 print $out;
574 }
575 }