protected function init() { global $swarmInstallDir; $this->checkAtty(); $supportsReadline = function_exists('readline_add_history'); if ($supportsReadline) { $historyFile = isset($_ENV['HOME']) ? "{$_ENV['HOME']}/.testswarm_eval_history" : "{$swarmInstallDir}/config/.testswarm_eval_history"; readline_read_history($historyFile); } while (!!($line = $this->cliInput())) { if ($supportsReadline) { readline_add_history($line); readline_write_history($historyFile); } $ret = eval($line . ";"); if (is_null($ret)) { echo "\n"; } elseif (is_string($ret) || is_numeric($ret)) { echo "{$ret}\n"; } else { var_dump($ret); } } print "\n"; exit; }
/** * {@inheritDoc} */ public function writeHistory() { // We have to write history first, since it is used // by Libedit to list history $res = readline_write_history($this->historyFile); if (!$res || !$this->eraseDups && !$this->historySize > 0) { return $res; } $hist = $this->listHistory(); if (!$hist) { return true; } if ($this->eraseDups) { // flip-flip technique: removes duplicates, latest entries win. $hist = array_flip(array_flip($hist)); // sort on keys to get the order back ksort($hist); } if ($this->historySize > 0) { $histsize = count($hist); if ($histsize > $this->historySize) { $hist = array_slice($hist, $histsize - $this->historySize); } } readline_clear_history(); foreach ($hist as $line) { readline_add_history($line); } return readline_write_history($this->historyFile); }
public function start() { $histfile = '.magesh_history'; if (PHP_OS == 'Linux') { readline_read_history($histfile); } do { $input = $this->_getInput($this->_prompt); if ($input === false) { break; } $cmd = $this->_formatInput($input); if (PHP_OS == 'Linux') { readline_add_history($input); readline_write_history($histfile); } echo "\n"; $result = null; try { $result = eval($cmd); } catch (Exception $e) { $result = $e->getMessage() . "\n\n" . $e->getTraceAsString() . "\n\n"; } $output = $this->_formatOutput($result); echo "Result: " . $output . "\n\n"; } while (true); return true; }
public function execute() { $dbw = wfGetDB(DB_MASTER); if ($this->hasArg()) { $fileName = $this->getArg(); $file = fopen($fileName, 'r'); if (!$file) { $this->error("Unable to open input file", true); } $error = $dbw->sourceStream($file, false, array($this, 'sqlPrintResult')); if ($error !== true) { $this->error($error, true); } else { exit(0); } } $useReadline = function_exists('readline_add_history') && Maintenance::posix_isatty(0); if ($useReadline) { global $IP; $historyFile = isset($_ENV['HOME']) ? "{$_ENV['HOME']}/.mwsql_history" : "{$IP}/maintenance/.mwsql_history"; readline_read_history($historyFile); } $wholeLine = ''; $newPrompt = '> '; $prompt = $newPrompt; while (($line = Maintenance::readconsole($prompt)) !== false) { if (!$line) { # User simply pressed return key continue; } $done = $dbw->streamStatementEnd($wholeLine, $line); $wholeLine .= $line; if (!$done) { $wholeLine .= ' '; $prompt = ' -> '; continue; } if ($useReadline) { # Delimiter is eated by streamStatementEnd, we add it # up in the history (bug 37020) readline_add_history($wholeLine . $dbw->getDelimiter()); readline_write_history($historyFile); } try { $res = $dbw->query($wholeLine); $this->sqlPrintResult($res, $dbw); $prompt = $newPrompt; $wholeLine = ''; } catch (DBQueryError $e) { $doDie = !Maintenance::posix_isatty(0); $this->error($e, $doDie); } } }
public static function readLine($prompt, ReadlineCompleter $compl = null, callable $filter = null) { if ($compl) { \readline_completion_function($compl); } $ret = \readline($prompt); if (self::$history_file) { readline_write_history(self::$history_file); } if ($filter) { $ret = $filter($ret); } return $ret; }
* Create a new ReadlineClient using $socket for communication. * * @param resource $socket */ public function __construct($socket) { $this->_socket = $socket; } /** * Start the client with an prompt and readline history path. * * This method never returns. * * @param string $prompt * @param string $historyFile */ public function start($prompt, $historyFile) { readline_read_history($historyFile); declare (ticks=1); pcntl_signal(SIGCHLD, SIG_IGN); pcntl_signal(SIGINT, array($this, 'clear'), true); // wait for the worker to finish executing hooks if (fread($this->_socket, 1) != EvalWorker::READY) { throw new \RuntimeException('EvalWorker failed to start'); } $parser = new ShallowParser(); $buf = ''; $lineno = 1; for (;;) { $this->_clear = false; $line = readline(sprintf('[%d] %s', $lineno, $buf == '' ? $prompt : str_pad('*> ', strlen($prompt), ' ', STR_PAD_LEFT))); if ($this->_clear) { $buf = ''; continue; } if (false === $line) { $buf = 'exit(0);'; // ctrl-d acts like exit } if (strlen($line) > 0) { readline_add_history($line); } $buf .= sprintf("%s\n", $line); if ($statements = $parser->statements($buf)) { ++$lineno; $buf = ''; foreach ($statements as $stmt) { if (false === ($written = fwrite($this->_socket, $stmt))) { throw new \RuntimeException('Socket error: failed to write data');
/** * Runs the shell. */ public function run() { $this->application->setAutoExit(false); $this->application->setCatchExceptions(true); if ($this->hasReadline) { readline_read_history($this->history); readline_completion_function(array($this, 'autocompleter')); } $this->output->writeln($this->getHeader()); $php = null; if ($this->processIsolation) { $finder = new PhpExecutableFinder(); $php = $finder->find(); $this->output->writeln(<<<EOF <info>Running with process isolation, you should consider this:</info> * each command is executed as separate process, * commands don't support interactivity, all params must be passed explicitly, * commands output is not colorized. EOF ); } while (true) { $command = $this->readline(); if (false === $command) { $this->output->writeln("\n"); break; } if ($this->hasReadline) { readline_add_history($command); readline_write_history($this->history); } if ($this->processIsolation) { $pb = new ProcessBuilder(); $process = $pb->add($php)->add($_SERVER['argv'][0])->add($command)->inheritEnvironmentVariables(true)->getProcess(); $output = $this->output; $process->run(function ($type, $data) use($output) { $output->writeln($data); }); $ret = $process->getExitCode(); } else { $ret = $this->application->run(new StringInput($command), $this->output); } if (0 !== $ret) { $this->output->writeln(sprintf('<error>The command terminated with an error status (%s)</error>', $ret)); } } }
/** * Destructor * * @return void */ public function __destruct() { fclose($this->input); if ($this->options['readline']) { readline_write_history($this->options['readline_hist']); } // Save config $fp = fopen($this->rc_file, 'w'); if ($fp === false) { return; } foreach ($this->options as $k => $v) { fwrite($fp, "{$k} = \"{$v}\"\n"); } fclose($fp); }
public static function init($paths = null, $history_path = null) { self::$_often = get_defined_functions(); self::$_often = array_merge(self::$_often['internal'], get_declared_classes()); if (is_null($paths)) { $paths = explode(PATH_SEPARATOR, get_include_path()); } self::$_paths = $paths; if (self::_supportedReadline()) { readline_completion_function(array(__CLASS__, 'autocomplete')); self::$__last = null; if (is_null($history_path)) { if ($home = getenv('HOME')) { $history_path = $home . '/.pprompt_history'; } } if (self::$__history_path = $history_path) { readline_read_history(self::$__history_path); } } unset($paths); unset($history_path); unset($home); while (self::$__l = self::_readline(">> ")) { if (self::_supportedReadline()) { if (is_null(self::$__last) or self::$__l != self::$__last) { readline_add_history(self::$__l); } if (self::$__history_path) { readline_write_history(self::$__history_path); } } try { eval(self::$__l . ";"); echo "\n"; } catch (Exception $e) { echo $e->getMessage() . "\n"; echo $e->getTraceAsString() . "\n"; } self::$_vars = get_defined_vars(); self::$__last = self::$__l; } }
public function execute() { $dbw = wfGetDB(DB_MASTER); if ($this->hasArg()) { $fileName = $this->getArg(); $file = fopen($fileName, 'r'); if (!$file) { $this->error("Unable to open input file", true); } $error = $dbw->sourceStream($file, false, array($this, 'sqlPrintResult')); if ($error !== true) { $this->error($error, true); } else { exit(0); } } $useReadline = function_exists('readline_add_history') && Maintenance::posix_isatty(0); if ($useReadline) { global $IP; $historyFile = isset($_ENV['HOME']) ? "{$_ENV['HOME']}/.mwsql_history" : "{$IP}/maintenance/.mwsql_history"; readline_read_history($historyFile); } $wholeLine = ''; while (($line = Maintenance::readconsole()) !== false) { $done = $dbw->streamStatementEnd($wholeLine, $line); $wholeLine .= $line; if (!$done) { continue; } if ($useReadline) { readline_add_history($wholeLine); readline_write_history($historyFile); } try { $res = $dbw->query($wholeLine); $this->sqlPrintResult($res, $dbw); $wholeLine = ''; } catch (DBQueryError $e) { $this->error($e, true); } } }
function read_input_line($prompt) { if (CONSOLE_INTERACTIVE) { if (CONSOLE_READLINE) { $line = readline($prompt); if (trim($line) != '') { readline_add_history($line); if (defined('CONSOLE_HISTORY')) { // Save often; it's easy to hit fatal errors. readline_write_history(CONSOLE_HISTORY); } } return $line; } else { return readline_emulation($prompt); } } else { return fgets(STDIN); } }
/** * Runs the shell. */ public function run() { $this->application->setAutoExit(false); $this->application->setCatchExceptions(true); readline_read_history($this->history); readline_completion_function(array($this, 'autocompleter')); $this->output->writeln($this->getHeader()); while (true) { $command = readline($this->application->getName() . ' > '); if (false === $command) { $this->output->writeln("\n"); break; } readline_add_history($command); readline_write_history($this->history); if (0 !== ($ret = $this->application->run(new StringInput($command), $this->output))) { $this->output->writeln(sprintf('<error>The command terminated with an error status (%s)</error>', $ret)); } } }
/** * Runs the shell. */ public function run() { $this->application->setAutoExit(false); $this->application->setCatchExceptions(false); if ($this->hasReadline) { readline_read_history($this->history); readline_completion_function(array($this, 'autocompleter')); } $this->output->writeln($this->getHeader()); while (true) { $command = $this->readline(); if (false === $command) { $this->output->writeln("\n"); break; } if ($this->hasReadline) { readline_add_history($command); readline_write_history($this->history); } $ret = $this->application->run(new StringInput($command), $this->output); } }
public function shutdown($event) { readline_write_history($event->getSubject()->getConfigDir() . '/history'); }
<?php $name = tempnam('/tmp', 'readline.tmp'); readline_add_history('foo'); readline_add_history(''); readline_add_history(1); readline_add_history(NULL); var_dump(readline_write_history($name)); var_dump(readline_read_history($name)); var_dump(file_get_contents($name)); readline_clear_history(); readline_write_history($name); var_dump(file_get_contents($name)); unlink($name);
public function execute() { $wiki = $this->getOption('wikidb') ?: false; // Get the appropriate load balancer (for this wiki) if ($this->hasOption('cluster')) { $lb = wfGetLBFactory()->getExternalLB($this->getOption('cluster'), $wiki); } else { $lb = wfGetLB($wiki); } // Figure out which server to use if ($this->hasOption('slave')) { $server = $this->getOption('slave'); if ($server === 'any') { $index = DB_SLAVE; } else { $index = null; for ($i = 0; $i < $lb->getServerCount(); ++$i) { if ($lb->getServerName($i) === $server) { $index = $i; break; } } if ($index === null) { $this->error("No slave server configured with the name '{$server}'.", 1); } } } else { $index = DB_MASTER; } // Get a DB handle (with this wiki's DB selected) from the appropriate load balancer $db = $lb->getConnection($index, array(), $wiki); if ($this->hasOption('slave') && $db->getLBInfo('master') !== null) { $this->error("The server selected ({$db->getServer()}) is not a slave.", 1); } if ($this->hasArg(0)) { $file = fopen($this->getArg(0), 'r'); if (!$file) { $this->error("Unable to open input file", true); } $error = $db->sourceStream($file, false, array($this, 'sqlPrintResult')); if ($error !== true) { $this->error($error, true); } else { exit(0); } } $useReadline = function_exists('readline_add_history') && Maintenance::posix_isatty(0); if ($useReadline) { global $IP; $historyFile = isset($_ENV['HOME']) ? "{$_ENV['HOME']}/.mwsql_history" : "{$IP}/maintenance/.mwsql_history"; readline_read_history($historyFile); } $wholeLine = ''; $newPrompt = '> '; $prompt = $newPrompt; while (($line = Maintenance::readconsole($prompt)) !== false) { if (!$line) { # User simply pressed return key continue; } $done = $db->streamStatementEnd($wholeLine, $line); $wholeLine .= $line; if (!$done) { $wholeLine .= ' '; $prompt = ' -> '; continue; } if ($useReadline) { # Delimiter is eated by streamStatementEnd, we add it # up in the history (bug 37020) readline_add_history($wholeLine . $db->getDelimiter()); readline_write_history($historyFile); } try { $res = $db->query($wholeLine); $this->sqlPrintResult($res, $db); $prompt = $newPrompt; $wholeLine = ''; } catch (DBQueryError $e) { $doDie = !Maintenance::posix_isatty(0); $this->error($e, $doDie); } } wfWaitForSlaves(); }
$serverCount = $lb->getServerCount(); for ($i = 0; $i < $serverCount; $i++) { $server = $lb->getServerInfo($i); $server['flags'] |= DBO_DEBUG; $lb->setServerInfo($i, $server); } } if ($d > 2) { $wgDebugFunctionEntry = true; } } $useReadline = function_exists('readline_add_history') && Maintenance::posix_isatty(0); if ($useReadline) { $historyFile = isset($_ENV['HOME']) ? "{$_ENV['HOME']}/.mweval_history" : "{$IP}/maintenance/.mweval_history"; readline_read_history($historyFile); } while (($line = Maintenance::readconsole()) !== false) { if ($useReadline) { readline_add_history($line); readline_write_history($historyFile); } $val = eval($line . ";"); if (wfIsHipHop() || is_null($val)) { echo "\n"; } elseif (is_string($val) || is_numeric($val)) { echo "{$val}\n"; } else { var_dump($val); } } print "\n";
public function doCommand($command) { $this->inReadline = false; // detect ctl-d if ($command === NULL) { exit(0); } // no need to process empty commands if (trim($command) == '') { return; } // internal command parser $matches = array(); if (preg_match("/\\s*\\{$this->commandEscapeChar}([\\w\\?]+)\\s?(.*)/", trim($command), $matches)) { $internalCommand = $matches[1]; $argsString = $matches[2]; $args = array(); if (preg_match_all("/(?:([\\w]+)\\s?)/", $argsString, $matches)) { $args = $matches[1]; } if (isset($this->internalCommands[$internalCommand])) { $this->internalCommands[$internalCommand]->run($this, $args); } else { print "Command '{$internalCommand}' does not exist.\n"; } return; } // normal command if (!empty($command) and function_exists('readline_add_history')) { readline_add_history($command); readline_write_history($this->historyFile()); } $command = preg_replace('/^\\//', '$_', $command); // "/" as a command will just output the last result. $requires = unserialize(file_get_contents($this->tmpFileShellCommandRequires)); if (!is_array($requires)) { $requires = array(); } $parsedCommand = "<?php\nforeach (" . var_export($requires, true) . " as \$file) {\n require_once(\$file);\n}\n\$__commandState = unserialize(file_get_contents('{$this->tmpFileShellCommandState}'));\nif (is_array(\$__commandState))\n{\n extract(\$__commandState);\n}\nob_start();\n\$_ = {$command};\n\$__out = ob_get_contents();\nob_end_clean();\n\$__allData = get_defined_vars();\nunset(\$__allData['GLOBALS'], \$__allData['argv'], \$__allData['argc'], \$__allData['_POST'], \$__allData['_GET'], \$__allData['_COOKIE'], \$__allData['_FILES'], \$__allData['_SERVER']);\nfile_put_contents('{$this->tmpFileShellCommandRequires}', serialize(get_included_files()));\nfile_put_contents('{$this->tmpFileShellCommandState}', serialize(\$__allData));\n"; #echo " $parsedCommand\n"; try { $_ = $this->lastResult; file_put_contents($this->tmpFileShellCommand, $parsedCommand); $result = NULL; $output = array(); $lastLine = exec("{$this->options[self::OPT_PHP_BIN]} {$this->tmpFileShellCommand} 2>&1", $output, $result); if ($result != 0) { throw new Exception("Fatal error executing php: " . join("\n", $output)); } // boostrap requires environment of command $requires = unserialize(file_get_contents($this->tmpFileShellCommandRequires)); foreach ($requires as $require) { if ($require === $this->tmpFileShellCommand) { continue; } require_once $require; } $lastState = unserialize(file_get_contents($this->tmpFileShellCommandState)); $this->lastResult = $lastState['_']; print $this->outputPrompt; if ($lastState['__out']) { print $lastState['__out'] . "\n"; } else { if (is_object($this->lastResult) && !is_callable(array($this->lastResult, '__toString'))) { print_r($this->lastResult) . "\n"; } else { print $this->lastResult . "\n"; } } // after the eval, we might have new classes. Only update it if real readline is enabled if (!empty($this->autocompleteList)) { $this->autocompleteList = array_merge($this->autocompleteList, get_declared_classes()); } } catch (Exception $e) { print "Uncaught exception with command:\n" . $e->getMessage() . "\n"; } }
public function doCommand($command) { print "\n"; if (trim($command) == '') { return; } if (!empty($command) and function_exists('readline_add_history')) { readline_add_history($command); readline_write_history($this->historyFile()); } $command = preg_replace('/^\\//', '$_', $command); // "/" as a command will just output the last result. $requires = unserialize(file_get_contents($this->tmpFileShellCommandRequires)); if (!is_array($requires)) { $requires = array(); } $parsedCommand = "<?php\n//require_once(getenv('PHOCOA_PROJECT_CONF'));\nforeach (" . var_export($requires, true) . " as \$file) {\n require_once(\$file);\n}\n\$__commandState = unserialize(file_get_contents('{$this->tmpFileShellCommandState}'));\nif (is_array(\$__commandState))\n{\n extract(\$__commandState);\n}\nob_start();\n\$_ = {$command};\n\$__out = ob_get_contents();\nob_end_clean();\n\$__allData = get_defined_vars();\nunset(\$__allData['GLOBALS'], \$__allData['argv'], \$__allData['argc'], \$__allData['_POST'], \$__allData['_GET'], \$__allData['_COOKIE'], \$__allData['_FILES'], \$__allData['_SERVER']);\nfile_put_contents('{$this->tmpFileShellCommandRequires}', serialize(get_included_files()));\nfile_put_contents('{$this->tmpFileShellCommandState}', serialize(\$__allData));\n"; #echo " $parsedCommand\n"; try { $_ = $this->lastResult; file_put_contents($this->tmpFileShellCommand, $parsedCommand); $result = NULL; $output = array(); $lastLine = exec("/opt/local/bin/php {$this->tmpFileShellCommand} 2>&1", $output, $result); if ($result != 0) { throw new Exception("Fatal error executing php: " . join("\n", $output)); } // boostrap requires environment of command $requires = unserialize(file_get_contents($this->tmpFileShellCommandRequires)); foreach ($requires as $require) { if ($require === $this->tmpFileShellCommand) { continue; } require_once $require; } $lastState = unserialize(file_get_contents($this->tmpFileShellCommandState)); $this->lastResult = $lastState['_']; if ($lastState['__out']) { print $lastState['__out'] . "\n"; } else { if (is_object($this->lastResult) && !is_callable(array($this->lastResult, '__toString'))) { print_r($this->lastResult) . "\n"; } else { print $this->lastResult . "\n"; } } // after the eval, we might have new classes. Only update it if real readline is enabled if (!empty($this->autocompleteList)) { $this->autocompleteList = array_merge($this->autocompleteList, get_declared_classes()); } } catch (Exception $e) { print "Uncaught exception with command:\n" . $e->getMessage() . "\n"; } }
/** * Read input * * @param * * @return string Input */ private function read() { $code = ''; $done = false; $lines = 0; $stack = array(); static $shifted; if (!$shifted) { // throw away argv[0] array_shift($_SERVER['argv']); $shifted = true; } do { $prompt = $lines > 0 ? '> ' : ($this->getOption('showtime') ? date('G:i:s ') : '') . $this->getOption('prompt'); if (count($_SERVER['argv'])) { $line = array_shift($_SERVER['argv']); } elseif ($this->readline_support) { $line = readline($prompt); } else { echo $prompt; $line = fgets($this->input); } // If the input was empty, return false; this breaks the loop. if ($line === false) { return false; } $done = true; $line = trim($line); // If the last char is a backslash, remove it and // accumulate more lines. if (substr($line, -1) == '\\') { $line = trim(substr($line, 0, strlen($line) - 1)); $done = false; } // check for curleys and parens, keep accumulating lines. $tokens = token_get_all("<?php {$line}"); foreach ($tokens as $t) { switch ($t) { case '{': case '(': array_push($stack, $t); break; case '}': if ('{' !== array_pop($stack)) { throw new \Exception('Unmatched closing brace.'); } break; case ')': if ('(' !== array_pop($stack)) { throw new \Exception('Unmatched closing paren.'); } break; } } if (count($stack) > 0) { $last_t = array_pop($tokens); if (is_array($last_t) && $last_t[0] == T_OPEN_TAG) { // if the last token was an open tag, this is nothing. } elseif ($stack[count($stack) - 1] === '{' && !in_array($last_t, array('{', '}', ';'))) { // allow implied semicolons inside curlies $line .= ';'; } $done = false; } $code .= $line; $lines++; } while (!$done); // Add the whole block to the readline history. if ($this->readline_support) { readline_add_history($code); readline_write_history($this->getOption('readline_hist')); } return $code; }
/** * @param string $command * @codeCoverageIgnore */ private function readlineWriteHistory($command) { if ($this->hasReadline) { readline_add_history($command); readline_write_history($this->historyFile); } }
public function execute() { global $IP; // We wan't to allow "" for the wikidb, meaning don't call select_db() $wiki = $this->hasOption('wikidb') ? $this->getOption('wikidb') : false; // Get the appropriate load balancer (for this wiki) if ($this->hasOption('cluster')) { $lb = wfGetLBFactory()->getExternalLB($this->getOption('cluster'), $wiki); } else { $lb = wfGetLB($wiki); } // Figure out which server to use $replicaDB = $this->getOption('replicadb', $this->getOption('slave', '')); if ($replicaDB === 'any') { $index = DB_REPLICA; } elseif ($replicaDB != '') { $index = null; $serverCount = $lb->getServerCount(); for ($i = 0; $i < $serverCount; ++$i) { if ($lb->getServerName($i) === $replicaDB) { $index = $i; break; } } if ($index === null) { $this->error("No replica DB server configured with the name '{$replicaDB}'.", 1); } } else { $index = DB_MASTER; } /** @var Database $db DB handle for the appropriate cluster/wiki */ $db = $lb->getConnection($index, [], $wiki); if ($replicaDB != '' && $db->getLBInfo('master') !== null) { $this->error("The server selected ({$db->getServer()}) is not a replica DB.", 1); } if ($index === DB_MASTER) { $updater = DatabaseUpdater::newForDB($db, true, $this); $db->setSchemaVars($updater->getSchemaVars()); } if ($this->hasArg(0)) { $file = fopen($this->getArg(0), 'r'); if (!$file) { $this->error("Unable to open input file", true); } $error = $db->sourceStream($file, null, [$this, 'sqlPrintResult']); if ($error !== true) { $this->error($error, true); } else { exit(0); } } if ($this->hasOption('query')) { $query = $this->getOption('query'); $this->sqlDoQuery($db, $query, true); wfWaitForSlaves(); return; } if (function_exists('readline_add_history') && Maintenance::posix_isatty(0)) { $historyFile = isset($_ENV['HOME']) ? "{$_ENV['HOME']}/.mwsql_history" : "{$IP}/maintenance/.mwsql_history"; readline_read_history($historyFile); } else { $historyFile = null; } $wholeLine = ''; $newPrompt = '> '; $prompt = $newPrompt; $doDie = !Maintenance::posix_isatty(0); while (($line = Maintenance::readconsole($prompt)) !== false) { if (!$line) { # User simply pressed return key continue; } $done = $db->streamStatementEnd($wholeLine, $line); $wholeLine .= $line; if (!$done) { $wholeLine .= ' '; $prompt = ' -> '; continue; } if ($historyFile) { # Delimiter is eated by streamStatementEnd, we add it # up in the history (bug 37020) readline_add_history($wholeLine . ';'); readline_write_history($historyFile); } $this->sqlDoQuery($db, $wholeLine, $doDie); $prompt = $newPrompt; $wholeLine = ''; } wfWaitForSlaves(); }
<?php readline_write_history(); readline_read_history(); echo "Done";
/** * {@inheritDoc} */ public function writeHistory() { return readline_write_history($this->historyFile); }
public function __destruct() { if (!empty($this->historyFile) && is_writable($this->historyFile)) { readline_write_history($this->historyFile); } }
public function mainProcess($sock, $pid) { $this->loopID = $pid; if (is_file($this->readlineHistory)) { readline_read_history($this->readlineHistory); } readline_write_history($this->readlineHistory); readline_completion_function(array($this, 'tabCompletion')); while (true) { $data = $this->IPCR($sock); switch ($data['type']) { case 'kick': $this->message($data['value']); $this->reLogin(); break; case 'message': $this->showMessage($data['value']); break; } if ($this->sessionName === null) { $this->prompt = '>>>'; } else { $this->prompt = "TO: {$this->userFriendList[$this->sessionName]['nick']} >>>"; } $userEnter = readline($this->prompt); readline_add_history($userEnter); if (empty($userEnter)) { $this->message('输入help获取相关帮助信息'); continue; } else { $userEnter = trim($userEnter); $this->commandExec($userEnter); } } pcntl_wait($status); }
/** * Run the interactive Shell * * The shell command runs Flow's interactive shell. This shell allows for * entering commands like through the regular command line interface but * additionally supports autocompletion and a user-based command history. * * @return void */ public function shellCommand() { if (!function_exists('readline_read_history')) { $this->outputLine('Interactive Shell is not available on this system!'); $this->quit(1); } $subProcess = false; $pipes = array(); $historyPathAndFilename = getenv('HOME') . '/.flow_' . md5(FLOW_PATH_ROOT); readline_read_history($historyPathAndFilename); readline_completion_function(array($this, 'autocomplete')); echo "Flow Interactive Shell\n\n"; while (true) { $commandLine = readline('Flow > '); if ($commandLine == '') { echo "\n"; break; } readline_add_history($commandLine); readline_write_history($historyPathAndFilename); $request = $this->requestBuilder->build($commandLine); $response = new Response(); $command = $request->getCommand(); if ($request === false || $command->getCommandIdentifier() === false) { echo "Bad command\n"; continue; } if ($this->bootstrap->isCompiletimeCommand($command->getCommandIdentifier())) { $this->dispatcher->dispatch($request, $response); $response->send(); if (is_resource($subProcess)) { $this->quitSubProcess($subProcess, $pipes); } } else { if (is_resource($subProcess)) { $subProcessStatus = proc_get_status($subProcess); if ($subProcessStatus['running'] === false) { proc_close($subProcess); } } if (!is_resource($subProcess)) { list($subProcess, $pipes) = $this->launchSubProcess(); if ($subProcess === false || !is_array($pipes)) { echo "Failed launching the shell sub process for executing the runtime command.\n"; continue; } $this->echoSubProcessResponse($pipes); } fwrite($pipes[0], $commandLine . "\n"); fflush($pipes[0]); $this->echoSubProcessResponse($pipes); if ($command->isFlushingCaches()) { $this->quitSubProcess($subProcess, $pipes); } } } if (is_resource($subProcess)) { $this->quitSubProcess($subProcess, $pipes); } echo "Bye!\n"; }
public function execute() { // Get a DB handle (with this wiki's DB select) from the appropriate load balancer if ($this->hasOption('cluster')) { $lb = wfGetLBFactory()->getExternalLB($this->getOption('cluster')); $dbw = $lb->getConnection(DB_MASTER); // master for external LB } else { $dbw = wfGetDB(DB_MASTER); // master for primary LB for this wiki } if ($this->hasArg(0)) { $file = fopen($this->getArg(0), 'r'); if (!$file) { $this->error("Unable to open input file", true); } $error = $dbw->sourceStream($file, false, array($this, 'sqlPrintResult')); if ($error !== true) { $this->error($error, true); } else { exit(0); } } $useReadline = function_exists('readline_add_history') && Maintenance::posix_isatty(0); if ($useReadline) { global $IP; $historyFile = isset($_ENV['HOME']) ? "{$_ENV['HOME']}/.mwsql_history" : "{$IP}/maintenance/.mwsql_history"; readline_read_history($historyFile); } $wholeLine = ''; $newPrompt = '> '; $prompt = $newPrompt; while (($line = Maintenance::readconsole($prompt)) !== false) { if (!$line) { # User simply pressed return key continue; } $done = $dbw->streamStatementEnd($wholeLine, $line); $wholeLine .= $line; if (!$done) { $wholeLine .= ' '; $prompt = ' -> '; continue; } if ($useReadline) { # Delimiter is eated by streamStatementEnd, we add it # up in the history (bug 37020) readline_add_history($wholeLine . $dbw->getDelimiter()); readline_write_history($historyFile); } try { $res = $dbw->query($wholeLine); $this->sqlPrintResult($res, $dbw); $prompt = $newPrompt; $wholeLine = ''; } catch (DBQueryError $e) { $doDie = !Maintenance::posix_isatty(0); $this->error($e, $doDie); } } wfWaitForSlaves(); }
/** * Save readline history to a file * * @param &io.File file * @return bool success * @throws io.IOException */ public function writeHistoryFile($file) { if (FALSE === readline_write_history($file->getURI())) { throw new IOException('Could not write history to ' . $file->getURI()); } return TRUE; }
<?php $name = tempnam('/tmp', 'readline.tmp'); readline_add_history("foo\n"); var_dump(readline_write_history($name)); var_dump(readline_clear_history()); var_dump(readline_read_history($name)); var_dump(readline_list_history()); unlink($name);