本文介绍了如何使用LibGit2Sharp获得对Git的文件的内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

BlobFixture.cs 检查代码,发现关于阅读文件的内容,如下面一些测试。

I checked code in BlobFixture.cs and found some tests about reading file's contents like below.

using (var repo = new Repository(BareTestRepoPath))
{
    var blob = repo.Lookup<Blob>("a8233120f6ad708f843d861ce2b7228ec4e3dec6");

    var contentStream = blob.GetContentStream();
    Assert.Equal(blob.Size, contentStream.Length);

    using (var tr = new StreamReader(contentStream, Encoding.UTF8))
    {
        string content = tr.ReadToEnd();
        Assert.Equal("hey there\n", content);
    }
}



但我不能找到获得文件的内容基于一个测试在文件的名称。是否有可能做到这一点,如果又如何?

But I cannot find a test that getting file's contents based on file's name. Is it possible to do that, if so how?

推荐答案

每个持有 TreeEntry 的集合。 A TreeEntry 保存有关指着 GitObject 一些元数据(名称,模式,OID,...)。在 GitObject 可以通过 TreeEntry 目标属性来访问>实例。

Each Tree holds a collection of TreeEntry. A TreeEntry holds some metadata (name, mode, oid, ...) about a pointed at GitObject. The GitObject can be accessed through the Target property of a TreeEntry instance.

在大多数情况下,一个 TreeEntry 将指向斑点或其他

Most of the time, a TreeEntry will point to a Blob or another Tree.

类型公开它接受的路径,轻松检索最终指向 TreeEntry 索引器。作为一个方便的方法,在提交暴露出这样一个索引为好。

The Tree type exposes an indexer which accepts a path to easily retrieve the finally pointed at TreeEntry. As a convenience method, the Commit exposes such an indexer as well.

这样的代码可以表达这种方式

Thus your code could be expressed this way.

using (var repo = new Repository(BareTestRepoPath))
{
    var commit = repo.Lookup<Commit>("deadbeefcafe"); // or any other way to retreive a specific commit
    var treeEntry = commit["path/to/my/file.txt");

    Debug.Assert(treeEntry.TargetType == TreeEntryTargetType.Blob);
    var blob = (Blob)treeEntry.Target;

    var contentStream = blob.GetContentStream();
    Assert.Equal(blob.Size, contentStream.Length);

    using (var tr = new StreamReader(contentStream, Encoding.UTF8))
    {
        string content = tr.ReadToEnd();
        Assert.Equal("hey there\n", content);
    }
}

这篇关于如何使用LibGit2Sharp获得对Git的文件的内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-14 06:51