Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

programmatically detect current git branch checked out from C# code

Is it possible to determine at build time through C# code what the currently checked out branch is within a git repository? If so how?

Ultimately, when on the master git branch, I want my connection string within my web.config file to point to the production server and I want my develop branch to always point to the development server. I could set a git flag on the file with the --assumed-unchanged, but... one should not assume a web.config file will be unchanged because there are many other legitimate changes to a project that can cause the config file to change and we WOULD want those changes to get tracked in the repo. We don't want to have to update the index or toggle this git flag each time this occurs. Also I've seen other solutions that alter the web.config file based on the build using transformations However this is not a viable solution either since I want ALL builds (debug and release) to always point to the same server per a given branch. The only time the config file should have it's connection string pointing to a different server is based on the branch that is currently checked out on.

So the idea here is, if we can DETECT through C# code what git branch is currently checked out then we could at build time modify the connnection string using the System.Configuration and System.Web.Configuration namespaces. If this is possible then it opens up a world of possibilities to better more seamlessly manage the workflow of branches with regards to which servers it points to while not losing track of other important changes made to the config file.

If we can figure out a way to implement this, then anyone who clones or forks my repository will automatically acquire this configuration setup by default.

Again this might not even be possible, but I thank anyone in advance who might have insight on how to accomplish this in C#

like image 799
glthomas Avatar asked Mar 14 '14 18:03

glthomas


Video Answer


2 Answers

ngit is a port of JGit to C#:

https://github.com/mono/ngit

You can do what you desire with JGit:

new FileRepository (some dir).getBranch ()

and those methods exist in NGit, so I'd imagine that you can do the same in C#.

like image 197
user3392484 Avatar answered Oct 20 '22 18:10

user3392484


Using LibGit2Sharp, a.Net binding to the libgit2 project:

using (var repo = new Repository("path/to/your/local/repo"))
{
   Branch checkedOutBranch = repo.Head;
   Console.WriteLine(checkedOutBranch.CanonicalName); // "refs/heads/master" for instance
   Console.WriteLine(checkedOutBranch.Name);          // "master" for instance
}
like image 24
nulltoken Avatar answered Oct 20 '22 16:10

nulltoken