補丁是一個文本檔,其內容類似於git diff
,但與代碼一樣,它也有關於提交的元數據; 例如提交ID,日期,提交消息等。我們可以從提交創建一個補丁,而其他人可以將它們應用到他們的存儲庫。
假設我們在專案實現了一個strcat
函數。並將編寫的代碼的路徑併發送給其他開發人員。 然後,其他開發人員可以將接收的補丁應用到自己的代碼中。
我們使用git format-patch
命令創建最新提交的修補程式。 如果要為特定提交創建修補程式,請在format-patch
命令後面指定 COMMIT_ID
。
$ pwd
/D/worksp/sample
Administrator@MY-PC /D/worksp/sample (master)
$ git status
On branch master
Your branch is up-to-date with 'origin/master'.
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/string.py
no changes added to commit (use "git add" and/or "git commit -a")
Administrator@MY-PC /D/worksp/sample (master)
$ git add src/string.py
Administrator@MY-PC /D/worksp/sample (master)
$ git commit -m "Added my_strcat function"
[master cea49f4] Added my_strcat function
1 file changed, 4 insertions(+), 1 deletion(-)
Administrator@MY-PC /D/worksp/sample (master)
$ git format-patch -1
0001-Added-my_strcat-function.patch
上述命令在當前工作目錄中創建.patch
檔。 其他開發人員可以使用這個補丁來修改他的檔。 Git分別提供兩個命令:git am
和 git apply
來應用補丁。 git apply
修改本地檔而不創建提交,而git am
會修改檔並創建提交。
要應用補丁並創建提交,請使用以下命令:
zaixian@ubuntu:~/git/sample$ pwd
/home/zaixian/git/sample/src
zaixian@ubuntu:~/git/sample$ git diff
zaixian@ubuntu:~/git/sample$ git status –s
zaixian@ubuntu:~/git/sample$ git apply 0001-Added-my_strcat-function.patch
zaixian@ubuntu:~/git/sample$ git status -s
修補程式成功應用,現在我們可以使用git diff
命令查看修改。
$ git diff
diff --git a/src/string.py b/src/string.py
index ab42b94..18f165f 100644
--- a/src/string.py
+++ b/src/string.py
@@ -6,4 +6,5 @@ var2 = "Python Programming"
print ("var1[0]: ", var1[0])
print ("var2[1:5]: ", var2[1:5]) # 切片 加索引
-
+def my_strcat(str1, str2):
+ return (str1+str2)