Exemple #1
0
 /**
  * Returns a colorized string
  *
  * @param string $string Message to colorize for output
  * @return string
  */
 private function colorize($string)
 {
     $colorization_setting = $this->runner->getConfig('colorize');
     $colorize = $colorization_setting == 'auto' && !\cli\Shell::isPiped() || is_bool($colorization_setting) && $colorization_setting;
     $colorized_string = \cli\Colors::colorize($string, $colorize);
     return $colorized_string;
 }
Exemple #2
0
 /**
  * Initializes the `Table` class.
  *
  * There are 3 ways to instantiate this class:
  *
  *  1. Pass an array of strings as the first paramater for the column headers
  *     and a 2-dimensional array as the second parameter for the data rows.
  *  2. Pass an array of hash tables (string indexes instead of numerical)
  *     where each hash table is a row and the indexes of the *first* hash
  *     table are used as the header values.
  *  3. Pass nothing and use `setHeaders()` and `addRow()` or `setRows()`.
  *
  * @param array  $headers  Headers used in this table. Optional.
  * @param array  $rows     The rows of data for this table. Optional.
  * @param array  $footers  Footers used in this table. Optional.
  */
 public function __construct(array $headers = null, array $rows = null, array $footers = null)
 {
     if (!empty($headers)) {
         // If all the rows is given in $headers we use the keys from the
         // first row for the header values
         if (empty($rows)) {
             $rows = $headers;
             $keys = array_keys(array_shift($headers));
             $headers = array();
             foreach ($keys as $header) {
                 $headers[$header] = $header;
             }
         }
         $this->setHeaders($headers);
         $this->setRows($rows);
     }
     if (!empty($footers)) {
         $this->setFooters($footers);
     }
     if (Shell::isPiped()) {
         $this->setRenderer(new Tabular());
     } else {
         $this->setRenderer(new Ascii());
     }
 }
Exemple #3
0
 private function init_colorization()
 {
     if ($this->config['colorize'] == 'auto') {
         $this->colorize = !\cli\Shell::isPiped();
     } else {
         $this->colorize = $this->config['colorize'];
     }
 }
Exemple #4
0
/**
 * Returns a colorized string
 *
 * @param string $string Message to colorize for output
 * @return string
 */
function colorize($string)
{
    $colorize = true;
    if (Terminus::getConfig('colorize') == 'auto') {
        $colorize = !\cli\Shell::isPiped();
    }
    $colorized_string = \cli\Colors::colorize($string, $colorize);
    return $colorized_string;
}
Exemple #5
0
 /**
  * Prints the progress bar to the screen with percent complete, elapsed time
  * and estimated total time.
  *
  * @param boolean  $finish  `true` if this was called from
  *                          `cli\Notify::finish()`, `false` otherwise.
  * @see cli\out()
  * @see cli\Notify::formatTime()
  * @see cli\Notify::elapsed()
  * @see cli\Progress::estimated();
  * @see cli\Progress::percent()
  * @see cli\Shell::columns()
  */
 public function display($finish = false)
 {
     $_percent = $this->percent();
     $percent = str_pad(floor($_percent * 100), 3);
     $msg = $this->_message;
     $msg = \cli\render($this->_formatMessage, compact('msg', 'percent'));
     $estimated = $this->formatTime($this->estimated());
     $elapsed = str_pad($this->formatTime($this->elapsed()), strlen($estimated));
     $timing = \cli\render($this->_formatTiming, compact('elapsed', 'estimated'));
     $size = \cli\Shell::columns();
     $size -= strlen($msg . $timing);
     $bar = str_repeat($this->_bars[0], floor($_percent * $size)) . $this->_bars[1];
     // substr is needed to trim off the bar cap at 100%
     $bar = substr(str_pad($bar, $size, ' '), 0, $size);
     \cli\out($this->_format, compact('msg', 'bar', 'timing'));
 }
Exemple #6
0
 /**
  * Initializes the `Table` class.
  *
  * There are 3 ways to instantiate this class:
  *
  *  1. Pass an array of strings as the first paramater for the column headers
  *     and a 2-dimensional array as the second parameter for the data rows.
  *  2. Pass an array of hash tables (string indexes instead of numerical)
  *     where each hash table is a row and the indexes of the *first* hash
  *     table are used as the header values.
  *  3. Pass nothing and use `setHeaders()` and `addRow()` or `setRows()`.
  *
  * @param array  $headers  Headers used in this table. Optional.
  * @param array  $rows     The rows of data for this table. Optional.
  */
 public function __construct(array $headers = null, array $rows = null)
 {
     if (!empty($headers)) {
         // If all the rows is given in $headers we use the keys from the
         // first row for the header values
         if (empty($rows)) {
             $rows = $headers;
             $keys = array_keys(array_shift($headers));
             $headers = array();
             foreach ($keys as $header) {
                 $headers[$header] = $header;
             }
         }
         $this->setHeaders($headers);
         $this->setRows($rows);
     }
     $className = '\\cli\\table' . (\cli\Shell::isPiped() ? '\\Tabular' : '\\Ascii');
     $this->setRenderer(new $className());
 }
Exemple #7
0
 /**
  * Set the widths of each column in the table.
  *
  * @param array  $widths  The widths of the columns.
  */
 public function setWidths(array $widths)
 {
     if (is_null($this->_constraintWidth)) {
         $this->_constraintWidth = (int) Shell::columns();
     }
     $col_count = count($widths);
     $col_borders_count = $col_count * strlen($this->_characters['border']);
     $table_borders_count = strlen($this->_characters['border']) * 1;
     $col_padding_count = $col_count * strlen($this->_characters['padding']) * 2;
     $max_width = $this->_constraintWidth - $col_borders_count - $table_borders_count - $col_padding_count;
     if ($widths && $max_width && array_sum($widths) > $max_width) {
         $avg = floor($max_width / count($widths));
         $resize_widths = array();
         $extra_width = 0;
         foreach ($widths as $width) {
             if ($width > $avg) {
                 $resize_widths[] = $width;
             } else {
                 $extra_width = $extra_width + ($avg - $width);
             }
         }
         if (!empty($resize_widths) && $extra_width) {
             $avg_extra_width = floor($extra_width / count($resize_widths));
             foreach ($widths as &$width) {
                 if (in_array($width, $resize_widths)) {
                     $width = $avg + $avg_extra_width;
                     $extra_width = $extra_width - $avg_extra_width;
                     array_shift($resize_widths);
                     // Last item gets the cake
                     if (empty($resize_widths)) {
                         $width = $width + $extra_width;
                     }
                 }
             }
         }
     }
     $this->_widths = $widths;
 }
Exemple #8
0
/**
 * Creates progress bar for operation in progress
 *
 * @param [string]  $message Message to be displayed with the progress bar
 * @param [integer] $count   Number of progress dots to be displayed
 * @return [\cli\progress\Bar] $progress_bar Object which handles display of bar
 */
function make_progress_bar($message, $count)
{
    if (\cli\Shell::isPiped()) {
        return new \Terminus\NoOp();
    }
    $progress_bar = new \cli\progress\Bar($message, $count);
    return $progress_bar;
}
 /**
  * Pads `$msg` to the width of the shell before passing to `cli\out`.
  *
  * @param string  $msg  The message to pad and pass on.
  * @param mixed   ...   Either scalar arguments or a single array argument.
  * @return void
  * @see cli\out()
  */
 public static function out_padded($msg)
 {
     $msg = self::_call('render', func_get_args());
     self::out(str_pad($msg, \cli\Shell::columns()));
 }
Exemple #10
0
/**
 * Pads `$msg` to the width of the shell before passing to `cli\out`.
 *
 * @param string  $msg  The message to pad and pass on.
 * @param mixed   ...   Either scalar arguments or a single array argument.
 * @return void
 * @see cli\out()
 */
function out_padded($msg)
{
    $args = func_get_args();
    $msg = call_user_func_array('\\cli\\render', $args);
    \cli\out(str_pad($msg, \cli\Shell::columns()));
}
Exemple #11
0
 /**
  * Create a bar that spans with width of the console
  *
  * ## OPTIONS
  *
  * [<character>]
  * : The character(s) to make the bar with. Default =
  *
  * [--c=<c>]
  * : Color for bar. Default %p
  *
  *
  * ## EXAMPLES
  *
  *     wp <command> bar
  *
  *     wp <command> bar '-~' --c='%r'
  *
  *     wp <command> bar '+-' --c='%r%3'
  */
 function bar($args = array(), $assoc_args = array())
 {
     $char = isset($args[0]) ? $args[0] : '=';
     $cols = \cli\Shell::columns();
     $line = substr(str_repeat($char, $cols), 0, $cols);
     if (!isset($assoc_args['c'])) {
         $color = '%p';
         // https://github.com/jlogsdon/php-cli-tools/blob/master/lib/cli/Colors.php#L113
     } else {
         $color = $assoc_args['c'];
         $color = '%' . trim($color, '%');
     }
     WP_CLI::line(WP_CLI::colorize($color . $line . '%n'));
 }
Exemple #12
0
 public static function progress_bar($message, $count)
 {
     if (\cli\Shell::isPiped()) {
         return new \ETSIS_CLI\NoOp();
     }
     return new \cli\progress\Bar($message, $count);
 }
Exemple #13
0
 /**
  * Pads `$msg` to the width of the shell before passing to `cli\out`.
  *
  * @param string  $msg  The message to pad and pass on.
  * @param mixed   ...   Either scalar arguments or a single array argument.
  * @return void
  * @see cli\out()
  */
 public static function out_padded($msg)
 {
     $args = func_get_args();
     $msg = call_user_func_array(array('\\cli\\Streams', 'render'), $args);
     \cli\Streams::out(str_pad($msg, \cli\Shell::columns()));
 }
Exemple #14
0
 public function testTables()
 {
     $this->resetStreams();
     $suffix = \cli\Shell::isPiped() ? "_piped" : "";
     $this->assertTrue(is_numeric($columns = \cli\Shell::columns()));
     $headers = array('First Name', 'Last Name', 'City', 'State');
     $data = array(array('Maryam', 'Elliott', 'Elizabeth City', 'SD'), array('Jerry', 'Washington', 'Bessemer', 'ME'), array('Allegra', 'Hopkins', 'Altoona', 'ME'), array('Audrey', 'Oneil', 'Dalton', 'SK'));
     $table = new \cli\Table();
     $table->setRenderer(new \cli\table\Ascii());
     $table->setHeaders($headers);
     $table->setRows($data);
     $table->display();
     $output = $this->getStreams();
     $this->assertEquals("", $output['errors']);
     $this->assertEquals(file_get_contents("test/output/table_1"), $output['contents']);
     $this->resetStreams();
     $table->sort(1);
     $table->display();
     $output = $this->getStreams();
     $this->assertEquals("", $output['errors']);
     $this->assertEquals(file_get_contents("test/output/table_2"), $output['contents']);
     $this->resetStreams();
     foreach ($data as $k => $v) {
         $data[$k] = array_combine(array("name", "surname", "city", "state"), $v);
     }
     $renderer = new \cli\table\Ascii();
     $renderer->setCharacters(array("corner" => "x", "line" => "=", "border" => "!"));
     $table = new \cli\Table($data);
     $table->setRenderer($renderer);
     $table->sort("surname");
     $table->display();
     $output = $this->getStreams();
     $this->assertEquals("", $output['errors']);
     $this->assertEquals(file_get_contents("test/output/table_3"), $output['contents']);
     $this->assertEquals("", \cli\Colors::color("reset"));
     $this->assertEquals("foo\tbar", \cli\table\Tabular::row(array("foo", "bar")));
     $this->assertNull(\cli\table\Tabular::border());
     // test output
     $this->resetStreams();
     \cli\out("  \\cli\\out sends output to STDOUT\n");
     \cli\out("  It does not automatically append a new line\n");
     \cli\out("  It does accept any number of %s which are then %s to %s for formatting\n", 'arguments', 'passed', 'sprintf');
     \cli\out("  Alternatively, {:a} can use an {:b} as the second argument.\n\n", array('a' => 'you', 'b' => 'array'));
     \cli\err('  \\cli\\err sends output to STDERR');
     \cli\err('  It does automatically append a new line');
     \cli\err('  It does accept any number of %s which are then %s to %s for formatting', 'arguments', 'passed', 'sprintf');
     \cli\err("  Alternatively, {:a} can use an {:b} as the second argument.\n", array('a' => 'you', 'b' => 'array'));
     \cli\line('  \\cli\\line forwards to \\cli\\out for output');
     \cli\line('  It does automatically append a new line');
     \cli\line('  It does accept any number of %s which are then %s to %s for formatting', 'arguments', 'passed', 'sprintf');
     \cli\line("  Alternatively, {:a} can use an {:b} as the second argument.\n", array('a' => 'you', 'b' => 'array'));
     $output = $this->getStreams();
     $this->assertEquals(file_get_contents("test/output/out_errors"), $output['errors']);
     $this->assertEquals(file_get_contents("test/output/out_contents"), $output['contents']);
     $string = "";
     $string .= \cli\render('  \\cli\\err sends output to STDERR' . "\n");
     $string .= \cli\render('  It does automatically append a new line' . "\n");
     $string .= \cli\render('  It does accept any number of %s which are then %s to %s for formatting' . "\n", 'arguments', 'passed', 'sprintf');
     $string .= \cli\render("  Alternatively, {:a} can use an {:b} as the second argument.\n\n", array('a' => 'you', 'b' => 'array'));
     $this->assertEquals(file_get_contents("test/output/out_errors"), $string);
     $this->resetStreams();
     $in = tmpfile();
     fputs($in, "quit\n");
     fseek($in, 0);
     \cli\Streams::setStream("in", $in);
     $line = \cli\prompt("prompt", false, "# ");
     $output = $this->getStreams();
     $this->assertEquals("quit", $line);
     $this->assertEquals("", $output['errors']);
     $this->assertEquals("prompt# ", $output['contents']);
     fseek($in, 0);
     $this->assertEquals("quit", \cli\input());
     fclose($in);
 }
Exemple #15
0
 private function init_colorization()
 {
     if ('auto' === $this->config['color']) {
         $this->colorize = !\cli\Shell::isPiped() && !\WP_CLI\Utils\is_windows();
     } else {
         $this->colorize = $this->config['color'];
     }
 }
Exemple #16
0
/**
 * Create a progress bar to display percent completion of a given operation.
 *
 * Progress bar is written to STDOUT, and disabled when command is piped. Progress
 * advances with `$progress->tick()`, and completes with `$progress->finish()`.
 * Process bar also indicates elapsed time and expected total time.
 *
 * ```
 * # `wp user generate` ticks progress bar each time a new user is created.
 * #
 * # $ wp user generate --count=500
 * # Generating users  22 % [=======>                             ] 0:05 / 0:23
 *
 * $progress = \WP_CLI\Utils\make_progress_bar( 'Generating users', $count );
 * for ( $i = 0; $i < $count; $i++ ) {
 *     // uses wp_insert_user() to insert the user
 *     $progress->tick();
 * }
 * $progress->finish();
 * ```
 *
 * @access public
 * @category Output
 *
 * @param string  $message  Text to display before the progress bar.
 * @param integer $count    Total number of ticks to be performed.
 * @return cli\progress\Bar|WP_CLI\NoOp
 */
function make_progress_bar($message, $count)
{
    if (\cli\Shell::isPiped()) {
        return new \WP_CLI\NoOp();
    }
    return new \cli\progress\Bar($message, $count);
}
Exemple #17
0
 /**
  * Create a bar that spans with width of the console
  *
  * @param array $args Only expects a zero-indexed value, the character to build the bar with
  * @param array $assoc_args
  *               string  'c'    Color value. Default %p
  *               integer 'w'    Width percentage, 0-100. Default 100
  *               string  'text' Message to show in bar
  */
 private function bar($args = array(), $assoc_args = array())
 {
     $char = isset($args[0]) ? $args[0] : '=';
     $cols = \cli\Shell::columns();
     if (isset($assoc_args['w'])) {
         $cols = floor($cols * ($assoc_args['w'] / 100));
     }
     $line = substr(str_repeat($char, $cols), 0, $cols);
     if (isset($assoc_args['text'])) {
         $text = "{$char}{$char}{$char} {$assoc_args['text']} ";
         $len = strlen($text);
         $line = $text . substr($line, $len);
     }
     if (!isset($assoc_args['c'])) {
         $color = '%p';
         // https://github.com/jlogsdon/php-cli-tools/blob/master/lib/cli/Colors.php#L113
     } else {
         $color = $assoc_args['c'];
         $color = '%' . trim($color, '%');
     }
     WP_CLI::log(WP_CLI::colorize($color . $line . '%n'));
 }