Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get file binary data out of Git repository using LibGit2Sharp?

I have decided to try and migrate my project from using GitSharp to LibGit2Sharp since GitSharp is no longer actively maintained. With GitSharp I was able to access the raw bytes of any file checked into my repo given a branch. I cannot locate any documentation or example code of how this is done using LibGit2Sharp.

Can someone give me and example of how this is done?

like image 899
Nick Avatar asked Jan 27 '12 18:01

Nick


People also ask

Can Git store binary files?

Git LFS is a Git extension used to manage large files and binary files in a separate Git repository. Most projects today have both code and binary assets. And storing large binary files in Git repositories can be a bottleneck for Git users. That's why some Git users add Git Large File Storage (LFS).

How do I remove a binary file from a git repository?

You can do this by getting your local repository in order using the git rebase command, then using the git push --force command to overwrite the server repository with your local repository.

How do I delete large binary files in git?

If the large file was added in the most recent commit, you can just run: git rm --cached <filename> to remove the large file, then. git commit --amend -C HEAD to edit the commit.


1 Answers

The Blob type exposes a Content property that returns a byte[].

The following test in extracted from the BlobFixture.cs file and demonstrates usage of this property.

[Test]
public void CanReadBlobContent()
{
    using (var repo = new Repository(BareTestRepoPath))
    {
        var blob = repo.Lookup<Blob>("a8233120f6ad708f843d861ce2b7228ec4e3dec6");
        byte[] bytes = blob.Content;
        bytes.Length.ShouldEqual(10);

        string content = Encoding.UTF8.GetString(bytes);
        content.ShouldEqual("hey there\n");
    }
}

In this particular test, the Blob GitObject is directly retrieved through the LookUp() method. You can also access Blobs from the Files property of a Tree.

Regarding your more specific request, the following unit test should show you how to access the raw bytes of a Blob from the tip of a Branch.

[Test]
public void CanRetrieveABlobContentFromTheTipOfABranch()
{
    using (var repo = new Repository(BareTestRepoPath))
    {
        Branch branch = repo.Branches["br2"];
        Commit tip = branch.Tip;
        Blob blob = (Blob)tip["README"].Target;
        byte[] content = blob.Content;

        content.Length.ShouldEqual(10);
    }
}

Note: This test shows another way of accessing a Blob (as an abstract TreeEntry). Thus, the use of the cast.

like image 52
nulltoken Avatar answered Oct 11 '22 06:10

nulltoken