I am trying to write a basic C# GIT function that commits and pushes a local working directory to its master repository. This is my first attempt at using GIT, and I am still trying to get my head around some of the basics.
Here is my code. It's not very complex, all it needs to do is make sure that the repository is updated with any changes from my working directory. It works, but with a caveat as described below
public void Sync()
{
using (var repo = new Repository(@"C:\Temp\Git\test"))
{
repo.Stage("*");
repo.Commit("This is my comment");
Remote remote = repo.Network.Remotes["origin"];
var options = new PushOptions();
options.CredentialsProvider = new CredentialsHandler(
(url, usernameFromUrl, types) =>
new UsernamePasswordCredentials()
{
Username = "myusername",
Password = "mypassword"
});
var pushRefSpec = @"refs/heads/master";
repo.Network.Push(remote, pushRefSpec, options, null, "push done...");
}
}
The problem I am facing is this. If I add or modify any files then they are updated accordingly in the repository. However if there are no files that need to be committed then the following exception is raised:
No changes; nothing to commit
What I would like to be able to do is determine if files need to be committed before attempting the commit operation, therefore being able to exit gracefully if nothing needs to be done. I.E something along the lines of:
if (there are files to commit)
{
repo.Commit("This is my comment");
}
Does anyone know how to achieve this?
As mentioned, this is my first attempt with GIT, so if there are better standards than my code above I would be very grateful if for any kind of advice.
Many thanks and best regards
It looks like you can use the Repository.RetrieveStatus() method to see if there are files that need to be committed:
RepositoryStatus status = repo.RetrieveStatus();
if (status.IsDirty)
{
// Stage, commit, and push your changes
}
If you're using Git on the command line (which seems like it could be a worthwhile exercise if you haven't used Git much the past), this looks to be equivalent to the git status command - it shows you files that have been modified, files that are staged for commit, and files that aren't currently tracked.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With