Azure Pipeline - 自動新增版號

前言

前一篇文章"建置組件加上自訂版號"的後半段提到,使用BuildId實作了版號自動新增,如下圖。

name: v1.0.$(Build.BuildId) ($(SourceBranchName))
...
    msbuildArgs: '/p:Configuration=release /p:AssemblyVersionNumber=$(versionNumber)'


但這個方式有一個問題是,BuildId是跟著整個Project走,Project內所有的Pipeline會共用此ID,所以下次取得是版號可能會跳號,例:1.0.213 變 1.0.219。

另外一個問題,BuildId只會一直累加,所以建置次變多了,數字會變得很奇怪,若Minor版號進版也無法重置。例如:1.0.5999、1.1.6000。

解決方式

使用內建函式counter,參數是第一個Key值,第二個回傳的預設值,每次叫用會依Key值,回傳一個自動加1的數字,例如:Key=1.0.0,第一次呼叫得到0,第二次呼叫得到1。
$[counter('1.0', 0)]

結合變數的使用,versionNumber變數,會得到1.0.0、1.0.1、1.0.2 以此類推....。若Minor進版的話(1.1),則counter會重算,變成1.1.0、1.1.1...
variables:
  version.MajorMinor: '1.0' 
  version.Revision: $[counter(variables['version.MajorMinor'], 0)]
  versionNumber: '$(version.MajorMinor).$(version.Revision)'


修改建置工作名稱

解決了版號問題,但產生了另一個問題! 建置工作的名稱,無法使用函式。
name: v1.0.$(Build.BuildId) ($(SourceBranchName)) $[counter('1.2', 0)]

名稱變成如下紅框,這樣建置工作無法跟發行的組件對應起來.....所以得另外使用其他方式解決此問題。
解決方式
使用PowerShell在建置執行時,修改名稱
- task: PowerShell@2
  displayName: Set the name of the build (i.e. the Build.BuildNumber)
  inputs:
    targetType: 'inline'
    script: |
      [string] $buildName = "v$(versionNumber) ($(Build.SourceBranchName))"
      Write-Host "Setting the name of the build to '$buildName'."
      Write-Host "##vso[build.updatebuildnumber]$buildName"

以下是我使用1.0.0及1.0.1建置的結果

完整的Azure Pipeline
trigger: none

pool:
  vmImage: 'windows-latest'

variables:
  solution: '**/*.sln'
  buildPlatform: 'Any CPU'
  buildConfiguration: 'Release'
  version.MajorMinor: '1.0.0' # Manually adjust the version number as needed for semantic versioning. Revision is auto-incremented.
  version.Revision: $[counter(variables['version.MajorMinor'], 0)] #max 65xxxx
  versionNumber: '$(version.MajorMinor).$(version.Revision)'

steps:
- task: NuGetToolInstaller@1

- task: PowerShell@2
  displayName: Set the name of the build (i.e. the Build.BuildNumber)
  inputs:
    targetType: 'inline'
    script: |
      [string] $buildName = "v$(versionNumber) ($(Build.SourceBranchName))"
      Write-Host "Setting the name of the build to '$buildName'."
      Write-Host "##vso[build.updatebuildnumber]$buildName"

- task: NuGetCommand@2
  displayName: 'Restore'
  inputs:
    restoreSolution: '$(solution)'
- task: VSBuild@1
  displayName: 'Build'
  inputs:
    solution: '$(solution)'
    msbuildArgs: '/p:Configuration=release /p:AssemblyVersionNumber=$(versionNumber)'
    platform: '$(buildPlatform)'
    configuration: '$(buildConfiguration)'

參考來源

這個網誌中的熱門文章

IIS 設定只允許特定IP進入