1

I'm trying to create somewhat of a version tag with branch:sha1.

I've managed to get the branch name, but I can't get the last commits sha1?

It should be fairly similar to JGit for Java as its a port of it, but I can't see any way the API is exposing this?

Here is what I have:

var repository = NGit.Api.Git.Open(Directory.GetParent(System.Reflection.Assembly.GetExecutingAssembly().Location)?.Parent?.Parent?.Parent?.Parent?.FullName);
var branch = repository.GetRepository().GetBranch();
var sha1 = "";

Console.WriteLine($"{branch}:{sha1}");
shingo
  • 18,436
  • 5
  • 23
  • 42
nyxusaha
  • 49
  • 6
  • Which exact library are you using? I'd personally recommend using LibGit2Sharp - I know the NuGet package is only marked as preview, but it's been very reliable for me, and is well-used. – Jon Skeet Mar 30 '23 at 09:39
  • @JonSkeet I'm using NGit, although I'll take a look at your suggestion. – nyxusaha Mar 30 '23 at 09:40
  • https://csharp.hotexamples.com/examples/NGit.Api/Git/-/php-git-class-examples.html – Chetan Mar 30 '23 at 09:43
  • Do you mean [this package](https://www.nuget.org/packages/ngit), that was last updated in 2011? – Jon Skeet Mar 30 '23 at 09:45
  • @JonSkeet yes, I've since answered this with LibGit2Sharp as ngit seems outdated. – nyxusaha Mar 30 '23 at 09:46

1 Answers1

1

Thanks to John Skeet's comment recommending LibGit2Sharp, here is how to do it:

var directory = Directory.GetParent(System.Reflection.Assembly.GetExecutingAssembly().Location)?.Parent
    ?.Parent
    ?.Parent
    ?.Parent
    ?.FullName;

using (var repo = new Repository(directory))
{
    var branch = repo.Head.FriendlyName;
    var sha1 = repo.Head.Commits.Last().Sha;
    
    Console.WriteLine($"{branch}:{sha1}");
}
nyxusaha
  • 49
  • 6