我想在我的 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="Git commit %25%25h committed on %25%25cd by %25%25cn" --date=iso > "$(ProjectDir)/version.txt"" />
</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)上运行?
为了避免成为“ DenverCoder9 ”,这是一个最终的工作解决方案:
有两个选项都使用Condition
属性的力量。
选项1:
复制一个PreBuild Exec
元素,每个元素都有一个类似 Unix 的 OS 的条件和一个用于非 Unix 类似 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>
选项 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="Git commit $(AddEscapeIfWin)%25h committed on $(AddEscapeIfWin)%25cd by $(AddEscapeIfWin)%25cn" --date=iso > "$(ProjectDir)/Resources/version.txt"" />
</Target>