使用 libgit2sharp 从远程下载一个文件(git 显示)

Download one file from remote (git show) using libgit2sharp

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

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

如何使用 以编程方式实现此目的?

根据 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);
                }
            }
        }
    }
}

作为 nulltoken , Lookup<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);
    }
}