21

In libgit2sharp https://github.com/libgit2/libgit2sharp/ how do you check for pending/uncommitted changes?

Simon
  • 33,714
  • 21
  • 133
  • 202
  • 7
    You can also have a look on the `RepositoryStatus status = repo.Index.RetrieveStatus();` method further info in the [unit tests](https://github.com/libgit2/libgit2sharp/blob/vNext/LibGit2Sharp.Tests/StatusFixture.cs) – nemesv Oct 13 '12 at 13:33
  • 1
    @nemesv this should really be an answer ... it's really good :) – Joel Martinez Feb 17 '14 at 15:51
  • 2
    It looks like repo.Index.RetrieveStatus() is deprecated in favor of repo.RetrieveStatus() – Jason Koopmans Dec 02 '14 at 19:07

3 Answers3

19

The following works for me:

///DEPRECATED - see comment from @derptastic
public bool HasUncommittedChanges
{
    get
    {
        using (var repo = new Repository(repositoryRoot))
        {
            RepositoryStatus status = repo.RetrieveStatus();
            return status.IsDirty;
        }
    }
}

Thanks to @Derptastic for the link to LibGit2Sharp Wiki

Valid
  • 767
  • 7
  • 14
  • 1
    This has given me false positives on repos where git itself doesn't find uncommitted changes, but `repo.isDirty` returns true. If you want a simple bool check for git diff (or essentially, "Do I have uncommitted changes"), from the official docs - https://github.com/libgit2/libgit2sharp/wiki/git-diff - `repo.Diff.Compare().Count > 0` – Derptastic May 12 '20 at 08:10
7

The following lines of code will provide the filename and the state of that file.

foreach (var item in repo1.RetrieveStatus())
{
  Console.WriteLine(item.FilePath);
  Console.WriteLine(item.State);
}    
user1438038
  • 5,821
  • 6
  • 60
  • 94
user5575670
  • 71
  • 1
  • 1
6

You can use repository.Diff.Compare().

    /// <summary>
    ///   Show changes between the working directory and the index.
    /// </summary>
    /// <param name = "paths">The list of paths (either files or directories) that should be compared.</param>
    /// <returns>A <see cref = "TreeChanges"/> containing the changes between the working directory and the index.</returns>
    public virtual TreeChanges Compare(IEnumerable<string> paths = null)

Passing no paths at all should give all changes.

perh
  • 1,668
  • 11
  • 14