directorytree / git
使用PHP调用Git命令
v1.1.0
2024-03-15 16:59 UTC
Requires
- php: ^7.3|^8.0
- titasgailius/terminal: ^1.0
Requires (Dev)
- phpunit/phpunit: ^9.3|^10.0|^11.0
README
一个轻量级的PHP类,用于在您的Web服务器上调用git命令。
需求
- PHP >= 7.3
安装
composer require directorytree/git
在开始之前,您必须确保使用 chdir()
将PHP的工作目录更改为Git仓库的根目录
// The current working directory: chdir(getcwd()); // A specific directory: chdir('/usr/sbin/httpd');
此包还假定Git已经安装,并且可在您的系统 PATH
中使用,因此它可以全局调用。
用法
创建一个新的 Git
实例,并设置您要工作的远程
use DirectoryTree\Git\Git; $git = new Git($remote = 'origin');
可用命令
拉取
返回 true
或 false
。
$git = new Git(); $successful = $git->pull('master'); $successful = $git->pull('v1.0.1');
抓取
返回 true
或 false
。
$git = new Git(); $successful = $git->fetch();
重置
返回 true
或 false
。
注意:除非指定其他情况,否则默认总是执行
hard
重置。
$git = new Git(); $successful = $git->reset($commitOrTag = 'v0.0.9'); $successful = $git->reset($commitOrTag = 'v0.0.9', $mode = 'soft');
远程
获取
返回一个远程URL的 array
(失败时返回空数组)
$urls = $git->getRemote('origin');
获取所有
返回一个包含远程及其URL的 array
(失败时返回空数组)
$remotes = $git->getRemotes();
添加
返回 true
或 false
。
$success = $git->addRemote('origin', 'https://github.com/DirectoryTree/Git');
设置URL
返回 true
或 false
。
$successful = $git->setRemoteUrl('origin', 'https://github.com/DirectoryTree/Git');
删除
返回 true
或 false
。
$successful = $git->removeRemote('origin');
标签
获取所有
返回一个标签的 array
(失败时返回空数组)
$tags = $git->getTags();
获取当前
返回当前仓库的标签(失败时返回 false
)。
$currentTag = $git->getCurrentTag();
获取最新
返回当前仓库的最新版本(失败时返回 false
)。
$latestTag = $git->getLatestTag();
获取下一个
返回给定标签之后的当前仓库的标签(失败时返回 false
)。
$nextTag = $git->getNextTag('v1.0.0');
获取上一个
$previousTag = $git->getPreviousTag('v1.0.1');
提交
获取所有
返回一个提交的 array
(失败时返回空数组)
$commits = $git->getCommits(); $commits = $git->getCommits(['from' => '9d26e0']); $commits = $git->getCommits(['from' => '9d26e0', 'to' => '8bf0de6']);
获取之间
上述方法的简写。
$commits = $git->getCommitsBetween($from = '9d26e0', $to = '8bf0de6');
测试
Git使用PHP包 TitasGailius/terminal 来运行所有命令。这意味着您可以使用它的测试框架来执行所有Git命令
use DirectoryTree\Git\Git; class GitTest extends TestCase { public function test_git_pull() { Terminal::fake([ 'git pull {{ $remote }} {{ $commit }} --ff-only' => Terminal::response()->successful() ]); $this->assertTrue((new Git)->pull('v1.0.0')); } }