<!--
***********************************************************************************************
Microsoft.NET.PackTool.targets

WARNING:  DO NOT MODIFY this file unless you are knowledgeable about MSBuild and have
          created a backup copy.  Incorrect changes to this file will make it
          impossible to load or build your projects from the command-line or the IDE.

Copyright (c) .NET Foundation. All rights reserved.
***********************************************************************************************
-->

<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <UsingTask TaskName="Microsoft.NET.Build.Tasks.GenerateToolsSettingsFile"
            AssemblyFile="$(MicrosoftNETBuildTasksAssembly)" />
  <UsingTask TaskName="Microsoft.NET.Build.Tasks.GenerateShims"
            AssemblyFile="$(MicrosoftNETBuildTasksAssembly)" />
  <UsingTask TaskName="Microsoft.NET.Build.Tasks.ResolveToolPackagePaths"
            AssemblyFile="$(MicrosoftNETBuildTasksAssembly)" />
  <UsingTask TaskName="Microsoft.NET.Build.Tasks.GetEmbeddedApphostPaths"
      AssemblyFile="$(MicrosoftNETBuildTasksAssembly)" />
  <UsingTask TaskName="Microsoft.NET.Build.Tasks.GetNuGetShortFolderName"
             AssemblyFile="$(MicrosoftNETBuildTasksAssembly)" />

  <!--
    Mark all dependency as private assets. But keep them as Publish. So dependency DLLs will be included in NuGet package, while
    there is no dependency in nuspec. And add Microsoft.NETCore.Platforms, which is used to select correct RID assets.
    -->
  <PropertyGroup>
    <_ToolsSettingsFilePath>$(BaseIntermediateOutputPath)DotnetToolSettings.xml</_ToolsSettingsFilePath>
    <SuppressDependenciesWhenPacking Condition=" '$(PackAsTool)' == 'true' ">true</SuppressDependenciesWhenPacking>
    <_PackToolPublishDependency Condition=" ('$(GeneratePackageOnBuild)' != 'true' and '$(NoBuild)' != 'true') and $(IsPublishable) == 'true' ">_PublishBuildAlternative</_PackToolPublishDependency>
    <_PackToolPublishDependency Condition=" ('$(GeneratePackageOnBuild)' == 'true' or '$(NoBuild)' == 'true') and $(IsPublishable) == 'true' ">$(_PublishNoBuildAlternativeDependsOn)</_PackToolPublishDependency>
  </PropertyGroup>

  <Target Name="PackTool" DependsOnTargets="GenerateToolsSettingsFileFromBuildProperty;$(_PackToolPublishDependency);_PackToolValidation" Condition=" '$(PackAsTool)' == 'true' ">
    <ItemGroup>
      <_GeneratedFiles Include="$(PublishDepsFilePath)" Condition="'$(GenerateDependencyFile)' != 'true' or '$(_UseBuildDependencyFile)' == 'true'" />
      <_GeneratedFiles Include="$(PublishRuntimeConfigFilePath)"/>
      <_GeneratedFiles Include="$(_ToolsSettingsFilePath)"/>
    </ItemGroup>

    <ResolveToolPackagePaths
      AppHostIntermediatePath="$(AppHostIntermediatePath)"
      ResolvedFileToPublish="@(ResolvedFileToPublish)"
      PublishDir="$(PublishDir)"
      TargetFrameworkMoniker="$(TargetFrameworkMoniker)"
      TargetPlatformMoniker="$(TargetPlatformMoniker)">

      <Output TaskParameter="ResolvedFileToPublishWithPackagePath" ItemName="_ResolvedFileToPublishWithPackagePath" />
    </ResolveToolPackagePaths>

    <ItemGroup>
      <TfmSpecificPackageFile Include="@(_GeneratedFiles)">
        <PackagePath>tools/$(_NuGetShortFolderName)/any/%(_GeneratedFiles.RecursiveDir)%(_GeneratedFiles.Filename)%(_GeneratedFiles.Extension)</PackagePath>
      </TfmSpecificPackageFile>

      <TfmSpecificPackageFile Include="@(_ResolvedFileToPublishWithPackagePath)">
        <PackagePath>%(_ResolvedFileToPublishWithPackagePath.PackagePath)</PackagePath>
      </TfmSpecificPackageFile>
    </ItemGroup>
  </Target>

  <PropertyGroup>
    <ToolCommandName Condition=" '$(ToolCommandName)' == '' ">$(TargetName)</ToolCommandName>
    <ToolEntryPoint Condition=" '$(ToolEntryPoint)' == '' ">$(TargetFileName)</ToolEntryPoint>
    <_GenerateToolsSettingsFileCacheFile Condition="'$(_GenerateToolsSettingsFileCacheFile)' == ''">$(IntermediateOutputPath)$(MSBuildProjectName).toolssettingsinput.cache</_GenerateToolsSettingsFileCacheFile>
    <_GenerateToolsSettingsFileCacheFile>$([MSBuild]::NormalizePath($(MSBuildProjectDirectory), $(_GenerateToolsSettingsFileCacheFile)))</_GenerateToolsSettingsFileCacheFile>
  </PropertyGroup>

  <Target Name="_GenerateToolsSettingsFileInputCache">
    <ItemGroup>
      <_GenerateToolsSettingsFileInputCacheToHash Include="$(ToolEntryPoint)" />
      <_GenerateToolsSettingsFileInputCacheToHash Include="$(ToolCommandName)" />
    </ItemGroup>

    <Hash ItemsToHash="@(_GenerateToolsSettingsFileInputCacheToHash)">
      <Output TaskParameter="HashResult" PropertyName="_GenerateToolsSettingsFileInputCacheHash" />
    </Hash>

    <WriteLinesToFile
      Lines="$(_GenerateToolsSettingsFileInputCacheHash)"
      File="$(_GenerateToolsSettingsFileCacheFile)"
      Overwrite="true"
      WriteOnlyWhenDifferent="true" />

    <!-- Don't include the cache file in FileWrites, because there is no support for cleaning
         intermediate outputs during PackAsTool. Adding it to FileWrites doesn't work because
         IncrementalClean during PackAsTool would add it to the clean file, but then IncrementalBuild
         during the Build target on a subsequent run would consider it to be orphaned (because this target
         which would add it to FileWrites hasn't run yet), and delete it. -->
  </Target>

  <Target Name="GenerateToolsSettingsFileFromBuildProperty"
          DependsOnTargets="_GenerateToolsSettingsFileInputCache"
          Inputs="$(_GenerateToolsSettingsFileCacheFile)"
          Outputs="$(_ToolsSettingsFilePath)">
    <GenerateToolsSettingsFile
       EntryPointRelativePath="$(ToolEntryPoint)"
       CommandName="$(ToolCommandName)"
       ToolsSettingsFilePath="$(_ToolsSettingsFilePath)" />
  </Target>

  <Target Name="_PackToolValidation" Condition=" '$(PackAsTool)' == 'true' ">

    <GetNuGetShortFolderName
      TargetFrameworkMoniker="$(TargetFrameworkMoniker)"
      TargetPlatformMoniker="$(TargetPlatformMoniker)">

      <Output TaskParameter="NuGetShortFolderName" PropertyName="_NuGetShortFolderName" />

    </GetNuGetShortFolderName>

    <NETSdkError Condition=" '$(SelfContained)' == 'true' "
             ResourceName="PackAsToolCannotSupportSelfContained" />

    <NETSdkError Condition=" '$(TargetFrameworkIdentifier)' != '.NETCoreApp' "
                 ResourceName="DotnetToolOnlySupportNetcoreapp" />

    <NETSdkError Condition=" '$(_TargetFrameworkVersionWithoutV)' &lt; '2.1' "
                 ResourceName="DotnetToolDoesNotSupportTFMLowerThanNetcoreapp21" />

    <NETSdkError Condition=" '$(TargetPlatformIdentifier)' != '' and '$(TargetFrameworkIdentifier)' == '.NETCoreApp' and $([MSBuild]::VersionGreaterThanOrEquals($(TargetFrameworkVersion), 5.0))"
             ResourceName="PackAsToolCannotSupportTargetPlatformIdentifier" />
  </Target>

  <!--
    ============================================================
                                        GenerateShimsAssets

    Generate packaged shims for signing when PackAsToolShimRuntimeIdentifiers is set
    ============================================================
    -->

  <PropertyGroup>
    <_ShimInputCacheFile Condition="'$(_ShimInputCacheFile)' == ''">$(IntermediateOutputPath)$(MSBuildProjectName).shiminput.cache</_ShimInputCacheFile>
    <_ShimInputCacheFile>$([MSBuild]::NormalizePath($(MSBuildProjectDirectory), $(_ShimInputCacheFile)))</_ShimInputCacheFile>
    <_ShimCreatedSentinelFile Condition="'$(_ShimCreatedSentinelFile)' == ''">$(IntermediateOutputPath)$(MSBuildProjectName).shimcreated.sentinel</_ShimCreatedSentinelFile>
    <_ShimCreatedSentinelFile>$([MSBuild]::NormalizePath($(MSBuildProjectDirectory), $(_ShimCreatedSentinelFile)))</_ShimCreatedSentinelFile>
    <PackagedShimOutputRootDirectory Condition=" '$(PackagedShimOutputRootDirectory)' == '' ">$(OutDir)</PackagedShimOutputRootDirectory>
  </PropertyGroup>

  <Target Name="GenerateShimsAssets"
          BeforeTargets="CopyFilesToOutputDirectory"
          DependsOnTargets="ResolvePackageAssets;_PackToolValidation;_GenerateShimInputCache;_ComputeExpectedEmbeddedApphostPaths"
          Condition="'$(PackAsTool)' == 'true' and $(PackAsToolShimRuntimeIdentifiers) != '' "
          Inputs="@(_GenerateShimsAssetsInput)"
          Outputs="$(_ShimCreatedSentinelFile)">

    <GenerateShims
      ApphostsForShimRuntimeIdentifiers="@(_ApphostsForShimRuntimeIdentifiers)"
      IntermediateAssembly="@(IntermediateAssembly->'%(FullPath)')"
      OutputType="$(OutputType)"
      PackagedShimOutputDirectory="$(PackagedShimOutputRootDirectory)/shims/$(_NuGetShortFolderName)"
      PackageId="$(PackageId)"
      PackageVersion="$(PackageVersion)"
      ShimRuntimeIdentifiers="@(_PackAsToolShimRuntimeIdentifiers)"
      TargetFrameworkMoniker="$(NuGetTargetMoniker)"
      ToolCommandName="$(ToolCommandName)"
      ToolEntryPoint="$(ToolEntryPoint)">

      <Output TaskParameter="EmbeddedApphostPaths" ItemName="_EmbeddedApphostPaths" />
    </GenerateShims>

    <!-- Workaround for https://github.com/dotnet/corefx/issues/31379
         LastWriteTime in shims are not accurate. And _ShimInputCacheFile will have later timestamp than generated shims.
         Use a created file to "record" LastWriteTime. And only use it in "Outputs" field for timestamp comparison.

         Touch Task uses the same API File.SetLastWriteTime underneath. So it also cannot be used.
    -->
    <WriteLinesToFile Lines="This file's LastWriteTime is used in incremental build" File="$(_ShimCreatedSentinelFile)" Overwrite="True" />

    <ItemGroup>
      <!-- Do this in an ItemGroup instead of as an output parameter so that it still gets added to the item set
           during incremental builds when the task is skipped -->
      <FileWrites Include="@(_EmbeddedApphostPaths)" />
      <FileWrites Include="$(_ShimCreatedSentinelFile)" />
    </ItemGroup>
  </Target>

  <Target Name="_ComputeExpectedEmbeddedApphostPaths">
    <GetEmbeddedApphostPaths
      PackagedShimOutputDirectory="$(PackagedShimOutputRootDirectory)/shims/$(_NuGetShortFolderName)"
      ShimRuntimeIdentifiers="@(_PackAsToolShimRuntimeIdentifiers)"
      ToolCommandName="$(ToolCommandName)">

      <Output TaskParameter="EmbeddedApphostPaths" ItemName="_EmbeddedApphostPaths" />
    </GetEmbeddedApphostPaths>
  </Target>

  <!-- To achieve incremental build with property change. When any property changes, WriteOnlyWhenDifferent will be triggered to write cache file.
  And the cache file's timestamp will be later, and it then triggers the incremental build.-->
  <Target Name="_GenerateShimInputCache" DependsOnTargets="ResolveAssemblyReferences">
    <ItemGroup>
      <_GenerateShimsAssetsInput Include="$(_ShimInputCacheFile)" />
      <_GenerateShimsAssetsInput Include="@(_ApphostsForShimRuntimeIdentifiers)"/>
      <_GenerateShimsAssetsInput Include="$(_ShimCreatedSentinelFile)"/>
      <_GenerateShimsAssetsInput Include="$(ProjectAssetsFile)"/>

      <_GenerateShimsAssetsInputCacheToHash Include="$(PackageId)"/>
      <_GenerateShimsAssetsInputCacheToHash Include="$(Version)"/>
      <_GenerateShimsAssetsInputCacheToHash Include="$(NuGetTargetMoniker)"/>
      <_GenerateShimsAssetsInputCacheToHash Include="$(ToolCommandName)"/>
      <_GenerateShimsAssetsInputCacheToHash Include="$(ToolEntryPoint)"/>
      <_GenerateShimsAssetsInputCacheToHash Include="$(PackAsToolShimRuntimeIdentifiers)"/>
    </ItemGroup>

    <Hash ItemsToHash="@(_GenerateShimsAssetsInputCacheToHash)">
      <Output TaskParameter="HashResult" PropertyName="_GenerateShimsAssetsInputCacheHash" />
    </Hash>

    <WriteLinesToFile Lines="$(_GenerateShimsAssetsInputCacheHash)" File="$(_ShimInputCacheFile)" Overwrite="True" WriteOnlyWhenDifferent="True" />

    <ItemGroup>
      <FileWrites Include="$(_ShimInputCacheFile)" />
    </ItemGroup>
  </Target>

</Project>
