コード例 #1
0
ファイル: class-wp-cli.php プロジェクト: roelven/wp-cli
 /**
  * Display a warning in the CLI and end with a newline
  *
  * @param string $message
  * @param string $label
  */
 static function warning($message, $label = 'Warning')
 {
     if (WP_CLI_QUIET) {
         return;
     }
     \cli\err('%C' . $label . ': %n' . self::error_to_string($message));
 }
コード例 #2
0
ファイル: StdErr.php プロジェクト: chrisnoden/talkback
 /**
  * Output the message
  *
  * @param $msg string output the string
  *
  * @return ChannelAbstract
  */
 public function write($msg)
 {
     $msg = $this->prepareMessage($msg);
     if (defined('PHP_WINDOWS_VERSION_MAJOR')) {
         printf('%s' . PHP_EOL, $msg);
     } else {
         if (class_exists('\\cli\\Streams')) {
             \cli\err($msg);
         } else {
             fwrite(STDERR, $msg . PHP_EOL);
         }
     }
     parent::written();
 }
コード例 #3
0
ファイル: Req.php プロジェクト: NavalKishor/PHP-Rocker
 /**
  * @param array $args
  * @param array $flags
  */
 public function call($args, $flags)
 {
     $client = Server::loadClient($args);
     if (empty($args['-p'])) {
         \cli\err('Parameter -p is required (path to request)');
     }
     $response = $client->request(isset($args['-X']) ? $args['-X'] : 'GET', trim($args['-p'], '/'), isset($args['-d']) ? parse_str($args['-d']) : array(), true);
     \cli\line('%_Status:%n ' . $response->status);
     if (in_array('--v', $flags)) {
         \cli\line('%_Headers:%n ');
         foreach ($response->headers as $name => $val) {
             \cli\line("   {$name}: {$val} ");
         }
     }
     \cli\line('%_Body:%n ' . PHP_EOL . str_replace('stdClass ', '', print_r($response->body, true)));
     //var_dump($response);
 }
コード例 #4
0
<?php

require 'vendor/autoload.php';
define('FEED_CURRENT', 'https://my.atlassian.com/download/feeds/current/jira-software.json');
$client = new GuzzleHttp\Client();
try {
    $feed_current = $client->request('GET', FEED_CURRENT)->getBody();
} catch (Exception $e) {
    \cli\err('Could not retieve Atlasian download feed.');
    exit(1);
}
$current_a = json_decode(trim((string) $feed_current, 'downloads()'), true);
$current_a = array_filter($current_a, function ($version) {
    if (substr($version['zipUrl'], -7) !== '.tar.gz') {
        return false;
    }
    return $version;
});
$versions = [];
foreach ($current_a as $version) {
    $versions[$version['version']] = $version;
}
uksort($versions, 'version_compare');
\cli\line(count($versions) . ' Versions Found:');
$tree = new \cli\Tree();
$tree->setData($versions);
$tree->setRenderer(new \cli\tree\Ascii());
$tree->display();
// Prepare for build
$data = end($versions);
$m = new Mustache_Engine();
コード例 #5
0
ファイル: example.php プロジェクト: thesmart/php-cli-tools
 $choice = \cli\menu($menu, null, 'Choose an example');
 \cli\line();
 switch ($choice) {
     case 'quit':
         break 2;
     case 'out_out':
         \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", array('a' => 'you', 'b' => 'array'));
         break;
     case 'out_err':
         \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.', array('a' => 'you', 'b' => 'array'));
         break;
     case 'out_line':
         \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.', array('a' => 'you', 'b' => 'array'));
         break;
     case 'notify_dots':
         test_notify(new \cli\notify\Dots('  \\cli\\notify\\Dots cycles through a set number of dots'));
         test_notify(new \cli\notify\Dots('  You can disable the delay if ticks take longer than a few milliseconds', 5, 0), 10, 100000);
         \cli\line('    All progress meters and notifiers extend \\cli\\Notify which handles the interval above.');
         break;
     case 'notify_spinner':
         test_notify(new \cli\notify\Spinner('  \\cli\\notify\\Spinner cycles through a set of characters to emulate a spinner'));
         break;
コード例 #6
0
ファイル: chalk.php プロジェクト: jacksleight/chalk
<?php

/*
 * Copyright 2015 Jack Sleight <http://jacksleight.com/>
 * This source file is subject to the MIT license that is bundled with this package in the file LICENCE.md. 
 */
use Chalk\App as Chalk;
if (php_sapi_name() != 'cli') {
    exit("Must be run from the command line\n");
}
$init = getcwd() . '/chalk-cli.php';
if (!is_file($init)) {
    exit("No 'chalk-cli.php' initialization file found in '" . getcwd() . "'\n");
}
$app = (require_once $init);
Chalk::isFrontend(false);
$cmds = [];
foreach ($app->dir('cli/cmds') as $file) {
    $cmds[$file->fileName()] = $file;
}
if (!isset($_SERVER['argv'][1]) || !isset($cmds[$_SERVER['argv'][1]])) {
    cli\err("Invalid command, valid commands are:\n  " . implode("\n  ", array_keys($cmds)));
    exit;
}
require_once $cmds[$_SERVER['argv'][1]]->name();
コード例 #7
0
                \cli\line('%G{:header}%n', compact('header'));
                continue;
            }
            list($key, $value) = explode(': ', $header, 2);
            \cli\line('%W{:key}%n: {:value}', compact('key', 'value'));
        }
        \cli\line("\n");
        print $response->getContent() . "\n";
        switch ($type) {
        }
    }
    public function run()
    {
        while (true) {
            $cmd = \cli\prompt($this->_prompt, false, null);
            if (preg_match('/^(HEAD|GET|POST|PUT|DELETE) (\\S+)$/', $cmd, $matches)) {
                $this->handleRequest($matches[1], $matches[2]);
                continue;
            }
            if ($cmd == '\\q') {
                break;
            }
        }
    }
}
try {
    $console = new HttpConsole(array_shift($argv) ?: '127.0.0.1:80');
    $console->run();
} catch (\Exception $e) {
    \cli\err("\n\n%R" . $e->getMessage() . "%n\n");
}
コード例 #8
0
ファイル: etsis_CLI.php プロジェクト: parkerj/eduTrac-SIS
 /**
  * Display a warning in the CLI and end with a newline
  *
  * @param string $message
  * @param string $label
  */
 public static function warning($message, $label = 'Warning')
 {
     if (ETSIS_CLI_QUIET) {
         return;
     }
     \cli\err('%C' . $label . ': %n' . $message);
 }
コード例 #9
0
 /**
  * @param string $message
  */
 protected static function showError($message)
 {
     \cli\line();
     \cli\err(\cli\Colors::colorize('%N%n%1' . $message . '%N%n'));
     return false;
 }
コード例 #10
0
ファイル: worker.php プロジェクト: nsmithuk/dynamo-queue-php
        cli\line("%gTable '{$config['table_name']}' has been created in {$settings['region']}%n");
    } catch (Exception $e) {
        cli\err("%rUnable to create table in DynamoDB: " . $e->getMessage() . "%n");
        exit(1);
    }
    exit(0);
}
//------------------------------------
// If we're performing a table cleanup
if ($arguments['cleanup']) {
    try {
        $ttl = $arguments['ttl'] && is_numeric($arguments['ttl']) ? (int) $arguments['ttl'] : 0;
        $deletedJobs = $queue->cleanupTable($ttl);
        cli\line("%g{$deletedJobs} jobs tidied up from '{$config['table_name']}'%n");
    } catch (Exception $e) {
        cli\err("%rUnable to cleanup table: " . $e->getMessage() . "%n");
        exit(1);
    }
    exit(0);
}
//------------------------------------
// Validate the table (and connection)
try {
    $valid = $queue->isTableValid();
    if (is_array($valid)) {
        $logger->alert("Errors were found when validating the table is setup correctly", $valid);
        exit(1);
    }
} catch (Exception $e) {
    $logger->alert("Unable to connect to DynamoDB (and validate the table)", ['exception' => $e]);
    exit(1);
コード例 #11
0
ファイル: schema-update.php プロジェクト: jacksleight/chalk
 */
if (cli\choose("Are you sure", 'yn', 'n') == 'n') {
    exit;
}
require_once $cmds['cache-clear']->name();
$schema = new \Doctrine\ORM\Tools\SchemaTool($app->em->value());
cli\line('Calculating changes..');
$stmts = $schema->getUpdateSchemaSql($app->em->getMetadataFactory()->getAllMetadata(), false);
if (!count($stmts)) {
    cli\line("Nothing to update");
    exit;
}
cli\line("The following statements will be executed:\n  " . implode("\n  ", $stmts));
if (cli\choose("Execute these statements", 'yn', 'n') == 'n') {
    exit;
}
$app->em->beginTransaction();
try {
    $bar = new cli\progress\Bar("Executing statements..", count($stmts), 1);
    $conn = $app->em->getConnection();
    foreach ($stmts as $stmt) {
        $conn->exec($stmt);
        $bar->tick();
    }
    $bar->finish();
    $app->em->commit();
} catch (Exception $e) {
    $app->em->rollback();
    cli\err('Error: ' . $e->getMessage());
}
require_once $cmds['proxy-generate']->name();
コード例 #12
0
ファイル: ToolsTest.php プロジェクト: titpetric/php-cli-tools
 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);
 }
コード例 #13
0
 /**
  * Display an error in the CLI and end with a newline
  *
  * @param string $message
  * @param string $label
  */
 static function error($message, $label = 'Error')
 {
     \cli\err('%R' . $label . ': %n' . self::errorToString($message));
     exit(1);
 }
コード例 #14
0
ファイル: Server.php プロジェクト: NavalKishor/PHP-Rocker
 /**
  * @inheritdoc
  */
 public function call($args, $flags)
 {
     // Check version and operations on remote server
     if (in_array('-c', $flags)) {
         $client = self::loadClient($args);
         \cli\line('%_Base URI:%n ' . $client->getBaseURI());
         \cli\line('%_Version:%n ' . $client->serverVersion());
         \cli\line('%_Operations:%n');
         $table = new \cli\Table();
         $table->setHeaders(array('Class', 'Methods', 'Path'));
         foreach ($client->request('GET', 'operations')->body as $data) {
             $table->addRow(array_values((array) $data));
         }
         $table->display();
     } elseif (isset($args['-r'])) {
         $servers = $this->loadStoredServerInfo();
         if (isset($servers[$args['-r']])) {
             unset($servers[$args['-r']]);
             file_put_contents($this->infoFile, serialize($servers));
             \cli\line('Server removed (add flag -l to list servers)');
         }
     } elseif (in_array('-l', $flags)) {
         $servers = $this->loadStoredServerInfo();
         $this->listServers($servers);
     } elseif (isset($args['-d'])) {
         $servers = $this->loadStoredServerInfo();
         if (empty($servers[$args['-d']])) {
             \cli\line('Server does not exist....');
             $this->listServers($servers);
         } else {
             $servers['__default'] = $args['-d'];
             file_put_contents($this->infoFile, serialize($servers));
             \cli\line('%gServer "' . $args['-d'] . '" set as default %n');
         }
     } else {
         \cli\line('Add remote server');
         \cli\line('--------------------');
         $name = \cli\prompt('Server name (any name of your choice)');
         $address = rtrim(\cli\prompt('Server address'), '/') . '/';
         $user = \cli\prompt('Admin e-mail');
         $pass = Utils::promptPassword('Admin password: '******'Secret (leave empty if not used)'));
         try {
             // Try to request server
             $auth = $user . ':' . $pass;
             if ($secret) {
                 $auth = 'RC4 ' . base64_encode(RC4Cipher::encrypt($secret, $auth));
             } else {
                 $auth = 'Basic ' . base64_encode($auth);
             }
             $client = new Client($address);
             $client->setAuthString($auth);
             $user = $client->me();
             // just to check that auth is correct
             if (!$user) {
                 throw new \Exception('Could not authenticate');
             }
             $version = $client->serverVersion();
             $this->addServer($name, $address, $auth);
             \cli\line('%gSuccessfully added server "' . $name . '" (v' . $version . ')%n');
             \cli\line('... add flag -l to list all added servers');
         } catch (\Exception $e) {
             \cli\err('Failed adding server with message "' . $e->getMessage() . '"');
         }
     }
 }
コード例 #15
0
/**
 * Loop Callback utility to create an array from a csv file.
 * Associative array if $index and $fieldDefinition are provided.
 *
 * @param string $line
 * @param int $index
 * @param array $fieldDefinition keys
 * @return array
 */
function parseCsv($line, $index = NULL, &$fieldDefinition = NULL)
{
    $values = str_getcsv($line, ',', '"');
    if ($index === 0) {
        $fieldDefinition = mapColumns($values);
    } else {
        if ($fieldDefinition) {
            if (count($fieldDefinition) == count($values)) {
                return array_combine($fieldDefinition, $values);
            } else {
                cli\err("field definition did not match:\n" . var_export($values, TRUE));
            }
        } else {
            return $values;
        }
    }
}
コード例 #16
0
ファイル: Console.php プロジェクト: jaeger-app/console
 /**
  * Outputs an error to the console
  * 
  * @param string $error
  *            The language key for the message to display
  */
 public function outputError($error)
 {
     \cli\err($this->getLang()->__($error));
 }