feat: 在 GitPull 函数中添加强制重置本地修改和更新远程分支的逻辑,确保本地代码与远程仓库保持一致

This commit is contained in:
lixiangwuxian 2025-05-05 02:14:26 +08:00
parent 2eb0d5de20
commit cb8c83e09a

View File

@ -6,17 +6,57 @@ import (
"os/exec"
)
// GitPull 拉取代码,丢弃本地修改
func GitPull() error {
workDir, err := os.Getwd()
if err != nil {
return err
}
cmd := exec.Command("git", "pull")
cmd.Dir = workDir
output, err := cmd.CombinedOutput()
// 先强制重置本地更改
resetCmd := exec.Command("git", "reset", "--hard", "HEAD")
resetCmd.Dir = workDir
resetOutput, err := resetCmd.CombinedOutput()
if err != nil {
return errors.New(string(output) + err.Error())
return errors.New(string(resetOutput) + err.Error())
}
// 获取当前分支名
branchCmd := exec.Command("git", "rev-parse", "--abbrev-ref", "HEAD")
branchCmd.Dir = workDir
branchOutput, err := branchCmd.CombinedOutput()
if err != nil {
return errors.New(string(branchOutput) + err.Error())
}
currentBranch := string(branchOutput)
// 获取远程仓库名通常是origin
remoteCmd := exec.Command("git", "remote")
remoteCmd.Dir = workDir
remoteOutput, err := remoteCmd.CombinedOutput()
if err != nil {
return errors.New(string(remoteOutput) + err.Error())
}
remoteName := "origin" // 默认使用origin如果没有远程仓库则使用默认值
if len(remoteOutput) > 0 {
remoteName = string(remoteOutput)
}
// 先获取所有远程分支最新信息
fetchCmd := exec.Command("git", "fetch", "--all")
fetchCmd.Dir = workDir
fetchOutput, err := fetchCmd.CombinedOutput()
if err != nil {
return errors.New(string(fetchOutput) + err.Error())
}
// 强制重置当前分支到远程分支处理远程分支被force push的情况
forceResetCmd := exec.Command("git", "reset", "--hard", remoteName+"/"+currentBranch)
forceResetCmd.Dir = workDir
forceResetOutput, err := forceResetCmd.CombinedOutput()
if err != nil {
return errors.New(string(forceResetOutput) + err.Error())
}
return nil
}