Introduction to Git operations with C#
Sometimes we may need to accomplish some git related operations using .NET. It can be a console application or another service. Regardless of the application type that we are using, we may need to do some git operations from basic level to some advanced level. In this situation, LibGit2Sharp library can be your savior for git operations with C#. This C# library was developed on top of libgit2.
Getting started
Here, I’m going to build a simple console application to perform some basic Git operations with C# .NET like clone a repository, modify a file, commit and push to the remote repository. First, we need to install the LibGit2Sharp nuget package into our project.
using the below command or using nuget package manager, we can install the package.
Install-Package LibGit2Sharp
Clone a repository
As the first operation, we are going to clone a remote repository programmatically. To access the remote repository we need the credentials. Here, I’m passing git username and token to the method along with the repo URL. Then using the static method Clone in Repository class, we can clone the remote repo to our local file system.
private (string path, string branch) CloneRepository(string gitUserName, string gitToken, string repoUrl)
{
try
{
var options = new CloneOptions
{
CredentialsProvider = (_url, _user, _cred) => new UsernamePasswordCredentials
{
Username = gitUserName,
Password = gitToken
},
};
var path = DateTime.Now.ToString("yyyyMMddHHmmss");
path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory + $"Git_{path}");
Console.WriteLine($"Cloning repository to: {path}");
Repository.Clone(repoUrl, path, options);
var branchName = $"Test_Branch_{DateTime.Now.ToString("yyyyMMddHHmmss")}";
using (var repo = new Repository(path))
{
Branch branch = repo.CreateBranch(branchName);
Branch currentBranch = Commands.Checkout(repo, branch);
Console.WriteLine($"Branch created!");
}
return new (path, branchName);
}
catch (Exception ex)
{
Console.WriteLine("Error occured during repository cloning!" + ex.Message);
throw;
}
}
We create a new Repository object and call the create branch method to create a new branch to do our modifications. Now we can do the changes to the files whatever we need once the Clone operation completed.
Commit and Push
Once the modifications to the files completed, we can call the Commit and Push methods. Here, we are passing git credentials again and in addition to that we need to pass the path and branch name to this method.
private string CommitAndPushChanges(string gitUserName, string gitToken, string email, string basePath, string branch)
{
try
{
using (var repo = new Repository(basePath))
{
RepositoryStatus status = repo.RetrieveStatus();
var filePaths = status.Modified.Select(mods => mods.FilePath).ToList();
foreach (var file in filePaths)
{
repo.Index.Add(file);
repo.Index.Write();
}
var signature = new Signature(gitUserName, email, DateTimeOffset.Now);
repo.Commit($"{branch} - These are my changes", signature, signature);
var remote = repo.Network.Remotes["origin"];
var options = new PushOptions
{
CredentialsProvider = (_url, _user, _cred) => new UsernamePasswordCredentials
{
Username = gitUserName,
Password = gitToken
},
};
var pushRefSpec = $"refs/heads/{branch}";
repo.Network.Push(remote, pushRefSpec, options); //Push changes to the remote repository
return branch;
}
}
catch (Exception)
{
Console.WriteLine("Error occured during pushing the changes!");
Console.WriteLine("Please manually commit and push the changes!");
throw;
}
}
First we check the git status of the branch and add the modified files to the index. Then commit with a comment and finally pushing the committed changes to the remote repository.
Whats more…
In addition to these simple operations, this library provides many other useful and sophisticated functions such as git add, git diff. You can find more info here.