refactor: 优化 GitPull 函数,移除多余的换行符和空格处理,增强代码可读性,并添加远程分支存在性检查逻辑

This commit is contained in:
lixiangwuxian 2025-05-05 02:45:30 +08:00
parent 2c4dc7f818
commit 1a31652751

View File

@ -4,6 +4,7 @@ import (
"errors"
"os"
"os/exec"
"strings"
)
// GitPull 拉取代码,丢弃本地修改
@ -28,7 +29,7 @@ func GitPull() error {
if err != nil {
return errors.New(string(branchOutput) + err.Error())
}
currentBranch := string(branchOutput)
currentBranch := strings.TrimSpace(string(branchOutput)) // 移除换行符和空格
// 获取远程仓库名通常是origin
remoteCmd := exec.Command("git", "remote")
@ -39,7 +40,7 @@ func GitPull() error {
}
remoteName := "origin" // 默认使用origin如果没有远程仓库则使用默认值
if len(remoteOutput) > 0 {
remoteName = string(remoteOutput)
remoteName = strings.TrimSpace(string(remoteOutput))
}
// 先获取所有远程分支最新信息
@ -50,21 +51,24 @@ func GitPull() error {
return errors.New(string(fetchOutput) + err.Error())
}
// 构建远程分支引用
remoteBranch := remoteName + "/" + currentBranch
// 检查远程分支是否存在
checkRemoteCmd := exec.Command("git", "rev-parse", "--verify", remoteBranch)
checkRemoteCmd.Dir = workDir
if checkRemoteErr := checkRemoteCmd.Run(); checkRemoteErr != nil {
// 远程分支不存在,只进行本地重置
return nil
}
// 强制重置当前分支到远程分支处理远程分支被force push的情况
forceResetCmd := exec.Command("git", "reset", "--hard", remoteName+"/"+currentBranch)
forceResetCmd := exec.Command("git", "reset", "--hard", remoteBranch)
forceResetCmd.Dir = workDir
forceResetOutput, err := forceResetCmd.CombinedOutput()
if err != nil {
return errors.New(string(forceResetOutput) + err.Error())
}
// 拉取最新代码
pullCmd := exec.Command("git", "pull")
pullCmd.Dir = workDir
pullOutput, err := pullCmd.CombinedOutput()
if err != nil {
return errors.New(string(pullOutput) + err.Error())
}
return nil
}