问题
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