9

I have a question about passing the branch name to my code as a string.

So we are using a git repository and the branch number also refers to the staging environment where the build is placed. Meaning, if my branch is 001, my url is 001.test.myapplication.com.

I am writing automated tests which are executed on the staging environment of the branch. My question is, is it possible to pass the branch number to my code so I can make it part of the URL I want to test on?

I am using visual studio 2017, selenium and specflow.

Andreas Willich
  • 5,665
  • 3
  • 15
  • 22
Anand
  • 1,899
  • 1
  • 13
  • 23

3 Answers3

27

I actually found a great solution which perfectly works. Sharing so in the future, others can use it too if they need to.

ProcessStartInfo startInfo = new ProcessStartInfo("git.exe");

startInfo.UseShellExecute = false;
startInfo.WorkingDirectory = "dir Here";
startInfo.RedirectStandardInput = true;
startInfo.RedirectStandardOutput = true;
startInfo.Arguments = "rev-parse --abbrev-ref HEAD";

Process process = new Process();
process.StartInfo = startInfo;
process.Start();

string branchname = process.StandardOutput.ReadLine();
Gangula
  • 5,193
  • 4
  • 30
  • 59
Anand
  • 1,899
  • 1
  • 13
  • 23
1

The usual way to do this is to generate a C# file containing this information as part of your build step.

There are already several good answers here:

Embed git commit hash in a .Net dll

Kristof
  • 104
  • 4
1

The git command in the earlier answer didn't work for me anymore in 2022. I use the following pre-build event in Visual Studio project properties:

git.exe branch --show-current > "$(ProjectDir)\Properties\BuildDate.txt"
echo %date% %time% >> "$(ProjectDir)\Properties\BuildDate.txt"

Define BuildDate.txt as an imported resource in the project's resource file, then use it like a regular resource string at runtime.

Chris Wendt
  • 539
  • 3
  • 6