Read the files at the spesific commit with libgit2sharp

江枫思渺然 提交于 2019-12-12 06:14:16

问题


There is a bare repository, I have a commit id, and want to read all the files at that commit without cloning.

This repository.Lookup<Tree>(repository.Commits.First().Tree.Sha) code give me only the files that are in the commit but I want also other files that exists at that level.

How to do that?


回答1:


My understanding of your question is that you're willing to access the whole content of a commit, not only the first level of the commit. The code below will work against a bare (or a standard) repository and will allow one to recursively access and examine the content of a commit.

In order to make it easier for you to test drive it, it dumps information (git object meta data along with blob content) in the console output.

RecursivelyDumpTreeContent(repo, "", commit.Tree);

[...]

private void RecursivelyDumpTreeContent(IRepository repo, string prefix, Tree tree)
{
    foreach (var treeEntry in tree)
    {
        var path = prefix + treeEntry.Name;
        var gitObject = treeEntry.Target;

        var meta = repo.ObjectDatabase.RetrieveObjectMetadata(gitObject.Id);
        Console.WriteLine("{0}\t{1}\t{2}\t{3}\t{4}", gitObject.Id, treeEntry.Mode, treeEntry.TargetType, meta.Size, path);

        if (treeEntry.TargetType == TreeEntryTargetType.Tree)
        {
            RecursivelyDumpTreeContent(repo, path + "/", (Tree)gitObject);
        }

        if (treeEntry.TargetType == TreeEntryTargetType.Blob)
        {
            Console.WriteLine((((Blob)gitObject).GetContentText()));
        }
    }
}

Would you precisely know the path of a specific file you'd like to access, use the indexer exposed by the Commit type in order to directly access the GitObject you're after.

For instance:

var blob = commit["path/to/my/file.txt"].Target as Blob;


来源:https://stackoverflow.com/questions/30277093/read-the-files-at-the-spesific-commit-with-libgit2sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!