MSBuild 目标检测跳过构建

MSBuild Target Detecting skipped build

当 MS build 构建解决方案时,它会跳过最新的项目。有没有办法在后续目标中检测到这一点,以避免做额外的不必要的工作?

案例示例是我的项目之一是在针对 AfterBuild 目标的构建过程之后创建 NuGet 包。如果跳过构建,那么我们可以得出不需要替换 Nuget 包的结论。

我试过 AfterBuild 和 CoreCompile

 <Target Name="DebugProps" AfterTargets="CoreCompile">
        <Message Importance="high" Text="Current Saved Properties are:"/>

日志文件输出:

 CoreCompile:
       Skipping target "CoreCompile" because all output files are up-to-date with respect to the input files.
       DebugProps:
         Current Saved Properties are:

我认为你可以在 msbuild 上使用 Inputs and outputs

试试这个:

  <Target Name="test123" BeforeTargets="CoreCompile">
        <ItemGroup>
            <File Include="$(TargetPath)"></File>
        </ItemGroup>
        <Copy SourceFiles="@(File)" DestinationFolder="$(SolutionDir)"></Copy>
        <Message Importance="high" Text="$(TargetName)"></Message>
  </Target>

  <Target Name="DebugProps" AfterTargets="Build" Inputs="$(TargetPath)" Outputs="$(SolutionDir)$(TargetFileName)">
        <Message Importance="high" Text="Current Saved Properties are:"/>
        
  </Target>

我找到了解决这个问题最有效的方法,就是将一个名为 TargetsTriggeredByCompilation 的特殊 属性 分配给您希望在核心编译完成后调用的目标。

增量构建跳过了核心编译,因此我在构建开始时将 属性 SkipPostBuildActions 设置为 true。然后将其进一步用作我希望以核心编译为条件的任何目标的条件。

一旦核心编译完成,它会触发我的EnablePostBuild目标,这个目标实习生将SkipPostBuildActions设置为false。然后启用后续构建目标。

<!-- Defines Targets that should be run after Compile, but skipped if Compile doesn't take place -->
<PropertyGroup>
    <TargetsTriggeredByCompilation>
        $(TargetsTriggeredByCompilation);
        EnablePostBuild
    </TargetsTriggeredByCompilation>
</PropertyGroup>
<Target Name="EnablePostBuild">
    <!-- Disable post build actions  -->
    <PropertyGroup>
        <SkipPostBuildActions>false</SkipPostBuildActions>
    </PropertyGroup>
</Target>

'$(SkipPostBuildActions)' == 'false' 用于 NugetProject 目标的示例:

    <!-- Creating Nuget Packages -->
    <Target Name="NugetProject" AfterTargets="PostBuild" Condition="'$(NugetProject)' == 'true' And '$(SkipPostBuildActions)' == 'false'" DependsOnTargets="GetVersion">

        <!-- Manages getting the assembly version for output folders -->
        <Message Importance="High" Text="Current Assembly Version  $(GitVersion_NuGetVersion)"/>

        <!-- Note the Exec Task needs to provide a path relative to current Project that is building -->
        <Exec Command="$(ToolsPath)NuGet.exe pack  -Version $(VersionStamp) -Symbols -SymbolPackageFormat snupkg -IncludeReferencedProjects -OutputDirectory $(LocalMachineNugetPath) -Verbosity detailed -Properties Configuration=$(Configuration)"/>
    </Target>

TargetsTriggeredByCompilation 由目标图内部深处的调用目标触发,该目标图是通过默认构建引入的。