Azure管道正确生成Go模块

ibrsph3r  于 2022-12-16  发布在  Go
关注(0)|答案(2)|浏览(95)

因为默认的用于构建go代码的azure-pipelines.yml模板不支持go模块,所以它看起来是如何支持的并不明显。
这是默认模板,不适用于go.modules:

# Go
# Build your Go project.
# Add steps that test, save build artifacts, deploy, and more:
# https://learn.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'
2uluyalo

2uluyalo1#

我也想在这里分享一个正确构建go模块包的模板的答案。也许这只是为了给你灵感需要考虑什么。我花了一些时间才做到这一点。
主要的难点是默认模板将GOPATH设置为管道工作目录,如果您通过go mod download下载模块到该目录,则会出现错误。这将导致在下一次管道运行时无法访问文件,从而使管道在仓库 checkout 时失败。
下面的方法只是将GOPATH设置为Agent.HomeDirectory,这也使下载的模块可用于后续的管道运行。
也许这能帮助某人

# Go
# Build your Go project.
# Add steps that test, save build artifacts, deploy, and more:
# https://learn.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'
mf98qq94

mf98qq942#

learn.microsoft中的.yml文件可以工作,但是它要求go.mod和main.go位于根目录中,管道应该支持典型的go项目结构,包含cmd/main.gopkg/internal/目录

相关问题