-
Notifications
You must be signed in to change notification settings - Fork 1k
Expand file tree
/
Copy pathclass-wp-cli.php
More file actions
1746 lines (1551 loc) · 52.2 KB
/
class-wp-cli.php
File metadata and controls
1746 lines (1551 loc) · 52.2 KB
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
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
use cli\Colors;
use Mustangostang\Spyc;
use WP_CLI\Configurator;
use WP_CLI\Dispatcher;
use WP_CLI\Dispatcher\CommandAddition;
use WP_CLI\Dispatcher\CommandFactory;
use WP_CLI\Dispatcher\CommandNamespace;
use WP_CLI\Dispatcher\CompositeCommand;
use WP_CLI\Dispatcher\RootCommand;
use WP_CLI\DocParser;
use WP_CLI\ExitException;
use WP_CLI\FileCache;
use WP_CLI\Loggers\Execution;
use WP_CLI\Path;
use WP_CLI\Process;
use WP_CLI\ProcessRun;
use WP_CLI\Runner;
use WP_CLI\SynopsisParser;
use WP_CLI\Utils;
use WP_CLI\WpHttpCacheManager;
/**
* Various utilities for WP-CLI commands.
*
* @phpstan-type GlobalConfig array{path: string|null, ssh: string|null, 'ssh-args': string[], http: string|null, url: string|null, user: string|null, 'skip-plugins': true|string[], 'skip-themes': true|string[], 'skip-packages': bool, require: string[], exec: string[], context: string, debug: string|true, prompt: false|string, quiet: bool, apache_modules: string[], 'assume-https': bool}
*
* @phpstan-type FlagParameter array{type: 'flag', name: string, description?: string, optional?: bool, repeating?: bool, aliases?: string[]}
* @phpstan-type AssocParameter array{type: 'assoc', name: string, description?: string, options?: string[], default?: string, optional?: bool, value: array{optional: bool, name?: string}, repeating?: bool, aliases?: string[]}
* @phpstan-type PositionalParameter array{type: 'positional', name: string, description?: string, optional?: bool, repeating?: bool}
* @phpstan-type GenericParameter array{type: 'generic', optional?: bool, repeating?: bool}
* @phpstan-type UnknownParameter array{type:'unknown', optional?: bool, repeating?: bool}
* @phpstan-type CommandSynopsis FlagParameter|AssocParameter|PositionalParameter|GenericParameter|UnknownParameter
*/
class WP_CLI {
private static $logger;
private static $hooks = [];
private static $hooks_passed = [];
private static $capture_exit = false;
private static $deferred_additions = [];
/**
* Cached list of global argument names.
*
* @var array|null
*/
private static $global_arg_names;
/**
* Set the logger instance.
*
* @param object $logger Logger instance to set.
*/
public static function set_logger( $logger ) {
self::$logger = $logger;
}
/**
* Get the logger instance.
*
* @return object $logger Logger instance.
*/
public static function get_logger() {
return self::$logger;
}
/**
* Get the Configurator instance
*
* @return Configurator
*/
public static function get_configurator() {
static $configurator;
if ( ! $configurator ) {
$configurator = new Configurator( WP_CLI_ROOT . '/php/config-spec.php' );
}
return $configurator;
}
/**
* @return RootCommand
*/
public static function get_root_command() {
static $root;
if ( ! $root ) {
$root = new RootCommand();
}
return $root;
}
public static function get_runner() {
static $runner;
if ( ! $runner ) {
$runner = new Runner();
}
return $runner;
}
/**
* @return FileCache
*/
public static function get_cache() {
static $cache;
if ( ! $cache ) {
$dir = Utils\get_cache_dir();
$ttl = (int) Utils\get_env_or_config( 'WP_CLI_CACHE_EXPIRY' ) ? : 15552000;
$max_size = (int) Utils\get_env_or_config( 'WP_CLI_CACHE_MAX_SIZE' ) ? : 314572800;
// 6 months, 300mb
$cache = new FileCache( $dir, $ttl, $max_size );
// Clean older files on shutdown with 1/50 probability.
// phpcs:ignore WordPress.WP.AlternativeFunctions.rand_mt_rand -- no crypto and WP not loaded.
if ( 0 === mt_rand( 0, 50 ) ) {
register_shutdown_function(
function () use ( $cache ) {
$cache->clean();
}
);
}
}
return $cache;
}
/**
* Set the context in which WP-CLI should be run
*/
public static function set_url( $url ) {
self::debug( 'Set URL: ' . $url, 'bootstrap' );
$url_parts = Utils\parse_url( $url );
self::set_url_params( $url_parts );
}
private static function set_url_params( $url_parts ) {
$f = function ( $key ) use ( $url_parts ) {
return Utils\get_flag_value( $url_parts, $key, '' );
};
if ( isset( $url_parts['host'] ) ) {
if ( isset( $url_parts['scheme'] ) && 'https' === strtolower( $url_parts['scheme'] ) ) {
$_SERVER['HTTPS'] = 'on';
} elseif ( ! self::get_config( 'assume-https' ) ) {
unset( $_SERVER['HTTPS'] );
}
$_SERVER['HTTP_HOST'] = $url_parts['host'];
if ( isset( $url_parts['port'] ) ) {
$_SERVER['HTTP_HOST'] .= ':' . $url_parts['port'];
}
$_SERVER['SERVER_NAME'] = $url_parts['host'];
}
$_SERVER['REQUEST_URI'] = $f( 'path' ) . ( isset( $url_parts['query'] ) ? '?' . $url_parts['query'] : '' );
$_SERVER['SERVER_PORT'] = Utils\get_flag_value( $url_parts, 'port', '80' );
$_SERVER['QUERY_STRING'] = $f( 'query' );
}
/**
* @return WpHttpCacheManager
*/
public static function get_http_cache_manager() {
static $http_cacher;
if ( ! $http_cacher ) {
$http_cacher = new WpHttpCacheManager( self::get_cache() );
}
return $http_cacher;
}
/**
* Colorize a string for output.
*
* Yes, you can change the color of command line text too. For instance,
* here's how `WP_CLI::success()` colorizes "Success: "
*
* ```
* WP_CLI::colorize( "%GSuccess:%n " )
* ```
*
* Uses `\cli\Colors::colorize()` to transform color tokens to display
* settings. Choose from the following tokens (and note 'reset'):
*
* * %y => ['color' => 'yellow'],
* * %g => ['color' => 'green'],
* * %b => ['color' => 'blue'],
* * %r => ['color' => 'red'],
* * %p => ['color' => 'magenta'],
* * %m => ['color' => 'magenta'],
* * %c => ['color' => 'cyan'],
* * %w => ['color' => 'grey'],
* * %k => ['color' => 'black'],
* * %n => ['color' => 'reset'],
* * %Y => ['color' => 'yellow', 'style' => 'bright'],
* * %G => ['color' => 'green', 'style' => 'bright'],
* * %B => ['color' => 'blue', 'style' => 'bright'],
* * %R => ['color' => 'red', 'style' => 'bright'],
* * %P => ['color' => 'magenta', 'style' => 'bright'],
* * %M => ['color' => 'magenta', 'style' => 'bright'],
* * %C => ['color' => 'cyan', 'style' => 'bright'],
* * %W => ['color' => 'grey', 'style' => 'bright'],
* * %K => ['color' => 'black', 'style' => 'bright'],
* * %N => ['color' => 'reset', 'style' => 'bright'],
* * %3 => ['background' => 'yellow'],
* * %2 => ['background' => 'green'],
* * %4 => ['background' => 'blue'],
* * %1 => ['background' => 'red'],
* * %5 => ['background' => 'magenta'],
* * %6 => ['background' => 'cyan'],
* * %7 => ['background' => 'grey'],
* * %0 => ['background' => 'black'],
* * %F => ['style' => 'blink'],
* * %U => ['style' => 'underline'],
* * %8 => ['style' => 'inverse'],
* * %9 => ['style' => 'bright'],
* * %_ => ['style' => 'bright']
*
* @access public
* @category Output
*
* @param string $string String to colorize for output, with color tokens.
* @return string Colorized string.
*/
public static function colorize( $string ) {
return Colors::colorize( $string, self::get_runner()->in_color() );
}
/**
* Schedule a callback to be executed at a certain point.
*
* Hooks conceptually are very similar to WordPress actions. WP-CLI hooks
* are typically called before WordPress is loaded.
*
* WP-CLI hooks include:
*
* * `before_add_command:<command>` - Before the command is added.
* * `after_add_command:<command>` - After the command was added.
* * `before_invoke:<command>` (1) - Just before a command is invoked.
* * `after_invoke:<command>` (1) - Just after a command is invoked.
* * `find_command_to_run_pre` - Just before WP-CLI finds the command to run.
* * `before_registering_contexts` (1) - Before the contexts are registered.
* * `before_wp_load` - Just before the WP load process begins.
* * `before_wp_config_load` - After wp-config.php has been located.
* * `after_wp_config_load` - After wp-config.php has been loaded into scope.
* * `after_wp_load` - Just after the WP load process has completed.
* * `before_run_command` (3) - Just before the command is executed.
*
* The parentheses behind the hook name denote the number of arguments
* being passed into the hook. For such hooks, the callback should return
* the first argument again, making them work like a WP filter.
*
* WP-CLI commands can create their own hooks with `WP_CLI::do_hook()`.
*
* If additional arguments are passed through the `WP_CLI::do_hook()` call,
* these will be passed on to the callback provided by `WP_CLI::add_hook()`.
*
* ```
* # `wp network meta` confirms command is executing in multisite context.
* WP_CLI::add_command( 'network meta', 'Network_Meta_Command', array(
* 'before_invoke' => function ( $name ) {
* if ( !is_multisite() ) {
* WP_CLI::error( 'This is not a multisite installation.' );
* }
* }
* ) );
* ```
*
* @access public
* @category Registration
*
* @param string $when Identifier for the hook.
* @param callable $callback Callback to execute when hook is called.
* @return void
*/
public static function add_hook( $when, $callback ) {
if ( array_key_exists( $when, self::$hooks_passed ) ) {
self::debug(
sprintf(
'Immediately invoking on passed hook "%s": %s',
$when,
Utils\describe_callable( $callback )
),
'hooks'
);
call_user_func_array( $callback, (array) self::$hooks_passed[ $when ] );
}
self::$hooks[ $when ][] = $callback;
}
/**
* Execute callbacks registered to a given hook.
*
* See `WP_CLI::add_hook()` for details on WP-CLI's internal hook system.
* Commands can provide and call their own hooks.
*
* @access public
* @category Registration
*
* @param string $when Identifier for the hook.
* @param mixed ...$args Optional. Arguments that will be passed onto the
* callback provided by `WP_CLI::add_hook()`.
* @return null|mixed Returns the first optional argument if optional
* arguments were passed, otherwise returns null.
*/
public static function do_hook( $when, ...$args ) {
self::$hooks_passed[ $when ] = $args;
$has_args = count( $args ) > 0;
if ( ! isset( self::$hooks[ $when ] ) ) {
if ( $has_args ) {
return $args[0];
}
return null;
}
self::debug(
sprintf(
'Processing hook "%s" with %d callbacks',
$when,
count( self::$hooks[ $when ] )
),
'hooks'
);
foreach ( self::$hooks[ $when ] as $callback ) {
self::debug(
sprintf(
'On hook "%s": %s',
$when,
Utils\describe_callable( $callback )
),
'hooks'
);
if ( $has_args ) {
$return_value = $callback( ...$args );
if ( isset( $return_value ) ) {
$args[0] = $return_value;
}
} else {
$callback();
}
}
if ( $has_args ) {
return $args[0];
}
return null;
}
/**
* Add a callback to a WordPress action or filter.
*
* `add_action()` without needing access to `add_action()`. If WordPress is
* already loaded though, you should use `add_action()` (and `add_filter()`)
* instead.
*
* @access public
* @category Registration
*
* @param string $tag Named WordPress action or filter.
* @param callable $function_to_add Callable to execute when the action or filter is evaluated.
* @param integer $priority Priority to add the callback as.
* @param integer $accepted_args Number of arguments to pass to callback.
* @return true
*/
public static function add_wp_hook( $tag, $function_to_add, $priority = 10, $accepted_args = 1 ) {
global $wp_filter, $merged_filters;
if ( function_exists( 'add_filter' ) ) {
add_filter( $tag, $function_to_add, $priority, $accepted_args );
} else {
$idx = self::wp_hook_build_unique_id( $tag, $function_to_add, $priority );
// phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited -- This is intentional & the purpose of this function.
$wp_filter[ $tag ][ $priority ][ $idx ] = [
'function' => $function_to_add,
'accepted_args' => $accepted_args,
];
unset( $merged_filters[ $tag ] );
}
return true;
}
/**
* Build Unique ID for storage and retrieval.
*
* Essentially _wp_filter_build_unique_id() without needing access to _wp_filter_build_unique_id()
*/
private static function wp_hook_build_unique_id( $tag, $function, $priority ) {
global $wp_filter;
static $filter_id_count = 0;
if ( is_string( $function ) ) {
return $function;
}
if ( is_object( $function ) ) {
// Closures are currently implemented as objects.
$function = [ $function, '' ];
} else {
$function = (array) $function;
}
if ( is_object( $function[0] ) ) {
// Object Class Calling.
if ( function_exists( 'spl_object_hash' ) ) {
return spl_object_hash( $function[0] ) . $function[1];
}
$obj_idx = get_class( $function[0] ) . $function[1];
// @phpstan-ignore property.notFound
if ( ! isset( $function[0]->wp_filter_id ) ) {
if ( false === $priority ) {
return false;
}
$obj_idx .= isset( $wp_filter[ $tag ][ $priority ] ) ? count( (array) $wp_filter[ $tag ][ $priority ] ) : $filter_id_count;
// @phpstan-ignore property.notFound
$function[0]->wp_filter_id = $filter_id_count;
++$filter_id_count;
} else {
$obj_idx .= $function[0]->wp_filter_id;
}
return $obj_idx;
}
if ( is_string( $function[0] ) ) {
// Static Calling.
return $function[0] . '::' . $function[1];
}
}
/**
* Register a command to WP-CLI.
*
* WP-CLI supports using any callable class, function, or closure as a
* command. `WP_CLI::add_command()` is used for both internal and
* third-party command registration.
*
* Command arguments are parsed from PHPDoc by default, but also can be
* supplied as an optional third argument during registration.
*
* ```
* # Register a custom 'foo' command to output a supplied positional param.
* #
* # $ wp foo bar --append=qux
* # Success: bar qux
*
* /**
* * My awesome closure command
* *
* * <message>
* * : An awesome message to display
* *
* * --append=<message>
* * : An awesome message to append to the original message.
* *
* * @when before_wp_load
* *\/
* $foo = function( $args, $assoc_args ) {
* WP_CLI::success( $args[0] . ' ' . $assoc_args['append'] );
* };
* WP_CLI::add_command( 'foo', $foo );
* ```
*
* @access public
* @category Registration
*
* @param string $name Name for the command (e.g. "post list" or "site empty").
* @param callable|object|string|string[] $callable Command implementation as a class, function or closure.
* @param array $args {
* Optional. An associative array with additional registration parameters.
*
* @type callable $before_invoke Callback to execute before invoking the command.
* @type callable $after_invoke Callback to execute after invoking the command.
* @type string $shortdesc Short description (80 char or less) for the command.
* @type string $longdesc Description of arbitrary length for examples, etc.
* @type string $synopsis The synopsis for the command (string or array).
* @type string $when Execute callback on a named WP-CLI hook (e.g. before_wp_load).
* @type bool $is_deferred Whether the command addition had already been deferred.
* }
* @return bool True on success, false if deferred, hard error if registration failed.
*
* @phpstan-param array{before_invoke?: callable, after_invoke?: callable, shortdesc?: string, longdesc?: string, synopsis?: string|CommandSynopsis[], when?: string, is_deferred?: bool} $args
*/
public static function add_command( $name, $callable, $args = [] ) {
// Bail immediately if the WP-CLI executable has not been run.
if ( ! defined( 'WP_CLI' ) ) {
return false;
}
$valid = false;
if ( is_callable( $callable ) ) {
$valid = true;
} elseif ( is_string( $callable ) && class_exists( $callable ) ) {
$valid = true;
} elseif ( is_object( $callable ) ) {
$valid = true;
} elseif ( is_array( $callable ) && Utils\is_valid_class_and_method_pair( $callable ) ) {
$valid = true;
}
if ( ! $valid ) {
if ( is_array( $callable ) ) {
$callable[0] = is_object( $callable[0] ) ? get_class( $callable[0] ) : $callable[0];
$callable = [ $callable[0], $callable[1] ];
}
self::error( sprintf( 'Callable %s does not exist, and cannot be registered as `wp %s`.', json_encode( $callable ), $name ) );
}
$addition = new CommandAddition();
self::do_hook( "before_add_command:{$name}", $addition );
if ( $addition->was_aborted() ) {
self::warning( "Aborting the addition of the command '{$name}' with reason: {$addition->get_reason()}." );
return false;
}
foreach ( [ 'before_invoke', 'after_invoke' ] as $when ) {
if ( isset( $args[ $when ] ) ) {
self::add_hook( "{$when}:{$name}", $args[ $when ] );
}
}
$path = preg_split( '/\s+/', $name ) ?: [];
$leaf_name = (string) array_pop( $path );
$command = self::get_root_command();
while ( ! empty( $path ) ) {
$subcommand_name = $path[0];
$parent = implode( ' ', $path );
$subcommand = $command->find_subcommand( $path );
// Parent not found. Defer addition or create an empty container as
// needed.
if ( ! $subcommand ) {
if ( isset( $args['is_deferred'] ) && $args['is_deferred'] ) {
$subcommand = new CompositeCommand(
$command,
$subcommand_name,
new DocParser( '' )
);
self::debug(
"Adding empty container for deferred command: {$name}",
'commands'
);
$command->add_subcommand( $subcommand_name, $subcommand );
} else {
self::debug( "Deferring command: {$name}", 'commands' );
/**
* @var callable $callable
*/
self::defer_command_addition(
$name,
$parent,
$callable,
$args
);
return false;
}
}
$command = $subcommand;
}
$leaf_command = CommandFactory::create( $leaf_name, $callable, $command );
// Only add a command namespace if the command itself does not exist yet.
if ( $leaf_command instanceof CommandNamespace
&& array_key_exists( $leaf_name, $command->get_subcommands() ) ) {
return false;
}
// Reattach commands attached to namespace to real command.
$subcommand_name = (array) $leaf_name;
$existing_command = $command->find_subcommand( $subcommand_name );
if ( $existing_command instanceof CompositeCommand && $existing_command->can_have_subcommands() ) {
if ( $leaf_command instanceof CommandNamespace || ! $leaf_command->can_have_subcommands() ) {
$command_to_keep = $existing_command;
} else {
$command_to_keep = $leaf_command;
}
self::merge_sub_commands( $command_to_keep, $existing_command, $leaf_command );
}
/** @var Dispatcher\Subcommand|Dispatcher\CompositeCommand|Dispatcher\CommandNamespace $leaf_command */
if ( ! $command->can_have_subcommands() ) {
throw new Exception(
sprintf(
"'%s' can't have subcommands.",
implode( ' ', Dispatcher\get_path( $command ) )
)
);
}
/** @var Dispatcher\Subcommand $leaf_command */
if ( isset( $args['shortdesc'] ) ) {
$leaf_command->set_shortdesc( $args['shortdesc'] );
}
if ( isset( $args['longdesc'] ) ) {
$leaf_command->set_longdesc( $args['longdesc'] );
}
if ( isset( $args['synopsis'] ) ) {
if ( is_string( $args['synopsis'] ) ) {
$leaf_command->set_synopsis( $args['synopsis'] );
} elseif ( is_array( $args['synopsis'] ) ) {
$synopsis = SynopsisParser::render( $args['synopsis'] );
$leaf_command->set_synopsis( $synopsis );
$long_desc = '';
$bits = explode( ' ', $synopsis );
foreach ( $args['synopsis'] as $key => $arg ) {
$long_desc .= $bits[ $key ] . "\n";
if ( ! empty( $arg['description'] ) ) {
$long_desc .= ': ' . $arg['description'] . "\n";
}
$yamlify = [];
foreach ( [ 'default', 'options' ] as $_key ) {
if ( isset( $arg[ $_key ] ) ) {
$yamlify[ $_key ] = $arg[ $_key ];
}
}
if ( ! empty( $yamlify ) ) {
$long_desc .= Spyc::YAMLDump( $yamlify );
$long_desc .= '---' . "\n";
}
$long_desc .= "\n";
}
if ( ! empty( $long_desc ) ) {
$long_desc = rtrim( $long_desc, "\r\n" );
$long_desc = '## OPTIONS' . "\n\n" . $long_desc;
if ( ! empty( $args['longdesc'] ) ) {
$long_desc .= "\n\n" . ltrim( $args['longdesc'], "\r\n" );
}
$leaf_command->set_longdesc( $long_desc );
}
}
}
if ( isset( $args['when'] ) ) {
self::get_runner()->register_early_invoke( $args['when'], $leaf_command );
}
$command_type = $leaf_command instanceof CommandNamespace ? 'namespace' : 'command';
if ( ! empty( $parent ) ) {
$sub_command = trim( str_replace( $parent, '', $name ) );
self::debug( "Adding {$command_type}: {$sub_command} in {$parent} Namespace", 'commands' );
} else {
self::debug( "Adding {$command_type}: {$name}", 'commands' );
}
$command->add_subcommand( $leaf_name, $leaf_command );
self::do_hook( "after_add_command:{$name}" );
return true;
}
/**
* Merge the sub-commands of two commands into a single command to keep.
*
* @param CompositeCommand $command_to_keep Command to merge the sub commands into. This is typically one of the
* two others.
* @param CompositeCommand $old_command Command that was already registered.
* @param CompositeCommand $new_command New command that is being added.
*/
private static function merge_sub_commands(
CompositeCommand $command_to_keep,
CompositeCommand $old_command,
CompositeCommand $new_command
) {
foreach ( $old_command->get_subcommands() as $subname => $subcommand ) {
$command_to_keep->add_subcommand( $subname, $subcommand, false );
}
foreach ( $new_command->get_subcommands() as $subname => $subcommand ) {
$command_to_keep->add_subcommand( $subname, $subcommand, true );
}
}
/**
* Defer command addition for a sub-command if the parent command is not yet
* registered.
*
* @param string $name Name for the sub-command.
* @param string $parent Name for the parent command.
* @param callable $callable Command implementation as a class, function or closure.
* @param array $args Optional. See `WP_CLI::add_command()` for details.
*/
private static function defer_command_addition( $name, $parent, $callable, $args = [] ) {
$args['is_deferred'] = true;
self::$deferred_additions[ $name ] = [
'parent' => $parent,
'callable' => $callable,
'args' => $args,
];
self::add_hook(
"after_add_command:$parent",
function () use ( $name ) {
$deferred_additions = WP_CLI::get_deferred_additions();
if ( ! array_key_exists( $name, $deferred_additions ) ) {
return;
}
$callable = $deferred_additions[ $name ]['callable'];
$args = $deferred_additions[ $name ]['args'];
WP_CLI::remove_deferred_addition( $name );
WP_CLI::add_command( $name, $callable, $args );
}
);
}
/**
* Get the list of outstanding deferred command additions.
*
* @return array Array of outstanding command additions.
*/
public static function get_deferred_additions() {
return self::$deferred_additions;
}
/**
* Remove a command addition from the list of outstanding deferred additions.
*/
public static function remove_deferred_addition( $name ) {
if ( ! array_key_exists( $name, self::$deferred_additions ) ) {
self::warning( "Trying to remove a non-existent command addition '{$name}'." );
}
unset( self::$deferred_additions[ $name ] );
}
/**
* Check if a command's arguments conflict with global arguments.
*
* Issues warnings for any command arguments that have the same name as
* global WP-CLI arguments (e.g., --debug, --user, --quiet).
*
* @param string $command_name The name of the command being registered.
* @param Dispatcher\Subcommand $command The command object to check.
*/
public static function check_global_arg_conflicts( $command_name, $command ) {
$synopsis = $command->get_synopsis();
if ( ! $synopsis ) {
return;
}
// Check if command has opted out of this check
if ( self::command_skips_global_arg_check( $command ) ) {
return;
}
// Get global argument names from config spec (cached)
if ( null === self::$global_arg_names ) {
self::$global_arg_names = [];
foreach ( self::get_configurator()->get_spec() as $key => $details ) {
if ( false === $details['runtime'] ) {
continue;
}
if ( isset( $details['deprecated'] ) ) {
continue;
}
if ( isset( $details['hidden'] ) ) {
continue;
}
self::$global_arg_names[] = $key;
}
}
// Parse the command's synopsis to get its argument names
$synopsis_params = SynopsisParser::parse( $synopsis );
$conflicts = [];
foreach ( $synopsis_params as $param ) {
// Check assoc and flag types; generic type has no specific name to conflict
if ( in_array( $param['type'], [ 'assoc', 'flag' ], true ) && isset( $param['name'] ) ) {
if ( in_array( $param['name'], self::$global_arg_names, true ) ) {
$conflicts[] = $param['name'];
}
}
}
// Warn about any conflicts found
foreach ( $conflicts as $conflict ) {
self::warning(
sprintf(
"The `%s` command is registering an argument '--%s' that conflicts with a global argument of the same name.",
$command_name,
$conflict
)
);
}
}
/**
* Check if a command has opted out of global argument conflict checking.
*
* Commands can use the @skipglobalargcheck tag in their PHPdoc to disable
* the warning for global argument conflicts.
*
* @param Dispatcher\Subcommand $command The command object to check.
* @return bool True if the command should skip the check, false otherwise.
*/
private static function command_skips_global_arg_check( $command ) {
$docparser = $command->get_docparser();
if ( ! $docparser ) {
return false;
}
return $docparser->has_tag( 'skipglobalargcheck' );
}
/**
* Display informational message without prefix, and ignore `--quiet`.
*
* Message is written to STDOUT. `WP_CLI::log()` is typically recommended;
* `WP_CLI::line()` is included for historical compat.
*
* @access public
* @category Output
*
* @param string $message Message to display to the end user.
* @param bool $newline Optional. Whether to append a newline to the end of the message. Default true.
* @return void
*/
public static function line( $message = '', $newline = true ) {
echo $message . ( $newline ? "\n" : '' );
}
/**
* Display informational message without prefix.
*
* Message is written to STDOUT, or discarded when `--quiet` flag is supplied.
*
* ```
* # `wp cli update` lets user know of each step in the update process.
* WP_CLI::log( sprintf( 'Downloading from %s...', $download_url ) );
* ```
*
* @access public
* @category Output
*
* @param string $message Message to write to STDOUT.
* @param bool $newline Optional. Whether to append a newline to the end of the message. Default true.
*/
public static function log( $message, $newline = true ) {
if ( null === self::$logger ) {
return;
}
self::$logger->info( $message, $newline );
}
/**
* Display success message prefixed with "Success: ".
*
* Success message is written to STDOUT, or discarded when `--quiet` flag is supplied.
*
* Typically recommended to inform user of successful script conclusion.
*
* ```
* # wp rewrite flush expects 'rewrite_rules' option to be set after flush.
* flush_rewrite_rules( \WP_CLI\Utils\get_flag_value( $assoc_args, 'hard' ) );
* if ( ! get_option( 'rewrite_rules' ) ) {
* WP_CLI::warning( "Rewrite rules are empty." );
* } else {
* WP_CLI::success( 'Rewrite rules flushed.' );
* }
* ```
*
* @access public
* @category Output
*
* @param string $message Message to write to STDOUT.
* @return void
*/
public static function success( $message ) {
if ( null === self::$logger ) {
return;
}
self::$logger->success( $message );
}
/**
* Display debug message prefixed with "Debug: " when `--debug` is used.
*
* Debug message is written to STDERR, and includes script execution time.
*
* Helpful for optionally showing greater detail when needed. Used throughout
* WP-CLI bootstrap process for easier debugging and profiling.
*
* ```
* # Called in `WP_CLI\Runner::set_wp_root()`.
* private static function set_wp_root( $path ) {
* define( 'ABSPATH', Utils\trailingslashit( $path ) );
* WP_CLI::debug( 'ABSPATH defined: ' . ABSPATH );
* $_SERVER['DOCUMENT_ROOT'] = realpath( $path );
* }
*
* # Debug details only appear when `--debug` is used.
* # $ wp --debug
* # [...]
* # Debug: ABSPATH defined: /srv/www/wordpress-develop.dev/src/ (0.225s)
* ```
*
* @access public
* @category Output
*
* @param string|WP_Error|Exception|Throwable $message Message to write to STDERR.
* @param string|bool $group Organize debug message to a specific group.
* Use `false` to not group the message.
* @return void
*/
public static function debug( $message, $group = false ) {
static $storage = [];
if ( ! self::$logger ) {
$storage[] = [ $message, $group ];
return;
}
if ( ! empty( $storage ) ) {
foreach ( $storage as $entry ) {
list( $stored_message, $stored_group ) = $entry;
self::$logger->debug( self::error_to_string( $stored_message ), $stored_group );
}
$storage = [];
}
self::$logger->debug( self::error_to_string( $message ), $group );
}
/**
* Display warning message prefixed with "Warning: ".
*
* Warning message is written to STDERR, or discarded when `--quiet` flag is supplied.
*
* Use instead of `WP_CLI::debug()` when script execution should be permitted
* to continue.
*
* ```
* # `wp plugin activate` skips activation when plugin is network active.
* $status = $this->get_status( $plugin->file );
* // Network-active is the highest level of activation status
* if ( 'active-network' === $status ) {
* WP_CLI::warning( "Plugin '{$plugin->name}' is already network active." );
* continue;
* }
* ```
*
* @access public
* @category Output
*
* @param string|WP_Error|Exception|Throwable $message Message to write to STDERR.
* @return void
*/
public static function warning( $message ) {
if ( null === self::$logger ) {
return;
}
self::$logger->warning( self::error_to_string( $message ) );
}
/**
* Display error message prefixed with "Error: " and exit script.