Search code examples
azure-devopscontinuous-integrationnugetazure-pipelinessemantic-versioning

Fetch version number in Nuget package step in Azure DevOps from csproj


Trying to set up a build pipeline where nugets built from pull-requests are suffixed with '-unstable'. However, I can't seem to get the version of the class-library project that is being built defined in its csproj file. I've tried every keyword I could think of and I've been unsuccessful in finding documentation or others with the same issue so far.

Any help would be appreciated.

Below are excerpts from relevant files:

class-library.csproj

<Project Sdk="Microsoft.NET.Sdk">
    <PropertyGroup>
        <TargetFramework>net462</TargetFramework>
        <Version>1.1.0.0</Version>
        <AppendTargetFrameworkToOutputPath>false</AppendTargetFrameworkToOutputPath>
    </PropertyGroup>
</Project>

ci-file.yaml

variables:
- group: BuildParameters
- name: BuildVersion
  ${{ if eq(variables['Build.SourceBranchName'], 'master') }}:
    value: '$(Version)'
  ${{ else }}:
    value: '$(Version).$(Build.BuildId)-unstable'

steps:
- template: template.yaml

template.yaml

- task: NuGetCommand@2
  displayName: 'NuGet Pack $(...)'
  inputs:
    command: pack
    packagesToPack: '$(...)'
    versioningScheme: byEnvVar
    versionEnvVar: BuildVersion


Solution

  • Based on your description, you need to get the version value in the csproj file.

    The version number in the csproj file cannot be read directly using variables.

    To meet your requirements, you need to add a task to read the version value in csproj file and set the version as pipeline variable. Then you can use the version number in the Nuget task.

    Here is an example: PowerShell script

    steps:
    - powershell: |
       $xml = [Xml] (Get-Content .\xxx.csproj)
       $version =$xml.Project.PropertyGroup.Version
       
       echo "$version" 
       echo "$(Build.SourceBranchName)" 
       
       if( "$(Build.SourceBranchName)" -eq "master") {
       echo "##vso[task.setvariable variable=version]$version "
       
       }else {
       $Newversion = "$version.$(Build.BuildId)-unstable"
       echo "##vso[task.setvariable variable=version]$Newversion"
       }
      displayName: 'PowerShell Script'
    

    Then you can use the variable $(version) in the next tasks.

    For more info, you can refer to this doc about set variables in Pipeline.