While building the C# project locally/CI server, I wanted to control the NuGet package reference in the .csproj file. If the developer is building a C# project on github master branch (locally/CI server) I would like to add RC build NuGet package reference otherwise PRE releases NuGet package reference. How to do this? Can someone please assist me?
Some thoughts like -
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
<GitBranch>$(GitBranch.Trim())</GitBranch>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="GitInfo" Version="2.2.0" />
</ItemGroup>
<Choose>
<When Condition="$(GitBranch) == 'master'">
<ItemGroup>
<PackageReference Include="Data.Account.Domain.Messaging" Version="1.0.0-rc*" IncludePrerelease="true" />
</ItemGroup>
</When>
<Otherwise>
<ItemGroup>
<PackageReference Include="Data.Account.Domain.Messaging" Version="1.0.0-pre*" IncludePrerelease="true" />
</ItemGroup>
</Otherwise>
</Choose>
</Project>
CodePudding user response:
You could read the git branch from the .git/HEAD file. Naive implementation like
<PropertyGroup>
<GitBranch>$([System.IO.File]::ReadAlltext('$(MsBuildThisFileDirectory)\.git\HEAD').Replace('ref: refs/heads/', '').Trim())</GitBranch>
</PropertyGroup>
You might want to adjust how you get the path to that file, and perhaps use something more robust (e.g. if you just checkout a random commit in git, the file won't contain a branch name but a commit SHA)