How to use Ls-Remote in NGit

373 views Asked by At

I am looking to do the following using NGit, but after nearly a full day am completely lost:

  • Create an empty repo
  • Add a remote "origin" using a URL and credentials
  • Run Ls-Remote to get the latest hashes of the master branch on origin

If anyone could show me an example of this in action I'd greatly appreciate it

1

There are 1 answers

2
linquize On BEST ANSWER
using System.Collections.Generic;
using System.Linq;
using NGit.Api;
using Sharpen;

// git init
string path = @"C:\git\repo1";
Git git = Git.Init().SetDirectory(new FilePath(path)).Call();
// after init, you can call the below line to open
// Git git = Git.Open(new FilePath(path));

// git remote origin
StoredConfig config = git.GetRepository().GetConfig();
config.SetString("remote", "origin", "url", @"http://user:[email protected]/user/repo1.git");
config.Save();

// git ls-remote
ICollection<Ref> refs = git.LsRemote().SetRemote("origin").Call();
Ref master = refs.FirstOrDefault(a => a.GetName() == "refs/heads/master");
if (master != null)
{
    string hash = master.GetObjectId().Name;
}