mirror of
https://github.com/runkids/skillshare.git
synced 2026-11-20 20:34:19 +00:00
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.
This commit is contained in:
+3
-11
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
+18
-3
@@ -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
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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<PullResponse | null>(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() {
|
||||
<AlertCircle size={16} />
|
||||
<span className="flex-1 whitespace-pre-wrap break-words">{runError}</span>
|
||||
{mergeFailed && <Button variant="secondary" size="sm" onClick={() => setConfirmForce(true)} disabled={writing}>{t('gitSync.pull.force.button')}</Button>}
|
||||
{pushRejected && <Button variant="secondary" size="sm" onClick={() => pull()} disabled={writing}>{t('gitSync.actions.pull')}</Button>}
|
||||
<button type="button" className="ss-ib !h-6 !w-6" aria-label={t('common.close')} onClick={() => setRunError('')}><X size={14} /></button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
Reference in New Issue
Block a user