Programmatically detects the current git branch extracted from C # code

Is it possible during build through C # to determine which branch that passed validation is in the git repository? If so, how?

Ultimately, when on the main git branch, I want my connection string in my web.config file to point to the production server, and I want my development branch to always point to the development server. I can set the git flag in the file with -assumed-unchanged, but ... it cannot be assumed that the web.config file will not change, because there are many other legitimate changes in the project that can cause the configuration of the file to change, and we would like to so that these changes are tracked in the repo. We do not want to update the index or change this git flag every time this happens. AlsoI have seen other solutions that modify assembly-based web.config file using transforms. However, this is not a viable solution, since I want ALL assemblies (debugging and release) to always point to the same server on each branch. The only time a configuration file should have a connection string pointing to another server is based on the branch that is currently checked.

So the idea is here: if we can DETECT through C # code that the git branch is currently being checked, then we could build time to change the connection string using the System.Configuration and System.Web.Configuration namespaces . If possible, this opens up a world of opportunities for smoother management of the branch workflow as to which servers it points to, without losing traces of other important changes made to the configuration file.

If we can figure out a way to implement this, then anyone who clones or modifies my repository will automatically set this default setting.

Again, this may not even be possible, but I thank someone in advance who could figure out how to do this in C #

+4
2

ngit - JGit #:

https://github.com/mono/ngit

, , JGit:

new FileRepository (some dir).getBranch ()

NGit, , #.

+4

LibGit2Sharp, a.Net libgit2:

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
}
+2

Source: https://habr.com/ru/post/1531834/


All Articles