【问题标题】:Make MSBuild Exec Command with git log work cross-platform使用 git log 使 MSBuild Exec 命令跨平台工作
【发布时间】: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)上运行?

【问题讨论】:

  • 为了避免类似的限制,我尝试通过别名使用 git 命令。
  • 你能在 Ubuntu 上使用 CodeTaskFactory 吗?如果所有其他方法都失败了,这更像是一种解决方法,但我之前完全使用过它,而不必处理转义的事情:它允许您只在 msbuild 文件中编写内联代码,在这种情况下,您将使用 Process 类启动 git。
  • @stijn 感谢您的建议。那是....肯定是一个有趣的解决方法!不要认为我可以在我当前的特定项目中逃脱,但了解该功能仍然很酷!
  • 如果没有人知道正确的语法并且解决方案是两个 Exec 语句,每个语句都有一个根据平台的条件,你应该考虑在github.com/Microsoft/msbuild 上提出这个问题,这不好转义规则不同。
  • 在双引号字符串中,可能并不总是需要双百分号转义。那么&lt;Exec Command="git log -1 --format=&amp;quot;Git commit %25h committed on %25cd by %25cn&amp;quot; --date=iso &amp;gt; &amp;quot;$(ProjectDir)/version.txt&amp;quot;" /&gt; 的结果是什么?

标签: .net-core msbuild csproj


【解决方案1】:

为避免成为“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>

【讨论】:

    猜你喜欢
    • 2011-02-15
    • 2018-06-15
    • 2014-04-03
    • 1970-01-01
    • 2015-12-25
    • 1970-01-01
    • 1970-01-01
    • 2022-08-02
    • 2011-07-11
    相关资源
    最近更新 更多