Gent
Gent

Reputation: 2685

How to make NuGet pack not overwrite an existing version

When building a NuGet Pack to an output directory, I do not want it to overwrite an existing version

Existing command:

".nuget\nuget.exe" pack "some.csproj" -output "c:\~packages"

I have looked through the documentation and cannot seem to find a switch that does it. I tried using a if exists "c:\~packages\some.nupkg" exit 1 but the problem is I do not have access to the version number in that context, so I cannot predictably provide a version to check for

Upvotes: 4

Views: 1140

Answers (2)

Rider Harrison
Rider Harrison

Reputation: 571

Use a script.

# Set variables for project and output paths
$projectPath = "$env:USERPROFILE\source\repos\YourProject\src\TheProject.csproj"
$outputPath = "$env:USERPROFILE\source\repos\YourProject\src\"

# Run nuget pack on the project
nuget pack $projectPath -IncludeReferencedProjects -Properties  Configuration=Release -OutputDirectory $outputPath 

# Get the version number from the .nupkg file name
$versionNumber = [System.IO.Path]::GetFileNameWithoutExtension((Get-ChildItem -Path $outputPath -Filter "*.nupkg" | Select-Object -First 1).Name)

# Set variables for source and destination nuget package folders
$sourceFolder = $outputPath
$destinationFolder = "X:\ExternalNugetFolder"

# Check if the package already exists in the destination folder
$packageExists = Test-Path "$destinationFolder\$versionNumber.nupkg"

if ($packageExists) {
    Write-Host "Package $versionNumber already exists in $destinationFolder. Deleting original package from $outputPath." -ForegroundColor Red
    # If the package exists in the destination folder, delete the original package
    Remove-Item "$outputPath\$versionNumber.nupkg"
} else {
    Write-Host "Package $versionNumber does not exist in $destinationFolder. Copying package from $outputPath to $destinationFolder and deleting original package from $outputPath." -ForegroundColor Green
    # If the package does not exist in the destination folder, copy it to the destination folder and delete the original package
    Copy-Item "$outputPath\$versionNumber.nupkg" "$destinationFolder\$versionNumber.nupkg"
    Remove-Item "$outputPath\$versionNumber.nupkg"
}

Upvotes: 1

Matt Ward
Matt Ward

Reputation: 47917

This is not currently possible using NuGet.exe.

The options are:

  1. Modify NuGet's source code to allow an extra command line option to support not overwriting the existing NuGet package if it exist. The PackCommand could be changed to support this.
  2. Write a utility to generate the correct package version, then check the package exists before running NuGet.exe. The package version information is read from the AssemblyInformationalVersionAttribute taken from the project's output assembly if you are using nuget pack projectfile.

Upvotes: 3

Related Questions