83 lines
2.4 KiB
PHP
83 lines
2.4 KiB
PHP
<?php
|
|
|
|
namespace App\Services\TG\Hook\Mod;
|
|
use App\Models\Article as ModelArticle;
|
|
|
|
class Git extends Base {
|
|
|
|
public function AddSshHostGithub()
|
|
{
|
|
|
|
// 定义要添加的主机
|
|
$host = 'github.com';
|
|
|
|
// 执行 ssh-keyscan 命令
|
|
$key = shell_exec("ssh-keyscan -t ed25519 $host");
|
|
|
|
// 检查是否成功获取到公钥
|
|
if ($key) {
|
|
// 获取 known_hosts 文件的路径
|
|
$knownHostsFile = '/root/.ssh/known_hosts';
|
|
|
|
// 检查 known_hosts 文件中是否已经存在该主机的公钥
|
|
if (strpos(file_get_contents($knownHostsFile), $host) === false) {
|
|
// 将公钥写入 known_hosts 文件
|
|
file_put_contents($knownHostsFile, $key, FILE_APPEND);
|
|
$sMsg = "公钥已成功添加到 $knownHostsFile\n";
|
|
} else {
|
|
$sMsg = "公钥已存在于 $knownHostsFile\n";
|
|
}
|
|
} else {
|
|
$sMsg = "无法获取 $host 的公钥\n";
|
|
}
|
|
|
|
$this->oTGHttp->sendToTG($sMsg);
|
|
|
|
$this->oHttp::response(200, 'ok');
|
|
|
|
}
|
|
|
|
// /Git#PullR 3
|
|
public function PullR($aParam)
|
|
{
|
|
|
|
$iId = $aParam['aArg'][1];
|
|
|
|
$aArticle = ModelArticle::find($iId);
|
|
|
|
$sProjectPath = env("BASE_DIR")."github/".$aArticle->user_name."-".$aArticle->project_name;
|
|
|
|
// 进入指定目录
|
|
if (!chdir($sProjectPath)) {
|
|
throw new \Exception("无法进入目录".$sProjectPath);
|
|
}
|
|
|
|
// 获取远程更新
|
|
$this->runCommand('git fetch origin');
|
|
|
|
// 硬重置到远程主分支
|
|
$this->runCommand('git reset --hard origin/main');
|
|
|
|
$this->oTGHttp->sendToTG("操作完成:已重置到远程主分支");
|
|
|
|
$this->oHttp::response(200, 'ok');
|
|
|
|
}
|
|
|
|
private function runCommand($command) {
|
|
$output = [];
|
|
$returnVar = 0;
|
|
exec($command, $output, $returnVar);
|
|
|
|
if ($returnVar !== 0) {
|
|
// 将输出数组转换为 JSON 格式
|
|
$jsonOutput = json_encode($output, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
|
|
|
|
$errorMessage = "命令失败: $command\n" . $jsonOutput . "\n";
|
|
|
|
throw new \Exception($errorMessage);
|
|
}
|
|
}
|
|
|
|
}
|