I want to do this in my ASP.NET Core 2.2 project:
git log -1 --format="Git commit %h committed on %cd by %cn" --date=iso
But then as a prebuild step I included it in the csproj like this:
<Target Name="PreBuild" BeforeTargets="PreBuildEvent">
<Exec Command="git log -1 --format="Git commit %25%25h committed on %25%25cd by %25%25cn" --date=iso > "$(ProjectDir)/version.txt"" />
</Target>
This works on Windows (if I understand correctly %25
is a percent in MSBuild terms, and the double percent is a command line escape, so we have %25%25
). It gives me this kind of version.txt
:
Git commit abcdef12345 committed on 2019-01-25 14:48:20 +0100 by Jeroen Heijmans
But if I execute the above with dotnet build
on Ubuntu 18.04, then I get this in my version.txt
:
Git commit %h committed on %cd by %cn
How can I restructure my Exec
element in a way that it runs on both Windows (Visual Studio, Rider, or dotnet CLI) and Linux (Rider, or dotnet CLI)?
To avoid being "DenverCoder9" here is a final working solution:
There are two options both using the power of the Condition
attribute.
Option 1:
Duplicate the PreBuild Exec
element each with a condition for Unix like OS and one for non Unix like OS.
<Target Name="PreBuild" BeforeTargets="PreBuildEvent">
<Exec Condition="!$([MSBuild]::IsOSUnixLike())" Command="git log -1 --format="Git commit %25%25h committed on %25%25cd by %25%25cn" --date=iso > "$(ProjectDir)/version.txt"" />
<Exec Condition="$([MSBuild]::IsOSUnixLike())" Command="git log -1 --format="Git commit %25h committed on %25cd by %25cn" --date=iso > "$(ProjectDir)/version.txt"" />
</Target>
Option 2:
Add a property group to the Directory.Build.props
file at the root level of you application and use it in your PreBuild Exec
command.
<!-- file: Directory.Build.props -->
<Project>
<!-- Adds batch file escape character for targets using Exec command when run on Windows -->
<PropertyGroup Condition="!$([MSBuild]::IsOSUnixLike())">
<AddEscapeIfWin>%25</AddEscapeIfWin>
</PropertyGroup>
</Project>
<!-- Use in *.csproj -->
<Target Name="PreBuild" BeforeTargets="PreBuildEvent">
<Exec Command="git log -1 --format="Git commit $(AddEscapeIfWin)%25h committed on $(AddEscapeIfWin)%25cd by $(AddEscapeIfWin)%25cn" --date=iso > "$(ProjectDir)/Resources/version.txt"" />
</Target>