服务器上有一个 Git 存储库,我和我的同事都可以从中推送和拉取。只要我们在提交之前拉动它就可以正常工作。
但是,如果他已经推送到主分支,同时我已经进行了本地提交,当我尝试拉取时,我会得到:
! [rejected] master -> master (non-fast-forward)
但我知道不应该有冲突。
我解决它的方法是拉入一个新的临时分支,然后将其合并到我的主人中,如下所示:
% git pull origin master:temp
From ssh://example.com/home/my/remote/repo
* [new branch] master -> temp
Already up-to-date.
% git merge temp
Already up-to-date.
% git push origin master:master
请注意,Git 表现得好像我什么都没做,但实际上我已经动摇它提交了。
最近我意识到,与其试图“说服”Git 我可以拉动。我可以假装我还没有提交git reset --soft HEAD^
,git stash
然后在此之上进行拉取和提交。
什么可能导致这种奇怪的挑剔行为?
我能够在我的本地机器上重现这个问题。这是我所做的:
首先,我创建了第一个“本地”存储库并添加了一个文件。
% cd
% mkdir local-1
% cd local-1/
% mkdir website
% cd website/
% git init
Initialized empty Git repository in /Users/jason/local-1/website/.git/
% touch file
% git add .
% git commit -m 'added file'
[master (root-commit) 6d4b322] added file
0 files changed, 0 insertions(+), 0 deletions(-)
create mode 100644 file
然后我创建了“远程”存储库。
% cd
% mkdir remote
% cd remote
% mkdir website.git
% cd website.git/
% git init --bare
Initialized empty Git repository in /Users/jason/remote/website.git/
然后我回到本地,创建一个 ref 并推送到远程。
% cd ~/local-1/website/
% git remote add web ~/remote/website.git
% git push web +master:refs/heads/master
Counting objects: 3, done.
Writing objects: 100% (3/3), 207 bytes, done.
Total 3 (delta 0), reused 0 (delta 0)
Unpacking objects: 100% (3/3), done.
To /Users/jason/remote/website.git
* [new branch] master -> master
之后,我将遥控器克隆到第二个本地。
% cd
% mkdir local-2
% cd local-2
% git clone ~/remote/website.git
Cloning into website...
done.
然后我从第二个本地创建了一个对远程的引用并推送(这是我认为我正在创建问题的地方)。
% cd website/
% git remote add web ~/remote/website.git
% git push web +master:refs/heads/master
Everything up-to-date
然后我对 local-2 进行了更改,提交并推送。
% touch another
% git add .
% git commit -m 'added another'
[master be91180] added another
0 files changed, 0 insertions(+), 0 deletions(-)
create mode 100644 another
% git push web
Counting objects: 3, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (2/2), done.
Writing objects: 100% (2/2), 238 bytes, done.
Total 2 (delta 0), reused 0 (delta 0)
Unpacking objects: 100% (2/2), done.
To /Users/jason/remote/website.git
6d4b322..be91180 master -> master
最后,我对 local-1 进行了不同的更改,提交并尝试推送。
% cd ~/local-1/website/
% touch something
% git add .
% git commit -m 'added something'
[master 3984529] added something
0 files changed, 0 insertions(+), 0 deletions(-)
create mode 100644 something
% git push web
To /Users/jason/remote/website.git
! [rejected] master -> master (non-fast-forward)
error: failed to push some refs to '/Users/jason/remote/website.git'
To prevent you from losing history, non-fast-forward updates were rejected
Merge the remote changes (e.g. 'git pull') before pushing again. See the
'Note about fast-forwards' section of 'git push --help' for details.
爆破!拉一下怎么样?
% git pull web master:master
From /Users/jason/remote/website
! [rejected] master -> master (non-fast-forward)
好的,那么问题就来了。我如何解决它?