C-F
C-F

Reputation: 1778

How do I control line endings conversion with LibGit2Sharp?

I am using LibGit2Sharp to access a remote Git repository. The scenario is as follows:

  1. Clone the repository from a remote URL using Repository.Clone method.
  2. Fetch from the remote repository using Commands.Fetch method.
  3. Navigate to a required commit by a tag commit = repo.Tags["myTag"].PeeledTarget as Commit;
  4. Get the commit tree tree = commit.Tree
  5. Navigate the tree and get a file blob blob = tree["my path"].Target as Blob
  6. Get file contents from the blob blob.GetContentStream()

As a result I get the file text with Unix line endings, as it is stored in the repository. But I prefer to have Windows line endings in my local copy.

I need to make Git automatically convert line endings for me, as it does with core.autocrlf config option. How do I do that with LibGit2Sharp?

Upvotes: 2

Views: 487

Answers (2)

Julien Richard
Julien Richard

Reputation: 26

I was struggling with the exact same issue.

To get the correct end of lines you need to call blob.GetContentStream(new FilteringOptions(relativePath)). The name is not really self explanatory but it will call a different function (git_blob_filtered_content_stream) that will return the content with transformed EOLs.

https://github.com/libgit2/libgit2sharp/blob/master/LibGit2Sharp/Blob.cs#L56

Upvotes: 0

VonC
VonC

Reputation: 1328212

Check if the LibGit2Sharp.Tests/BlobFixture.cs does prove that core.autocrlf is active:

    [InlineData("false", "hey there\n")]
    [InlineData("input", "hey there\n")]
    [InlineData("true", "hey there\r\n")]
    public void CanGetBlobAsFilteredText(string autocrlf, string expectedText)
    {
        SkipIfNotSupported(autocrlf);

        var path = SandboxBareTestRepo();
        using (var repo = new Repository(path))
        {
            repo.Config.Set("core.autocrlf", autocrlf);

            var blob = repo.Lookup<Blob>("a8233120f6ad708f843d861ce2b7228ec4e3dec6");

            var text = blob.GetContentText(new FilteringOptions("foo.txt"));

            Assert.Equal(expectedText, text);
        }
    }

Note though, as mentioned in libgit2/libgit2sharp issue 1195#:

notes, core.autocrlf is terrible and deprecated and should very much be avoided in favor of a properly configured .gitattributes everywhere.

The OP C-F confirms in the comments:

Apparently I have to check the type of the blob using IsBinary property and use GetContentText or GetContentStream accordingly

Upvotes: 1

Related Questions