Git으로 작업하다 보면 어떤 이유로든 커밋 히스토리를 수정해야 할 때가 있습니다. 가장 최근 한 개의 커밋은 commit에 --amend 플래그를 붙이면 되고, 더 예전의 커밋을 수정하려면 rebase 명령을 이용하여 수정할 수 있습니다. rebase는 사용자가 선택한 과거부터 HEAD까지의 커밋을 순서대로 다시 커밋하는 역할을 합니다. 따라서 rebase를 이용해 과거의 커밋 메시지를 수정하거나, 커밋의 순서를 바꾸거나, 여러 개의 커밋을 하나로 합칠 수 있습니다. 단, 과거부터 HEAD 범위에만 적용 가능하며, 7개 전 커밋부터 3개 전 커밋과 같은 형태의 rebase는 불가능합니다.

$ git rebase -i HEAD~3

마지막 3개의 커밋을 수정하게 됩니다. 이를 실행하면 텍스트 편집기가 열리고, 그 안에는 수정하려는 커밋의 목록이 펼쳐집니다.

edit

pick f7f3f6d changed my name a bit
pick 310154e updated README formatting and added blame
pick a5f4a0d added cat-file

# Rebase 710f0f8..a5f4a0d onto 710f0f8
#
# Commands:
#  p, pick = use commit
#  r, reword = use commit, but edit the commit message
#  e, edit = use commit, but stop for amending
#  s, squash = use commit, but meld into previous commit
#  f, fixup = like "squash", but discard this commit's log message
#  x, exec = run command (the rest of the line) using shell
#
# These lines can be re-ordered; they are executed from top to bottom.
#
# If you remove a line here THAT COMMIT WILL BE LOST.
#
# However, if you remove everything, the rebase will be aborted.
#
# Note that empty commits are commented out

특정 커밋에서 실행을 멈추게 하려면 스크립트를 수정해야 합니다. pickedit으로 수정하면 그 커밋에서 멈추게 됩니다. 가장 오래된 커밋인 f7f3f6d의 메시지를 수정하려면, 아래와 같이 편집하면 됩니다.

edit f7f3f6d changed my name a bit
pick 310154e updated README formatting and added blame
pick a5f4a0d added cat-file

이 상태에서 저장하고 편집기를 종료(:wq)하면 Git은 목록에 있는 커밋 중에서 가장 오래된 커밋으로 이동하고, 커밋을 순서대로 다시 수행하던 도중 edit을 만나 아래와 같은 메시지를 보여줍니다.

$ git rebase -i HEAD~3
Stopped at 7482e0d... updated the gemspec to hopefully work better
You can amend the commit now, with

       git commit --amend

Once you’re satisfied with your changes, run

       git rebase --continue

뭘 해야 하는지 알려줍니다. git commit --amend를 실행해 커밋 메시지를 수정하고, git rebase --continue를 실행하면 됩니다. 그럼 rebase가 해당 커밋을 적용한 후 다음 커밋으로 이동합니다.

squash

rebase를 이용해 커밋을 합칠 수 있습니다. squash라는 기능을 이용하며, rebase를 실행하면 나오는 가이드에 아래와 같이 squash에 대한 도움말이 적혀 있습니다.

s, squash = use commit, but meld into previous commit

해당 커밋과 바로 이전 커밋을 합친다고 합니다. 3개의 커밋을 하나로 합치려면 스크립트를 아래와 같이 수정합니다.

pick f7f3f6d changed my name a bit
squash 310154e updated README formatting and added blame
squash a5f4a0d added cat-file

저장하고 편집기를 종료(:wq)하면 3개의 커밋 메시지를 merge할 수 있도록 에디터를 즉시 실행해 줍니다.

# This is a combination of 3 commits.
# The first commit's message is:
changed my name a bit

# This is the 2nd commit message:

updated README formatting and added blame

# This is the 3rd commit message:

added cat-file

이 메시지를 저장하면 3개의 커밋이 모두 합쳐진 하나의 커밋만 남습니다. squash를 계속해서 진행한 후, force push하면 원하는 대로 커밋이 합쳐집니다.

'Git 레거시 글' 카테고리의 다른 글

[Git] Fork와 Pull request  (0) 2018.08.12
[Git] Cherry-pick  (0) 2018.05.30
[Git] 커밋 되돌리기  (0) 2018.05.28
[Git] 다시 커밋하기  (0) 2018.05.27
[Git] 파일 상태 Lifecycle 관리하기  (0) 2018.05.26

+ Recent posts