Try   HackMD

Git patch add ( git add -p ) 的問題

我在練習使用 git add -p 的時候遇到了一個問題,

為了講解自己創了一個檔案如下( test.c ):

#include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { int a = 0; return 0; }

先將這個檔案直接 add 並 commit :

$ git add test.c
$ git commit -m "Test"

完成後我再回去修改 test.c :

#include <string.h> #include <stdio.h> #include <stdlib.h> #define A 0 int main(int argc, char *argv[]) { int a = 0; return 0; }

差別如下:

diff --git a/test.c b/test.c index 787df04..2b90595 100644 --- a/test.c +++ b/test.c @@ -1,6 +1,9 @@ +#include <string.h> #include <stdio.h> #include <stdlib.h> +#define A 0 + int main(int argc, char *argv[]) { int a = 0;

此時我使用 git add -p 命令來挑選需要 add 的部份:

diff --git a/test.c b/test.c index 787df04..2b90595 100644 --- a/test.c +++ b/test.c @@ -1,6 +1,9 @@ +#include <string.h> #include <stdio.h> #include <stdlib.h> +#define A 0 + int main(int argc, char *argv[]) { int a = 0; (1/1) Stage this hunk [y,n,q,a,d,s,e,?]? s

我選擇 s 選項讓各個 hunks 分開:

Split into 2 hunks. @@ -1,3 +1,4 @@ +#include <string.h> #include <stdio.h> #include <stdlib.h> (1/2) Stage this hunk [y,n,q,a,d,j,J,g,/,e,?]? e

這邊是重點,我選擇 e 選項進入編輯 patch 模式:

# Manual hunk edit mode -- see bottom for a quick guide. @@ -1,3 +1,4 @@ +#include <string.h> #include <stdio.h> #include <stdlib.h> # --- # To remove '-' lines, make them ' ' lines (context). # To remove '+' lines, delete them. # Lines starting with # will be removed. # # If the patch applies cleanly, the edited hunk will immediately be # marked for staging. # If it does not apply cleanly, you will be given an opportunity to # edit again. If all lines of the hunk are removed, then the edit is # aborted and the hunk is left unchanged.

我什麼都沒有改就直接 :wq 退出,這邊大家可以注意到 #include <stdlib.h> 底下的那行空白,那行是有一個 space 的,表示那行不變,我了解如果沒有那個空白就會出錯,所以問題應該不是那邊沒有 space 的。

:wq 退出後就出現錯誤訊息:

error: 打修補檔失敗:test.c:1
error: test.c:修補檔未套用
Your edited hunk does not apply. Edit again (saying "no" discards!) [y/n]? 

這邊我做過很多次測試,只要 edit 的 hunk 片段「第一行」是

+ 行或
行,也就是有修改的行,而且最後一行是空行,就會發生錯誤,如上面的例子。

我也想過是不是編輯器的問題,將 git 的 core.editor 改成 vscode, gedit 等等,也都會出現問題。我也查過資料,有資料說有可能是編輯器在儲存時會把最後多餘的空白去掉,即使在這邊它不是多餘的,但我並沒有把我的 vim 加上這些功能(如 .vimrc 中的設定),我甚至重新安裝了 vim 、 將 git 更新到最新版本依然沒有解決。

我的系統與軟體版本:

作業系統: Ubuntu 20.04.1 LTS 64 位元
GNOME 版本: 3.36.3
視窗系統: X11
Git 版本: 2.30.2
Vim 版本: VIM - Vi IMproved 8.1 (2018 May 18, compiled Apr 15 2020 06:40:31)