2013-11-20 38 views
1

我發現使用libgit2一個單一的文件得到一個差異的唯一方式的git的差異是通過git_diff_foreach和檢查在diff_file_cb回調的文件名。只有一個文件

這不是我想要這樣做的方式,我一直在尋找更容易的東西。

是否有另一種方法可以做到這一點?

+0

[看看這個答案](http://stackoverflow.com/questions/16563021/how-to-get-the-diff-of-a-single-file-with-libgit2) –

+0

是的,我有。我認爲解決這個問題的方法是使用git_diff_index_to_workdir()和pathspec選項 – AndreDurao

回答

0

使用pathspec選項和git_diff_index_to_workdit代替git_diff_foreach

char *pathspec = "foo.bar"; 
git_diff_options opts = GIT_DIFF_OPTIONS_INIT; 
opts.pathspec.strings = &pathspec; 
opts.pathspec.count = 1; 
git_diff_index_to_workdir(&diff, repo, NULL, &opts); 
3

只是爲了澄清,git_diff_index_to_workdir(或git_diff_tree_to_tree或另一個這樣的功能)要容易得多認定的修改過的文件列表,然後git_diff_foreach遍歷找到的文件和差異文本。您可以在git_diff_index_to_workdir的選項結構中傳遞「pathspec」,這將限制正在檢查的文件。你會這樣做,如前面的答案所述。

作爲稍寬例如,如果你想diff的一組更復雜的文件,你可以寫這樣的:

git_diff *diff; 
git_diff_options opts = GIT_DIFF_OPTIONS_INIT; 
char *files[3]; 

files[0] = "myfile.txt"; 
files[1] = "yourfile.txt"; 
files[2] = "some/directory/*.h" 

opts.pathspec.count = 3; 
opts.pathspec.strings = files; 

if (git_diff_index_to_workdir(&diff, repo, NULL, &opts) < 0) { 
    printf("Failed to diff\n"); 
    exit(1); 
} 

git_diff_foreach(diff, file_cb, NULL, NULL, NULL); 

git_diff_free(diff); 

只要你喜歡你可以傳遞儘可能多的文件名或文件模式。如果要禁用模式匹配行爲(即擴展*等),則可以編寫opts.flags |= GIT_DIFF_DISABLE_PATHSPEC_MATCH,並且只會使用精確的文件名匹配。

相關問題