aboutsummaryrefslogtreecommitdiffstats
path: root/maintenance/includes/MaintenanceParameters.php
blob: a03b769359589c4f2f98d75f88269e6c02365722 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
<?php
/**
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 * http://www.gnu.org/copyleft/gpl.html
 *
 * @file
 */

namespace MediaWiki\Maintenance;

use UnexpectedValueException;

/**
 * Command line parameter handling for maintenance scripts.
 *
 * @since 1.39
 * @ingroup Maintenance
 */
class MaintenanceParameters {

	/**
	 * Array of desired/allowed params
	 * @var array<string,array>
	 * @phan-var array<string,array{desc:string,require:bool,withArg:string,shortName:string|bool,multiOccurrence:bool}>
	 */
	private $mOptDefs = [];

	/** @var array<string,string> Mapping short options to long ones */
	private $mShortOptionMap = [];

	/** @var array<int,array> Desired/allowed args */
	private $mArgDefs = [];

	/** @var array<string,int> Map of arg names to offsets */
	private $mArgOffsets = [];

	/** @var bool Allow arbitrary options to be passed, or only specified ones? */
	private $mAllowUnregisteredOptions = false;

	/** @var string|null Name of the script currently running */
	private $mName = null;

	/** @var string|null A description of the script, children should change this via addDescription() */
	private $mDescription = null;

	/** @var array<string,string> This is the list of options that were actually passed */
	private $mOptions = [];

	/** @var array<int,string> This is the list of arguments that were actually passed */
	private $mArgs = [];

	/** @var array<string,array> maps group names to lists of option names */
	private $mOptionGroups = [];

	/**
	 * Used to read the options in the order they were passed.
	 * This is an array of arrays where
	 * 0 => the option name and 1 => option value.
	 *
	 * @var array
	 */
	private $optionsSequence = [];

	/** @var string[] */
	private $errors = [];

	/** @var string */
	private $usagePrefix = 'php maintenance/run.php';

	/**
	 * Returns a reference to a member field.
	 * This is a backwards compatibility hack, it should be removed as soon as possible!
	 *
	 * @param string $fieldName
	 *
	 * @return mixed A reference to a member field
	 * @internal For use by the Maintenance class, for backwards compatibility support.
	 */
	public function &getFieldReference( string $fieldName ) {
		return $this->$fieldName;
	}

	/**
	 * Assigns a list of options to the given group.
	 * The given options will be shown as part of the given group
	 * in the help message.
	 *
	 * @param string $groupName
	 * @param array $paramNames
	 */
	public function assignGroup( string $groupName, array $paramNames ) {
		$this->mOptionGroups[ $groupName ] = array_merge(
			$this->mOptionGroups[ $groupName ] ?? [],
			$paramNames
		);
	}

	/**
	 * Checks to see if a particular option in supported. Normally this means it
	 * has been registered by the script via addOption.
	 * @param string $name The name of the option<string,string>
	 * @return bool true if the option exists, false otherwise
	 */
	public function supportsOption( string $name ) {
		return isset( $this->mOptDefs[$name] );
	}

	/**
	 * Add a option to the script. Will be displayed on --help
	 * with the associated description
	 *
	 * @param string $name The name of the param (help, version, etc)
	 * @param string $description The description of the param to show on --help
	 * @param bool $required Is the param required?
	 * @param bool $withArg Is an argument required with this option?
	 * @param string|bool $shortName Character to use as short name
	 * @param bool $multiOccurrence Can this option be passed multiple times?
	 */
	public function addOption( string $name, string $description, bool $required = false,
		bool $withArg = false, $shortName = false, bool $multiOccurrence = false
	) {
		$this->mOptDefs[$name] = [
			'desc' => $description,
			'require' => $required,
			'withArg' => $withArg,
			'shortName' => $shortName,
			'multiOccurrence' => $multiOccurrence
		];

		if ( $shortName !== false ) {
			$this->mShortOptionMap[$shortName] = $name;
		}
	}

	/**
	 * Checks to see if a particular option was set.
	 *
	 * @param string $name The name of the option
	 * @return bool
	 */
	public function hasOption( string $name ): bool {
		return isset( $this->mOptions[$name] );
	}

	/**
	 * Get the value of an option, or return the default.
	 *
	 * If the option was defined to support multiple occurrences,
	 * this will return an array.
	 *
	 * @param string $name The name of the param
	 * @param mixed|null $default Anything you want, default null
	 * @return mixed
	 * @return-taint none
	 */
	public function getOption( string $name, $default = null ) {
		if ( $this->hasOption( $name ) ) {
			return $this->mOptions[$name];
		} else {
			return $default;
		}
	}

	/**
	 * Define a positional argument. getArg() can later be used to get the value given
	 * for the argument, by index or by name.
	 *
	 * @param string $arg Name of the arg, like 'start'
	 * @param string $description Short description of the arg
	 * @param bool $required Is this required?
	 * @param bool $multi Does it allow multiple values? (Last arg only)
	 * @return int the offset of the argument
	 */
	public function addArg( string $arg, string $description, bool $required = true, bool $multi = false ): int {
		if ( isset( $this->mArgOffsets[$arg] ) ) {
			throw new UnexpectedValueException( "Argument already defined: $arg" );
		}

		$argCount = count( $this->mArgDefs );
		if ( $argCount ) {
			$prevArg = $this->mArgDefs[ $argCount - 1 ];
			if ( !$prevArg['require'] && $required ) {
				throw new UnexpectedValueException(
					"Required argument {$arg} cannot follow an optional argument {$prevArg['name']}"
				);
			}

			if ( $prevArg['multi'] ) {
				throw new UnexpectedValueException(
					"Argument {$arg} cannot follow multi-value argument {$prevArg['name']}"
				);
			}
		}

		$this->mArgDefs[] = [
			'name' => $arg,
			'desc' => $description,
			'require' => $required,
			'multi' => $multi,
		];

		$ofs = count( $this->mArgDefs ) - 1;
		$this->mArgOffsets[$arg] = $ofs;
		return $ofs;
	}

	/**
	 * Remove an option. Useful for removing options that won't be used in your script.
	 * @param string $name The option to remove.
	 */
	public function deleteOption( string $name ) {
		unset( $this->mOptDefs[$name] );
		unset( $this->mOptions[$name] );

		foreach ( $this->optionsSequence as $i => [ $opt, ] ) {
			if ( $opt === $name ) {
				unset( $this->optionsSequence[$i] );
				break;
			}
		}
	}

	/**
	 * Sets whether to allow unknown options to be passed to the script.
	 * By default, unknown options cause an error.
	 * @param bool $allow Should we allow?
	 */
	public function setAllowUnregisteredOptions( bool $allow ) {
		$this->mAllowUnregisteredOptions = $allow;
	}

	/**
	 * Set a short description of what the script does.
	 */
	public function setDescription( string $text ) {
		$this->mDescription = $text;
	}

	/**
	 * Was a value for the given argument provided?
	 * @param int|string $argId The index (from zero) of the argument, or
	 *                   the name declared for the argument by addArg().
	 * @return bool
	 */
	public function hasArg( $argId ): bool {
		// arg lookup by name
		if ( is_string( $argId ) && isset( $this->mArgOffsets[$argId] ) ) {
			$argId = $this->mArgOffsets[$argId];
		}

		return isset( $this->mArgs[$argId] );
	}

	/**
	 * Get an argument.
	 * @param int|string $argId The index (from zero) of the argument, or
	 *                   the name declared for the argument by addArg().
	 * @param string|null $default The default if it doesn't exist
	 * @return string|null
	 * @return-taint none
	 */
	public function getArg( $argId, ?string $default = null ): ?string {
		// arg lookup by name
		if ( is_string( $argId ) && isset( $this->mArgOffsets[$argId] ) ) {
			$argId = $this->mArgOffsets[$argId];
		}

		return $this->mArgs[$argId] ?? $default;
	}

	/**
	 * Get arguments.
	 * @param int|string $offset The index (from zero) of the first argument, or
	 *                   the name declared for the argument by addArg().
	 * @return string[]
	 */
	public function getArgs( $offset = 0 ): array {
		if ( is_string( $offset ) && isset( $this->mArgOffsets[$offset] ) ) {
			$offset = $this->mArgOffsets[$offset];
		}

		return array_slice( $this->mArgs, $offset );
	}

	/**
	 * Get the name of an argument at the given index.
	 *
	 * @param int $argIndex The integer value (from zero) for the arg
	 *
	 * @return string|null The name of the argument, or null if the argument does not exist.
	 */
	public function getArgName( int $argIndex ): ?string {
		return $this->mArgDefs[ $argIndex ]['name'] ?? null;
	}

	/**
	 * Programmatically set the value of the given option.
	 * Useful for setting up child scripts, see runChild().
	 *
	 * @param string $name
	 * @param mixed|null $value
	 */
	public function setOption( string $name, $value ): void {
		$this->mOptions[$name] = $value;
	}

	/**
	 * Programmatically set the value of the given argument.
	 * Useful for setting up child scripts, see runChild().
	 *
	 * @param string|int $argId
	 * @param string $value
	 */
	public function setArg( $argId, $value ): void {
		// arg lookup by name
		if ( is_string( $argId ) && isset( $this->mArgOffsets[$argId] ) ) {
			$argId = $this->mArgOffsets[$argId];
		}
		$this->mArgs[$argId] = $value;
	}

	/**
	 * Clear all parameter values.
	 * Note that all parameter definitions remain intact.
	 */
	public function clear() {
		$this->mOptions = [];
		$this->mArgs = [];
		$this->optionsSequence = [];
		$this->errors = [];
	}

	/**
	 * Merge options declarations from $other into this instance.
	 */
	public function mergeOptions( MaintenanceParameters $other ) {
		$this->mOptDefs = $other->mOptDefs + $this->mOptDefs;
		$this->mShortOptionMap = $other->mShortOptionMap + $this->mShortOptionMap;

		$this->mOptionGroups = array_merge_recursive( $this->mOptionGroups, $other->mOptionGroups );

		$this->clear();
	}

	/**
	 * Load params and arguments from a given array
	 * of command-line arguments
	 *
	 * @param array $argv The argument array.
	 * @param int $skip Skip that many elements at the beginning of $argv.
	 */
	public function loadWithArgv( array $argv, int $skip = 0 ) {
		$this->clear();

		$options = [];
		$args = [];
		$this->optionsSequence = [];

		// Ignore a number of arguments at the beginning of the array.
		// Typically used to ignore the script name at index 0.
		$argv = array_slice( $argv, $skip );

		# Parse arguments
		for ( $arg = reset( $argv ); $arg !== false; $arg = next( $argv ) ) {
			if ( $arg == '--' ) {
				# End of options, remainder should be considered arguments
				$arg = next( $argv );
				while ( $arg !== false ) {
					$args[] = $arg;
					$arg = next( $argv );
				}
				break;
			} elseif ( substr( $arg, 0, 2 ) == '--' ) {
				# Long options
				$option = substr( $arg, 2 );
				if ( isset( $this->mOptDefs[$option] ) && $this->mOptDefs[$option]['withArg'] ) {
					$param = next( $argv );
					if ( $param === false ) {
						$this->error( "Option --$option needs a value after it!" );
					}

					$this->setOptionValue( $options, $option, $param );
				} else {
					$bits = explode( '=', $option, 2 );
					$this->setOptionValue( $options, $bits[0], $bits[1] ?? 1 );
				}
			} elseif ( $arg == '-' ) {
				# Lonely "-", often used to indicate stdin or stdout.
				$args[] = $arg;
			} elseif ( substr( $arg, 0, 1 ) == '-' ) {
				# Short options
				$argLength = strlen( $arg );
				for ( $p = 1; $p < $argLength; $p++ ) {
					$givenShort = $arg[$p];
					$option = $givenShort;
					if ( !isset( $this->mOptDefs[$givenShort] ) && isset( $this->mShortOptionMap[$givenShort] ) ) {
						$option = $this->mShortOptionMap[$givenShort];
					}

					if ( isset( $this->mOptDefs[$option]['withArg'] ) && $this->mOptDefs[$option]['withArg'] ) {
						$param = next( $argv );
						if ( $param === false ) {
							$this->error( "Option -$givenShort needs a value after it!" );
						}
						$this->setOptionValue( $options, $option, $param );
					} else {
						$this->setOptionValue( $options, $option, 1 );
					}
				}
			} else {
				$args[] = $arg;
			}
		}

		$this->mOptions = $options;
		$this->mArgs = $args;
	}

	/**
	 * Helper function used solely by loadWithArgv
	 * to prevent code duplication
	 *
	 * This sets the param in the options array based on
	 * whether or not it can be specified multiple times.
	 *
	 * @param array &$options
	 * @param string $option
	 * @param mixed $value
	 */
	private function setOptionValue( array &$options, string $option, $value ) {
		$this->optionsSequence[] = [ $option, $value ];

		if ( isset( $this->mOptDefs[$option] ) ) {
			$multi = $this->mOptDefs[$option]['multiOccurrence'];
		} else {
			$multi = false;
		}
		$exists = array_key_exists( $option, $options );
		if ( $multi && $exists ) {
			$options[$option][] = $value;
		} elseif ( $multi ) {
			$options[$option] = [ $value ];
		} elseif ( !$exists ) {
			$options[$option] = $value;
		} else {
			$this->error( "Option --$option given twice" );
		}
	}

	private function error( string $msg ) {
		$this->errors[] = $msg;
	}

	/**
	 * Get any errors encountered while processing parameters.
	 *
	 * @return string[]
	 */
	public function getErrors(): array {
		return $this->errors;
	}

	/**
	 * Whether any errors have been recorded so far.
	 */
	public function hasErrors(): bool {
		return (bool)$this->errors;
	}

	/**
	 * Set the script name, for use in the help message
	 */
	public function setName( string $name ) {
		$this->mName = $name;
	}

	/**
	 * Get the script name, as shown in the help message
	 */
	public function getName(): string {
		return $this->mName;
	}

	/**
	 * Force option and argument values.
	 *
	 * @internal
	 *
	 * @param array $opts
	 * @param array $args
	 */
	public function setOptionsAndArgs( array $opts, array $args ) {
		$this->mOptions = $opts;
		$this->mArgs = $args;

		$this->optionsSequence = [];
		foreach ( $opts as $name => $value ) {
			$array = (array)$value;

			foreach ( $array as $v ) {
				$this->optionsSequence[] = [ $name, $v ];
			}
		}
	}

	/**
	 * Run some validation checks on the params, etc.
	 *
	 * Error details can be obtained via getErrors().
	 *
	 * @return bool
	 */
	public function validate() {
		$valid = true;
		# Check to make sure we've got all the required options
		foreach ( $this->mOptDefs as $opt => $info ) {
			if ( $info['require'] && !$this->hasOption( $opt ) ) {
				$this->error( "Option --$opt is required!" );
				$valid = false;
			}
		}
		# Check arg list too
		foreach ( $this->mArgDefs as $k => $info ) {
			if ( $info['require'] && !$this->hasArg( $k ) ) {
				$this->error( 'Argument <' . $info['name'] . '> is required!' );
				$valid = false;
			}
		}
		if ( !$this->mAllowUnregisteredOptions ) {
			# Check for unexpected options
			foreach ( $this->mOptions as $opt => $val ) {
				if ( !$this->supportsOption( $opt ) ) {
					$this->error( "Unexpected option --$opt!" );
					$valid = false;
				}
			}
		}

		return $valid;
	}

	/**
	 * Get help text.
	 */
	public function getHelp(): string {
		$screenWidth = 80; // TODO: Calculate this!
		$tab = "    ";
		$descWidth = $screenWidth - ( 2 * strlen( $tab ) );

		ksort( $this->mOptDefs );

		$output = [];

		// Description ...
		if ( $this->mDescription ) {
			$output[] = "\n" . wordwrap( $this->mDescription, $screenWidth ) . "\n";
		}
		$output[] = "\nUsage: {$this->usagePrefix} " . basename( $this->mName );

		// ... append options ...
		if ( $this->mOptDefs ) {
			$output[] = ' [OPTION]...';

			foreach ( $this->mOptDefs as $name => $opt ) {
				if ( $opt['require'] ) {
					$output[] = " --$name";

					if ( $opt['withArg'] ) {
						$vname = strtoupper( $name );
						$output[] = " <$vname>";
					}
				}
			}
		}

		// ... and append arguments.
		if ( $this->mArgDefs ) {
			$args = '';
			foreach ( $this->mArgDefs as $arg ) {
				$argRepr = $this->getArgRepresentation( $arg );

				$args .= ' ';
				$args .= $argRepr;
			}
			$output[] = $args;
		}
		$output[] = "\n\n";

		// Go through the declared groups and output the options for each group separately.
		// Maintain the remaining options in $params.
		$params = $this->mOptDefs;
		foreach ( $this->mOptionGroups as $groupName => $groupOptions ) {
			$output[] = $this->formatHelpItems(
				array_intersect_key( $params, array_flip( $groupOptions ) ),
				$groupName,
				$descWidth, $tab
			);
			$params = array_diff_key( $params, array_flip( $groupOptions ) );
		}

		$output[] = $this->formatHelpItems(
			$params,
			'Script specific options',
			$descWidth, $tab
		);

		// Print arguments
		if ( count( $this->mArgDefs ) > 0 ) {
			$output[] = "Arguments:\n";
			// Arguments description
			foreach ( $this->mArgDefs as $info ) {
				$argRepr = $this->getArgRepresentation( $info );
				$output[] =
					wordwrap(
						"$tab$argRepr: " . $info['desc'],
						$descWidth,
						"\n$tab$tab"
					) . "\n";
			}
			$output[] = "\n";
		}

		return implode( '', $output );
	}

	private function formatHelpItems( array $items, string $heading, int $descWidth, string $tab ): string {
		if ( $items === [] ) {
			return '';
		}

		$output = [];

		$output[] = "$heading:\n";

		foreach ( $items as $name => $info ) {
			$out = $name;

			if ( $info['shortName'] !== false ) {
				$out .= ' (-' . $info['shortName'] . ')';
			}

			if ( $info['withArg'] ) {
				$vname = strtoupper( $name );
				$out .= " <$vname>";
			}

			$output[] =
				wordwrap(
					"$tab--$out: " . strtr( $info['desc'], [ "\n" => "\n$tab$tab" ] ),
					$descWidth,
					"\n$tab$tab"
				) . "\n";
		}

		$output[] = "\n";

		return implode( '', $output );
	}

	/**
	 * Returns the names of defined options
	 * @return string[]
	 */
	public function getOptionNames(): array {
		return array_keys( $this->mOptDefs );
	}

	/**
	 * Returns any option values
	 */
	public function getOptions(): array {
		return $this->mOptions;
	}

	/**
	 * Returns option values as an ordered sequence.
	 * Useful for option chaining (Ex. dumpBackup.php).
	 * @return array[] a list of pairs of like [ $option, $value ]
	 */
	public function getOptionsSequence(): array {
		return $this->optionsSequence;
	}

	public function setUsagePrefix( string $usagePrefix ) {
		$this->usagePrefix = $usagePrefix;
	}

	private function getArgRepresentation( array $argInfo ): string {
		if ( $argInfo['require'] ) {
			$rep = '<' . $argInfo['name'] . '>';
		} else {
			$rep = '[' . $argInfo['name'] . ']';
		}

		if ( $argInfo['multi'] ) {
			$rep .= '...';
		}

		return $rep;
	}

}