git 提交解決本地與遠程沖突


首先介紹一下背景。

如果有一個工程A,開始時test.txt 的內容如下

chenfool
hello world

作者通過 git clone 的方式,將這個項目download 到本地。

 

此時,作者手賤,直接在web 端,將test.txt 修改成為

chenfool
123
hello world

 

過了一段時間后,作者突然想起要修改本地的test.txt文件,在本地 clone 版本中,對test.txt 文件修改如下

chenfool
456
hello world

然后想將本地的test.txt 提交到遠程中,在push 時,會報大概如下的錯

hint: Updates were rejected because the remote contains work that you do
hint: not have locally. This is usually caused by another repository pushing
hint: to the same ref. You may want to first integrate the remote changes
hint: (e.g., 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.

 

執行 git status 查看,它就告訴你有一個commit 還沒有提交呢

On branch master
Your branch is ahead of 'origin/master' by 1 commit.
  (use "git push" to publish your local commits)

nothing to commit, working tree clean

 

此時,你可以嘗試一下使用 git pull ,將遠程代碼和本地代碼強行 merge 一下,如果能夠正常merge ,則是其他問題導致了錯誤,如果是沖突,就可以往下看了

執行 git pull 時,會報告錯誤 (有一些敏感信息被作者抹除了,可能和讀者真實執行有出入)

remote: Counting objects: 6, done.
remote: Compressing objects: 100% (5/5), done.
remote: Total 6 (delta 4), reused 0 (delta 0)
Unpacking objects: 100% (6/6), done.
From http://192.168.1.1/chenfool/
   4c7cd0c..5b8e16f  master     -> origin/master
Auto-merging test.txt
CONFLICT (content): Merge conflict in test.txt
Automatic merge failed; fix conflicts and then commit the result.

 

此時再執行 git status 命令,就可以看到真正的錯誤了

On branch master
Your branch and 'origin/master' have diverged,
and have 1 and 1 different commits each, respectively.
  (use "git pull" to merge the remote branch into yours)

You have unmerged paths.
  (fix conflicts and run "git commit")
  (use "git merge --abort" to abort the merge)

Unmerged paths:
  (use "git add <file>..." to mark resolution)

    both modified:   test.txt

打印的信息說得很明白,就是test.txt 這個文件,被多個人修改了,並且無法實現智能合並,需要人工干預了。

 

我們可以怎么做呢?解決的方式簡單粗暴,就是對比local 和remote 兩端的差異,然后選擇自己想要的內容,然后提交。

這里作者交代一下,因為作者的環境為mac,所以比對文件差異使用 Kaleidoscope 可視化工具。

Kaleidoscope 軟件讀者可以在這里了解更多集成的信息。

 

使用 git mergetool test.txt 命令,git 會自動調用 Kaleidoscope 軟件,讓讀者自由對比其中差異,以及修改自己想要提交的內容。

讀者可以發現,左手邊是local 文件的內容,右手邊是remote 文件的內容,而中間則是讓讀者自由編輯的部分。整個界面非常的友好。

讀者在中間部分正確修改好內容后,直接保存退出。

 

此時,在local 本地,會發現test.txt 文件變成了兩個,一個名為 test.txt ,一個名為 test.txt.orig。

test.txt 是修改后的文件,也是我們即將要提交的文件。

test.txt.orig 文件則是記錄了原來 local 和 remote 文件差異的文件。實際上到這個步驟,test.txt.orig 已經沒有啥用處,讀者們可以自行將其刪除。

 

開始提交了,讀者會發現實際上就是重新add 和commit 了一次,但是它確實能夠解決提交沖突的問題。

git add test.txt
git commit -m "for test"
git push origin master

 

  • 題外話

如果讀者只是非常渴望可以將本地的文件覆蓋 remote 的文件,可以通過一下方式來進行操作。

在 git push origin master 失敗后,首先備份一下本地即將提交的文件,未來要用。

然后 git pull ,將remote 的內容download 本地。

此時,用戶就可以通過 git status 了解是哪些文件發生了沖突。

然后再將剛才備份的文件直接覆蓋本地剛剛 git pull 后的文件。

再依次執行 git add 、 git commit 和 git push origin master,就可以簡單粗暴地將 local 文件覆蓋 remote 文件。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM