ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Git] error: failed to push some refs to ... / fatal: refusing to merge unrelated histories 에러가 났을 때 해결방법
    IT/개발 관련(DB, Git, Docker, Blockchain 등) 2019. 9. 1. 16:03

    상황 설명.

     

    1. 깃헙에 원격 저장소 생성 후 initial commit

     

    2. intellij에 프로젝트 생성 후 깃 로컬 저장소로 만듦. 커밋.

    $ git init

    $git commit -am "commit msg"

     

    3. 로컬에서 작업하고 원격으로 push하기 위해 원격 저장소 추가

    $ git remote add origin {내 원격 저장소 주소}

     

    4. 로컬에 원격 저장소 추가했으니까 pull / push 할 수 있겠지 룰루랄라~~ 하며 push했지만.. 실패.

    $ git push origin master
    To {내 원격 repository 주소}
     ! [rejected]        master -> master (non-fast-forward)
    error: failed to push some refs to {내 원격 repository 주소}
    hint: Updates were rejected because the tip of your current branch is behind
    hint: its remote counterpart. Integrate the remote changes (e.g.
    hint: 'git pull ...') before pushing again.
    hint: See the 'Note about fast-forwards' in 'git push --help' for details.

     

    5. 음? hint 보니까 pull 하라네? 그래서 해봤더니 또 실패.

    $git pull origin master
    From https://github.com/begoodat/springboot-jenkins-docker-slack
     * branch            master     -> FETCH_HEAD
    fatal: refusing to merge unrelated histories

     

    6. 해결책을 찾아보니, --allow-unrelated-histories 옵션을 사용하면 된다고 한다!!

    $ git pull origin master --allow-unrelated-histories

     

    7. 위와 같이 옵션을 함께 적어주니 원격의 브랜치와 로컬의 브랜치를 병합(merge)하는 commit을 한 뒤, pull이 되었다!
    $ git push origin master
    Enumerating objects: 13, done.
    Counting objects: 100% (13/13), done.
    Delta compression using up to 4 threads.
    Compressing objects: 100% (4/4), done.
    Writing objects: 100% (12/12), 880 bytes | 440.00 KiB/s, done.
    Total 12 (delta 0), reused 0 (delta 0)
    To {내 원격 repository 주소}
       3d8e943..f1467c8  master -> master

     

     

    8. 왜 이런 에러가 발생한건지 이유가 궁금해서 원인을 찾아보았다.

     

    나는 pull 명령어의 옵션으로 '--allow-unrelated-histories'를 사용했지만, 원래는 git merge 명령어의 옵션인듯 하다.

    pull 명령어와 함께 사용했을 땐, 원격과 로컬 브랜치의 merge commit이 먼저 일어나고 pull을 해준다.

     

    https://git-scm.com/docs/git-merge 참고해서 가져온 git merge manual

     

    --allow-unrelated-histories

    By default, git merge command refuses to merge histories that do not share a common ancestor. This option can be used to override this safety when merging histories of two projects that started their lives independently. As that is a very rare occasion, no configuration variable to enable this by default exists and will not be added.

     

    처음에 로컬에 프로젝트를 생성할 때, 원격의 저장소로부터 clone이나 pull로 받아왔으면 둘은 같은 베이스 히스토리를 가지고 시작한다. 

    하지만 원격과 로컬에 따로 저장소를 생성하고 커밋했기 때문에, 깃은 이 둘을 베이스 히스토리가 완전히 다른 프로젝트라고 인식을 한 것.

    이런 경우는 극히 드문 경우이기 때문에 위험할 수 있으므로 pull / push가 디폴트로 안됐던 것이다;

    위와 같은 옵션으로 깃에게 서로 다른 베이스 히스토리를 가졌지만 병합(merge)을 허용한다고 알려주는 것이다. 

     

Designed by Tistory.