고급 Git 가이드: Git Stash, 재설정, Rebase 등
게시 됨: 2022-03-11모든 개발자는 버전 제어에 대해 잘 알고 있어야 하며 Git은 소프트웨어 개발의 버전 제어에 대한 사실상의 표준이 되었습니다.
하지만 종종 개발자는 몇 가지 간단한 명령만 배우고 Git 기록의 힘과 Git이 사용자를 훨씬 더 효율적으로 만들기 위해 할 수 있는 다른 작업을 간과합니다. 예를 들어, 릴리스 관리는 git tag
를 사용하는 Git으로 매우 쉽습니다.
저는 Git 온라인(Github 포함)의 고급 과정을 수강하고 Github과 함께 초보자 Git 수업을 진행했습니다. 내가 좋아하는 Git 기능에 대한 기술 기사가 많지 않다는 것을 알았을 때 동료 개발자와 공유할 기회가 생겼습니다. 이 게시물에서는 다음과 같은 고급 Git 기능을 활용하는 방법을 배웁니다.
-
git stash
, 코드를 임시로 로컬에 저장합니다. - 커밋을 수행하기 전에 코드를 정리할 수 있는
git reset
-
git bisect
나쁜 커밋을 찾아내는 함수 - 커밋을 결합할 수 있는
git squash
-
git rebase
, 한 브랜치에서 다른 브랜치로 변경 사항을 적용할 수 있습니다.
힘내 숨김
Git stash를 사용하면 커밋하지 않고도 코드를 저장할 수 있습니다. 이것이 어떻게 유용합니까? 다음 시나리오를 상상해 보십시오.
당신은 이미 3개의 깔끔하고 깔끔한 커밋을 만들었지만, 꽤 지저분한 커밋되지 않은 코드도 있습니다. 디버깅 코드를 먼저 제거하지 않고 커밋하고 싶지 않을 것입니다. 그러다가 갑자기 다른 일을 해야 해서 지점을 옮겨야 하는 상황이 발생합니다. 이것은 main
분기에 있고 기능에 대한 새 분기를 만드는 것을 잊은 경우에 자주 발생할 수 있습니다. 지금 코드는 다음과 같습니다.
$ git status On branch my-feature 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: css/common.scss no changes added to commit (use "git add" and/or "git commit -a")
$ git diff diff --git a/css/common.scss b/css/common.scss index 2090cc4..90fd457 100644 --- a/css/common.scss +++ b/css/common.scss @@ -13,6 +13,6 @@ body { font-family: "Proxima Nova", Arial, sans-serif; font-size: 13px; - color: #333; + color: red; background-color: #f00; }
git stash
를 실행하면 커밋되지 않은 코드가 커밋되지 않고 사라집니다. 스태싱은 분기에 임시 로컬 커밋을 저장하는 것과 같습니다. stash를 원격 저장소로 푸시하는 것은 불가능하므로 stash는 개인적인 용도로만 사용됩니다.
$ git stash Saved working directory and index state WIP on my-feature: 49ee696 Change text color
이제 분기가 마지막 커밋을 수행할 때와 같이 나타납니다. 이제 코드를 잃지 않거나 지저분한 커밋 없이 안전하게 분기를 변경할 수 있습니다. 브랜치로 다시 전환하고 git stash list
를 실행하면 다음과 같은 stash 목록이 표시됩니다.
$ git stash list stash@{0}: WIP on my-feature: 49ee696 Change text color
git stash apply
를 실행하여 숨긴 콘텐츠를 쉽게 다시 적용할 수 있습니다. git stash apply stash@{1}
('1'은 마지막 stash 이전의 두 번째를 나타냄)를 실행하여 특정 stash(두 번 이상 stashed한 경우)를 적용할 수도 있습니다. 다음은 두 개 이상의 커밋을 숨기고 다른 숨김을 적용하는 예입니다.
$ git diff diff --git a/css/common.scss b/css/common.scss index 2090cc4..90fd457 100644 --- a/css/common.scss +++ b/css/common.scss @@ -13,6 +13,6 @@ body { font-family: "Proxima Nova", Arial, sans-serif; font-size: 13px; - color: #333; + color: red; background-color: #f00; } $ git stash Saved working directory and index state WIP on my-feature: 49ee696 Change text color $ git diff diff --git a/css/common.scss b/css/common.scss index 2090cc4..b63c664 100644 --- a/css/common.scss +++ b/css/common.scss @@ -13,6 +13,6 @@ body { font-family: "Proxima Nova", Arial, sans-serif; font-size: 13px; - color: #333; + color: red; background-color: #f00; } $ git stash Saved working directory and index state WIP on my-feature: 49ee696 Change text color
$ git stash list stash@{0}: WIP on my-feature: 49ee696 Change text color stash@{1}: WIP on my-feature: 49ee696 Change text color stash@{2}: WIP on my-feature: 49ee696 Change text color $ git stash apply stash@{2} On branch my-feature 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: css/common.scss no changes added to commit (use "git add" and/or "git commit -a")
git stash apply stash@{2}
는 텍스트 색상을 빨간색으로 변경할 때 가장 오래된 숨김 코드를 적용했습니다.
$ git diff diff --git a/css/common.scss b/css/common.scss index 2090cc4..90fd457 100644 --- a/css/common.scss +++ b/css/common.scss @@ -13,6 +13,6 @@ body { font-family: "Proxima Nova", Arial, sans-serif; font-size: 13px; - color: #333; + color: red; background-color: #f00; }
stash를 복원한 후 작업을 커밋하지 않기로 결정했다면 git checkout .
, 커밋되지 않은 모든 코드를 재설정합니다.
Git stash를 사용하는 방법에 대한 또 다른 예: 새 파일이 있고 그 중 하나에 버그가 있다고 가정해 보겠습니다. 의심되는 버그 파일을 제외한 모든 파일을 스테이징하지 않은 상태로 두면(코드를 스테이징해야 함) 해당 파일을 스테이징하고 문제를 해결할 수 있습니다. 숨김 파일이 문제가 아닌 경우 숨김 파일을 복원할 수 있습니다.
$ git status On branch my-feature Untracked files: (use "git add <file>..." to include in what will be committed) css/colors.scss nothing added to commit but untracked files present (use "git add" to track)
$ git add css/colors.scss $ git stash Saved working directory and index state WIP on my-feature: 0d8deef delete colors $ git status On branch my-feature nothing to commit, working tree clean $ git stash apply stash@{0} On branch my-feature Changes to be committed: (use "git reset HEAD <file>..." to unstage) new file: css/colors.scss
git stash branch
를 사용하여 숨김 커밋을 새 기능 분기 또는 디버깅 분기로 전달할 수도 있습니다.
$ git status On branch my-feature 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: css/common.scss no changes added to commit (use "git add" and/or "git commit -a") $ git stash Saved working directory and index state WIP on my-feature: 66f3f3b Add colors file $ git stash branch debugging-branch M css/common.scss Switched to a new branch 'debugging-branch' Unstaged changes after reset: M css/common.scss On branch debugging-branch 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: css/common.scss Dropped refs/stash@{0} (d140624f60d8deef7bceb0d11fc80ed4fd47e0a1)
stash를 적용한 경우 stash는 삭제되지 않습니다. git drop
을 사용하여 숨김을 개별적으로 제거하거나 git stash clear
를 사용하여 모든 숨김을 제거할 수 있습니다.
$ git stash list stash@{0}: WIP on my-feature: 66f3f3b Add colors file stash@{1}: WIP on my-feature: 0d8deef delete colors stash@{2}: WIP on my-feature: 49ee696 Change text color $ git stash drop stash@{2} Dropped stash@{2} (8ed6d2ce101aa2e28c8ccdc94cb12df8e5c468d6) $ git stash list stash@{0}: WIP on my-feature: 66f3f3b Add colors file stash@{1}: WIP on my-feature: 0d8deef delete colors $ git stash clear $ git stash list $
힘내 재설정
실수로 지저분한 코드를 커밋한 상황에 처한 경우 "소프트" 재설정을 수행할 수 있습니다. 이는 코드가 아직 커밋되지 않은 것처럼 표시됨을 의미합니다. 그런 다음 더 깨끗한 커밋을 하기 전에 IDE에서 코드를 정리할 수 있습니다. 이렇게 하려면 git reset --soft HEAD~1
을 실행할 수 있습니다. 이것은 가장 최근 커밋을 재설정합니다. ~
예를 들어 git reset --soft HEAD~2
뒤에 숫자를 변경하여 둘 이상의 커밋을 재설정할 수 있습니다.
$ git reset --soft HEAD~1 $ git status On branch debugging-branch Changes to be committed: (use "git reset HEAD <file>..." to unstage) modified: css/common.scss 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: css/common.scss
$ git diff diff --git a/css/common.scss b/css/common.scss index 2090cc4..90fd457 100644 --- a/css/common.scss +++ b/css/common.scss @@ -13,6 +13,6 @@ body { font-family: "Proxima Nova", Arial, sans-serif; font-size: 13px; - color: $grey; + color: red; background-color: #f00; }
Git 재설정은 특히 새로운 Git 사용자를 가르칠 때 좀 더 혼란스럽습니다. 소프트 리셋은 진짜 실수를 위해 예약해야 하는 반면 숨김은 코드를 교환하는 데 사용할 수 있습니다.
하드 리셋( git reset --hard HEAD~1
)을 수행할 수도 있습니다. 이 유형의 재설정은 기본적으로 마지막 커밋을 지웁니다. 커밋을 복원할 방법이 없기 때문에 특히 분기를 푸시하는 경우 하드 리셋을 수행하는 데 매우 주의해야 합니다.
힘내 양분
내가 가장 좋아하는 Git 도구는 git bisect
입니다. 나는 단지 몇 번만 그것을 필요로했지만, 내가 그것을했을 때, 그것은 매우 귀중했습니다! 저는 주로 강력한 디버깅 후에도 아무도 근본 원인을 찾지 못한 문제가 있는 대규모 코드베이스에서 사용했습니다.
git bisect
는 기본적으로 주어진 두 커밋 간에 이진 검색을 수행한 다음 특정 커밋의 세부 정보를 제공합니다. 먼저 Git에 기능이 작동하고 있다는 것을 알고 있는 좋은 커밋과 잘못된 커밋을 제공해야 합니다. 하나의 좋은 커밋과 하나의 나쁜 커밋이 있는 한 커밋은 몇 년 차이가 날 수 있습니다(시간을 거슬러 올라갈수록 더 어려워집니다!).
git bisect
의 가장 재미있는 점은 시작할 때 버그가 있는 커밋을 누가 작성했는지 알지 못한다는 것입니다. 버그가 도입된 위치를 찾는 흥분으로 인해 몇 명의 동료가 내 컴퓨터 주위에 모여들었습니다!
시작하려면 버그가 있는 브랜치를 확인하고 좋은 커밋을 찾으세요. 커밋 기록을 살펴보고 커밋 해시를 찾은 다음 해당 커밋을 확인하고 분기를 테스트해야 합니다. 작업하기에 좋은 지점과 나쁜 지점을 찾으면 git bisect
실행할 수 있습니다.
이 시나리오에서 텍스트는 우리가 만든 이 웹사이트에서 빨간색이지만(UI 디자이너를 사용할 수는 있지만) 빨간색이 된 방법과 시기는 알 수 없습니다. 이것은 매우 간단한 예입니다. 실제 시나리오에서는 제출/작동하지 않는 양식과 같이 훨씬 덜 분명한 문제가 있을 수 있습니다.
git log
를 실행하면 선택할 커밋 목록을 볼 수 있습니다.
$ git log commit a3cfe7f935c8ad2a2c371147b4e6dcd1a3479a22 (HEAD -> main) Author: Ursula Clarke <[email protected]> Date: Tue Jan 11 10:52:57 2021 +0100 Update .gitignore file for .DS_Store commit 246e90977790967f54e878a8553332f48fae6edc Author: Ursula Clarke <[email protected]> Date: Tue Jan 11 10:51:23 2021 +0100 Change styling of page commit d647ac489ad43b3c6eaea5aceb02b0a7d7e5cf8e Author: Ursula Clarke <[email protected]> Date: Tue Jan 11 10:50:48 2021 +0100 Change text color commit 032a41136b6653fb9f7d81aef573aed0dac3dfe9 Author: Ursula Clarke <[email protected]> Date: Tue Jan 11 10:42:57 2021 +0100 Change text color commit 246e90977790967f54e878a8553332f48fae6edc Author: Ursula Clarke <[email protected]> Date: Tue Jan 11 10:41:23 2021 +0100 delete colors commit d647ac489ad43b3c6eaea5aceb02b0a7d7e5cf8e Author: Ursula Clarke <[email protected]> Date: Tue Jan 11 10:50:48 2021 +0100 Change text color commit ce861e4c6989a118aade031020fd936bd28d535b Author: Ursula Clarke <[email protected]> Date: Tue Jan 11 10:07:36 2021 +0100 ...
가장 최근 커밋 해시에서 웹 페이지를 열면 텍스트가 빨간색이므로 문제가 있음을 알 수 있습니다.
이제 우리는 이등분을 시작하고 Git에게 잘못된 커밋이 있다고 알립니다.
$ git bisect start $ git bisect bad 8d4615b9a963ef235c2a7eef9103d3b3544f4ee1
이제 시간을 거슬러 올라가 텍스트가 빨간색이 아닌 커밋을 찾습니다. 여기에서 첫 번째 커밋을 확인하려고 합니다...
$ git checkout ce861e4c6989a118aade031020fd936bd28d535b Note: checking out 'ce861e4c6989a118aade031020fd936bd28d535b'. You are in 'detached HEAD' state. You can look around, make experimental changes and commit them, and you can discard any commits you make in this state without impacting any branches by performing another checkout. If you want to create a new branch to retain commits you create, you may do so (now or later) by using -b with the checkout command again. Example: git checkout -b <new-branch-name> HEAD is now at ce861e4 Add CSS styles
… 웹페이지 새로고침…
텍스트가 더 이상 빨간색이 아니므로 좋은 커밋입니다! 최신 커밋, 즉 나쁜 커밋에 가까울수록 더 좋습니다.
$ git checkout d647ac489ad43b3c6eaea5aceb02b0a7d7e5cf8e Previous HEAD position was ce861e4c6989a118aade031020fd936bd28d535b Add CSS styles HEAD is now at d647ac4 Change text color
이제 Git은 올바른 커밋을 찾기 전에 검색해야 하는 커밋 수를 알려줍니다. Git이 트래버스하는 커밋 수는 좋은 커밋과 나쁜 커밋 사이에 얼마나 많은 커밋이 있는지에 따라 다릅니다(시간이 길수록 Git이 반복해야 하는 횟수가 늘어남).
이제 지점을 다시 테스트하고 문제가 사라졌는지 확인해야 합니다. 프론트 엔드 리포지토리에 노드 모듈을 다시 설치해야 할 수도 있기 때문에 모듈을 정기적으로 업데이트하는 경우 때때로 이것이 약간 번거로울 수 있습니다. 데이터베이스 업데이트가 있는 경우 이를 업데이트해야 할 수도 있습니다.
git bisect
는 좋은 커밋과 나쁜 커밋 중간에 자동으로 커밋을 확인합니다. 여기서는 잘못된 커밋을 찾기 위한 한 단계를 추정합니다.
$ git bisect good 1cdbd113cad2f452290731e202d6a22a175af7f5 Bisecting: 1 revision left to test after this (roughly 1 step) [ce861e4c6989a118aade031020fd936bd28d535b] Add CSS styles $ git status HEAD detached at ce861e4 You are currently bisecting, started from branch '8d4615b'. (use "git bisect reset" to get back to the original branch)
페이지를 새로고침하고 문제가 해결되었는지 확인하십시오. 문제는 여전히 존재하므로 Git에게 이것이 여전히 잘못된 커밋이라고 알립니다. Git은 체크아웃한 커밋을 사용하므로 이번에는 커밋 해시를 참조할 필요가 없습니다. Git이 가능한 모든 단계를 통과할 때까지 이 프로세스를 반복해야 합니다.
$ git bisect bad Bisecting: 0 revisions left to test after this (roughly 0 steps) [cbf1b9a1be984a9f61b79ae5f23b19f66d533537] Add second paragraph to page
페이지를 새로 고치면 문제가 다시 사라지므로 좋은 커밋입니다.

이 단계에서 Git은 첫 번째 잘못된 커밋을 발견했습니다.
$ git bisect good ce861e4c6989a118aade031020fd936bd28d535b is the first bad commit commit ce861e4c6989a118aade031020fd936bd28d535b Author: Ursula Clarke <[email protected]> Date: Tue Jan 11 10:52:57 2021 +0100 Add CSS styles :000000 100644 0000000000000000000000000000000000000000 092bfb9bdf74dd8cfd22e812151281ee9aa6f01a M css
이제 git show
를 사용하여 커밋 자체를 표시하고 문제를 식별할 수 있습니다.
$ git show ce861e4c6989a118aade031020fd936bd28d535b commit ce861e4c6989a118aade031020fd936bd28d535b Author: Ursula Clarke <[email protected]> Date: Tue Jan 11 10:52:57 2021 +0100 Add CSS styles diff --git a/css/base.scss b/css/base.scss index e69de29..26abf0f 100644 --- a/css/base.scss +++ b/css/base.scss @@ -1,7 +1,7 @@ body { background-color: $white; margin: 0px; line-height: 20px; - color: $grey; + color: red; }
완료되면 git bisect reset
을 실행하여 분기를 정상 작동 상태로 재설정할 수 있습니다.
커밋이 가까울수록 Git이 문제를 더 쉽게 찾을 수 있지만 이전에 10단계를 거쳐 여전히 잘못된 커밋을 쉽게 찾을 수 있습니다. 작동이 보장되지는 않지만 대부분의 경우 문제를 발견했습니다. 축하합니다. 이제 코드 고고학자가 되셨습니다!
커밋 스쿼시
저는 이전에 글로벌 조직의 오픈 소스 프로젝트에서 풀 타임으로 일했으며 커밋을 스쿼시하거나 결합하는 것이 얼마나 중요한지 빠르게 배웠습니다. 고용주가 요구하지 않더라도 좋은 습관이라고 생각합니다. 나중에 빌드한 기능을 검토하고 편집해야 하는 다른 개발자에게 특히 유용합니다.
왜 커밋을 스쿼시합니까?
- 리포지토리의 기고자가 더 쉽게 읽을 수 있습니다. 다음과 같은 커밋 목록이 있다고 상상해보십시오.
- 캐러셀 슬라이더 구현
- 캐러셀에 스타일 추가
- 캐러셀에 버튼 추가
- 캐러셀이 있는 IE의 이상한 문제 수정
- 캐러셀에서 여백 조정
이것을 "홈페이지에 캐러셀 추가"라는 단일 커밋으로 스쿼시하는 것이 훨씬 쉽습니다.
- 풀 요청을 할 때마다 커밋을 하나로 묶어야 하는 경우 커밋 메시지를 이해하기 쉽고 관련성 있게 유지하도록 권장합니다. "WIP", "로그인 페이지 버그 수정" 또는 "오타 수정"이라는 커밋을 본 적이 있습니까? "#444 로그인 페이지에 대한 버그 수정 - $scope 기능 누락으로 인한 깜박임 수정"과 같은 관련 커밋 이름을 갖는 것이 중요합니다.
커밋을 스쿼시하고 싶지 않은 이유는 매우 상세하고 긴 기능을 작업 중이고 나중에 버그를 발견할 경우에 대비하여 일일 기록을 유지하기를 원하기 때문일 수 있습니다. 그러면 기능을 더 쉽게 디버그할 수 있습니다. 그러나 기능을 메인 브랜치에 체크인하고 버그가 없다고 확신할 때 여전히 스쿼시하는 것이 합리적입니다.
이 시나리오에서는 5개의 커밋을 수행했지만 모두 하나의 기능과 관련되어 있습니다. 내 커밋 메시지는 분리된 장점과 너무 밀접하게 관련되어 있습니다. 내 모든 커밋은 이 새로운 기능의 페이지 스타일 지정에 관한 것입니다.
$ git log commit a8fbb81d984a11adc3f72ce27dd0c39ad24403b7 (HEAD -> main) Author: Ursula Clarke <[email protected]> Date: Tue Jan 11 11:16:10 2021 +0100 Import colors commit e2b3ddd5e8b2cb1e61f88350d8571df51d43bee6 Author: Ursula Clarke <[email protected]> Date: Tue Jan 11 11:15:32 2021 +0100 Add new color commit d647ac489ad43b3c6eaea5aceb02b0a7d7e5cf8e Author: Ursula Clarke <[email protected]> Date: Tue Jan 11 10:50:48 2021 +0100 Change text color commit c005d9ceeefd4a8d4e553e825fa40aaafdac446e Author: Ursula Clarke <[email protected]> Date: Tue Jan 11 09:59:57 2021 +0100 Add CSS styles commit 9e046b7df59cef07820cc90f694fabc666731bd2 Author: Ursula Clarke <[email protected]> Date: Tue Jan 11 09:56:28 2021 +0100 Add second paragraph to page commit 5aff973577d67393d914834e8af4c5d07248d628 Author: Ursula Clarke <[email protected]> Date: Mon Jan 10 16:04:22 2021 +0100 Add colors CSS file and edit background color
git merge --squash
를 사용할 수도 있지만 커밋을 체리 선택하면 커밋 설명을 더 쉽게 볼 수 있기 때문에 rebase
를 사용하는 것이 더 명확하다고 생각합니다. git merge --squash
를 실행하는 경우 먼저 커밋을 하드 리셋해야 하며( git reset --hard HEAD~1
) 이 작업을 수행하는 데 필요한 커밋 수와 혼동하기 쉽습니다. git rebase
가 더 시각적인 것으로 나타났습니다.
git rebase -i --root
를 실행하여 시작하면 명령줄의 기본 텍스트 편집기가 커밋 목록과 함께 열립니다.
pick eb1eb3c Update homepage pick 5aff973 Add colors CSS file and edit background color pick 9e046b7 Add second paragraph to page pick c005d9c Add CSS styles pick d647ac4 Change text color pick e2b3ddd Add new color pick a8fbb81 Import colors # Rebase a8fbb81 onto b862ff2 (7 commands) # # 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 # d, drop = remove commit # # 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
마지막 몇 개의 커밋을 스쿼시하고 싶을 수도 있습니다. 이 경우 git rebase -i HEAD~3
을 실행하면 마지막 세 커밋이 표시됩니다.
pick eb1eb3c Update homepage pick 5aff973 Add colors CSS file and edit background color pick 9e046b7 Add second paragraph to page # Rebase b862ff2..9e046b7 onto b862ff2 (3 commands) # # 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 # d, drop = remove commit # # 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
이제 아래와 같이 모든 커밋을 첫 번째 커밋으로 스쿼시할 수 있습니다.
pick eb1eb3c Update homepage squash 5aff973 Add colors CSS file and edit background color squash 9e046b7 Add second paragraph to page # Rebase b862ff2..9e046b7 onto b862ff2 (3 commands) # # 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 # d, drop = remove commit # # 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
파일을 저장하면 Git에서 편집할 커밋 메시지를 엽니다.
# This is a combination of 3 commits. # This is the 1st commit message: Update homepage # This is the commit message #2: Add colors CSS file and edit background color # This is the commit message #3: Add second paragraph to page # Please enter the commit message for your changes. Lines starting # with '#' will be ignored, and an empty message aborts the commit. # # Date: Wed Jan 13 18:31:28 2021 +0100 # # interactive rebase in progress; onto b862ff2 # Last commands done (3 commands done): # squash 5aff973 Add colors CSS file and edit background color # squash 9e046b7 Add second paragraph to page # No commands remaining. # You are currently rebasing branch 'main' on 'b862ff2'. # # Changes to be committed: # new file: .gitignore # new file: css/base.css # new file: css/base.scss # new file: css/colors.css # new file: css/colors.css.map # new file: css/colors.scss # new file: css/common.css # new file: css/common.scss # new file: index.html #
리베이스를 하는 동안 커밋 설명을 읽기 쉽게 편집할 수도 있습니다.
Implement new design for homepage. Add .gitignore file for Sass folder. # Please enter the commit message for your changes. Lines starting # with '#' will be ignored, and an empty message aborts the commit. #
이 파일을 다시 저장하면 완료됩니다! Git 로그를 다시 보면 깨끗한 커밋이 하나만 있음을 알 수 있습니다.
[detached HEAD 574ec7e] Implement new design for homepage. Add .gitignore file for Sass folder. Date: Wed Jan 13 18:31:28 2021 +0100 10 files changed, 215 insertions(+) create mode 100644 .gitignore create mode 100644 css/base.css create mode 100644 css/base.scss create mode 100644 css/colors.css create mode 100644 css/colors.css.map create mode 100644 css/colors.scss create mode 100644 css/common.css create mode 100644 css/common.scss create mode 100644 index.html create mode 100644 verylargefile.txt Successfully rebased and updated refs/heads/main. $ git log commit 574ec7e5d7d7a96427e049cad9806cdef724aedd (HEAD -> main) Author: Ursula Clarke <[email protected]> Date: Wed Jan 13 18:31:28 2021 +0100 Implement new design for homepage. Add .gitignore file for Sass folder.
힘내 리베이스
개발자는 일반적으로 git rebase
를 사용하는 것을 주저합니다. 왜냐하면 그들은 rebase를 사용하여 코드베이스에서 파일을 영구적으로 삭제할 수 있다는 것을 알고 있기 때문입니다.
위에서 보았듯이 git rebase
는 코드를 유지하고 정리하고 삭제하는 데 사용할 수 있습니다. 하지만 정말로 기록에서 파일을 영구적으로 제거하려면 어떻게 해야 할까요?
한 번 우리 개발 팀의 구성원이 실수로 코드베이스에 매우 큰 파일을 커밋한 시나리오를 목격했습니다. 훨씬 더 큰 브랜치의 일부였기 때문에 큰 파일은 코드 검토에서 눈에 띄지 않고 실수로 메인 브랜치로 체크인되었습니다. 이것은 누군가가 저장소를 다시 복제하려고 할 때마다 문제가 되었습니다. 다운로드하는 데 매우 오랜 시간이 걸렸습니다! 그리고 물론, 문제의 파일은 불필요했습니다. 파일이 메인 브랜치에 대한 마지막 커밋이라면 문제가 되지 않았을 것입니다. 이 경우 하드 리셋( git reset --hard HEAD~1
)을 실행하고 브랜치를 강제로 푸시할 수 있습니다.
마찬가지로 파일이 주어진 커밋의 유일한 변경 사항인 경우 git reset --hard <commit-id>
를 실행하여 전체 커밋을 제거할 수 있습니다. 그러나 우리 시나리오에서는 큰 파일이 기록에 남기고 싶은 다른 코드와 함께 마지막에서 두 번째 커밋으로 커밋되었습니다.
번거로운 커밋을 찾으면 git checkout
과 커밋 해시를 사용하여 확인하세요.
$ git checkout ce861e4c6989a118aade031020fd936bd28d535b Note: checking out 'ce861e4c6989a118aade031020fd936bd28d535b'. You are in 'detached HEAD' state. You can look around, make experimental changes and commit them, and you can discard any commits you make in this state without impacting any branches by performing another checkout. If you want to create a new branch to retain commits you create, you may do so (now or later) by using -b with the checkout command again. Example: git checkout -b <new-branch-name> HEAD is now at ce861e4 Add CSS styles
파일을 제거하거나 코드를 편집하고 그대로 유지하려는 코드를 그대로 둡니다.
$ rm verylargefile.txt $ git status HEAD detached at ce861e4 Changes not staged for commit: (use "git add/rm <file>..." to update what will be committed) (use "git checkout -- <file>..." to discard changes in working directory) deleted: verylargefile.txt no changes added to commit (use "git add" and/or "git commit -a")
git add -A
를 실행하여 삭제된 파일이 준비되고 Git이 파일을 제거할 것임을 알도록 하십시오. 이제 git commit --amend -v
를 실행하면 Git이 커밋 메시지를 편집하라는 메시지를 표시합니다.
그런 다음 git rebase --onto HEAD <commit-id> main
실행합니다. 여기에서 병합 충돌이 발생할 수 있습니다. 즉, 새 커밋과 이전 코드 간에 충돌이 있습니다. Git은 충돌을 해결하도록 요청할 것입니다.
$ git add -A $ git status HEAD detached at ce861e4 Changes to be committed: (use "git reset HEAD <file>..." to unstage) deleted: verylargefile.txt $ git commit --amend -v [detached HEAD 7c9516a] Add CSS styles Date: Thu Jan 14 14:43:54 2021 +0100 3 files changed, 9 insertions(+), 2 deletions(-) create mode 100644 css/common.css.map delete mode 100644 verylargefile.txt $ git status HEAD detached from ce861e4 nothing to commit, working tree clean $ git rebase --onto HEAD ce861e4 First, rewinding head to replay your work on top of it... Fast-forwarded HEAD to HEAD.
텍스트 편집기에서 파일을 열면 Git이 색인 파일의 두 가지 버전을 표시한 것을 볼 수 있습니다. 원하는 변경 사항을 유지하려면 하나를 제거하거나 편집하기만 하면 됩니다.
<p> Toptal was created by engineers. We are entrepreneurs, all passionate about working with top tech talent and exciting companies from all over the world. </p> <<<<<<< HEAD <p> Toptal connects the top 3% of freelance talent all over the world. </p> </main> </body> </html> ======= </main> </body> </html> >>>>>>> Add index file
<<<<<<< HEAD
와 등호 줄 사이의 코드는 하나의 버전이고 등호와 >>>>>>> Add index file
사이의 코드는 "인덱스 파일 추가" 커밋의 버전입니다. . 따라서 한 버전에는 "Toptal은 전 세계의 상위 3% 프리랜서 인재를 연결합니다"라는 추가 단락이 있는 반면 다른 버전에는 없는 것을 볼 수 있습니다.
편집한 파일을 저장하고 git add filename
다음에 git rebase --continue
를 실행하십시오. 변경 사항이 없으면 git rebase --skip
실행할 수도 있습니다. "큰 파일" 커밋과 main의 최신 커밋 사이에 많은 커밋이 있는 경우 리베이스를 진행하는 데 시간이 걸릴 수 있습니다.
인내심을 갖고 대규모 팀에 속해 있다면 두 번째 의견을 확인하십시오! 가능하면 병합하려는 커밋을 작성한 사람과 상의하는 것이 특히 중요합니다.
병합 변경 사항은 최신 변경 사항이 아니라 기록의 특정 커밋과 관련이 있음을 기억하십시오. 즉, 사이트의 텍스트가 Arial이었을 때 커밋을 편집하고 있고 지금은 Verdana인 경우 글꼴 페이스로 Arial의 히스토리를 사용하여 해당 커밋을 계속 유지해야 합니다.
또한 Git에서 공백이나 줄 끝 문자가 보이면 병합 충돌이 발생할 수 있으므로 주의하십시오!
커밋 및 풀 그 이상
Git은 많은 개발자가 생각하는 것보다 강력합니다. 초보자를 소개하는 경우 이러한 귀중한 기능에 대한 몇 가지 팁을 제공해야 합니다. 보다 효율적인 워크플로를 만듭니다.
Git에 대해 더 알고 싶으십니까? Toptal의 Git 팁 및 사례 페이지를 살펴보십시오.