Friday, April 1, 2016

วิธีแก้ Git Conflict เวลา commit file เดียวกัน

Git Conflict

โดยปกติแล้ว git merge จะรวมโค๊ดให้เราเองอัตโนมัติ แต่ก็จะมีข้อยกเว้นเมื่อ แก้ไขไฟล์เดียวๆกัน ลองนึกถึงกรณีที่เราและเพื่อนร่วมทีม แก้ไขไฟล์เดียวกัน Git จะเกิดการ conflict เมื่อเราจะ merge โค๊ด โดยไม่รู้ว่าจะใช้โค๊ดของเราหรือของเพื่อน วิธีแก้ก็คือ ทำการ edit แล้ว commit ไปใหม่นั่นเอง
ตัวอย่างคร่าวๆ ของไฟล์ที่เกิด conflict
git pull

Auto-merging README.md
CONFLICT (content): Merge conflict in README.md
Automatic merge failed; fix conflicts and then commit the result.
และตัวอย่างไฟล์
git101
---

Sample git repo

<<<<<<< HEAD
edit on sublime text.
=======
last edit on browser via github.com
>>>>>>> origin/master
format ของไฟล์ conflict จะถูกขั้นด้วย <<<<<<< HEAD จนถึง ======= สำหรับโค๊ดส่วนที่เราแก้ไข และ =======ถึง >>>>>>>> branch_name ส่วนที่เป็นโค๊ดของคนอื่นๆ/branch อื่น
วิธีแก้ก็แค่ลบพวกโค๊ดส่วนเกินออก แล้วแก้ไขใหม่ให้เรียบร้อย จากนั้นลองเช็คสถานะ จะขึ้นประมาณนี้
git status

Your branch and 'origin/master' have diverged,
and have 1 and 1 different commit each, respectively.
  (use "git pull" to merge the remote branch into yours)
You have unmerged paths.
  (fix conflicts and run "git commit")

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

    both modified:   README.md

no changes added to commit (use "git add" and/or "git commit -a")
ก็ commit และ push ได้ปกติแล้วครับ
git add README.md
git commit -m "fixed conflict on README.md"
git push
เป็นอันเรียบร้อย
ที่มา  http://devahoy.com/posts/introduction-to-git-and-github/#step6

No comments:

Post a Comment