private function prompt($question, $default) { try { $response = \cli\prompt($question, $default); } catch (\Exception $e) { Terminus::line(); return false; } return $response; }
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; } } }
function do_readline($prompt = 'command > ') { if (function_exists('readline')) { $cmd = readline($prompt); if ($cmd === '') { return null; } readline_add_history($cmd); } else { $cmd = \cli\prompt("mwp "); if ($cmd === '') { return null; } } $args = explode(" ", $cmd); return $args; }
/** * @param string $prompt * @return string */ public static function promptPassword($prompt = 'Enter Password: '******'/^win/i', PHP_OS)) { $vbscript = sys_get_temp_dir() . 'prompt_password.vbs'; file_put_contents($vbscript, 'wscript.echo(InputBox("' . addslashes($prompt) . '", "", "password here"))'); $command = "cscript //nologo " . escapeshellarg($vbscript); $password = rtrim(shell_exec($command)); unlink($vbscript); return $password; } else { $command = "/usr/bin/env bash -c 'echo OK'"; if (rtrim(shell_exec($command)) !== 'OK') { trigger_error("Can't invoke bash"); return \cli\prompt($prompt, false, ''); } $command = "/usr/bin/env bash -c 'read -s -p \"" . addslashes($prompt) . "\" mypassword && echo \$mypassword'"; $password = rtrim(shell_exec($command)); echo "\n"; return $password; } }
/** * @param $dotenv * @param $template * @param $assoc_args */ protected function init_from_template(Dotenv_File &$dotenv, $template, $assoc_args) { $template_path = get_filepath(['file' => $template]); if (!file_exists($template_path)) { WP_CLI::error("Template file does not exist at: {$template_path}"); return; } if (!is_readable($template_path)) { WP_CLI::error("Template file is not readable at: {$template_path}"); return; } if (!$dotenv->is_writable()) { WP_CLI::error('Environment file is not readable at: ' . $dotenv->get_filepath()); return; } WP_CLI::line("Initializing from template: {$template_path}"); copy($template_path, $dotenv->get_filepath()); // we can't use WP-CLI --prompt because we're working off the template, not the synopsis if (!($interactive = \WP_CLI\Utils\get_flag_value($assoc_args, 'interactive'))) { return; } $dotenv->load(); // reload the new copied data from template WP_CLI::line('Interactive init'); WP_CLI::line('Specify a new value for each key, or leave blank for no change.'); // iterate over each line and prompt for a new value $dotenv->map(function ($line) use($dotenv) { $pair = $dotenv->get_pair_for_line($line); if (!$pair['key']) { return $line; } $user_value = \cli\prompt($pair['key'], $pair['value']); if (!strlen($user_value)) { return $line; } return format_line($pair['key'], $user_value); }); $dotenv->save(); }
/** * Prompt the user for input * * @param array $arg_options Elements as follow: * string message Message to give at prompt * mixed default Returned if user does not select a valid option * @return string * @throws TerminusException */ public function prompt(array $arg_options = []) { $default_options = ['message' => '', 'default' => null]; $options = array_merge($default_options, $arg_options); try { $response = \cli\prompt($options['message']); } catch (\Exception $e) { throw new TerminusException($e->getMessage, [], 1); } if (empty($response)) { return $options['default']; } return $response; }
/** * Prompt the user for input * * @param string $message */ static function prompt($message = '', $params = array(), $default = null) { if (!empty($params)) { $message = vsprintf($message, $params); } $response = \cli\prompt($message); if (empty($response) and $default) { $response = $default; } return $response; }
private function prompt_if_files_will_be_overwritten($filename, $force) { $should_write_file = true; if (!file_exists($filename)) { return true; } WP_CLI::warning('File already exists'); WP_CLI::log($filename); if (!$force) { do { $answer = cli\prompt('Skip this file, or replace it with scaffolding?', $default = false, $marker = '[s/r]: '); } while (!in_array($answer, array('s', 'r'))); $should_write_file = 'r' === $answer; } $outcome = $should_write_file ? 'Replacing' : 'Skipping'; WP_CLI::log($outcome . PHP_EOL); return $should_write_file; }
} else { $obj->install(); _('- installed ' . $class); } } $userFactory = new \Rocker\Object\User\UserFactory($db); // todo: check if it exists an admin $hasAdmin = $userFactory->metaSearch(array('admin' => 1))->getNumMatching() > 0; // Ask for e-mail _('## Create admin user'); while (empty($email)) { $email = Rocker\Console\Utils::promptAllowingEmpty('E-mail'); if (empty($email) && !$hasAdmin) { _('%rYou must create an admin user%n'); } elseif (empty($email) && $hasAdmin) { $email = 'skip'; } else { if (filter_var($email, FILTER_VALIDATE_EMAIL) === false) { _('%rNot a valid e-mail%n'); $email = null; } } } // Create admin user if ($email != 'skip') { $nick = \cli\prompt('Nick name'); $password = \Rocker\Console\Utils::promptPassword('Password: '******'%gRocker Server v' . \Rocker\Server::VERSION . ' was successfully installed :) %n');
/** * CLI input prompt * * @param $question * @param $default * * @return bool */ function prompt($question, $default) { try { $response = \cli\prompt($question, $default); } catch (\Exception $e) { WP_CLI::line(); return false; } return $response; }
/** * @param string $menu */ protected static function askAlternatePath($menu) { $valid = false; while ($valid === false) { try { self::setInstallPath(self::validatePath(\cli\prompt($menu, $default = false, $marker = ': '))); return true; } catch (Exception $e) { self::showError($e->getMessage()); } } }
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("[0m", \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); }
/** * Prompt the user for input * * @param [string] $message Message to give at prompt * @param [mixed] $default Returned if user does not select a valid option * @return [string] $response */ static function prompt($message = '', $default = null) { if (!empty($params)) { $message = vsprintf($message, $params); } try { $response = \cli\prompt($message); } catch (\Exception $e) { throw new TerminusException($e->getMessage, array(), -1); } if (empty($response) && $default) { $response = $default; } return $response; }
/** * @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() . '"'); } } }
/** * Prompt the user for input at the command line or use a default. * * @param $question * @param $default * * @return bool */ protected function prompt($question, $default) { try { return \cli\prompt($question, $default); } catch (\Exception $e) { WP_CLI::error($e->getMessage()); die; } }
/** * @inheritdoc */ public function call($args, $flags) { $client = Server::loadClient($args); if (!$client) { return; } // Create user if (isset($args['-c'])) { $email = \cli\prompt('E-mail'); $pass = Utils::promptPassword('Password: '******'Meta (query string)'); $meta = array(); foreach (explode('&', $metaData) as $data) { $parts = explode('=', $data); if (count($parts) == 2) { $meta[trim($parts[0])] = trim($parts[1]); } } try { $user = $client->createUser($args['-c'], $email, $pass, $meta); self::displayUser($user); } catch (DuplicationException $e) { \cli\line('%rUser with given e-mail already exists%n'); } catch (\InvalidArgumentException $e) { \cli\line('Invalid arguments, message: ' . $e->getMessage()); } } elseif (isset($args['-l'])) { $user = $client->loadUser($args['-l']); if ($user) { self::displayUser($user); } else { \cli\line('-No user found'); } } elseif (isset($args['-r'])) { $user = $client->loadUser($args['-r']); if ($user) { $yes = \cli\prompt('Do you really want to delete "' . $user->nick . '" (y/n)'); if ($yes[0] == 'y') { $client->deleteUser($args['-r']); \cli\line('...user deleted'); } } else { \cli\line('User not found'); } } elseif (isset($args['-q'])) { $limit = isset($args['-lim']) ? $args['-lim'] : 50; $offset = isset($args['-off']) ? $args['-off'] : 0; $search = array(); foreach (explode('&', $args['-q']) as $que) { $parts = explode('=', $que); $search[$parts[0]] = $parts[1]; } $result = $client->search('user', $search, $offset, $limit); if (in_array('-v', $flags)) { print_r($result); } $this->displaySearchResult($result); } elseif (isset($args['-u'])) { $user = $client->loadUser($args['-u']); if ($user) { self::displayUser($user); \cli\line('Update user "%_' . $user->nick . '%n" (leave values empty if not wanting to change a property)'); $nick = Utils::promptAllowingEmpty('New nick'); $email = Utils::promptAllowingEmpty('New e-mail'); $pass = Utils::promptPassword('New password: '******'Meta'); $meta = array(); foreach (explode('&', $metaData) as $data) { $parts = explode('=', $data); if (count($parts) == 2) { $meta[trim($parts[0])] = trim($parts[1]); } } $user = $client->updateUser($user->id, $nick, $email, $pass, $meta); \cli\line('%_%gUser updated%n'); self::displayUser($user); } else { \cli\line('User not found'); } } else { $this->help(); } }