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

5jdjgkvh  于 2023-02-18  发布在  Git
关注(0)|答案(2)|浏览(139)

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

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

如何使用libgit2sharp编程实现这一点?

s71maibg

s71maibg1#

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

h43kikqp2#

正如nulltoken在注解中所说,Lookup<T>()可以使用colon-pathspec语法。

using (var repo = new Repository(repoPath))
{
    // The line below is the important one.
    var blob = repo.Lookup<Blob>(commitSha + ":" + path);

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

标记线是Andrzej Gis's answer的更改。它替换commit =file =blob =线。此外,commitSha可以是任何refspec:v3.17.0HEADorigin/master等等。

相关问题