[Git] Git Add Patch

ryeoni·2022년 10월 5일
1

Git

목록 보기
2/7

개요


초반에는 주로 아래처럼 커밋을 하고는 했다.


$ git add .
$ git commit -m “commit message”
$ git push origin master

모든 코드를 스테이징 영역에 올리다보니 정확히 어떤 코드가 올라갔는지 알 수가 없었고 일부 파일만 올리고 싶은 경우도 있었다. 물론 git add [filename] 으로 특정 파일만 올릴 수 있지만 git add -p가 더 좋은 방법이라고 생각해서 이제는 add 할 때 무조건 -p 옵션을 사용한다.


git add -patch


git add --patch의 줄임말은 git add -p이며 대화형 명령으로 보다 구체적인 커밋을 수행할 수 있는 옵션이다. 작동 방식은 코드의 모든 변경 사항을 거치고 스테이징할지 여부를 결정할 수 있도록 한 번에 큰 덩어리를 표시한다.


수정 후 파일의 일부분만 스테이징 영역에 추가하려면 다음 명령어를 실행하면 된다.


git add -p
// or 
git add --patch

변경된 파일과 해당 파일의 수정 부분을 단위별로 나누어서 표시하고 하나씩 준비할지 묻는 메시지가 표시된다. 여기서 보이는 변경사항의 하나의 단위를 hunk 라고 부른다. 이 hunk 단위로 추가할지 말지를 정할 수 있다.


diff --git a/lib/simplegit.rb b/lib/simplegit.rb
index dd5ecc4..57399e0 100644
--- a/lib/simplegit.rb
+++ b/lib/simplegit.rb
@@ -22,7 +22,7 @@ class SimpleGit
   end

   def log(treeish = 'master')
-    command("git log -n 25 #{treeish}")
+    command("git log -n 30 #{treeish}")
   end

   def blame(path)
Stage this hunk [y,n,a,d,/,j,J,g,e,?]?

이 시점에는 많은 옵션이 있다. ? 입력하면 수행할 수 있는 작업 목록이 표시된다.


Stage this hunk [y,n,a,d,/,j,J,g,e,?]? ?
y - stage this hunk
n - do not stage this hunk
a - stage this and all the remaining hunks in the file
d - do not stage this hunk nor any of the remaining hunks in the file
g - select a hunk to go to
/ - search for a hunk matching the given regex
j - leave this hunk undecided, see next undecided hunk
J - leave this hunk undecided, see next hunk
k - leave this hunk undecided, see previous undecided hunk
K - leave this hunk undecided, see previous hunk
s - split the current hunk into smaller hunks
e - manually edit the current hunk
? - print help

여기서 주로 사용하는건 y 또는 n 이다. 준비가 된 코드는 y 를 입력하여 스테이징 영역에 올리고 보류할 경우 n 을 입력한다. 이 과정에서 지우지 못한 콘솔이나 테스트용 코드를 발견해서 수정하기도 한다.


사용해야 하는 이유


  • 스테이징에 추가하기 전에 변경사항을 직접 확인하여 한 번 더 수정할 수 있다.
  • 코드를 수정할 때 커밋단위로 나누어서 작업하지 않고 여러 작업이 섞이는 경우 관련된 부분만 나누어서 스테이징에 추가할 수 있다.
  • 커밋을 논리적인 단위로 나눌 수 있다.

Reference


7.2 Git 도구 - 대화형 명령
Staging Commits with “Git Add Patch”
git add -p 와 git commit -v 의 사용

profile
기록하는 습관 ✏️ 공유하고 싶은 정보들 🔎

0개의 댓글