From 1a31652751a6320a22a86ab2ae512cbbfd6743fe Mon Sep 17 00:00:00 2001 From: lixiangwuxian Date: Mon, 5 May 2025 02:45:30 +0800 Subject: [PATCH] =?UTF-8?q?refactor:=20=E4=BC=98=E5=8C=96=20GitPull=20?= =?UTF-8?q?=E5=87=BD=E6=95=B0=EF=BC=8C=E7=A7=BB=E9=99=A4=E5=A4=9A=E4=BD=99?= =?UTF-8?q?=E7=9A=84=E6=8D=A2=E8=A1=8C=E7=AC=A6=E5=92=8C=E7=A9=BA=E6=A0=BC?= =?UTF-8?q?=E5=A4=84=E7=90=86=EF=BC=8C=E5=A2=9E=E5=BC=BA=E4=BB=A3=E7=A0=81?= =?UTF-8?q?=E5=8F=AF=E8=AF=BB=E6=80=A7=EF=BC=8C=E5=B9=B6=E6=B7=BB=E5=8A=A0?= =?UTF-8?q?=E8=BF=9C=E7=A8=8B=E5=88=86=E6=94=AF=E5=AD=98=E5=9C=A8=E6=80=A7?= =?UTF-8?q?=E6=A3=80=E6=9F=A5=E9=80=BB=E8=BE=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- util/automatic.go | 26 +++++++++++++++----------- 1 file changed, 15 insertions(+), 11 deletions(-) diff --git a/util/automatic.go b/util/automatic.go index 0a4b6ba..2b3b343 100644 --- a/util/automatic.go +++ b/util/automatic.go @@ -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 }