あふん

ぷろぐらむとか

Golang で lint と test をしたい時の CircleCI の config.yaml

f:id:ponde_m:20190324215637p:plain:w300

テンプレ的に使いたいことがあるので。

TL;DR

version: 2.1

executors:
  build:
    parameters:
      go-version:
        type: string
    docker:
      - image: circleci/golang:<< parameters.go-version >>
        environment:
          GO111MODULE: "on"
    working_directory: /go/src/d-kuro/go-sandbox

commands:
  go_mod_download:
    steps:
      - restore_cache:
          name: Restore go modules cache
          keys:
            - go-modules-{{ checksum "go.sum" }}

      - run: go mod download

      - save_cache:
          name: Save go modules cache
          key: go-modules-{{ checksum "go.sum" }}
          paths:
            - "/go/pkg/mod"

jobs:
  build:
    parameters:
      go-version:
        type: string
      golangci-lint-version:
        type: string

    executor:
      name: build
      go-version: << parameters.go-version >>

    steps:
      - checkout

      - go_mod_download

      - run:
          name: Install GolangCI-Lint
          command: curl -sfL https://install.goreleaser.com/github.com/golangci/golangci-lint.sh | sh -s v<< parameters.golangci-lint-version >>

      - run:
          name: Run GolangCI-Lint
          command: ./bin/golangci-lint run --tests --disable-all --enable=goimports --enable=golint --enable=govet --enable=errcheck --enable=staticcheck
      - run:
          name: Run Tests
          command: go test -race -v ./...

workflows:
  golang-workflow:
    jobs:
      - build:
          go-version: "1.12.1"
          golangci-lint-version: "1.15.0"

やりたいこと

  • Go Modules を用いた依存関係の解決
  • lint
  • test

これだけ。最低限実行しなきゃいけないものだけできていればいいかなという感じです。

Go Modules

commands:
  go_mod_download:
    steps:
      - restore_cache:
          name: Restore go modules cache
          keys:
            - go-modules-{{ checksum "go.sum" }}

      - run: go mod download

      - save_cache:
          name: Save go modules cache
          key: go-modules-{{ checksum "go.sum" }}
          paths:
            - "/go/pkg/mod"

go mod download というコマンドを使って依存パッケージのダウンロードを行います。事前に GO111MODULE という環境変数on を突っ込んでおきます。

Go Modules でダウンロードしたあれこれの保存場所は $GOPATH/pkg/mod になるのでそこをキャッシュするようにしています。

Lint

Lint は GolangCI-Lint を実行します。

github.com

GolangCI-Lint は Golang のいろんな Linter をまとめて実行してくれるやつです。ここら辺の話は「GolangCI を使ってコードの品質を保ちながら快適な Golang 生活を送る話」というタイトルである勉強会で LT をしているので、その資料をそのまま貼ります。

今回は複数人で開発する用に最低限の Linter を実行するようにしています。

  • goimports
  • golint
  • govet
  • errcheck
  • staticcheck

Test

特別書くことがないやつ。

race オプションをつけとくとデータ競合を検知してくれます。

golang.org

まとめ

最低限の Lint と Test だけならこれを使い回せば大丈夫かなって思ってます。CircleCI 2.1 のことを完全に理解してないのでもっといい書き方とかあれば改善していきたい。

おまけ

Go Modules を用いた依存解決は CircleCI Orbs が公開されていたりします。

https://circleci.com/orbs/registry/orb/timakin/go-module