#git (1)

push까지 해버린 git commit 원복하는 방법


공동 repository에 push까지 해버린 commit을 되돌리는 방법은 경우에 따라 두 가지가 있는 것 같습니다.
커밋 개수가 한 두 건 일 때 git revert를 사용하는 방법이 있고, 커밋 개수가 너무 많아 하나씩 revert하기 힘든 경우가 있을 수 있습니다. 여기서는 git revert를 사용하지 않고 원복하는 방법을 알려드립니다.

1. commit log 확인

2. reset (원하는 시점으로 되돌아가기)

3. revert (특정 시점 이후의 변경사항 되돌리기)

4. force push (되돌린 내용을 공동 repo에 반영하기)


1. commit history에서 원복 시점의 커밋 확인

keichee$ git log -5 --pretty=format:"%h - %an, %ar : %s"

148444a6a - keichee, 4 days ago : Merge branch 'dev-sentry' into stage

eebdd9202 - keichee, 4 days ago : dev 환경 로깅 sentry 연동

1c74ca53e - john, 5 days ago : Merge pull request #1238 in test/repo from release/200202 to stage

6544cd10a - john, 5 days ago : Merge pull request #1237 in test/repo from feature/200202 to release

754046d47 - tom, 5 days ago : test commit 1


git log 명령어를 이용해서 commit 히스토리를 확인 할 수 있습니다.

이때 옵션으로 -5 를 입력해주면 최신순으로 5개 까지만 조회를 할 수 있고 

옵션을 주지 않으면 페이징 처리되어 계속 조회할 수 있습니다.

뒤에 pretty 옵션을 주면 위 결과처럼 조회가 되는데 pretty 옵션을 안주면 commit 하나의 내용이 총 6줄에 걸쳐서 표시가 되기 때문에 한눈에 보기가 힘듧니다.


2. 원하는 시점으로 Reset 

위에서 조회한 5개의 커밋들 중에 john이 5일 전에 커밋한 내용까지만 적용하고 keichee가 커밋한 내용을 revert시켜보겠습니다.

commit it가 1c74ca53e인 것을 확인하고 아래와 같이 reset 합니다.

keichee$ git reset 1c74ca53e

Unstaged changes after reset:

M       src/main/resources/logback-spring.xml


3. Revert

reset을 하면 1c74ca53e 커밋까지 완료된 상태로 되돌아 갑니다.

그리고 그 이후의 커밋에 대해서는 수정상태로 변경됩니다.

이때 git status로 확인을 해보면 아래와 같이 확인 할 수 있습니다.

keichee$ git status

On branch test-revert

Changes not staged for commit:

  (use "git add <file>..." to update what will be committed)

  (use "git checkout -- <file>..." to discard changes in working directory)


        modified:   src/main/resources/logback-spring.xml

이제 이렇게 수정된 내용들에 대해서 원복해보겠습니다.

keichee$ git checkout -- src/main/resources/logback-spring.xml

파일들이 너무 많아 이렇게 하기가 불편하다면 아래와 같이 할 수도 있습니다.

# Revert changes to modified files.

git reset --hard


# Remove all untracked files and directories.

# '-f' is force, '-d' is remove directories.

git clean -fd

출처 : https://stackoverflow.com/questions/5807137/how-to-revert-uncommitted-changes-including-files-and-folders


4. Force push

keichee$ git push -f

Total 0 (delta 0), reused 0 (delta 0)

remote: 

remote: Create pull request for test-revert:

remote:   https://git.repository/compare/commits?sourceBranch=refs/heads/test-revert

remote: 

To https://git.repository

 + 61495b45b...1c74ca53e test-revert -> test-revert (forced update)



이상입니다.

오늘도 즐코딩하세요~