Download one file from remote (git show) using libgit2sharp

本小妞迷上赌 提交于 2019-12-12 10:44:11

问题


Using git show, I can fetch the contents of a particular file from a particular commit, without changing the state of my local clone:

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

How can I achieve this programatically using libgit2sharp?


回答1:


According to the documentation:

$ git show 807736c691865a8f03c6f433d90db16d2ac7a005:a.txt

Is equivalent to the code below:

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



回答2:


As nulltoken says in the comments, Lookup<T>() can use colon-pathspec syntax.

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


来源:https://stackoverflow.com/questions/53264430/download-one-file-from-remote-git-show-using-libgit2sharp

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