iT邦幫忙

2017 iT 邦幫忙鐵人賽
DAY 21
0
自我挑戰組

Git學習筆記系列 第 21

只add部分資料進暫存區(stage area)

有時候我們開發上會遇到

同一支程式

可能裡面包含了A功能及B功能的程式碼

若我們想要明確的控管commit

只要包含A功能,而不要包含B功能的程式碼片段

這時候可以利用git add --patch 這個指令

假設現在有個網頁 index.html ,內容如下

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
</body>
</html>

接著我們開發了一個段落,內容如下

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>first page</title>
</head>
<body>
	<div>func01</div>
	<div>func02</div>
	<div>func03</div>
</body>
</html>

此時可以發現我改了兩個地方,分別是

  •   <title>first page</title>
    
  •   及<body>內多了3個div
      <div>func01</div>
      <div>func02</div>
      <div>func03</div>
    

假設title內容的變更是為了A功能

body內容的變更是為了B功能

這時候我們可以透過互動指令來完成

$ git add --patch index.html 
diff --git a/index.html b/index.html
index dead1b9..6b2356c 100644
--- a/index.html
+++ b/index.html
@@ -2,9 +2,11 @@
 <html>
 <head>
     <meta charset="UTF-8">
-    <title>Document</title>
+    <title>first page</title>
 </head>
 <body>
-
+	<div>func01</div>
+	<div>func02</div>
+	<div>func03</div>
 </body>
 </html>
Stage this hunk [y,n,q,a,d,/,s,e,?]?

這邊回問號可以查看縮寫代表的意思

Stage this hunk [y,n,q,a,d,/,s,e,?]??
y - stage this hunk
n - do not stage this hunk
q - quit; do not stage this hunk or any of the remaining ones
a - stage this hunk and all later hunks in the file
d - do not stage this hunk or any of the later 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

這時候git是問你是否要把這兩個區塊都放到暫存區以供commit

但因為我們不希望這兩個功能的程式混在一起commit

所以我們選擇s,s表示split the current hunk into smaller hunks

也就是請git把幫你選擇的異動區塊再切小一點

Stage this hunk [y,n,q,a,d,/,s,e,?]? s
Split into 2 hunks.
@@ -2,6 +2,6 @@
 <html>
 <head>
     <meta charset="UTF-8">
-    <title>Document</title>
+    <title>first page</title>
 </head>
 <body>

選了s之後,可以發現git顯示「Split into 2 hunks.」,這就是表示他再切小一點之後會分為兩個區塊

第一個區塊就是title那塊

假設他就是我們要的功能A的程式碼片段,我們就可以選y,讓git將它加入暫存區等待commit

接下來的區塊就是body內的div

@@ -6,5 +6,7 @@
 </head>
 <body>
-
+	<div>func01</div>
+	<div>func02</div>
+	<div>func03</div>
 </body>
 </html>
Stage this hunk [y,n,q,a,d,/,K,g,e,?]? n

這邊我們選n,因為我們不希望功能B的程式碼片段隨著功能A,commit出去

選完之後確認狀態會發現是一個MM的狀態

$ git status -s
MM index.html

commit 上去

$ git commit -m "2nd commit"
[master 66a9576] 2nd commit
 1 file changed, 1 insertion(+), 1 deletion(-)

commit上去之後,查git status會發現狀態是M

$ git status -s
 M index.html

再來我們就可以把功能B的異動也加進暫存區,並且commit上去

這樣我們就會得到2個commit,而且是可以區分為功能A跟功能B的commit

Git 工具 - 互動式暫存


上一篇
git 基本中的基本
下一篇
合併多個commit為1個
系列文
Git學習筆記31
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言