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

4

我想在我的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)上运行?


为了避免类似的限制,我尝试通过别名使用git命令。 - UserName
你能在Ubuntu上使用CodeTaskFactory吗?如果其他方法都无法解决问题,这更像是一个解决办法,但我以前用过它,正好不需要处理转义的问题:它允许你在msbuild文件中直接编写内联代码,在这种情况下,你可以使用Process类来启动git。 - stijn
@stijn 感谢您的建议。那是一个有趣的解决方法!我不认为我能在我的当前项目中使用它,但了解这个功能还是很酷的! - Jeroen
如果没有其他人知道正确的语法,而解决方案是根据平台有两个Exec语句,每个语句都有一个条件,那么您应该考虑在https://github.com/Microsoft/msbuild上提出此问题,因为转义规则不同并不好。 - stijn
在双引号字符串中,双倍百分号转义可能并不总是必需的。那么 <Exec Command="git log -1 --format=&quot;Git commit %25h committed on %25cd by %25cn&quot; --date=iso &gt; &quot;$(ProjectDir)/version.txt&quot;" /> 的结果是什么? - Troopers
我找到了评论1,其中解释了为什么在Windows机器上需要进行双重转义。但对于非Windows机器仍然存在相同的问题。 - Danny Van Der Sluijs
1个回答

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>

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接