gpt4 book ai didi

php - 在 PHP 上实时执行 git 命令

转载 作者:太空宇宙 更新时间:2023-11-04 11:49:41 25 4
gpt4 key购买 nike

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

克隆到项目名称 ?并且不显示下一条消息,例如

远程:枚举对象

远程:计数对象

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

git SS

这是我执行实时命令的函数

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');

谁能帮帮我?

最佳答案

您需要使用--progress 开关。

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

Progress status is reported on the standard error stream by default when it is attached to a terminal, unless -q is specified. This flag forces progress status even if the standard error stream is not directed to a terminal.

你应该像这样运行 git clone:

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

问题是:

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

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

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

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

关于php - 在 PHP 上实时执行 git 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56415703/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com