使 MSBuild Exec 命令与 git log 跨平台工作

Jer*_*oen 4 msbuild csproj .net-core

我想在我的 ASP.NET Core 2.2 项目中执行此操作:

git log -1 --format="Git commit %h committed on %cd by %cn" --date=iso
Run Code Online (Sandbox Code Playgroud)

但随后作为预构建步骤,我将其包含在 csproj 中,如下所示:

<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>
Run Code Online (Sandbox Code Playgroud)

这适用于 Windows(如果我理解正确的话%25,它是 MSBuild 术语中的百分比,而双百分比是命令行转义,所以我们有%25%25)。它给了我这样的version.txt

Git commit abcdef12345 committed on 2019-01-25 14:48:20 +0100 by Jeroen Heijmans
Run Code Online (Sandbox Code Playgroud)

但是如果我在 Ubuntu 18.04 上执行上面的命令dotnet build,那么我会在我的version.txt

Git commit %h committed on %cd by %cn
Run Code Online (Sandbox Code Playgroud)

如何重构我的Exec元素,使其能够在 Windows(Visual Studio、Rider 或 dotnet CLI)和 Linux(Rider 或 dotnet CLI)上运行?

小智 5

为了避免成为“ DenverCoder9 ”,这里有一个最终的工作解决方案:

有两个选项都使用Condition属性的力量。

选项1:

复制该PreBuild Exec元素,每个元素具有一个适用于类 Unix 操作系统的条件和一个适用于非类 Unix 操作系统的条件。

<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>
Run Code Online (Sandbox Code Playgroud)

选项2:

将属性组添加到Directory.Build.props应用程序根级别的文件中,并在PreBuild Exec命令中使用它。

<!-- 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> 
Run Code Online (Sandbox Code Playgroud)
<!-- 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>
Run Code Online (Sandbox Code Playgroud)