将大型解决方案转换为中央包管理 (CPM)

问题描述 投票:0回答:1

我有一个大型解决方案,我想将其转换为使用中央包管理。这将使管理所有 nuget 包变得更容易,并确保所有项目使用相同的版本。

但是手动执行此操作需要大量工作。有什么工具可以使用吗?

.net-core nuget
1个回答
0
投票

您可以使用一些工具:

选项 1 - CentralizedPackageConverter

这个工具将完成工作:https://github.com/Webreaper/CentralizedPackageConverter

选项 2 - CentralPackageManagementMigrator

这是另一个工具:https://github.com/oshvartz/CentralPackageManagementMigrator

我注意到这个工具会删除 .csproj 文件中的空行,这是需要注意的。

选项 3 - PowerShell

在发现上述工具之前,我编写了这个 PowerShell 脚本。对于大多数情况来说应该足够了:

# Find all *.csproj files in the specified directory
$csprojFiles = Get-ChildItem -Filter *.csproj -Recurse

# Array to store unique package references
$uniquePackageReferences = @{}

# Loop through each *.csproj file
foreach ($file in $csprojFiles) {
    # Read the content of the file
    $content = Get-Content $file.FullName -Raw

    # Define the regex pattern to match the package references
    $pattern = '<PackageReference\s+Include="([^"]+)"\s+Version="([^"]+)"'

    # Find all matches in the content
    $references = [regex]::Matches($content, $pattern)

    # Loop through each match
    foreach ($match in $references) {
        $packageName = $match.Groups[1].Value
        $packageVersion = $match.Groups[2].Value

        # Replace the match in the content
        $content = $content -replace $match.Value, "<PackageReference Include=`"$packageName`""

        # Add the unique package reference to the dictionary if it doesn't exist
        if (-not $uniquePackageReferences.ContainsKey($packageName)) {
            $uniquePackageReferences[$packageName] = $packageVersion
        }
    }

    $content = $content -replace '\s+$', ''
    
    # Write the modified content back to the file
    Set-Content -Path $file.FullName -Value $content
}

# Get sorted reference keys from the dictionary
$sortedKeys = $uniquePackageReferences.Keys | Sort-Object

# Output unique package references with versions
foreach ($key in $sortedKeys) {
    $packageVersion = $uniquePackageReferences[$key]
    Write-Output "<PackageVersion Include=`"$key`" Version=`"$packageVersion`" />"
}

# Write content to Directory.Packages.props file
@"
<Project>
    <PropertyGroup>
      <ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
    </PropertyGroup>
    <ItemGroup>
$($sortedKeys | ForEach-Object { "        <PackageVersion Include=`"$_`" Version=`"$($uniquePackageReferences[$_])`" />`n" })
    </ItemGroup>
</Project>
"@ | Set-Content -Path "Directory.Packages.props"
© www.soinside.com 2019 - 2024. All rights reserved.