执行命令

@param  array $cmds

@return array
340021
public function runCommand(...$cmds): array
    {
        $this->logger->notice('执行服务命令: ' . implode(' ', $cmds));

        $command = array_merge([
                Config::get('run_command'),
                'server:run'
            ], $cmds);


        $process = new Process(function ($worker) use ($command) {
            $worker->exec(Config::get('php_bin', 'php'), $command);
        }, true);

        $process->start();

        $this->logger->debug(
            '命令: ' . Config::get('php_bin', 'php') . implode(' ', $command)
        );

        $recv = Process::wait();

        $this->logger->debug('结果: ' . json_encode($recv));

        return $recv;
    }
1216387
public function findCommand(array $commands, $commandName) {
        $matches = [];

        foreach ($commands as $command) {
            if ($this->compareCommandName($command->getName(), $commandName)) {
                $matches[] = $command;
            }
        }

        if (count($matches) === 1) {
            return $matches[0];
        } else if (count($matches) === 0) {
            throw new CommandNotFoundException(s(
                'Could not find a command that matches "%s".',
                $commandName
            ));
        } else {
            $qualifiedCommandNames = '';

            foreach ($matches as $command) {
                $qualifiedCommandNames .= "\n" . $command->getName();
            }

            throw new AmbiguousCommandException(s(
                'Please be more precise with the command name. ' .
                'There are several commands that qualify for "%s": %s',
                $commandName,
                $qualifiedCommandNames
            ));
        }
    }
440073
public function commandSubcommandStates(CommandInterface $cmd)
    {
        $args = [];
        $cmds = $this->visibleCommands($cmd->getCommands());
        foreach ($cmds as $c) {
            $args[] = sprintf("'%s:->%s'", $c->name(), $c->name()); // generate argument states
        }

        return $args;
    }
188320
protected function extractFromCommand($cmd, $filter = null) {
		$output = [];
		$exitCode = null;
		$this->begin();
		exec("$cmd", $output, $exitCode);
		$this->end();
		if(/*$exitCode !== 0 || */!is_array($output)) {
			throw new ShellException("Command $cmd failed.");
		}
		/** @var string $filter */
		if($filter !== null) {
			$newArray = [];
			foreach($output as $line) {
				$value = $filter($line);
				if($value === false) {
					continue;
				}
				$newArray[] = $value;
			}
			$output = $newArray;
		}
		if(!isset($output[0])) // empty array
		{
			return null;
		}
		return $output;
	}
31807
public static function detectCmdLocationInPaths($cmd, array $paths) : string
    {
        foreach ($paths as $path) {
            $command = $path . DIRECTORY_SEPARATOR . $cmd;
            $bin     = self::getExecutable($command);
            if (null !== $bin) {
                return $bin;
            }
        }
        return '';
    }
1120392
private function send_req($cmd, $params) {
        $req = [$cmd];
        foreach ($params as $p) {
            if (is_array($p)) {
                $req = array_merge($req, $p);
            } else {
                $req[] = $p;
            }
        }

        return $this->send($req);
    }
1142906
public static function run($args=null){
      if (PHP_SAPI != 'cli') return false;
      if($args) {
        $_args = $args;
        static::$file = basename(isset($_SERVER['PHP_SELF'])?$_SERVER['PHP_SELF']:__FILE__);
       } else {
        $_args = $_SERVER['argv'];
        static::$file = basename(array_shift($_args));
      }
      foreach($_args as $e) if(strpos($e,'-')===0) {
        $h = explode('=',$e);
        static::$options[ltrim(current($h),'-')] = isset($h[1])?$h[1]:true;
      } else {
        static::$arguments[] = $e;
      }

      if(isset(static::$arguments[0])){
        $command = array_shift(static::$arguments);
        if (empty(static::$commands[$command]))
          return static::triggerError("Unknown command [".$command."].");
        $cmd = static::$commands[$command];
        $pars_vector = [];
        foreach ($cmd[0] as $_idx => $segment) {
          if ($segment[0]==':'){
            // Extract paramenter
            if (isset(static::$arguments[$_idx])){
               $pars_vector[] = static::$arguments[$_idx];
            } else return static::triggerError("Command [".$command."] needs more parameters");
          } else {
            // Match command
            if (empty(static::$arguments[$_idx]) || $segment!=static::$arguments[$_idx])
              return static::triggerError("Command [".$command."] is incomplete.");
          }
        }
        $returns = call_user_func_array($cmd[1], $pars_vector);
        echo is_scalar($returns) ? "$returns" : json_encode($returns, JSON_PRETTY_PRINT);
        return true;
      } else {
        static::help();
        return false;
      }
    }
29784
protected function formatRunCommand(array $commands)
    {
        $last = end($commands);

        return 'RUN ' . implode("\r\n  && ", array_map(
            function ($value) use ($last) {
                return $last !== $value ? "{$value} \\" : $value;
            },
            $commands
        ));
    }
666237
public function mustRun($cmd, $error = null)
    {
        return $this->helper->mustRun($this->output, $cmd, $error);
    }
886496
private function ps($service) {
        $rtn = $this->sendCommand('ps', ['service' => $service]);
        if ($rtn) {
            $this->output('monitor');
            $pcnt = count($rtn['ps']);
            $this->output(($pcnt ? '├── ' : '└── ') . $this->color->str($rtn['ssid'], 'green'));
            foreach ($rtn['ps'] as $s => $ids) {
                $pcnt--;
                if ($ids) {
                    $this->output(($pcnt ? '├── ' : '└── ') . $s);
                    $pids = array_keys($ids);
                    $cnt  = count($pids);
                    for ($i = 0; $i < $cnt - 1; $i++) {
                        $this->output(($pcnt ? '│   ├── ' : '    ├── ') . $pids[ $i ]);
                    }
                    $this->output(($pcnt ? '│   └── ' : '    └── ') . $pids[ $cnt - 1 ]);
                }
            }
        }
    }
1179050
public static Process exec(String... cmds) {
		if (ArrayUtil.isEmpty(cmds)) {
			throw new NullPointerException("Command is empty !");
		}

		// 单条命令的情况
		if (1 == cmds.length) {
			final String cmd = cmds[0];
			if (StrUtil.isBlank(cmd)) {
				throw new NullPointerException("Command is empty !");
			}
			cmds = StrUtil.splitToArray(cmd, StrUtil.C_SPACE);
		}

		Process process;
		try {
			process = new ProcessBuilder(cmds).redirectErrorStream(true).start();
		} catch (IOException e) {
			throw new IORuntimeException(e);
		}
		return process;
	}
847512
public function run($cmd, array $args)
    {
        if (!isset($this->commands[$cmd])) {
            $this->error(sprintf('command %s not exists', $cmd));
        }
        $response = new Response();
        $driverId = isset($args['target']) ? $this->getDriverId($args['target']) : '';
        $driverId = !$driverId && isset($args['targets']) ? $this->getDriverId(current($args['targets'])) : $driverId;
        $interface = $this->getInterfaceByCmd($cmd);
        /*
         * @var string          $name
         * @var DriverInterface $driver
         */
        $data = null;
        foreach ($this->driverList as $name => $driver) {
            if (!$driverId || $driverId == $name) {
                if ($driver instanceof $interface) {
                    if ($driver->mount()) {
                        $data = $this->runCmd($driver, $cmd, $args, $response);
                    }
                    $driver->unmount();
                } else {
                    $this->error(sprintf('command "%s" not supported, please use interface "%s"', $cmd, $interface));
                }
                $this->addDisabledCommand($driver);
                $response->setOptions($driver->getOptions());
            }

            $response->addFile($driver->getRootFileInfo());
        }
        if (!empty($args['init'])) {
            $response->setApi(DriverInterface::VERSION);
        }

        return $data ?: $response;
    }
592998
public function run(array $options = []) {
        if (!CLI)
            return FrontController::processRequest($options);

        if (sizeof($this->commands) > 1)
            echoPre('At the moment multi-level commands are not supported.');

        /** @var Command|null $cmd */
        $cmd = first($this->commands);
        return $cmd ? $cmd->run() : 0;
    }
679908
private function cmdClone($args)
    {
        $cmd = new CloneCommand($this->cwd);

        return $cmd->run(array_slice($args, 1));
    }
309506
private function cmdCheck($args)
    {
        $cmd = new CheckCommand($this->cwd);

        return $cmd->run(array_slice($args, 1));
    }
776922
protected function invokeCommands(array $commands) {
    foreach ($commands as $key => $value) {
      if (is_numeric($key)) {
        $command = $value;
        $args = [];
      }
      else {
        $command = $key;
        $args = $value;
      }
      $this->invokeCommand($command, $args);
    }
  }
422452
public static StringBuffer runCommand(String[] cmd) {
    StringBuffer retval = new StringBuffer(MAX_OUTPUT_LENGTH);
    Process p;
    try {
      p = Runtime.getRuntime().exec(cmd);
      InputStream tmp = p.getInputStream();
      p.waitFor();
      int c;
      while ((c = tmp.read()) != -1)
        retval.append((char) c);
    } catch (IOException e) {
      e.printStackTrace();
    } catch (InterruptedException e) {
      e.printStackTrace();
    }

    return retval;
  }