【问题标题】:live execute git command on PHP在 PHP 上实时执行 git 命令
【发布时间】:2019-06-02 13:57:13
【问题描述】:

我一直在尝试用 PHP 克隆存储库,为什么输出只显示我

cloning into project-name ? 并且不向我显示下一条消息,例如

远程:枚举对象

远程:计数对象

接收对象 19% (591/3095), 5.06 MiB | 1024.00 KiB/s

这是我执行实时命令的功能

ob_implicit_flush(true);ob_end_flush();

function liveExecuteCommand($cmd)
{

    // while (@ ob_end_flush()); // end all output buffers if any

    $proc = popen("$cmd 2>&1 ; echo Exit status : $?", 'r');

    $live_output     = "";
    $complete_output = "";

    while (!feof($proc))
    {
        $live_output     = fread($proc, 4096);
        $complete_output = $complete_output . $live_output;
        echo "$live_output";
        // @ flush();
    }

    pclose($proc);

    // get exit status
    preg_match('/[0-9]+$/', $complete_output, $matches);

    // return exit status and intended output
    return array (
                    'exit_status'  => intval($matches[0]),
                    'output'       => str_replace("Exit status : " . $matches[0], '', $complete_output)
                 );
}

然后我调用函数:

liveExecuteCommand('git clone https://username:password@gitlab.com/example/project.git');

谁能帮帮我?

【问题讨论】:

    标签: php linux git console exec


    【解决方案1】:

    您需要使用--progress 开关。

    来自 git-clone(1) 手册页:

    默认情况下在标准错误流上报告进度状态 当它连接到终端时,除非指定了 -q。这面旗帜 即使标准错误流不是强制进度状态 定向到终端。

    你应该像这样运行git clone

    liveExecuteCommand('git clone --progress https://username:password@gitlab.com/example/project.git');
    

    问题是:

    1. 当您在 shell 中运行 git clone 时,您将连接到一个终端,这些缓冲流可以很好地工作(您可以看到计数器在移动,等等。就像一个交互式界面)
    2. 当您的代码通过 PHP 运行时,它没有附加到终端,因此这种输出将是完全垃圾(即:计数器更新的许多行,直到达到 100%,等等。)

    您可以使用一些技巧来解决这个问题。其中之一是安装expect,它还提供了unbuffer,可以解决这个问题。

    liveExecuteCommand('unbuffer git clone --progress https://username:password@gitlab.com/example/project.git');
    

    此外,如果您要打印到网页,请检查它是否有助于将您的 echo "$live_output" 包装为 echo nl2br($live_output)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-29
      相关资源
      最近更新 更多