PackageReference 将版本逻辑解析为 API

PackageReference Resolve Version Logic as API

是否有任何可通过 MSBuild 任务、目标或其他方式访问的 API 允许我查询给定 PackageReference 将解析(或已经解析)到哪个版本的 NuGet 包?

例如,如果我有一个 csproj

<PackageReference Include=“MyPkg” Version=“1.*”/>

而且我有一个我想要的自定义目标

<MyTarget>
  <GetVersionOfResolvedPackageReference Name=“MyPkg” OutputProperty=“IWantToKnowThis” /> <!— or something —>
  ...

来自How NuGet resolves package dependencies

When the NuGet restore process runs prior to a build, it resolves dependencies first in memory, then writes the resulting graph to a file called project.assets.json in the obj folder of a project using PackageReference. MSBuild then reads this file and translates it into a set of folders where potential references can be found, and then adds them to the project tree in memory.


<#
.Synopsis
    Represents the method that
    returns the project.assets
    content as object.
#>
function Get-ProjectAssest([System.String]$Assest) {

    return (Get-Content $Assest | ConvertTo-Json | ConvertFrom-Json).value |
                                                   ConvertFrom-Json
}

Get-ChildItem -Path . 'project.assets.json' -Recurse | ForEach-Object { Get-ProjectAssest($_.FullName) } | ForEach-Object {

    # K = Package Identity
    # V = Package Version
    $_.libraries | ForEach-Object { $_.PSObject.Properties.Name } | Out-File 'PackageReference.ini' -Append 
}

PowerShell 脚本递归解析目录以查找 project.assets.json 并将结果写入 PackageReference.ini 文件。您可以通过 Exec task and after that read file via ReadLinesFromFile 从 MSBuild 调用脚本并执行进一步处理。


NOTE: Represented script will be produce duplicates of PackageReference lines for multiple projects.