Azure pipeline 正确构建 go 模块

Azure pipeline build go modules correctly

因为用于构建 go 代码的默认 azure-pipelines.yml 模板不支持 go 模块,所以支持它的样子并不明显。

这是默认模板,不适用于 go.modules:

# Go
# Build your Go project.
# Add steps that test, save build artifacts, deploy, and more:
# https://docs.microsoft.com/azure/devops/pipelines/languages/go

trigger:
- master

pool:
  vmImage: ubuntu-latest

variables:
  GOBIN:  '$(GOPATH)/bin' # Go binaries path
  GOROOT: '/usr/local/go1.11' # Go installation path
  GOPATH: '$(system.defaultWorkingDirectory)/gopath' # Go workspace path
  modulePath: '$(GOPATH)/src/github.com/$(build.repository.name)' # Path to the module's code

steps:
- script: |
    mkdir -p '$(GOBIN)'
    mkdir -p '$(GOPATH)/pkg'
    mkdir -p '$(modulePath)'
    shopt -s extglob
    shopt -s dotglob
    mv !(gopath) '$(modulePath)'
    echo '##vso[task.prependpath]$(GOBIN)'
    echo '##vso[task.prependpath]$(GOROOT)/bin'
  displayName: 'Set up the Go workspace'

- script: |
    go version
    go get -v -t -d ./...
    if [ -f Gopkg.toml ]; then
        curl https://raw.githubusercontent.com/golang/dep/master/install.sh | sh
        dep ensure
    fi
    go build -v .
  workingDirectory: '$(modulePath)'
  displayName: 'Get dependencies, then build'

我也想在这里分享一个正确构建 go 模块包的模板的答案。也许这只是为了启发您需要考虑的内容。我花了一些时间才到达那里。

主要的痛点是默认模板将 GOPATH 设置为管道工作目录,如果您通过 go mod download 将模块下载到其中,这是错误的。这将导致下一个管道中的文件无法访问 运行,导致管道在存储库签出期间失败。

以下方法只是将 GOPATH 设置为 Agent.HomeDirectory,这也使下载的模块可用于后续管道 运行s。

也许对某人有帮助

# Go
# Build your Go project.
# Add steps that test, save build artifacts, deploy, and more:
# https://docs.microsoft.com/azure/devops/pipelines/languages/go

trigger: 
- main
- feature/*

pool: ubuntu-latest

variables:
  GOPATH: '$(Agent.HomeDirectory)/go' # Go workspace path
  GOBIN:  '$(GOPATH)/bin' # Go binaries path
  GOROOT: '/opt/hostedtoolcache/go/1.15.8/x64' # Go installation path
  

stages:
- stage: Build
  displayName: Build image
  
  jobs:  
  - job: BuildAndTest
    displayName: Build And Test
    pool: ubuntu-latest
    steps:
    - checkout: self
    - script: |
        export PATH="$(GOROOT)/bin:$(PATH)"
        printenv
        ls -la
        go env
        go version
        go mod download
        go build ./...
        go test ./... 
      workingDirectory: '$(Build.SourcesDirectory)'
      displayName: 'Get dependencies, then build and test'