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?
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?
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);
}
}
}
}
}
var b = repo.Lookup<Blob>("807736c691865a8f03c6f433d90db16d2ac7a005:a.txt");
:-/ –
Nahshunn As nulltoken says in the comments, Lookup<T>()
can use colon-pathspec syntax.
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);
}
}
The tagged line is the change from Andrzej Gis's answer. It replaces the commit =
, file =
, and blob =
lines. Also, commitSha
can be any refspec: v3.17.0
, HEAD
, origin/master
, etc.
© 2022 - 2024 — McMap. All rights reserved.
Lookup<T>()
method which accepts an extended sha1 syntax:var c = repo.Lookup<Commit>("807736c691865a8f03c6f433d90db16d2ac7a005:a.txt");
(cf. github.com/libgit2/libgit2sharp/blob/…). Note: This won't "download" from the remote, but will harvest the local git repository (asgit show
does) – Nahshunn