Git 충돌 발생했을 때 해결하기

여러 사람들과 작업을 하다보면, 병합을 해야하는 상황이 많이 발생한다. 그때마다 해당 글을 보려고 정리

충돌하는 이유

간단하게 생각해서 여러 사람이 같은 파일을 수정한다고 치자, 병합을 해야 할 것이다. 그런데 깃은 어떤 파일을 유지해야 하는지 결정할 수 없다.

예시

해당 오류는 하나의 브랜치를 여러 사람들이 작업하는 경우 자주 볼 수 있는 오류이다. 원격 저장소(git)의 히스토리와 로컬 브랜치의 히스토리가 달라진 경우에 발생한다.

error: failed to push some refs to '<repository>'
hint: Updates were rejected because the remote contains work that you do not
hint: have locally. This is usually caused by another repository pushing to
hint: the same ref. If you want to integrate the remote changes, use
hint: 'git pull' before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.

해결하기

git pull origin <branch_name>
git push origin <branch_name>

이 경우에는 충돌이 발생해서 병합 커밋이 발생할 수 있음

충돌이 발생한 경우 메시지

PS D:\coding\merge-test2> git pull origin main
From <저장소>
 * branch            main       -> FETCH_HEAD
Auto-merging index.html
CONFLICT (content): Merge conflict in index.html
Automatic merge failed; fix conflicts and then commit the result.

충돌이 발생한 코드

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1>Hello World</h1>
<<<<<<< HEAD
    <p>충돌을 만들자</p>
=======
    <p>Lorem ipsum dolor sit, amet consectetur adipisicing elit. Id reprehenderit quo itaque eligendi eos blanditiis reiciendis deserunt ipsa, possimus excepturi! Natus, inventore culpa aut quos laborum illo ipsa velit provident.</p>
>>>>>>> 7e5531814ad3e6448f1f4967286781925c90b0ce
</body>
</html>

<<<<<<< HEAD 부분 → 현재 로컬 브랜치에 있는 내용

======= → 두 버전의 경계를 의미

>>>>>>> 7e5531814ad3e6448f1f4967286781925c90b0ce → 병합하려는 브랜치(다른 브랜치)의 해당 커밋 해시

이런 의미이고, 어떤 내용을 유지할지 결정한 후, 충돌 마커를 삭제하고 수정하면 된다.

  • 어떤 부분에서 충돌이 발생했는지 확인
  • 어떤 내용을 유지할지 결정
  • 충돌 부분을 수정하고 저장
  • Git에 변경 사항 알려주기 (git push)

Leave a Comment