From 51af1d30bade7fd512be3a66921daa7b06256221 Mon Sep 17 00:00:00 2001 From: Willie Date: Fri, 25 Sep 2026 02:18:00 +0800 Subject: [PATCH] fix(git): recover when two machines push to the same source repo Once both machines committed, the UI push was rejected and the follow-up pull failed with "Need to specify how to reconcile divergent branches", leaving no way out without a terminal. Pull now merges explicitly and aborts a conflicted merge so a later commit-all cannot push conflict markers; a rejected push returns push_rejected so the UI offers Pull. --- cmd/skillshare/pull.go | 14 ++------- internal/git/info.go | 21 +++++++++++-- internal/git/info_test.go | 48 +++++++++++++++++++++++++++++ internal/server/handler_git.go | 6 ++++ internal/server/handler_git_test.go | 19 ++++++++++++ ui/src/pages/GitSyncPage.tsx | 5 +++ 6 files changed, 99 insertions(+), 14 deletions(-) diff --git a/cmd/skillshare/pull.go b/cmd/skillshare/pull.go index d058cd749..60413a29f 100644 --- a/cmd/skillshare/pull.go +++ b/cmd/skillshare/pull.go @@ -3,7 +3,6 @@ package main import ( "errors" "fmt" - "os" "os/exec" "strings" "time" @@ -114,17 +113,10 @@ func pullFromRemote(cfg *config.Config, dryRun, force bool) error { } } else { spinner.Update("Running git pull...") - cmd = exec.Command("git", "pull") - cmd.Dir = source - if len(authEnv) > 0 { - cmd.Env = append(os.Environ(), authEnv...) - } - pullOutput, err := cmd.CombinedOutput() - if err != nil { + if _, err := gitops.PullWithEnv(source, authEnv); err != nil { spinner.Fail("git pull failed") - outStr := string(pullOutput) - fmt.Print(outStr) - hintGitRemoteError(outStr) + fmt.Println(err.Error()) + hintGitRemoteError(err.Error()) return fmt.Errorf("git pull failed: %w", err) } } diff --git a/internal/git/info.go b/internal/git/info.go index 4016c2c97..2ac928d1f 100644 --- a/internal/git/info.go +++ b/internal/git/info.go @@ -248,11 +248,17 @@ func PullWithProgress(repoPath string, extraEnv []string, onProgress func(string } info.BeforeHash = beforeHash - args := []string{"pull", "--quiet"} + // Merge explicitly: without pull.rebase/pull.ff configured, git refuses to + // reconcile a branch that both this machine and the remote moved. + args := []string{"pull", "--no-rebase", "--ff", "--no-edit", "--quiet"} if onProgress != nil { - args = []string{"pull", "--progress"} + args[len(args)-1] = "--progress" } if err := runGitWithProgress(repoPath, args, extraEnv, onProgress); err != nil { + // A conflicted merge would leave markers that a later commit-all picks up. + abort := exec.Command("git", "merge", "--abort") + abort.Dir = repoPath + abort.Run() // best-effort; fails harmlessly when no merge started return nil, err } @@ -508,11 +514,20 @@ func PushRemoteWithEnv(dir string, extraEnv []string) error { err := cmd.Run() if err != nil { - return install.WrapGitError(outBuf.String(), err, install.UsedTokenAuth(extraEnv)) + wrapped := install.WrapGitError(outBuf.String(), err, install.UsedTokenAuth(extraEnv)) + out := outBuf.String() + if strings.Contains(out, "[rejected]") && (strings.Contains(out, "fetch first") || strings.Contains(out, "non-fast-forward")) { + return fmt.Errorf("%w: %v", ErrPushRejected, wrapped) + } + return wrapped } return nil } +// ErrPushRejected reports that the remote has commits this repository lacks, +// so the push needs a pull first. +var ErrPushRejected = errors.New("remote has commits this machine does not have; pull first, then push") + // PushArgs returns the git push arguments for dir. The first push sets // upstream, targeting origin's default branch when it is named differently // from the local branch (origin is fetched to find it). Later pushes name a diff --git a/internal/git/info_test.go b/internal/git/info_test.go index ad72a1b93..e60d3c6c2 100644 --- a/internal/git/info_test.go +++ b/internal/git/info_test.go @@ -512,6 +512,54 @@ func TestPullWithProgress(t *testing.T) { } } +// divergeFromRemote commits remoteFile on another clone and pushes it, then +// commits localFile in repo without pushing, as two machines syncing would. +func divergeFromRemote(t *testing.T, remote, repo string, remoteFile, localFile [2]string) { + t.Helper() + other := cloneRepo(t, remote) + for _, c := range []struct { + dir string + file [2]string + }{{other, remoteFile}, {repo, localFile}} { + runGit(t, c.dir, "config", "user.email", "test@test.com") + runGit(t, c.dir, "config", "user.name", "test") + if err := os.WriteFile(filepath.Join(c.dir, c.file[0]), []byte(c.file[1]), 0644); err != nil { + t.Fatal(err) + } + runGit(t, c.dir, "add", "-A") + runGit(t, c.dir, "commit", "-m", "edit "+c.file[0]) + } + runGit(t, other, "push", "origin", "HEAD:main") +} + +func TestPullWithProgress_MergesDivergedHistory(t *testing.T) { + remote := createBareRemoteWithBranch(t, "main", map[string]string{"README.md": "# v1\n"}) + repo := cloneRepo(t, remote) + divergeFromRemote(t, remote, repo, [2]string{"remote.md", "r\n"}, [2]string{"local.md", "l\n"}) + + if _, err := PullWithProgress(repo, nil, nil); err != nil { + t.Fatalf("expected diverged pull to merge, got: %v", err) + } + for _, f := range []string{"remote.md", "local.md"} { + if _, err := os.Stat(filepath.Join(repo, f)); err != nil { + t.Errorf("expected %s after merge: %v", f, err) + } + } +} + +func TestPullWithProgress_ConflictLeavesRepoClean(t *testing.T) { + remote := createBareRemoteWithBranch(t, "main", map[string]string{"README.md": "# v1\n"}) + repo := cloneRepo(t, remote) + divergeFromRemote(t, remote, repo, [2]string{"README.md", "# remote\n"}, [2]string{"README.md", "# local\n"}) + + if _, err := PullWithProgress(repo, nil, nil); err == nil { + t.Fatal("expected a conflicting pull to fail") + } + if status := runGit(t, repo, "status", "--porcelain"); status != "" { + t.Fatalf("expected the merge to be aborted, got status:\n%s", status) + } +} + func TestForcePullWithProgress(t *testing.T) { remote := createBareRemoteWithBranch(t, "main", map[string]string{ "README.md": "# v1\n", diff --git a/internal/server/handler_git.go b/internal/server/handler_git.go index 88da4e001..da51c9515 100644 --- a/internal/server/handler_git.go +++ b/internal/server/handler_git.go @@ -514,6 +514,12 @@ func (s *Server) handlePush(w http.ResponseWriter, r *http.Request) { } if err := git.PushRemoteWithAuth(src); err != nil { + if errors.Is(err, git.ErrPushRejected) { + // The UI offers a pull for this code. + s.writeOpsLog("push", "error", start, args, err.Error()) + writeCodedError(w, http.StatusConflict, "push_rejected", err.Error(), nil) + return + } fail(err) return } diff --git a/internal/server/handler_git_test.go b/internal/server/handler_git_test.go index 1d5544991..2073b8748 100644 --- a/internal/server/handler_git_test.go +++ b/internal/server/handler_git_test.go @@ -436,6 +436,25 @@ func postPull(s *Server, body string) *httptest.ResponseRecorder { return rr } +func TestHandlePush_RemoteAheadReportsPushRejected(t *testing.T) { + s, src := newTestServer(t) + initServerGitRepo(t, src) + remote := filepath.Join(t.TempDir(), "remote.git") + testutil.RunGit(t, "", "init", "--bare", remote) + testutil.RunGit(t, src, "remote", "add", "origin", remote) + testutil.RunGit(t, src, "push", "-u", "origin", "HEAD") + pushRemoteFile(t, remote, "remote-skill/SKILL.md", "# remote\n") + addSkill(t, src, "local-skill") + + req := httptest.NewRequest(http.MethodPost, "/api/push", strings.NewReader(`{}`)) + rr := httptest.NewRecorder() + s.handler.ServeHTTP(rr, req) + + if rr.Code != http.StatusConflict || !strings.Contains(rr.Body.String(), `"push_rejected"`) { + t.Fatalf("expected 409 push_rejected, got %d: %s", rr.Code, rr.Body.String()) + } +} + func TestHandlePull_FirstPullConflictCanBeForced(t *testing.T) { s, src := newTestServer(t) initServerGitRepo(t, src) diff --git a/ui/src/pages/GitSyncPage.tsx b/ui/src/pages/GitSyncPage.tsx index 560cb8383..d5e641179 100644 --- a/ui/src/pages/GitSyncPage.tsx +++ b/ui/src/pages/GitSyncPage.tsx @@ -36,6 +36,8 @@ export default function GitSyncPage() { const [runError, setRunError] = useState(''); // A first pull whose history cannot merge; the error note then offers a force pull. const [mergeFailed, setMergeFailed] = useState(false); + // A push the remote rejected because it has newer commits; the error note then offers a pull. + const [pushRejected, setPushRejected] = useState(false); const [confirmForce, setConfirmForce] = useState(false); const [note, setNote] = useState(''); const [pulled, setPulled] = useState(null); @@ -50,12 +52,14 @@ export default function GitSyncPage() { setBusy(kind); setRunError(''); setMergeFailed(false); + setPushRejected(false); setNote(''); try { await work(); } catch (err) { setRunError((err as Error).message); setMergeFailed(err instanceof ApiError && err.code === 'merge_failed'); + setPushRejected(err instanceof ApiError && err.code === 'push_rejected'); } finally { setBusy(null); refresh(); @@ -165,6 +169,7 @@ export default function GitSyncPage() { {runError} {mergeFailed && } + {pushRejected && } )}