-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTaskRunner.php
1572 lines (1334 loc) · 47.6 KB
/
TaskRunner.php
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
/**
* Blend - PHP Task Runner
*
* @author Marwan Al-Soltany <[email protected]>
* @copyright Marwan Al-Soltany 2021
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
declare(strict_types=1);
namespace MAKS\Blend;
/**
* @package MAKS\Blend
* @link https://github.com/MarwanAlsoltany/blend Blend Repository
*
* @method void handleException(\Throwable $exception) Exception handler function.
* @method void handleError(int $code, string $message, string $file, int $line) Error handler function.
* @method mixed shutdown() Shutdown function. This method is abstract, implement it using `self::extend()`.
*/
class TaskRunner
{
/**
* Package repo.
*
* @var string
*
* @since 1.1.1
*/
public const REPO = 'https://github.com/MarwanAlsoltany/blend';
/**
* Package name.
*
* @var string
*
* @since 1.0.10
*/
public const NAME = 'Blend';
/**
* Package version.
*
* @var string
*/
public const VERSION = 'v1.1.1';
/**
* Default executables.
*
* @var array
*/
public const EXECUTABLES = [
'php' => [
'./bin/*',
],
];
/**
* Default task name translations.
*
* @var array
*/
public const TRANSLATIONS = [
// file extensions with dots, come first to minimize unexpected name translations
'/\.(php|phar|sh)/' => '',
'/[-_\\\\\/\s]/' => ':',
'@' => '', '#' => '', '$' => '', '&' => '', '?' => '', '!' => '',
'(' => '', ')' => '', '{' => '', '}' => '', '[' => '', ']' => '',
'+' => '', '*' => '', '=' => '', '^' => '', '~' => '', '%' => '',
'.' => '', ',' => '', ';' => '', '`' => '', '"' => '', "'" => '',
];
/**
* Default config.
*
* @var array
*/
public const CONFIG = [
'autoload' => null, // (string|null)
'merge' => null, // (bool|null)
'executables' => null, // (array[]|null)
'translations' => null, // (string[]|null)
'ansi' => null, // (bool|null)
'quiet' => null, // (bool|null)
'tasks' => null, // (array[]|null)
];
/**
* Task success code.
*
* @var int
*
* @since 1.0.2
*/
public const SUCCESS = 0;
/**
* Task failure code.
*
* @var int
*
* @since 1.0.2
*/
public const FAILURE = 1;
/**
* Task type callback.
*
* @var string
*/
public const CALLBACK_TASK = 'callback';
/**
* Task type shell.
*
* @var string
*/
public const SHELL_TASK = 'shell';
/**
* Task type internal.
*
* @var string
*/
protected const INTERNAL_TASK = 'internal';
/**
* A reference to the `$argc` global variable.
*
* @var int
*/
public int $argc;
/**
* A reference to the `$argv` global variable.
*
* @var array
*/
public array $argv;
/**
* An array of the arguments that could be passed to the executed task.
*
* @var array
*/
public array $args;
/**
* Environment variable.
*
* @var string
*/
private string $envVar;
/**
* Task runner path.
*
* @var string
* @since 1.0.4
*/
protected string $path;
/**
* Task runner ID.
*
* @var string
*/
protected string $id;
/**
* Task runner name.
*
* @var string
*/
protected string $name;
/**
* Task runner version.
*
* @var string
*/
protected string $version;
/**
* The current task name passed to the task runner.
*
* @var string
*/
protected string $task;
/**
* Task runner tasks.
*
* @var array
*/
protected array $tasks;
/**
* Magic methods added via `self::extend()`.
*
* @var array
*/
protected array $methods;
/**
* The results of commands executed via `self::exec()`.
*
* @var array
*
* @since 1.0.7
*/
protected array $results;
/**
* The executables that will be loaded.
*
* @var array
*/
protected array $executables;
/**
* The translations that will be applied to tasks names.
*
* @var array
*/
protected array $translations;
/**
* The currently loaded configuration.
*
* @var array
*/
protected array $config;
/**
* Whether or not to turn on ANSI colors for the output.
*
* @var bool
*/
protected bool $ansi;
/**
* Whether or not to turn on the output.
*
* @var bool
*/
protected bool $quiet;
/**
* Class constructor.
* Use `self::extend()` to add a method with the name shutdown to be used as a shutdown function that is bound to the object.
*
* @param array[]|null $executables [optional] Executables to load. Example: `['php' => ['./bin', './scripts'], ...]`, paths can be glob patterns.
* @param string[]|null $translations [optional] Task name translations `['search' => 'replacement', ...]`.
* @param mixed[]|null $config [optional] The configuration to use. If a configuration file is found in CWD or a parent, this will be overridden.
* @param bool $ansi [optional] Whether or not to turn on ANSI colors for the output.
* @param bool $quiet [optional] Whether or not to turn on the output.
*/
public function __construct(?array $executables = null, ?array $translations = null, ?array $config = null, bool $ansi = true, bool $quiet = false)
{
global $argv;
global $argc;
$this->argc = &$argc;
$this->argv = &$argv;
$this->args = array_slice($argv, 2);
$this->path = realpath($this->argv[0]);
$this->id = basename($this->argv[0]);
$this->name = ucfirst($this->id);
$this->envVar = 'TR_' . strtr(strtoupper($this->id), ['.' => '_', '-' => '_']);
$this->version = static::VERSION;
$this->task = $this->argv[1] ?? '';
$this->tasks = [];
$this->methods = [];
$this->results = [];
$this->executables = $executables ?? static::EXECUTABLES;
$this->translations = $translations ?? static::TRANSLATIONS;
$this->config = $config ?? static::CONFIG;
$this->ansi = $ansi;
$this->quiet = $quiet;
$this->registerHandlers();
$this->checkEnvironment();
$this->checkConfiguration();
$this->bootstrap();
}
public function __destruct()
{
$this->restoreHandlers();
}
public function __call(string $method, array $arguments)
{
if (isset($this->methods[$method])) {
return $this->methods[$method](...$arguments);
}
$class = static::class;
if ($method === 'shutdown') {
return $class;
}
throw new \BadMethodCallException("Call to undefined method {$class}::{$method}()");
}
public function __toString()
{
return sprintf('%s [%s]', self::class, $this->path);
}
/**
* Extends the class with a magic method using the passed callback.
* The passed function will get converted to a closure and get bound to the object
* with `object` visibility (can access private, protected, and public members).
*
* @param string $name Method name.
* @param callable $callback The callback to use as method body.
*
* @return callable The created bound closure.
*/
public function extend(string $name, callable $callback): callable
{
$method = \Closure::fromCallable($callback);
$method = \Closure::bind($method, $this, $this);
return $this->methods[$name] = $method;
}
/**
* Registers error handler, exception handler, and shutdown function.
*
* @return void
*/
private function registerHandlers(): void
{
$this->extend('handleError', function (int $code, string $message, string $file, int $line): void {
throw new \ErrorException($message, 1, $code, $file, $line);
});
$this->extend('handleException', function (\Throwable $exception): void {
$this->write(
['', '@(b,r)[{ ERROR }] %s @(y)[{[%s]}]', ''],
[$exception->getMessage(), (new \ReflectionClass($exception))->getShortName()]
);
$this->terminate(static::FAILURE);
});
set_time_limit(0);
set_error_handler([$this, 'handleError']);
set_exception_handler([$this, 'handleException']);
register_shutdown_function([$this, 'shutdown']);
}
/**
* Restores the error handler and the exception handler.
*
* @return void
*/
private function restoreHandlers(): void
{
restore_error_handler();
restore_exception_handler();
}
/**
* Checks the environment for TR_* variable, validates its pattern and updates class internal state.
*
* @return void
*
* @throws \RuntimeException If TR_* variable pattern is invalid.
*/
private function checkEnvironment(): void
{
$env = getenv($this->envVar);
if (!$env) {
return;
}
if (!preg_match('/(.+):((.+)(,*)\+?)/', $env)) {
throw new \RuntimeException("The '{$this->envVar}' environment variable pattern is invalid, it does not match 'exe:dir,...+...'");
}
$executables = [];
foreach (explode('+', $env) ?: [] as $exec) {
$exec = explode(':', strtr($exec, [':\\' => '?\\']));
$dirs = $exec[1] ?? '';
$exec = $exec[0] ?? '';
$dirs = explode(',', strtr($dirs, ['?\\' => ':\\']));
$executables[$exec] = $dirs;
}
$this->executables = array_merge_recursive($this->executables, $executables);
}
/**
* Checks the CWD or its parent(s) for a configuration file, validates its entries and updates class internal state.
*
* @return void
*
* @throws \RuntimeException If the configuration is invalid.
*/
private function checkConfiguration(): void
{
$config = $this->config;
$rootRegex = '/(^\/$)|(^[A-Z]:(\\\|\/)$)/i';
$cwd = getcwd();
while (!preg_match($rootRegex, $cwd)) {
$php = sprintf('%s/%s.config.%s', $cwd, $this->id, 'php');
$json = sprintf('%s/%s.config.%s', $cwd, $this->id, 'json');
if (file_exists($file = $php) || file_exists($file = $json)) {
$type = strtoupper(pathinfo($file, PATHINFO_EXTENSION));
$config = $type === 'JSON'
? json_decode(file_get_contents($file), true)
: include($file);
$config['__PATH__'] = realpath($file);
break;
}
$cwd = dirname($cwd);
}
$invalid = array_diff_key(array_flip(array_keys(static::CONFIG)), $config);
if ($invalid) {
$missing = "['" . implode("', '", array_flip($invalid)) . "']";
throw new \RuntimeException("Blend config file '{$config['__PATH__']}' is invalid, missing {$missing}");
}
$this->config = $config;
}
/**
* Terminates the task runner by exiting the script.
*
* @param mixed $code The exit code.
*
* @return void This method exists the script.
*/
protected function terminate($code = 0): void
{
exit($code); // @codeCoverageIgnore
}
/**
* Bootstraps the task runner by adding predefined tasks.
*
* @return void
*/
protected function bootstrap(): void
{
$config = (object)[
'autoload' => (string)($this->config['autoload'] ?? null),
'merge' => (bool)($this->config['merge'] ?? true),
'executables' => (array)($this->config['executables'] ?? null),
'translations' => (array)($this->config['translations'] ?? null),
'ansi' => (bool)($this->config['ansi'] ?? $this->ansi),
'quiet' => (bool)($this->config['quiet'] ?? $this->quiet),
'tasks' => (array)($this->config['tasks'] ?? null),
];
$this->executables = array_merge_recursive($config->merge ? $this->executables : [], $config->executables);
$this->executables = array_map(fn ($executable) => array_filter(array_unique($executable)), $this->executables);
// remove duplicated keys of the translations array if the arrays gonna merge, so that overrides get added to the end of the stack
$this->translations = array_diff_key($this->translations, $config->merge ? $config->translations : []);
$this->translations = array_merge($config->merge ? $this->translations : [], $config->translations);
$this->ansi = $config->ansi;
$this->quiet = $config->quiet;
// all tasks get added after the config is fully loaded and merged
$this->addTask('help', 'Displays help message', static::INTERNAL_TASK, sprintf('php %s help', $this->id));
$this->addTask('list', 'Lists available tasks', static::INTERNAL_TASK, sprintf('php %s list', $this->id));
$this->addTask('exec', 'Executes CLI commands', static::INTERNAL_TASK, sprintf('php %s exec', $this->id));
if (!empty($config->autoload)) {
require $config->autoload;
}
foreach ($config->tasks as $name => $task) {
$task['name'] = $task['name'] ?? (string)$name;
$this->makeTask($task);
}
$tasks = $this->load($this->executables) ?? [];
foreach ($tasks as $task) {
$this->addTask(
$task['name'],
$task['description'],
$task['executor'],
$task['executable'],
$task['arguments']
);
}
}
/**
* Loads tasks from the specified executables array.
*
* @param array[] $executables An array where the key is the executer program and the value is an array of glob patterns.
*
* @return array|null
*
* @throws \Exception If an executables directory is a file.
*/
protected function load(array $executables): ?array
{
static $prefixes = [];
$tasks = null;
foreach ($executables as $executor => $directories) {
foreach ($directories as $directory) {
if (is_file($directory)) {
throw new \Exception("A directory path or a glob pattern was expected, got a path to a file '{$directory}'");
}
if (is_dir($directory)) {
$directory = rtrim($directory, '/') . '/*';
}
$prefix = isset($prefixes['']) ? dirname($directory) : '';
$files = glob($directory) ?: [];
$prefixes[$prefix] = sprintf('[%s@%s]:%s', $executor, $directory, $prefix);
foreach ($files as $executable) {
if (!is_file($executable)) {
continue;
}
$name = trim(sprintf('%s-%s', $prefix, basename($executable)), '-');
$tasks[$name] = [
'name' => $name,
'description' => null,
'executor' => $executor,
'executable' => $executable,
'arguments' => null,
];
}
}
}
return $tasks;
}
/**
* Translates the passed string using the specified translations.
*
* @param string $string The string to translate.
* @param array|null $translations The translations to use. If null is passed, class translations will be used instead.
*
* @return string The translated string. Note that the returned string will always be trimmed from non-alphanumeric characters.
*/
protected function translate(string $string, ?array $translations = null): string
{
$translations = $translations ?? $this->translations;
$set = md5(serialize($translations));
static $patterns = [];
if (!isset($patterns[$set])) {
$patterns[$set] = [];
set_error_handler(fn ($code) => $code, E_WARNING);
foreach ($translations as $from => $to) {
// if the key is a regex, keep it as is, otherwise make a regex out of it
[$pattern, $replacement] = preg_match($from, '') !== false // if valid
? [$from, $to]
: ['/' . preg_quote($from, '/') . '/', addcslashes($to, '$')];
$patterns[$set][$pattern] = $replacement;
}
restore_error_handler();
$patterns[$set]['/^[^[:alpha:]]+/'] = ''; // task name must start with a letter
$patterns[$set]['/[^[:alnum:]]+$/'] = ''; // task name must end with a letter or number
}
return preg_replace(
array_keys($patterns[$set]),
array_values($patterns[$set]),
strtolower(trim($string))
);
}
/**
* Formats a string like `*printf()` functions with the ability to add ANSI colors using the placeholder `@(foreground,background)[{text}]`.
*
* @param string $format A formatted string.
* @param mixed ...$values Format values.
*
* @return string
*/
protected function format(string $format, ...$values): string
{
static $colors = [
'black' => ['FG' => 30, 'BG' => 40],
'red' => ['FG' => 31, 'BG' => 41],
'green' => ['FG' => 32, 'BG' => 42],
'yellow' => ['FG' => 33, 'BG' => 43],
'blue' => ['FG' => 34, 'BG' => 44],
'magenta' => ['FG' => 35, 'BG' => 45],
'cyan' => ['FG' => 36, 'BG' => 46],
'white' => ['FG' => 37, 'BG' => 47],
'default' => ['FG' => 39, 'BG' => 49],
];
$text = vsprintf($format, $values);
$regex = '/@\((\w+),?(\w+)?\)\[\{(.*?)\}\]/s'; // @(white,black)[{text}] or @(w,b)[{txt}]
$callback = function (array $matches) use (&$colors): string {
$foreground = $matches[1];
$background = $matches[2];
$text = $matches[3];
if (!$this->ansi) {
return $text;
}
foreach ([&$foreground, &$background] as &$color) {
$color = strtolower($color);
if (strlen($color) > 0 && strlen($color) <= 3) {
$names = preg_grep("/^{$color}/i", array_keys($colors));
$color = current($names);
}
}
$fg = $colors[$foreground]['FG'] ?? $colors['default']['FG'];
$bg = $colors[$background]['BG'] ?? $colors['default']['BG'];
return "\e[{$fg};{$bg}m{$text}\e[0m";
};
$result = preg_replace_callback($regex, $callback, $text);
if (!$this->ansi) {
$result = preg_replace('/\\x1b[[][^A-Za-z]*[A-Za-z]/', '', $result);
}
return $result;
}
/**
* Writes out a formatted text block from the specified lines and format value.
* Available placeholders: `@name`, `@executor`, `@executable`, `@task`, `@runner`, and `@(foreground,background)[{text}]`
*
* @param string[] $lines An array of strings with format placeholders.
* @param mixed[] $formatValues [optional] Format values.
*
* @return void
*/
protected function write(array $lines, array $formatValues = []): void
{
if ($this->quiet) {
return;
}
static $placeholders = [];
if ($task = $this->getTask($this->task)) {
$placeholders = [
'@runner' => $this,
'@task' => $task,
'@name' => $task->name,
'@executor' => $task->executor,
'@executable' => $task->executable,
];
}
$text = str_ireplace(
array_keys($placeholders),
array_values($placeholders),
implode(PHP_EOL, $lines)
);
echo $this->format($text, ...$formatValues), PHP_EOL;
}
/**
* Prints out a help message listing all tasks of the task runner.
*
* @return void
*/
protected function displayHelp(): void
{
$this->write(
['', "\e[4mBased on \e]8;;%s/tree/%s\e\\%s %s\e]8;;\e\\ by \e[1mMarwan Al-Soltany\e[0m", ''],
[static::REPO, static::VERSION, static::NAME, static::VERSION]
);
$this->write(
['', 'Running as @(b,w)[{ %s }]', ''],
[$this->getUser()]
);
$this->write(
[
'',
'@(y)[{Usage:}]',
'%3s php @(r)[{%s}] @(g)[{<task>}] [options] [--] [arguments]',
'',
'@(y)[{Examples:}]',
'%3s php @(r)[{%s}] @(g)[{help}]',
'%3s php @(r)[{%s}] @(g)[{some:task}] -o --opt -- arg',
'',
'@(y)[{Tasks:}]',
],
['', $this->id, '', $this->id, '', $this->id]
);
$this->listTasks($this->tasks);
$this->write(
[
'',
'@(y)[{Options/Arguments:}]',
'%3s All will be passed to the executed task.',
'%3s To preserve "double quotes", use \'single quotes\' around them.',
'',
],
['', '']
);
$listExecutables = function ($array) {
return implode(' + ', array_map(
fn ($executables, $executor) => vsprintf('(%s):["%s"]', [
$executor,
implode('","', $executables)
]),
array_values($array),
array_keys($array)
));
};
$this->write(
[
'',
'Use the environment variable @(c)[{%s}] to set one or more directories',
'and/or glob patterns to load executables from (default: @(c)[{%s}]).',
'@(c)[{%s}] pattern: @(m)[{exe}]@(y)[{:}]@(c)[{dir}]@(y)[{,}]@(c)[{...}]@(y)[{+}]...',
'@(c)[{%s}] example: @(m)[{php}]@(y)[{:}]@(c)[{bin}]@(y)[{,}]@(c)[{cmd}]@(y)[{+}]@(m)[{node}]@(y)[{:}]@(c)[{bin}]@(y)[{+}]...',
'',
'If more than one pattern/directory is specified, the tasks will be',
'prefixed with the containing directory name to minimize collisions.',
'To prevent the prefixing behaviour, provide a translation therefor.',
'',
'Currently loading: @(c)[{%s}]',
'',
'',
'@(b,c)[{ CONFIG }] @(r)[{%s}]',
'',
],
[
$this->envVar,
$listExecutables(static::EXECUTABLES),
$this->envVar,
$this->envVar,
$listExecutables($this->executables) ?: 'NONE',
$this->config['__PATH__'] ?? 'N/A'
]
);
$this->terminate(static::SUCCESS);
}
/**
* Prints out a hint message listing tasks matching the current task of the task runner.
*
* @return void
*/
protected function displayHint(): void
{
$this->write(
['', 'The task with the name @(b,r)[{ %s }] was not found!'],
[$this->task]
);
$pattern = strlen($this->task) > 1
? sprintf('/(%s)/i', implode(')|(', array_filter(explode('\:', preg_quote($this->task, '/')))))
: sprintf('/^%s+/i', preg_quote($this->task, '/'));
$matches = preg_grep($pattern, array_keys($this->tasks)) ?: [];
$matchedTasks = array_map(fn ($match) => $this->tasks[$match], $matches);
$disabledTasks = array_filter($this->tasks, fn ($task) => in_array($task, $matchedTasks) && $task->disabled);
$enabledTasks = array_filter($this->tasks, fn ($task) => in_array($task, $matchedTasks) && !$task->disabled);
if (!count($matchedTasks)) {
$this->write(['']);
$this->terminate(static::FAILURE);
return;
}
if ($count = count($disabledTasks)) {
$this->write(['', '@(r)[{Found %d disabled matching task(s).}]'], [$count]);
}
if ($count = count($enabledTasks)) {
$this->write(['', '@(y)[{Found %d possible matching task(s):}]'], [$count]);
}
$this->listTasks($enabledTasks);
$altTasks = [];
foreach ($matchedTasks as $task) {
if ($task->disabled || $task->hidden) {
continue;
}
$altTasks[] = $this->format(' @(blue)[{->}] php @(r)[{%s}] @(g)[{%s}]', $this->id, $task->name);
}
if (!empty($altTasks)) {
$this->write(
['', '@(blue)[{Run the following instead:}]', '%s'],
[implode(PHP_EOL, $altTasks)]
);
}
$this->write(['']);
$this->terminate(static::FAILURE);
}
/**
* Prints out a list of all available tasks of the task runner.
*
* @return void
*/
protected function displayList(): void
{
$this->write(['', '@(y)[{Available Tasks:}]']);
$this->listTasks($this->tasks);
$this->write(['']);
$this->terminate(static::SUCCESS);
}
/**
* Prints out the result of executing the current argument of the task runner.
*
* @return void
*/
protected function displayExec(): void
{
$command = implode(' ', $this->args);
$this->write(
['', '[@(c)[{%s}]] @(b,y)[{ EXECUTING }] %s'],
[date('H:i:s'), $command]
);
$time = microtime(true);
$code = $this->exec($command);
$time = (microtime(true) - $time) * 1000;
$this->write(
['[@(c)[{%s}]] @(b,%s)[{ %s }] @(m)[{%.2fms}]', ''],
[date('H:i:s'), $code > static::SUCCESS ? 'r' : 'g', 'DONE', $time]
);
$this->terminate($code);
}
/**
* Prints out a list of the passed tasks.
*
* @param object[] $tasks The tasks to list.
*
* @return void
*/
protected function listTasks(array $tasks): void
{
$cw = max(array_map('strlen', array_keys($tasks)) ?: [13]) + 3; // column width
foreach ($tasks as $task) {
if ($task->hidden) {
continue;
}
if ($task->disabled) {
$this->write(
["%3s @(r)[{%-{$cw}.{$cw}s}] @(blue)[{->}] @(r)[{(disabled)}] %s @(m)[{[%s]}]"],
['', '*****', '*******', '***']
);
continue;
}
$this->write(
["%3s @(g)[{%-{$cw}.{$cw}s}] @(blue)[{->}] %s @(m)[{[%s]}]"],
['', $task->name, $task->description ?? $task->executable, $task->executor]
);
}
}
/**
* Executes a shell command using `passthru()`.
* This is useful for interactive commands and/or long running processes with output.
*
* @param string|string[] $cmd A string or an array of commands to execute.
* @param bool $escape [optional] Whether to escape shell meta-characters (like: &#;`|*?~<>^()[]{}$) in the command(s) or not.
*
* @return int The status code of the executed command.
* Note that if multiple commands are passed only the code of the last one will be returned.
* Use `self::getExecResult()` to get all info about the executed command.
*
* @throws \InvalidArgumentException If the command is an empty string.
*
* @since 1.0.11
*/
public function passthru($cmd, bool $escape = true): int
{
$commands = (array)$cmd;
$windows = PHP_OS === 'WINNT';
$code = null;
foreach ($commands as $index => $command) {
$command = $escape ? escapeshellcmd(trim($command)) : trim($command);
$command = $windows ? preg_replace('`(?<!^) `', '^ ', $command) : $command; // escape spaces on windows
if (!strlen($command)) {
throw new \InvalidArgumentException('No valid command is specified');
}
fwrite(STDOUT, PHP_EOL);
passthru($command, $code);
fwrite($code ? STDERR : STDOUT, PHP_EOL);
$cmd = $commands[$index];
$cid = md5(trim($cmd));
$this->results[$cid] = [
'command' => $cmd,
'pid' => null,
'output' => null,
'code' => (int)$code,
];
}
return (int)$code;
}
/**
* Executes a shell command synchronously or asynchronous and prints out its result if possible.
*
* @param string|string[] $cmd A string or an array of commands to execute.
* @param bool $async [optional] Whether the command(s) should be a background process (asynchronous) or not (synchronous).
* @param bool $escape [optional] Whether to escape shell meta-characters (like: &#;`|*?~<>^()[]{}$) in the command(s) or not. This parameter is ignored if `$async` is set to `true`.
*
* @return int The status code of the executed command (or PID if asynchronous).
* Note that if multiple commands are passed only the code/PID of the last one will be returned.
* Use `self::getExecResult()` to get all info about the executed command.
*
* @throws \InvalidArgumentException If the command is an empty string.
*/
public function exec($cmd, bool $async = false, bool $escape = true): int
{
$commands = (array)$cmd;
$windows = PHP_OS === 'WINNT';
$code = null;
$pid = null;
foreach ($commands as $index => $command) {
$command = $async || $escape ? escapeshellcmd(trim($command)) : trim($command);
$command = $windows ? preg_replace('`(?<!^) `', '^ ', $command) : $command; // escape spaces on windows
$wrapper = $async
? ($windows ? 'start /B %s > NUL' : '/usr/bin/nohup %s > /dev/null 2>&1 & echo $!;')
: ($escape ? '%s 2>&1' : '%s');