Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Download one file from remote (git show) 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?

like image 726
sdgfsdh Avatar asked Nov 12 '18 14:11

sdgfsdh


People also ask

Can I download a single file from git?

If it's just a single file, you can go to your GitHub repo, find the file in question, click on it, and then click “View Raw”, “Download” or similar to obtain a raw/downloaded copy of the file and then manually transfer it to your target server.

How to remove file from git status?

The easiest way to delete a file in your Git repository is to execute the “git rm” command and to specify the file to be deleted. Note that by using the “git rm” command, the file will also be deleted from the filesystem.


1 Answers

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);
                }
            }
        }
    }
}
like image 140
Andrzej Gis Avatar answered Oct 05 '22 14:10

Andrzej Gis