Search code examples
.net-coremsbuildcsproj

Make MSBuild Exec Command with git log work cross-platform


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=&quot;Git commit %25%25h committed on %25%25cd by %25%25cn&quot; --date=iso &gt; &quot;$(ProjectDir)/version.txt&quot;" />
</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)?


Solution

  • 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=&quot;Git commit %25%25h committed on %25%25cd by %25%25cn&quot; --date=iso &gt; &quot;$(ProjectDir)/version.txt&quot;" />
      <Exec Condition="$([MSBuild]::IsOSUnixLike())" Command="git log -1 --format=&quot;Git commit %25h committed on %25cd by %25cn&quot; --date=iso &gt; &quot;$(ProjectDir)/version.txt&quot;" />
    </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=&quot;Git commit $(AddEscapeIfWin)%25h committed on $(AddEscapeIfWin)%25cd by $(AddEscapeIfWin)%25cn&quot; --date=iso &gt; &quot;$(ProjectDir)/Resources/version.txt&quot;" />
    </Target>