2010年10月26日 星期二

原始碼 diff and patch

開發專案的時候常常需要協同合作,可以不用把所有原始碼寄給對方,只把寄自己修改過的內容就可以。下面是一個操作實例,修正內容我們可以用diff 指令產生,而對方用 patch 把你修正的內容加入原始碼。


1. 自己開發的程式內容
檔案列表如下
test/Makefile
test/test.c
test.c 內容如下
#include <stdio.h>
int main(int argc, char **argv)
{
    printf("Hello World!\n");
    return 0;
}
2. 打包寄給協同開發者
將 test 整個打包
tar czvf test.tgz test/
3. 協同開發者開始更改
tar zxvf test.tgz
cp test test1 -rf
檔案列表如下
test1/Makefile
test1/test.c
test1/README
README 內容如下
Hello! It's README file.
修改 test.c 內容如下
#include <stdio.h>
int main(int argc, char **argv)
{
        printf("Hello World!\n");
        printf("Hello c program\n");

        return 0;
}
4. 產生 patch 檔
語法如下
diff -Naur [from-file] [to-file] > [YourFileName.patch]
-N    In  directory comparison, if a file is found in only one directory, treat it as present but empty in the other directory.
-a    Treat  all  files as text and compare them line-by-line, even if they do not seem to be text.
-u    Use the unified output format.
-r    When comparing directories, recursively compare any subdirectories found.
依我們的情況下指令如下,產生 test.patch 檔
diff -Naur test test1 > test.patch
test.patch 內容如下
diff -Naur test/README test1/README
--- test/README 1970-01-01 08:00:00.000000000 +0800
+++ test1/README        2010-06-09 16:01:32.000000000 +0800
@@ -0,0 +1 @@
+Hello! It's README file.
diff -Naur test/test.c test1/test.c
--- test/test.c 2010-06-09 16:01:06.000000000 +0800
+++ test1/test.c        2010-06-09 16:00:25.000000000 +0800
@@ -3,5 +3,6 @@
 int main(int argc, char **argv)
 {
        printf("Hello World!\n");
+       printf("Hello c program\n");
        return 0;
 }
將 test.patch 寄回給原開發者
5. 開始 patch
patch 語法如下
patch -p0 < [patchfile]
將之前的test.tgz解開
tar zxvf test.tgz
patch -p0 < test.patch
[~]# patch -p0 < test.patch
patching file test/README
patching file test/test.c
6. 移除 patch 內容
再作一次patch即可,程式會詢問你
或者也可以增加參數 -R 來回覆修改
patch -p0 < test.patch
或是
patch -R -p0 < test.patch
[~]# patch -p0 < test.patch
The next patch would create the file test/README,
which already exists!  Assume -R? [n] y
patching file test/README
patching file test/test.c
Reversed (or previously applied) patch detected!  Assume -R? [n] y


沒有留言:

張貼留言