【Azure DevOps系列】Azure DevOps構建併發布Nuget程式包

HueiFeng發表於2020-09-07

在Azure DevOps中,管道可以用來構建解決方案,O(∩_∩)O哈哈~快萬能了,本章主要介紹如何建立Nuget包並且將其釋出到Nuget伺服器的過程。
file

前面我建立了一個非常簡單的類庫,這邊我不做過多敘述,接下來我們需要進行編輯csproj檔案,當我們建立Nuget包時,我們將使用dotnet pack命令。這於傳統的Nuget cli稍微有點不同,在傳統的Nuget CLI中,我們建立nuspec檔案並針對nuspec執行nuget packdotnet pack命令將從csproj建立一個nuspec檔案,然後將程式碼打包到一個nupkg檔案中,需要將一些關鍵資訊新增到csproj檔案中,以確保它可以正確的建立Nuget包。首先我們需要一個PackageId,這將是Nuget包本身的名稱,根據我們要釋出的位置這個名稱必須是唯一的,接下來是Version,它將是已釋出的軟體包的版本號,正如下所示是我們的csproj檔案

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>netstandard2.0</TargetFramework>
    <PackageId>AzureDevOpsTest.Common</PackageId>
    <Version>1.0.0</Version>
    <Authors>HueiFeng</Authors>
    <Description>Test project of common utils</Description>
    <IsPackable>true</IsPackable>
  </PropertyGroup>

</Project>

我們需要在Azure DevOps中建立專案,並進行git倉庫的繫結,當繫結完之後我們先來建立相關的服務賬號資訊,步驟如下所示:

file

file

file

構建專案(dotnet build)

- task: DotNetCoreCLI@2
  displayName: 'dotnet build'
  inputs:
    command: 'build'
    arguments: '--configuration $(buildConfiguration)'

打包專案(dotnet pack)

使用nobuild意味著在執行pack之前不會編譯專案,因為它已經在上面的步驟中構建了

- task: DotNetCoreCLI@2
  displayName: "dotnet pack"
  inputs:
    command: 'pack'
    arguments: '--configuration $(buildConfiguration)'
    packagesToPack: '**/*.csproj'
    nobuild: true
    versioningScheme: 'off'

釋出專案(nuget push)

如下所示這種方式適合在Azure DevOps組織內的製品庫,當然在製品庫中可以設定可見性,我們可以設定對該程式包的公開和私有。allowPackageConflicts:true代表在版本重複的情況下,可以進行跳過重複的版本,避免返回409。但是這種方式在Nuget.exe中無法進行使用,這將避免不了返回409影響我們流水線的正常性。我們只能進行選擇通過dotnet nuget push的方式進行忽略併發布,下面第二個程式碼片段所寫。

對於這個問題其實我尋求過答案,但是團隊這邊給出的是:

I have discussed this with the team and we have decided not to add this functionality to the task. Instead of using these "bulkier" tasks we now recommend using the NuGet Authenticate task to authenticate to Azure DevOps Artifacts feeds and to use a script task with nuget/dotnet to use the parameters you need.
The reason for this is that the NuGet/Dotnet clients are actively being developed and new parameters and functionality are being added often. To keep up with all of the updates causes a lot of extra support for these bulky tasks. Please use example above to set up your pipeline with the '--skip-duplicate' parameter. Thank you for understanding.

這是痛苦的這將代表我們無法通過如下這種很簡單的方式不得不選擇通過dotnet nuget push進行釋出,不太清真了。。。

- task: NuGetCommand@2
  inputs:
    command: 'push'
    packagesToPush: '$(Build.ArtifactStagingDirectory)/**/*.nupkg;!$(Build.ArtifactStagingDirectory)/**/*.symbols.nupkg'
    nuGetFeedType: 'external'
    publishFeedCredentials: 'hueifeng_nuget'
    allowPackageConflicts: true
- task: DotNetCoreCLI@2
  displayName: "dotnet push"
  inputs:
    command: 'custom'
    custom: 'dotnet nuget push $(Build.ArtifactStagingDirectory)/**/*.nupkg -k $(APIKey) -s https://api.nuget.org/v3/index.json  --skip-duplicate'

Reference

https://github.com/hueifeng/AzureDevOpsDemo/tree/demo03

相關文章