简体   繁体   中英

git diff of just one file

The only way I found to get a diff from a single file using libgit2 is through git_diff_foreach and checking the filename at the diff_file_cb callback.

It's not the way I wanted to do this, I was looking for something easier.

Is there another way to do this?

Just to clarify, git_diff_index_to_workdir (or git_diff_tree_to_tree or another such function) finds the list of changed files and then git_diff_foreach walks through the found files and the text of the diffs. You can pass a "pathspec" in the options structure for git_diff_index_to_workdir that will limit the files being checked. You would do that as mentioned in the prior answer.

As a slightly broader example, if you wanted to diff a more complex set of files, you could write something like:

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);

You can pass as many file names or file patterns as you like. If you want to disable the pattern matching behavior (ie expanding * and such), you can write opts.flags |= GIT_DIFF_DISABLE_PATHSPEC_MATCH and only exact file name matches will be used.

Much easier using the pathspec option and git_diff_index_to_workdit instead of 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM