Download one file from remote (git show) using libgit2sharp
Asked Answered
W

2

6

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 ?

Wait answered 12/11, 2018 at 14:38 Comment(0)
S
10

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);
                }
            }
        }
    }
}
Selfpossessed answered 12/11, 2018 at 15:24 Comment(2)
Or you could leverage the 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 (as git show does)Nahshunn
Sorry, that would be var b = repo.Lookup<Blob>("807736c691865a8f03c6f433d90db16d2ac7a005:a.txt"); :-/Nahshunn
E
0

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.

Emmen answered 19/11, 2019 at 17:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.