문제상황
원격저장소와 로컬 저장소 모두 생성하지 않은 상태에서 로컬에서 작업한 결과물을 깃허브에 올려놓으려고 했다.
- 로컬에서 git init을 통해 로컬 저장소를 만들어주고
- 깃허브에서 repository를 만들었다.
이제 이 로컬 저장소의 내용을 깃허브 원격저장소에 올려야 하는데
git push를 통해 올리려고 하니깐 두 저장소가 연결되어 있지 않아서 문제가 생겼다.
그래서 git remote add origin [깃허브 원격저장소 주소]
를 통해 로컬 저장소에 원격저장소를 연결 해주고
git push -u origin main:main
을 하니깐 아래와 같은 에러 메시지가 나왔다.
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.
대충 내 로컬 저장소가 원격저장소의 내용을 갖고 있지 않아서 push할 수 없다는 내용인데, 원격저장소의 내용을 로컬저장소로 끌어온 적이 없기 때문에 당연한 거였다. 그래서
git pull origin main
을 통해 원격저장소의 내용을 로컬저장소로 가져와서 merge하려고 했다.
(pull = fetch + merge)
- branch main -> FETCH_HEAD
hint: You have divergent branches and need to specify how to reconcile them.
hint: You can do so by running one of the following commands sometime before
hint: your next pull:
hint:
hint: git config pull.rebase false # merge
hint: git config pull.rebase true # rebase
hint: git config pull.ff only # fast-forward only
hint:
hint: You can replace "git config" with "git config --global" to set a default
hint: preference for all repositories. You can also pass --rebase, --no-rebase,
hint: or --ff-only on the command line to override the configured default per
hint: invocation.
fatal: Need to specify how to reconcile divergent branches.
라는 에러메시지가 나왔다. 로컬 저장소랑 원격 저장소가 공통된 내용이 없다는 건데, A가 로컬 저장소의 커밋
원격 저장소 커밋 이력: A-------->
로컬 저장소 커밋 이력: B-------->
이런 상태라서 둘이 공통된 게 아예 없어서 그렇다.
원래는 A---->B----> (원격 저장소 커밋 이력)
|
|-->C---> (로컬 저장소 커밋 이력)
이런 상태에서 B를 C로 pull하기 때문이다.
git pull origin main --rebase
을 해줬다.
이러면
원격 저장소 커밋 이력: A-------->
로컬 저장소 커밋 이력: B-------->
에서 A를 Base로 해서 A와 B의 차이를 merge한 C라는 커밋을 만든다.
A--------->C
그리고 로컬 저장소 커밋인 B를 삭제한다.
그러면 C가 로컬 저장소에 남는다. 이 C는 A에 Based on 하고 있기 때문에
git push origin local branch name:remote branch name
을 해주면 원격저장소에 커밋 C가 남는다.( A----->C)

git rebase의 내용: https://velog.io/@kwonh/Git-Rebase%EB%9E%80
git pull rebase: https://sanghye.tistory.com/43