Search code examples
gitgit-checkoutlibgit2libgit2sharp

LibGit2Sharp CheckoutPaths() to Revert a File without specifying a Branch


I would like to do the equivalent of git checkout -- file to discard changes in a file not yet staged for commit.

I have seen the question around how to checkout from a specific commit, however I don't want to specify any specific commit or branch.

In the following code, the parameter for commitishOrBranchSpec appears to be required, but cannot be null or an empty string; is there a value that can be specified here that indicates default, similar to the lack of specifying any branch or commit in the git command line above?

using (var repo = new Repository(workingDir))
{
    // $TODO: Figure out what to pass for parameter 1,
    // commitishOrBranchSpec (null and "" don't work)
    repo.CheckoutPaths("", Enumerable.Repeat(filePath, 1));
}

Solution

  • I have seen the question around how to checkout from a specific commit, however I don't want to specify any specific commit or branch.

    You must specify something to checkout. If you want to emulate git checkout -- file, then you can simply use the HEAD branch. For example:

    repo.checkoutPaths(repo.Head, new string[] { filePath }, checkoutOptions);