From 09b2675c65e767c032dca99388090546a4841b2c Mon Sep 17 00:00:00 2001 From: engigu Date: Wed, 6 May 2026 23:55:59 +0800 Subject: [PATCH] chore: update repo pull way --- cmd/reposync/reposync.go | 31 +++++++++++++++++++++++++++---- 1 file changed, 27 insertions(+), 4 deletions(-) diff --git a/cmd/reposync/reposync.go b/cmd/reposync/reposync.go index a2f73e3..688c5d5 100644 --- a/cmd/reposync/reposync.go +++ b/cmd/reposync/reposync.go @@ -172,11 +172,23 @@ func syncGit(cfg Config) { defer restore() if pathExists(gitDir) { - fmt.Println("检测到已存在仓库,执行 git pull") - if cfg.Branch != "" { - runCmd([]string{"git", "checkout", cfg.Branch}, dest, env) + fmt.Println("检测到已存在仓库,正在更新...") + runCmd([]string{"git", "fetch", "--all"}, dest, env) + + targetBranch := cfg.Branch + if targetBranch != "" { + // 如果切换了分支,或者当前分支偏离,强制切换并对齐远程 + runCmd([]string{"git", "checkout", "-B", targetBranch, "origin/" + targetBranch}, dest, env) + } else { + targetBranch = getCurrentBranch(dest, env) + } + + if targetBranch != "" { + fmt.Printf("执行强制同步 (reset --hard origin/%s)\n", targetBranch) + runCmd([]string{"git", "reset", "--hard", "origin/" + targetBranch}, dest, env) + } else { + runCmd([]string{"git", "pull", "--rebase"}, dest, env) } - runCmd([]string{"git", "pull"}, dest, env) } else { fmt.Println("执行 git clone") parentDir := filepath.Dir(dest) @@ -478,6 +490,17 @@ func isDirEmpty(path string) bool { return err == io.EOF } +func getCurrentBranch(dir string, env []string) string { + cmd := exec.Command("git", "rev-parse", "--abbrev-ref", "HEAD") + cmd.Dir = dir + cmd.Env = env + out, err := cmd.Output() + if err != nil { + return "" + } + return strings.TrimSpace(string(out)) +} + // preserve moves specified paths to a temporary location and returns a function to restore them func preserve(baseDir string, paths string) func() { if paths == "" || !pathExists(baseDir) {