Skip to content
VulumeCode edited this page Feb 4, 2022 · 2 revisions

git-diff

Compare with working directory or index

Return changes in working directory

Git

$ git diff

LibGit2Sharp

using (var repo = new Repository("path/to/your/repo"))
{
    foreach (TreeEntryChanges c in repo.Diff.Compare<TreeChanges>())
    {
        Console.WriteLine(c);
    }
}

Return changes in index

Git

$ git diff --cached

LibGit2Sharp

using (var repo = new Repository("path/to/your/repo"))
{
    foreach (TreeEntryChanges c in repo.Diff.Compare<TreeChanges>(repo.Head.Tip?.Tree,
                                                  DiffTargets.Index))
    {
        Console.WriteLine(c);
    }
}

Return changes in index and working directory

Git

$ git diff HEAD

LibGit2Sharp

using (var repo = new Repository("path/to/your/repo"))
{
    foreach (TreeEntryChanges c in repo.Diff.Compare<TreeChanges>(repo.Head.Tip.Tree,
                                                  DiffTargets.Index | DiffTargets.WorkingDirectory))
    {
        Console.WriteLine(c);
    }
}

Return patch changes in a specific file between commits in a repository

Git

$ git diff

LibGit2Sharp

string result;
using (var repo = new Repository("path/to/your/repo"))
{
    List<Commit> CommitList = new List<Commit>();
    foreach (LogEntry entry in repo.Commits.QueryBy("relative/path/to/your/file").ToList())
        CommitList.Add(entry.Commit);
    CommitList.Add(null); // Added to show correct initial add

    int ChangeDesired = 0; // Change difference desired
    var repoDifferences = repo.Diff.Compare<Patch>((Equals(CommitList[ChangeDesired + 1], null)) ? null : CommitList[ChangeDesired + 1].Tree, (Equals(CommitList[ChangeDesired], null)) ? null : CommitList[ChangeDesired].Tree);
    PatchEntryChanges file = null;
    try { file = repoDifferences.First(e => e.Path == "relative/path/to/your/file");}
    catch {} // If the file has been renamed in the past- this search will fail
    if (!Equals(file, null))
    {
        result = file.Patch;
    }
}