/** * Executo command on shell * @param Shell $shell * @return bool * @throws \Exception */ public function run(Shell $shell) { $match = NULL; while (true) { fwrite($shell->getStream(), $this->__cmd); switch ($key = expect_expectl($shell->getStream(), $cases = $this->formatCases(), $match)) { case in_array($key, $cases): // Run next if ($this->__next instanceof TCommand) { $this->__next->run($shell); } if ('break' == ($result = $this->__cases_list[$key]->proceed($shell->getStream(), $match))) { break; } $shell->addCmd($this->__cmd); $shell->addResult($this->formatResult($result)); return true; break 2; case EXP_EOF: case EXP_FULLBUFFER: break 2; case EXP_TIMEOUT: throw new \Exception("Connection time out"); break 2; default: throw new \Exception("Error has occurred!"); break 2; } } return false; }
/** * @param array $args * * @return array */ public function read($args = []) { $args = $this->processOptions($args); $this->shell->exec('git fetch -u'); $this->shell->exec("git log {$args['revision range']} --pretty=format:%s", $output); return $output; }
public function testCount() { $gerador = new Gerador(); $vector = $gerador->gerar(500); $shell = new Shell(); $array = Asort($vector); $this->assertEquals($array, $shell->run($vector)); }
/** * Tests the truncateModels function * * @return void * @covers ::truncateModels */ public function testTruncateModels() { $this->_shell->expects($this->at(0))->method('out')->with($this->equalTo('Truncate model Apple...')); $this->_shell->expects($this->at(1))->method('out')->with($this->equalTo('Truncate model Banana...')); $this->_shell->expects($this->at(2))->method('out')->with($this->equalTo('Truncate model Pear...')); $models = array('Apple', 'Banana', 'Pear'); $this->_truncator->truncateModels($models); }
public function testProjectDir() { $projectDir = __DIR__ . '/../../../../'; $shell = new Shell($projectDir); $testCommand = 'vendor/bin/phpunit'; $result = $shell->exec($testCommand, ['--version']); $this->assertContains('PHPUnit', $result); }
/** * Truncate the given models * * @param array $modelsToTruncate An array of models (names) to truncate * @return void * @todo Improve testability by extracting the model object retrieval part. */ public function truncateModels($modelsToTruncate) { foreach ($modelsToTruncate as $modelName) { $this->_shell->out(__('Truncate model %s...', $modelName), 1, Shell::VERBOSE); $model = ClassRegistry::init($modelName); $datasource = $model->getDataSource(); $datasource->truncate($model->table); } }
/** * @param array $args * * @return array */ public function read($args = []) { $args = $this->processOptions($args); $delim = "---<EOM>---"; $command = "git log {$args['revision range']} --pretty=format:\"{$this->format}{$delim}\""; $output = substr($this->shell->shell_exec($command), 0, -1 * strlen($delim . PHP_EOL)); $output = explode(PHP_EOL . $delim . PHP_EOL, $output); return $output; }
/** * Parse file * @param string $Filename relative path (from FRONTEND_PATH) to file */ public function parseFile($Filename) { $File = FRONTEND_PATH . $Filename; $this->Filename = FRONTEND_PATH . $Filename . '.temp'; $Command = new PerlCommand(); $Command->setScript('fittorunalyze.pl', '"' . $File . '" 1>"' . $this->Filename . '"'); $Shell = new Shell(); $Shell->runCommand($Command); $this->readFile(); }
/** * Is Perl available? * * Tries to run a testscript and returns true if succeeded. * @return boolean */ public static function isPerlAvailable() { try { $Command = new PerlCommand(); $Command->setScript('test.pl', ''); $Shell = new Shell(); $Shell->runCommand($Command); return $Shell->getOutput() == 'success'; } catch (Exception $Exception) { return false; } }
/** * Handle the run shell action * @return ShellResult */ public function doShell() { // $shell is derived from RunResult $shell = new Shell(); while (!$shell->isEOF()) { if ($shell->isFail()) { break; } $input = $shell->readInput(); if ($input === FALSE) { break; } // Available shell commands (for help sreen) $shell_commands = array('dump', 'exit', 'help'); // Interpret shell keywords switch ($input) { case 'exit': break 2; case 'dump': $this->stdout(print_r($this->getMemory()->getData(), true)); break; case 'help': $extension_manager = $this->getExtensionManager(); $exports = $extension_manager->exports(); $this->stdout(PHP_EOL); $this->stdout(str_pad(' Commands:', 13) . join(', ', $shell_commands) . PHP_EOL); $this->stdout(str_pad(' Keywords:', 13) . join(', ', $this->getLanguageKeywords()) . PHP_EOL); $this->stdout(str_pad(' Functions:', 13) . join(', ', $exports) . PHP_EOL); $this->stdout(PHP_EOL); break; default: // Assume is code $this->setCode($input); $result = $this->doRun(); // TODO: Finished this // dd($result); // $this->stdout() // Handle printing errors if ($result->isFail()) { foreach ($result->getErrors() as $error) { $this->stderr($this->outputFormatErrorMessage($error)); } } break; } // TODO: Provide interface for setting position :/ $this->line++; $this->column = 0; } $shell->setData($this->getMemory()->getData()); return $shell; }
/** * Add sub-commands. * * @return ConsoleOptionParser */ public function getOptionParser() { $parser = parent::getOptionParser(); $parser->addSubcommand('core', array('help' => 'Delete all cache within CakePHP', 'parser' => array('description' => 'This command will clear all cache in CakePHP using the Cache engine settings.', 'options' => array('config' => array('short' => 'c', 'help' => 'Cache Config', 'default' => 'default'), 'key' => array('short' => 'k', 'help' => 'Cache Key', 'default' => ''))))); $parser->addSubcommand('apc', array('help' => 'Delete all cache within APC', 'parser' => array('description' => 'This command will clear all cache in APC, including user, system and opcode caches.'))); return $parser; }
public static function instance() { if (!self::$_instance instanceof Shell) { self::$_instance = new self(); } return self::$_instance; }
/** * Executa comando * * @param Object $oInput * @param Object $oOutput * @access public * @return void */ public function execute($oInput, $oOutput) { $oOutput->write("baixando atualizações...\r"); $oComando = $this->getApplication()->execute('cvs update -dRP'); $aRetornoComandoUpdate = $oComando->output; $iStatusComandoUpdate = $oComando->code; /** * Caso CVS encontre conflito, retorna erro 1 */ if ($iStatusComandoUpdate > 1) { $oOutput->writeln('<error>Erro nº ' . $iStatusComandoUpdate . ' ao execurar cvs update -dR:' . "\n" . $this->getApplication()->getLastError() . '</error>'); return $iStatusComandoUpdate; } $oOutput->writeln(str_repeat(' ', \Shell::columns()) . "\r" . "Atualizações baixados"); $sComandoRoot = ''; /** * Senha do root */ $sSenhaRoot = $this->getApplication()->getConfig('senhaRoot'); /** * Executa comando como root * - caso for existir senha no arquivo de configuracoes */ if (!empty($sSenhaRoot)) { $sComandoRoot = "echo '{$sSenhaRoot}' | sudo -S "; } $oComando = $this->getApplication()->execute($sComandoRoot . 'chmod 777 -R ' . getcwd()); $aRetornoComandoPermissoes = $oComando->output; $iStatusComandoPermissoes = $oComando->code; if ($iStatusComandoPermissoes > 0) { throw new Exception("Erro ao atualizar permissões dos arquivos, configura a senha do root: cvsgit config -e"); } }
/** * Override loadTasks() to handle paths * * @access public */ function loadTasks() { parent::loadTasks(); $task = Inflector::classify($this->command); if (isset($this->{$task}) && !in_array($task, array('Project', 'DbConfig'))) { if (empty($this->{$task}->path)) { $path = Inflector::underscore(Inflector::pluralize($this->command)); $this->{$task}->path = $this->params['working'] . DS . $path . DS; } if (isset($this->params['connection'])) { $this->{$task}->connection = $this->params['connection']; } foreach ($this->args as $i => $arg) { if (strpos($arg, '.')) { list($this->params['plugin'], $this->args[$i]) = pluginSplit($arg); break; } } if (isset($this->params['plugin'])) { $this->{$task}->plugin = $this->params['plugin']; } if (!is_dir($this->{$task}->path)) { $this->err(sprintf(__("%s directory could not be found.\nBe sure you have created %s", true), $task, $this->{$task}->path)); $this->_stop(); } } }
/** * Runs task */ protected function _run() { $this->_Process = new TaskProcess($this->_task['command'] . $this->_argsToString($this->_task['arguments']), $this->_task['path']); $this->_Process->setTimeout($this->_task['timeout']); try { $this->_Process->start(function ($type, $buffer) { if ('err' === $type) { $this->_Shell->err($buffer); $this->_task['stderr'] .= $buffer; } else { $this->_Shell->out($buffer); $this->_task['stdout'] .= $buffer; } $this->_TaskServer->updated($this->_task); }); while ($this->_Process->isRunning()) { $this->_task['process_id'] = (int) $this->_Process->getPid(); $this->_TaskServer->updateStatistics($this->_task); $this->_Process->checkTimeout(); sleep(Configure::read('Task.checkInterval')); if ($this->_TaskServer->mustStop($this->_task['id'])) { $this->_Process->stop(Configure::read('Task.stopTimeout')); $this->_task['code'] = 143; $this->_task['code_string'] = TaskProcess::$exitCodes[143]; return $this->_stopped(true); } } $this->_task['code'] = $this->_Process->getExitCode(); $this->_task['code_string'] = $this->_Process->getExitCodeText(); } catch (Exception $Exception) { $this->_task['code'] = 134; $this->_task['code_string'] = $Exception->getMessage(); } $this->_stopped(false); }
function main() { parent::loadTasks(); $this->out('Import Upload Shell'); $this->hr(); $this->_setAvailableImportFiles(); if (empty($this->args)) { $imports = $this->_interactive(); } else { $imports = $this->_determineImportIds(implode(' ', $this->args)); } if (!empty($imports)) { foreach ($imports as $import) { $importUpload = $this->ImportUpload->create($import); if ($filename = $this->ImportUpload->filePath()) { $importUpload['ImportUpload']['file_path'] = $filename; if (!empty($import['ImportDelimiter'])) { $options = array('delimiter' => $import['ImportDelimiter']['delimiter'], 'excel_reader' => $import['ImportDelimiter']['use_excel_reader'], 'qualifier' => $import['ImportUpload']['text_qualifier']); } if ($this->Parser->execute($filename, $options)) { $this->ImportUpload->saveField('total', $this->Parser->getRowCount()); $this->ImportUpload->saveField('is_importing', 1); } die('here'); } else { } } } }
/** * Initialization method. We have to jump through some hoops to * allow our shell to work correctly from a plugin path. * @return null * @access public */ public function initialize() { require realpath(CAKE . '..' . DS) . DS . 'app' . DS . 'config' . DS . 'database.php'; require CAKE . 'libs' . DS . 'model' . DS . 'model.php'; require CAKE . 'libs' . DS . 'model' . DS . 'app_model.php'; parent::initialize(); }
/** * initialize * * @access public */ public function initialize() { parent::initialize(); if ($this->_dataPath == null) { $this->_dataPath = APP . 'Plugin' . DS . 'Ekidata' . DS . 'Vendor' . DS . 'data' . DS; } }
function out($data) { if (is_scalar($data)) { parent::out($data); } else { parent::out(print_r($data, true)); } }
public function __construct($stdout = null, $stderr = null, $stdin = null) { $this->setTerminalWidth(); App::import('Core', 'Router'); InfinitasPlugin::loadForInstaller(); parent::__construct($stdout, $stderr, $stdin); $this->__verbose = isset($this->params['verbose']) && $this->params['verbose']; }
/** * __construct * @param type $stdout * @param type $stderr * @param type $stdin */ public function __construct($stdout = null, $stderr = null, $stdin = null) { parent::__construct($stdout, $stderr, $stdin); $this->Config = new OvenConfig(); $this->stdout->styles('good', array('text' => 'green')); $this->stdout->styles('bad', array('text' => 'red')); $this->stdout->styles('ok', array('text' => 'yellow')); }
/** * Override initialize * * @access public */ function __construct(&$dispatch) { parent::__construct($dispatch); $this->path = $this->params['working'] . DS . 'tests' . DS . 'fixtures' . DS; if (!class_exists('CakeSchema')) { App::import('Model', 'CakeSchema', false); } }
/** * Creates a file at given path, checks if the file exists * * @param string $path Where to put the file. * @param string $contents Content to put in the file. * @return boolean Success * @link http://book.cakephp.org/2.0/en/console-and-shells.html#Shell::createFile */ public function createFile($path, $contents) { if (is_file($path) && $this->params['keep'] === true) { $this->out(__d('cake_console', 'Skipping file %s.', $path)); return false; } return parent::createFile($path, $contents); }
/** * */ public function startup() { parent::startup(); if (!empty($this->params['y']) && !is_bool($this->params['y'])) { array_unshift($this->args, $this->params['y']); $this->interactive = false; } }
/** * getOptionParser * * @return Parser */ public function getOptionParser() { $parser = parent::getOptionParser(); $parser->addSubcommand('generate', array('help' => '<model> <version> Generate a new image version', 'boolean' => true)); $parser->addSubcommand('remove', array('help' => '<model> <version> Remove an image version', 'boolean' => true)); $parser->addOption('storageModel', array('short' => 's', 'help' => __('The storage model for image processing you want to use.'))); $parser->addOption('limit', array('short' => 'l', 'help' => __('Limits the amount of records to be processed in one batch'))); return $parser; }
public function getOptionParser($task = false) { $this->stdout->styles('option', array('bold' => true)); $parser = parent::getOptionParser(); $options = array('path' => array('short' => 'p', 'default' => 'APP', 'help' => 'comma-delimited path list (constants or strings)'), 'exclude' => array('short' => 'e', 'default' => NULL, 'help' => 'comma-delimited path exclusion list (constants or strings)'), 'mode' => array('short' => 'm', 'default' => 'interactive', 'choices' => array('interactive', 'diff', 'silent'), 'help' => "<option>interactive</option> shows errors individually and prompts for change\n" . "<option>diff</option> writes a unified diff to current directory without changing files\n" . "<option>silent</option> corrects all errors without prompting\n"), 'files' => array('short' => 'f', 'default' => 'php', 'help' => 'comma-delimited extension list, defaults to php')); $parser->addOptions($options); $parser->description('<info>Ensure code is error-free and follows conventions</info>'); return $parser; }
public function __construct($stdout, $stderr, $stdin) { parent::__construct($stdout, $stderr, $stdin); /** * Configure output variable to log to screen * rather than string. */ Configure::write('log_output', true); }
/** * Initialize shell */ function initialize() { parent::initialize(); if (Configure::load('cron_mailer') !== false) { $this->settings = array_merge($this->settings, Configure::read('CronMailer')); } App::import('Component', 'CronMailer.CronMailer'); $this->CronMailer =& new CronMailerComponent(); }
function initialize() { parent::initialize(); App::import('Core', 'Controller'); App::import('Component', 'Qdmail'); $this->Controller =& new Controller(); $this->Qdmail =& new QdmailComponent(null); $this->Qdmail->startup($this->Controller); }
/** * Create the configuration object used in other classes. * */ public function startup() { parent::startup(); $config = null; if (isset($this->params['config'])) { $config = $this->params['config']; } AssetConfig::clearAllCachedKeys(); $this->_Config = AssetConfig::buildFromIniFile($config); }