My current client is using a micro services architecture. As such they have a lot of Git repositories.
We needed a script to clone them all, switch to a branch, and produce a report of which services are used by other services.
In order to do this we've written some LinqPad scripts using LibGit2Sharp. We soon hit a problem as our Git server requires authentication and obviously we didn’t want to hard code user credentials into a script.
We're using the latest version Git, so we already have Microsoft's Git Credential Manager for Windows installed. It's securely storing our Git credentials, but how do we access them from C# code?
The solution
It turns out it's easy to do, but not very well documented.
Microsoft recently published the Git Credential Manager client on NuGet. You can grab it here:
PM> Install-Package Microsoft.Alm.Authentication
You'll also need LibGit2Sharp:
PM> Install-Package Install-Package LibGit2Sharp -Pre
Note:
There seems to be an issue with the latest version of LibGit2Sharp (0.22.0 at time of writing) and LinqPad / Visual Studio.
I found 0.21.0.176 works with LinqPad and the latest 0.23.0 pre release works in Visual Studio.
Once you have those packages installed, this C# code snippet is all you need:
var secrets = new SecretStore("git");
var auth = new BasicAuthentication(secrets);
var creds = auth.GetCredentials(new TargetUri("https://github.com"));
var options = new CloneOptions
{
CredentialsProvider = (_url, _user, _cred) => new UsernamePasswordCredentials
{
Username = creds.Username,
Password = creds.Password
},
};
Repository.Clone("https://github.com/kevinkuszyk/private-repro.git", @"c:\projects", options);