Crack a command line.

@param string $toProcess the command line to process.

@return string[] the command line broken into strings.
An empty or null toProcess parameter results in a zero sized array.

@throws \BuildException
428646
public static function translateCommandline(string $toProcess = null): array
    {
        if ($toProcess === null || $toProcess === '') {
            return [];
        }

        // parse with a simple finite state machine

        $normal = 0;
        $inQuote = 1;
        $inDoubleQuote = 2;

        $state = $normal;
        $args = [];
        $current = "";
        $lastTokenHasBeenQuoted = false;

        $tokens = preg_split('/(["\' ])/', $toProcess, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
        while (($nextTok = array_shift($tokens)) !== null) {
            switch ($state) {
                case $inQuote:
                    if ("'" === $nextTok) {
                        $lastTokenHasBeenQuoted = true;
                        $state = $normal;
                    } else {
                        $current .= $nextTok;
                    }
                    break;
                case $inDoubleQuote:
                    if ("\"" === $nextTok) {
                        $lastTokenHasBeenQuoted = true;
                        $state = $normal;
                    } else {
                        $current .= $nextTok;
                    }
                    break;
                default:
                    if ("'" === $nextTok) {
                        $state = $inQuote;
                    } elseif ("\"" === $nextTok) {
                        $state = $inDoubleQuote;
                    } elseif (" " === $nextTok) {
                        if ($lastTokenHasBeenQuoted || $current !== '') {
                            $args[] = $current;
                            $current = "";
                        }
                    } else {
                        $current .= $nextTok;
                    }
                    $lastTokenHasBeenQuoted = false;
                    break;
            }
        }

        if ($lastTokenHasBeenQuoted || $current !== '') {
            $args[] = $current;
        }

        if ($state === $inQuote || $state === $inDoubleQuote) {
            throw new BuildException('unbalanced quotes in ' . $toProcess);
        }

        return $args;
    }
726034
public function top($parse = true)
    {
        if (!file_exists($this->tmp_path.'/system')) {
            mkdir($this->tmp_path.'/system', 0755, true);
        }
        shell_exec('top -n 1 -b > '.$this->tmp_path.'/system/top-output');
        usleep(25000);
        $result = trim(file_get_contents($this->tmp_path.'/system/top-output'));

        if ($parse) {
            $lines = explode(PHP_EOL, $result);

            // detect start by empty line space
            $start = 0;
            foreach ($lines as $no => $line) {
                if (trim($line) == '') {
                    $start = $no;
                    break;
                }
            }
            // filter out header lines
            foreach (range(0, $start) as $key) {
                unset($lines[$key]);
            }

            //remove column line
            unset($lines[$start+1]);

            // define columns
            $columns = [
                'PID',
                'USER',
                'PR',
                'NI',
                'VIRT',
                'RES',
                'SHR',
                'S',
                '%CPU',
                '%MEM',
                'TIME+',
                'COMMAND'
            ];

            // match rows for columns and set into return
            $result = [];
            foreach ($lines as $row => $line) {
                $column = array_values(array_filter(explode(' ', $line), 'strlen'));
                foreach ($columns as $col => $key) {
                    $result[$row][$key] = @$column[$col];
                }
            }
            $result = array_values($result);
        }
        return $result;
    }
529463
public function projectBranch($opts = ['format' => 'table', 'fields' => ''])
    {
        $result = $this->taskProjectBranch()
            ->run();

        if (!$result->wasSuccessful()) {
            $this->exitError("Failed to run command");
        }

        $data = $result->getData();
        return new PropertyList(['branch' => $data['data'][0]['message']]);
    }
842327
public function getTopCharacters(Request\Top\TopCharactersRequest $request): array
    {
        $crawler = $this->ghoutte->request('GET', $request->getPath());
        try {
            $parser = new Parser\Top\TopCharactersParser($crawler);

            return $parser->getTopCharacters();
        } catch (\Exception $e) {
            throw ParserException::fromRequest($request, $e);
        }
    }
257265
public function getProcessesInfo() : array {
        $processIds = [];
        $processes  = [];
        $data       = [];

        exec('pgrep php', $processIds);
        exec('ps ahxwwo pid:1,command:1 | grep php | grep -v grep | grep -v emacs', $processes);

        foreach($processes as $process) {
            $pid = explode(' ', trim($process), 2)[0];

            if( in_array($pid, $processIds) ) {
                $data[] = new ProcessInfo($process);
            }
        }

        return $data;
    }
1366025
public function getProcess()
    {
        $this->processBuilder->setArguments(array());

        foreach ($this->options as $option => $value) {
            if (!$value) {
                continue;
            }

            if (!in_array($option, static::$nonPrefixedOptions)) {
                $option = sprintf('--%s', $option);
            }

            $this->processBuilder->add($option);

            if (true !== $value) {
                $this->processBuilder->add($value);
            }
        }

        $this->processBuilder->add('-')->add($this->getOutput());

        $process = $this->processBuilder->getProcess();
        $process->setCommandLine(sprintf('echo "%s" | %s', addslashes($this->getInput()), $process->getCommandLine()));

        return $process;
    }
1116820
@Override
    protected List<ChecksumFile> getFilesToProcess()
    {
        final List<ChecksumFile> filesToProcess = new ArrayList<ChecksumFile>();
        for ( final FileSet fileSet : fileSets )
        {
            final DirectoryScanner scanner = new DirectoryScanner();
            final String fileSetDirectory = (new File( fileSet.getDirectory() ) ).getPath();

            scanner.setBasedir( fileSetDirectory );
            String[] includes;
            if ( fileSet.getIncludes() != null && !fileSet.getIncludes().isEmpty() )
            {
                final List<String> fileSetIncludes = fileSet.getIncludes();
                includes = fileSetIncludes.toArray( new String[fileSetIncludes.size()] );
            }
            else
            {
                includes = DEFAULT_INCLUDES;
            }
            scanner.setIncludes( includes );

            if ( fileSet.getExcludes() != null && !fileSet.getExcludes().isEmpty() )
            {
                final List<String> fileSetExcludes = fileSet.getExcludes();
                scanner.setExcludes( fileSetExcludes.toArray( new String[fileSetExcludes.size()] ) );
            }

            scanner.addDefaultExcludes();

            scanner.scan();

            for ( String filePath : scanner.getIncludedFiles() )
            {
                filesToProcess.add( new ChecksumFile( (new File( fileSetDirectory ) ).getPath(), new File( fileSetDirectory, filePath ), null, null ) );
            }
            }

        return filesToProcess;
    }
147733
protected function buildProcess()
    {
        if (!\count($this->arguments)) {
            throw new LogicException('You must add command arguments before the process can build.');
        }

        $process = new Process($this->arguments, $this->workingDirectory);

        $process->setCommandLine($process->getCommandLine());

        return $process;
    }
626512
public function restart()
    {
        $process = $this->getProcess([
            'restart',
            $this->name,
        ]);

        $process->run();

        if (!$process->isSuccessful()) {
            throw new CommandFailedException($process);
        }
    }
407449
public function main()
    {
        $message = $this->getMessage();
        if ($message === '') {
            throw new BuildException('"message" is a required parameter');
        }

        $user = $this->getUser();

        $clone = $this->getFactoryInstance('commit');
        $msg = sprintf("Commit: '%s'", $message);
        $this->log($msg, Project::MSG_INFO);
        $clone->setQuiet($this->getQuiet());
        $clone->setMessage($message);

        if (trim($user) === "") {
            throw new BuildException('"user" parameter can not be set to ""');
        }
        if ($user !== null) {
            $clone->setUser($user);
            $this->log("Commit: user = '$user'", Project::MSG_VERBOSE);
        }

        if ($this->repository === '') {
            $project = $this->getProject();
            $dir = $project->getProperty('application.startdir');
        } else {
            $dir = $this->repository;
        }
        $this->log('DIR:' . $dir, Project::MSG_INFO);
        $this->log('REPO: ' . $this->repository, Project::MSG_INFO);
        $cwd = getcwd();
        chdir($dir);

        try {
            $this->log("Executing: " . $clone->asString(), Project::MSG_INFO);
            $output = $clone->execute();
            if ($output !== '') {
                $this->log($output);
            }
        } catch (Exception $ex) {
            $msg = $ex->getMessage();
            $this->log("Exception: $msg", Project::MSG_INFO);
            $p = strpos($msg, 'hg returned:');
            if ($p !== false) {
                $msg = substr($msg, $p + 13);
            }
            chdir($cwd);
            throw new BuildException($msg);
        }
        chdir($cwd);
    }
534786
public function passThroughProcess(Process $process)
    {
        if ($this->output->isVeryVerbose()) {
            $this->output->writeln(sprintf('<bg=blue;fg=white;> RUN </> <fg=blue>%s</>', $process->getCommandLine()));
        }
        $process->run(function ($type, $buffer) {
            $this->output->write($buffer);
        });

        return $process;
    }
484605
private function getPipe()
    {
        if (!isset($this->pipe) || !isset($this->proc)) {
            $desc = [['pipe', 'r'], $this->stream, \fopen('php://stderr', 'w')];
            $this->proc = \proc_open($this->cmd, $desc, $pipes);

            if (!\is_resource($this->proc)) {
                throw new \RuntimeException('Error opening output stream');
            }

            $this->pipe = $pipes[0];
        }

        return $this->pipe;
    }
468788
private function buildProcess(string $process, string $fullServiceName) {
      $methods = array_flip(get_class_methods($fullServiceName));

      if (!array_key_exists(($process), $methods)) {

        throw new \Nuki\Exceptions\Base('No available process is found for the provided service');
      }
      
      return $process;
    }
1224062
public function getProcess(): Process
    {
        if (count($this->prefix) === 0 && count($this->arguments) === 0) {
            throw new MethodCallException('You must add arguments before calling getProcess()');
        }

        $arguments = array_merge($this->prefix, $this->arguments);
        $command = implode(' ', array_map('escapeshellarg', $arguments));

        if ($this->inheritEnv) {
            $env = array_replace($_SERVER, $this->environment);
        } else {
            $env = $this->environment;
        }

        $process = new Process(
            $command,
            $this->directory,
            $env,
            $this->input,
            $this->timeout,
            $this->stdout,
            $this->stderr
        );

        if ($this->outputDisabled) {
            $process->disableOutput();
        }

        return $process;
    }
297041
public function main()
    {
        if (null === $this->getRepository()) {
            throw new BuildException('"repository" is required parameter');
        }
        if (null === $this->getBranchname()) {
            throw new BuildException('"branchname" is required parameter');
        }

        $client = $this->getGitClient(false, $this->getRepository());
        $command = $client->getCommand('checkout');
        $command
            ->setOption('no-track', $this->isNoTrack())
            ->setOption('q', $this->isQuiet())
            ->setOption('force', $this->isForce())
            ->setOption('b', $this->isCreate())
            ->setOption('B', $this->isForceCreate())
            ->setOption('m', $this->isMerge());
        if ($this->isNoTrack()) {
            $command->setOption('track', $this->isTrack());
        }

        $command->addArgument($this->getBranchname());

        if (null !== $this->getStartPoint()) {
            $command->addArgument($this->getStartPoint());
        }

        $this->log('git-checkout command: ' . $command->createCommandString(), Project::MSG_INFO);

        try {
            $output = $command->execute();
        } catch (Exception $e) {
            throw new BuildException('Task execution failed.', $e);
        }

        $this->log(
            sprintf('git-checkout: checkout "%s" repository', $this->getRepository()),
            Project::MSG_INFO
        );
        $this->log('git-checkout output: ' . str_replace('\'', '', trim($output)), Project::MSG_INFO);
    }
1197402
protected function shell($cmd, $passthru = false)
    {
        $out = [];
        $return = 0;

        if (true === $passthru) {
            passthru(sprintf('%s 2>&1', $cmd), $return);
            $out = null;
        } else {
            exec(sprintf('%s 2>&1', $cmd), $out, $return);
            $out = join(PHP_EOL, $out);
            if ($this->getOutput()->getVerbosity() >= OutputInterface::VERBOSITY_VERY_VERBOSE) {
                $this->getOutput()->writeln($out);
            }
        }

        if (0 < $return) {
            throw new \RuntimeException(sprintf("Error when executing '%s'", $cmd), 50);
        }

        return $out;
    }
1136869
public function actionStop($trys=3)
    {
        $pid = $this->getMasterPid();
        Console::stdout("stopping $pid ...");
        while( $trys>0 ){
            if(!posix_kill($pid, SIGTERM)) {
                Console::stdout(" success.\r\n");
                exit(0);
            }
            
            $trys--;
            usleep(300000);
        }
        
        if($trys <=0){
            Console::error(" failed !\r\n");
        }
        exit(5);
    }