Use semantic versioning for NuGet packages built from Azure DevOps

When developing open source software published to nuget feeds, E.G nuget.org, versioning becomes really important. Semantic versioning is a popular versioning scheme that introduces three positive numbers that all together forms the version number. Those number are formatted as MAJOR.MINOR.PATCH.

  • MAJOR increases when incompatible changes are made.
  • MINOR increases when changes are made in a backward compatible manner
  • PATCH increases when you make backward compatible bug fixes

The first two numbers are always changed manually when creating the package. For the number that represents PATCH, we can do this automatically with a little hidden gem in Azure DevOps.

Given that you are using the NugetCommand@2 task from Azure DevOps marketplace, you can select versioning scheme byEnvVar that tells the task to fetch the version number from the Environment Variables by the key versionEnvVar.

- task: NuGetCommand@2
  displayName: "Push"
  inputs:
  command: "push"
  feedsToUse: "select" 
  packagesToPush: "nupackages-to-push"
  nuGetFeedType: "internal"
  publishVstsFeed: "myPrivateFeed"
  versioningScheme: "byEnvVar"
  versionEnvVar: PackageVersion
  allowPackageConflicts: false

To set the variables, head over to the Variables section for your pipeline and declare four variables:

Name Value
Major 1
Minor 0
Patch $[counter(format('{0}.{1}', variables['Major'], variables['Minor']), 0)]
PackageVersion $(Major).$(Minor).$(Patch)

Note that the variable PackageVersion is the one we refer to in our NugetCommand@2 task.

Happy Coding!