From cb8c83e09a907c12f7bc4aa676fbf530e41eb4b6 Mon Sep 17 00:00:00 2001 From: lixiangwuxian Date: Mon, 5 May 2025 02:14:26 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E5=9C=A8=20GitPull=20=E5=87=BD?= =?UTF-8?q?=E6=95=B0=E4=B8=AD=E6=B7=BB=E5=8A=A0=E5=BC=BA=E5=88=B6=E9=87=8D?= =?UTF-8?q?=E7=BD=AE=E6=9C=AC=E5=9C=B0=E4=BF=AE=E6=94=B9=E5=92=8C=E6=9B=B4?= =?UTF-8?q?=E6=96=B0=E8=BF=9C=E7=A8=8B=E5=88=86=E6=94=AF=E7=9A=84=E9=80=BB?= =?UTF-8?q?=E8=BE=91=EF=BC=8C=E7=A1=AE=E4=BF=9D=E6=9C=AC=E5=9C=B0=E4=BB=A3?= =?UTF-8?q?=E7=A0=81=E4=B8=8E=E8=BF=9C=E7=A8=8B=E4=BB=93=E5=BA=93=E4=BF=9D?= =?UTF-8?q?=E6=8C=81=E4=B8=80=E8=87=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- util/automatic.go | 48 +++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 44 insertions(+), 4 deletions(-) diff --git a/util/automatic.go b/util/automatic.go index 487b160..f227533 100644 --- a/util/automatic.go +++ b/util/automatic.go @@ -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 }