Search code examples
c#libgit2sharp

How to execute "git reset --hard" in libgit2sharp


Libgit2sharp has a lot of potential, but some things that are very simple in regular git are an abolute mess to replicate with the library

git reset --hard

is one of them. A simple 3 word command that has no real equivalent in Libgit2sharp, since the reset command there requires at least the commit you want to reset to, something that the "real" git reset --hard automatically gathers


Solution

  • The following code replicates the regular command-line git reset --hard as closely as possible. It dynamically looks up the tracked upstream branch for which we want to reset and then finds the "base" commit at which the two branches diverge and then resets to that.

    Took me a couple of days and a lot of errors (some of them only showing up in very specific settings, when I had the upstream branch name hardcoded at first)

            {
                try {
                    using (var repo = new Repository(localRepoPath))
                    {
                        var trackedBranch = repo.Head.TrackedBranch;
    
                        Commit originHeadCommit = repo.ObjectDatabase.FindMergeBase(repo.Branches[trackedBranch.FriendlyName].Tip, repo.Head.Tip);
                        repo.Reset(LibGit2Sharp.ResetMode.Hard, originHeadCommit);
                    }       
                }catch(Exception e)
                {
                    System.Diagnostics.Trace.TraceError("Error when resetting the local GIT repo, a git pull will be attempted next: " + e.Message + " \b" + e.StackTrace);
                    return false;
                }
                return true;
            }