gitlab ci cache/keep 阶段之间的 golang 包

gitlab ci cache/keep golang packages between stages

我使用 gitlab-ci 来测试、编译和部署一个小的 golang 应用程序,但问题是这些阶段花费的时间比必要的要长,因为它们必须获取所有依赖项cies每一次。

如何在两个阶段(测试和构建)之间保持 golang 依赖ci?

这是我当前 gitlab-ci 配置的一部分:

test:
    stage: test
    script:
        # get dependencies
        - go get github.com/foobar/...
        - go get github.com/foobar2/...
        # ...
        - go tool vet -composites=false -shadow=true *.go
        - go test -race $(go list ./... | grep -v /vendor/)

compile:
    stage: build
    script:
        # getting the same dependencies again
        - go get github.com/foobar/...
        - go get github.com/foobar2/...
        # ...
        - go build -race -ldflags "-extldflags '-static'" -o foobar
    artifacts:
        paths:
            - foobar

这是一项非常棘手的任务,因为 GitLab does not allow caching outside the project directory。一个快速而肮脏的任务是将 $GOPATH 的内容复制到项目内的某个目录下(比如 _GO),将其缓存并在每个阶段开始时将其复制回 $GOPATH:

after_script:
  - cp -R $GOPATH ./_GO || :

before_script:
  - cp -R _GO $GOPATH

cache:
  untracked: true
  key: "$CI_BUILD_REF_NAME"
  paths:
    - _GO/

警告:这只是一个(相当丑陋的)解决方法,我自己还没有测试过。它应该只展示一个可能的解决方案。

Yan Foto, you can only use paths that are within the project workspace. But you can move the $GOPATH to be inside your project, as suggested by extrawurst blog所述。

test:
  image: golang:1.11
  cache:
    paths:
      - .cache
  script:
    - mkdir -p .cache
    - export GOPATH="$CI_PROJECT_DIR/.cache"
    - make test