-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCLI.php
More file actions
775 lines (738 loc) · 23.8 KB
/
Copy pathCLI.php
File metadata and controls
775 lines (738 loc) · 23.8 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
<?php declare(strict_types=1);
/*
* This file is part of Webisters CLI Library.
*
* (c) Hafiz Muhammad Moaz <thewebisters@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Framework\CLI;
use Framework\CLI\Styles\BackgroundColor;
use Framework\CLI\Styles\ForegroundColor;
use Framework\CLI\Styles\Format;
use JetBrains\PhpStorm\Pure;
use Stringable;
use ValueError;
/**
* Class CLI.
*
* @see https://en.wikipedia.org/wiki/ANSI_escape_code
*
* @package cli
*/
class CLI
{
protected static string $reset = "\033[0m";
/**
* The style codes used by strlen(), built once from the style enums.
*
* @var array<int,string>
*/
protected static array $styleCodes = [];
/**
* ANSI mode override set by setAnsi(). Null means "not explicitly set",
* so automatic detection applies.
*/
protected static ?bool $ansiOverride = null;
/**
* Tells if normal output should be suppressed.
*/
protected static bool $quiet = false;
/**
* Tells if it is running on a Windows OS.
*
* @return bool
*/
#[Pure]
public static function isWindows() : bool
{
return \str_starts_with(\strtoupper(\PHP_OS), 'WIN');
}
/**
* Tells if the current terminal likely supports ANSI escape sequences.
*
* An explicit setAnsi() call wins, then the FORCE_COLOR and NO_COLOR
* conventions, then the TTY check, then the per platform detection.
*
* @return bool
*/
public static function supportsAnsi() : bool
{
$override = static::$ansiOverride;
if ($override !== null) {
return $override;
}
$environment = static::colorEnvironment();
if ($environment !== null) {
return $environment;
}
// Redirected or piped output is not a terminal: never emit escape
// sequences there.
if (\function_exists('stream_isatty') && !\stream_isatty(\STDOUT)) {
return false;
}
// Windows 10+ supports ANSI in most terminals.
if (\DIRECTORY_SEPARATOR === '\\') {
return \getenv('ANSICON') !== false
|| \getenv('WT_SESSION') !== false
|| \getenv('TERM_PROGRAM') === 'vscode'
|| (\function_exists('sapi_windows_vt100_support')
&& sapi_windows_vt100_support(\STDOUT));
}
return true;
}
/**
* Read the FORCE_COLOR and NO_COLOR conventions.
*
* See https://no-color.org.
*
* @return bool|null True when colors are forced, false when they are
* disabled, null when neither variable is set
*/
protected static function colorEnvironment() : ?bool
{
if (\getenv('FORCE_COLOR') !== false) {
return true;
}
if (\getenv('NO_COLOR') !== false) {
return false;
}
return null;
}
/**
* Enable or disable ANSI escape sequences.
*
* Pass null to go back to automatic detection (environment conventions,
* TTY check and platform detection).
*
* @param bool|null $enabled Whether to enable ANSI, or null for automatic
*/
public static function setAnsi(?bool $enabled) : void
{
static::$ansiOverride = $enabled;
}
/**
* Tells if ANSI escape sequences are enabled.
*
* Unlike supportsAnsi(), the raw flag is returned without consulting the
* terminal, so the value set by setAnsi() can be restored.
*
* @return bool
*/
#[Pure]
public static function isAnsi() : bool
{
return static::$ansiOverride ?? true;
}
/**
* Enable or disable quiet mode.
*
* @param bool $quiet Whether to suppress normal output
*/
public static function setQuiet(bool $quiet) : void
{
static::$quiet = $quiet;
}
/**
* Tells if quiet mode is enabled.
*
* @return bool
*/
#[Pure]
public static function isQuiet() : bool
{
return static::$quiet;
}
/**
* Join path segments using the current platform separator.
*
* @param string ...$segments
*
* @return string
*/
public static function path(string ...$segments) : string
{
$parts = [];
$first = true;
foreach ($segments as $segment) {
if ($segment === '') {
continue;
}
// Preserve the leading separator of the first segment so absolute
// paths (e.g. "/home/user" on Linux) stay absolute; only trim the
// trailing separator there. Interior segments are trimmed on both
// sides to avoid duplicated separators.
$parts[] = $first ? \rtrim($segment, '/\\') : \trim($segment, '/\\');
$first = false;
}
return \implode(\DIRECTORY_SEPARATOR, $parts);
}
/**
* Get the screen width.
*
* @param int $default
*
* @return int
*/
public static function getWidth(int $default = 80) : int
{
$width = \getenv('COLUMNS');
if ($width !== false && \is_numeric($width) && (int) $width > 0) {
return (int) $width;
}
$width = \filter_input(\INPUT_SERVER, 'COLUMNS', \FILTER_VALIDATE_INT);
if ($width !== false && $width !== null && $width > 0) {
return $width;
}
return $default;
}
/**
* Displays text wrapped to a certain width.
*
* @param string $text
* @param int|null $width
*
* @return string Returns the wrapped text
*/
public static function wrap(string $text, ?int $width = null) : string
{
$width ??= static::getWidth();
return \wordwrap($text, $width, \PHP_EOL, true);
}
/**
* Calculate the multibyte length of a text without style characters.
*
* @param string $text The text being checked for length
*
* @return int
*/
public static function strlen(string $text) : int
{
if (static::$styleCodes === []) {
$codes = [];
foreach (ForegroundColor::cases() as $case) {
$codes[] = $case->getCode();
}
foreach (BackgroundColor::cases() as $case) {
$codes[] = $case->getCode();
}
foreach (Format::cases() as $case) {
$codes[] = $case->getCode();
}
$codes[] = static::$reset;
static::$styleCodes = $codes;
}
$text = \str_replace(static::$styleCodes, '', $text);
// Strip any other escape sequence (256 color, true color, hyperlinks,
// cursor moves, ...) so invisible bytes are not counted as characters.
$text = \preg_replace("/\x1b\\[[0-9;]*[A-Za-z]/", '', $text) ?? '';
$text = \preg_replace("/\x1b\\][^\x07]*?(?:\x07|\x1b\\\\)/", '', $text) ?? '';
return \mb_strlen($text);
}
/**
* Applies styles to a text.
*
* @param string $text The text to be styled
* @param ForegroundColor|string|null $color Foreground color
* @param BackgroundColor|string|null $background Background color
* @param array<Format|string> $formats The text formats
*
* @throws ValueError For invalid color, background or format
*
* @return string Returns the styled text
*/
public static function style(
string $text,
ForegroundColor | string | null $color = null,
BackgroundColor | string | null $background = null,
array $formats = []
) : string {
$string = '';
if ($color !== null) {
$string = \is_string($color)
? ForegroundColor::from($color)->getCode()
: $color->getCode();
}
if ($background !== null) {
$string .= \is_string($background)
? BackgroundColor::from($background)->getCode()
: $background->getCode();
}
if ($formats) {
foreach ($formats as $format) {
$string .= \is_string($format)
? Format::from($format)->getCode()
: $format->getCode();
}
}
if (!static::supportsAnsi()) {
return $text;
}
$string .= $text . static::$reset;
return $string;
}
/**
* Write a text in the output.
*
* Optionally with styles and width wrapping.
*
* @param string $text The text to be written
* @param ForegroundColor|string|null $color Foreground color
* @param BackgroundColor|string|null $background Background color
* @param int|null $width Width to wrap the text. Null to do not wrap.
*/
public static function write(
string $text,
ForegroundColor | string | null $color = null,
BackgroundColor | string | null $background = null,
?int $width = null
) : void {
if (static::isQuiet()) {
return;
}
if ($width !== null) {
$text = static::wrap($text, $width);
}
if ($color !== null || $background !== null) {
$text = static::style($text, $color, $background);
}
\fwrite(\STDOUT, $text . \PHP_EOL);
}
/**
* Writes a success message.
*
* @param string $text The message to be written
*/
public static function success(string $text) : void
{
static::write($text, ForegroundColor::green);
}
/**
* Writes an informational message.
*
* @param string $text The message to be written
*/
public static function info(string $text) : void
{
static::write($text, ForegroundColor::cyan);
}
/**
* Prints a new line in the output.
*
* @param int $lines Number of lines to be printed
*/
public static function newLine(int $lines = 1) : void
{
if (static::isQuiet()) {
return;
}
for ($i = 0; $i < $lines; $i++) {
\fwrite(\STDOUT, \PHP_EOL);
}
}
/**
* Creates a "live line".
*
* Erase the current line, move the cursor to the beginning of the line and
* writes a text.
*
* @param string $text The text to be written
* @param bool $finalize If true the "live line" activity ends, creating a
* new line after the text
*/
public static function liveLine(string $text, bool $finalize = false) : void
{
if (static::isQuiet()) {
return;
}
// See: https://stackoverflow.com/a/35190285
$string = '';
if (static::supportsAnsi()) {
$string .= "\33[2K";
}
$string .= "\r";
$string .= $text;
if ($finalize) {
$string .= \PHP_EOL;
}
\fwrite(\STDOUT, $string);
}
/**
* Render a progress bar using a live line.
*
* @param int $step Current step, starting from zero
* @param int $total Total number of steps
* @param string $label Optional leading label
*/
public static function progress(int $step, int $total, string $label = '') : void
{
if (static::isQuiet()) {
return;
}
$percent = $total > 0 ? (int) \round($step / $total * 100) : 100;
$width = 15;
$filled = $total > 0 ? (int) \round($width * $percent / 100) : $width;
$bar = \str_repeat('#', $filled) . \str_repeat('-', $width - $filled);
$text = (($label !== '') ? $label . ' ' : '') . '[' . $bar . '] ' . $percent . '%';
static::liveLine($text, $step >= $total && $total > 0);
}
/**
* Render a spinner frame using a live line.
*
* @param int $frame The frame index, incremented on each call
* @param bool $finalize True to clear the spinner and add a new line
*/
public static function spinner(int $frame = 0, bool $finalize = false) : void
{
if (static::isQuiet()) {
return;
}
if ($finalize) {
static::liveLine('', true);
return;
}
$frames = ['|', '/', '-', '\\'];
static::liveLine($frames[$frame % \count($frames)]);
}
/**
* Register a handler for the given POSIX signal when pcntl is available.
*
* @param int $signal The signal number
* @param callable $handler The signal handler
*
* @return bool True if the handler was registered, false if pcntl is unavailable
*/
public static function onSignal(int $signal, callable $handler) : bool
{
if (!\function_exists('pcntl_signal')) {
return false;
}
return \pcntl_signal($signal, $handler, true);
}
/**
* Register a cleanup handler for the interrupt signal (Ctrl+C) when available.
*
* @param callable $handler The signal handler
*
* @return bool True if the handler was registered
*/
public static function onSigint(callable $handler) : bool
{
if (!\defined('SIGINT')) {
return false;
}
return static::onSignal(\SIGINT, $handler);
}
/**
* Restore the default handler for a POSIX signal when pcntl is available.
*
* @param int $signal The signal number
*
* @return bool True if the handler was restored
*/
public static function restoreSignal(int $signal) : bool
{
if (!\function_exists('pcntl_signal')) {
return false;
}
return \pcntl_signal($signal, \SIG_DFL);
}
/**
* Performs audible beep alarms.
*
* @param int $times How many times should the beep be played
* @param int $usleep Interval in microseconds
*/
public static function beep(int $times = 1, int $usleep = 0) : void
{
if (static::isQuiet()) {
return;
}
for ($i = 0; $i < $times; $i++) {
\fwrite(\STDOUT, "\x07");
\usleep($usleep);
}
}
/**
* Writes a message box.
*
* @param array<int,string>|string $lines One line as string or multi-lines as array
* @param BackgroundColor|string $background Background color
* @param ForegroundColor|string $color Foreground color
*/
public static function box(
array | string $lines,
BackgroundColor | string $background = BackgroundColor::black,
ForegroundColor | string $color = ForegroundColor::white
) : void {
$width = static::getWidth();
$width -= 2;
if (!\is_array($lines)) {
$lines = [
$lines,
];
}
$allLines = [];
foreach ($lines as &$line) {
$length = static::strlen($line);
if ($length > $width) {
$line = static::wrap($line, $width);
}
foreach (\explode(\PHP_EOL, $line) as $subLine) {
$allLines[] = $subLine;
}
}
unset($line);
$blankLine = \str_repeat(' ', $width + 2);
$text = static::style($blankLine, $color, $background);
foreach ($allLines as $line) {
$end = \str_repeat(' ', $width - static::strlen($line)) . ' ';
$end = static::style($end, $color, $background);
$text .= static::style(' ' . $line . $end, $color, $background);
}
$text .= static::style($blankLine, $color, $background);
static::write($text);
}
/**
* Writes a message to STDERR and optionally exit with a custom code.
*
* @param string $message The error message
* @param int|null $exitCode Set null to do not exit
*/
public static function error(string $message, ?int $exitCode = 1) : void
{
static::beep();
\fwrite(\STDERR, static::style($message, ForegroundColor::red) . \PHP_EOL);
if ($exitCode !== null) {
exit($exitCode);
}
}
/**
* Clear the terminal screen.
*/
public static function clear() : void
{
if (static::isQuiet()) {
return;
}
if (static::supportsAnsi()) {
\fwrite(\STDOUT, "\e[H\e[2J");
return;
}
\fwrite(\STDOUT, \str_repeat(\PHP_EOL, 3));
}
/**
* Get user input.
*
* NOTE: It is possible pass multiple lines ending each line with a backslash.
*
* @param string $prepend Text prepended in the input. Used internally to
* allow multiple lines
*
* @return string Returns the user input
*/
public static function getInput(string $prepend = '') : string
{
$input = \fgets(\STDIN);
$input = $input === false ? '' : \trim($input);
$prepend .= $input;
$eolPos = false;
if ($prepend) {
$eolPos = \strrpos($prepend, '\\', -1);
}
if ($eolPos !== false) {
$prepend = \substr_replace($prepend, \PHP_EOL, $eolPos);
$prepend = static::getInput($prepend);
}
return $prepend;
}
/**
* Prompt a question.
*
* @param string $question The question to prompt
* @param array<int,string>|string|null $options Answer options. If an array
* is set, the default answer is the first value. If is a string, it will
* be the default.
*
* @return string The answer
*/
public static function prompt(string $question, array | string | null $options = null) : string
{
if ($options !== null) {
$options = \is_array($options)
? \array_values($options)
: [$options];
}
if ($options) {
$opt = $options;
$opt[0] = static::style($opt[0], null, null, [Format::bold]);
$optionsText = isset($opt[1])
? \implode(', ', $opt)
: $opt[0];
$question .= ' [' . $optionsText . ']';
}
$question .= ': ';
\fwrite(\STDOUT, $question);
$answer = static::getInput();
if ($answer === '' && isset($options[0])) {
$answer = $options[0];
}
return $answer;
}
/**
* Prompt a question with secret answer.
*
* @param string $question The question to prompt
*
* @see https://dev.to/mykeels/reading-passwords-from-stdin-in-php-1np9
*
* @return string The secret answer
*/
public static function secret(string $question) : string
{
$question .= ': ';
\fwrite(\STDOUT, $question);
if (!static::isWindows() && \function_exists('shell_exec')) {
@\shell_exec('stty -echo');
try {
return \trim((string) \fgets(\STDIN));
} finally {
@\shell_exec('stty echo');
}
}
return \trim((string) \fgets(\STDIN));
}
/**
* Prompt a question with a masked answer.
*
* Instead of disabling the terminal echo like secret(), each typed
* character is echoed as the given mask character. On Windows or when
* the required POSIX functions are unavailable, input is still read
* normally and simply not echoed.
*
* @param string $question The question to prompt
* @param string $mask The character echoed for each typed character
*
* @return string The masked answer
*/
public static function masked(string $question, string $mask = '*') : string
{
$question .= ': ';
\fwrite(\STDOUT, $question);
if (static::isWindows()
|| !\function_exists('shell_exec')
|| !\function_exists('stream_isatty')
|| !\stream_isatty(\STDIN)
) {
// Without an interactive TTY the echo cannot be controlled,
// so fall back to a plain line read.
return \trim((string) \fgets(\STDIN));
}
@\shell_exec('stty -echo 2>/dev/null');
$answer = '';
try {
while (true) {
$char = \fgetc(\STDIN);
$code = $char === false ? 0 : \ord($char);
if ($char === false || $code === 10) {
break;
}
if ($code === 13) {
// consume the \n that follows on Windows-style line endings
\fgetc(\STDIN);
break;
}
if ($code === 127 || $code === 8) {
$answer = \substr($answer, 0, -1);
\fwrite(\STDOUT, \chr(8) . ' ' . \chr(8));
continue;
}
$answer .= $char;
\fwrite(\STDOUT, $mask);
}
\fwrite(\STDOUT, \PHP_EOL);
return $answer;
} finally {
@\shell_exec('stty echo 2>/dev/null');
}
}
/**
* Creates a well formatted table.
*
* @param array<array<Stringable|scalar>> $tbody Table body rows
* @param array<Stringable|scalar> $thead Table head fields
*/
public static function table(array $tbody, array $thead = []) : void
{
if (static::isQuiet()) {
return;
}
// All the rows in the table will be here until the end
$tableRows = [];
// We need only indexes and not keys
if (!empty($thead)) {
$tableRows[] = \array_values($thead);
}
foreach ($tbody as $tr) {
// cast tr to array if is not - (objects...)
$tableRows[] = \array_values((array) $tr);
}
// Yes, it really is necessary to know this count
$totalRows = \count($tableRows);
// Store all columns lengths
// $allColsLengths[row][column] = length
$allColsLengths = [];
// Store maximum lengths by column
// $maxColsLengths[column] = length
$maxColsLengths = [];
// Read row by row and define the longest columns
for ($row = 0; $row < $totalRows; $row++) {
$column = 0; // Current column index
foreach ($tableRows[$row] as $col) {
// Sets the size of this column in the current row
$allColsLengths[$row][$column] = static::strlen((string) $col);
// If the current column does not have a value among the larger ones
// or the value of this is greater than the existing one
// then, now, this assumes the maximum length
if (!isset($maxColsLengths[$column])
|| $allColsLengths[$row][$column] > $maxColsLengths[$column]) {
$maxColsLengths[$column] = $allColsLengths[$row][$column];
}
// We can go check the size of the next column...
$column++;
}
}
// Read row by row and add spaces at the end of the columns
// to match the exact column length
for ($row = 0; $row < $totalRows; $row++) {
$column = 0;
foreach ($tableRows[$row] as $col => $value) {
$diff = $maxColsLengths[$column] - $allColsLengths[$row][$col];
if ($diff) {
$tableRows[$row][$column] .= \str_repeat(' ', $diff);
}
$column++;
}
}
$table = $line = '';
// Joins columns and append the well formatted rows to the table
foreach ($tableRows as $row => $value) {
// Set the table border-top
if ($row === 0) {
$line = '+';
foreach (\array_keys($value) as $col) {
$line .= \str_repeat('-', $maxColsLengths[$col] + 2) . '+';
}
$table .= $line . \PHP_EOL;
}
// Set the vertical borders
$table .= '| ' . \implode(' | ', $value) . ' |' . \PHP_EOL;
// Set the thead and table borders-bottom
if (($row === 0 && !empty($thead)) || $row + 1 === $totalRows) {
$table .= $line . \PHP_EOL;
}
}
\fwrite(\STDOUT, $table);
}
}