使用libgit2sharp

时间:2018-11-12 14:38:02

标签: c# git f# libgit2 libgit2sharp

使用git show,我可以从特定提交中获取特定文件的内容,而无需更改本地克隆的状态

$ git show <file>
$ git show <commit>:<file>

如何使用以编程方式实现这一目标?

2 个答案:

答案 0 :(得分:4)

根据documentation

$ git show 807736c691865a8f03c6f433d90db16d2ac7a005:a.txt

等效于以下代码:

using System;
using System.IO;
using System.Linq;
using System.Text;
using LibGit2Sharp;

namespace ConsoleApp2
{
    class Program
    {
        static void Main(string[] args)
        {
            var pathToFile = "a.txt";
            var commitSha = "807736c691865a8f03c6f433d90db16d2ac7a005";
            var repoPath = @"path/to/repo";

            using (var repo =
                new Repository(repoPath))
            {
                var commit = repo.Commits.Single(c => c.Sha == commitSha);
                var file =  commit[pathToFile];

                var blob = file.Target as Blob;
                using (var content = new StreamReader(blob.GetContentStream(), Encoding.UTF8))
                {
                    var fileContent = content.ReadToEnd();
                    Console.WriteLine(fileContent);
                }
            }
        }
    }
}

答案 1 :(得分:0)

作为null令牌says in the commentsLookup<T>() can use冒号路径规范语法。

using (var repo = new Repository(repoPath))
{
    // This line is the change from Andrzej Gis
    var blob = repo.Lookup<Blob>(commitSha + ":" + path);

    using (var content = new StreamReader(blob.GetContentStream(), Encoding.UTF8))
    {
        var fileContent = content.ReadToEnd();
        Console.WriteLine(fileContent);
    }
}