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?
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.