Warm tip: This article is reproduced from serverfault.com, please click

.net core-使用 git log 使 MSBuild Exec 命令跨平台工作

(.net core - Make MSBuild Exec Command with git log work cross-platform)

发布于 2019-01-25 15:28:38

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

git log -1 --format="Git commit %h committed on %cd by %cn" --date=iso

但是作为预构建步骤,我将它包含在 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>

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

Git commit abcdef12345 committed on 2019-01-25 14:48:20 +0100 by Jeroen Heijmans

但是,如果我在 Ubuntu 18.04 上执行上述dotnet build操作,那么我会在我的version.txt

Git commit %h committed on %cd by %cn

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

Questioner
Jeroen
Viewed
0
Danny Van Der Sluijs 2021-10-14 03:06:14

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

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

选项1:

复制一个PreBuild Exec元素,每个元素都有一个类似 Unix 的 OS 的条件和一个用于非 Unix 类似 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>

选项 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> 
<!-- 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>