はじめに
GoのカバレッジをPRにコメントする方法を2つご紹介したいと思います。
CodeCov
出力したカバレッジを可視化してPull Requestにコメントします。
Go以外にも色々な言語に対応しており、出力すると以下のようにPRのコメントが追加されます。
ちなみに、複数ユーザでの使用など条件によっては料金がかかります。
設定ファイルはcodecov.yml
に記述し、自分は以下のように設定しています。
coverage:
status:
project:
default:
informational: true
patch:
default:
informational: true
comment:
layout: "reach, diff, flags, files, header, footer"
behavior: default
require_changes: false
require_base: true
require_head: true
hide_project_coverage: false
自分は閾値など設定してしまうと、不要なコードを削除するだけのPull RequestだとActionが落ちてしまうので、informational: true
の箇所で失敗しないようにしております。
自分は少しハマったのですが、設定ファイルの設定値が間違っていた場合は、エラーがGitHub Action上で確認できません。CodeCovのHP上では確認できます。また、開発環境で以下を叩くことで、設定ファイルが有効化を確認できます。
curl --data-binary @codecov.yml https://codecov.io/validate
設定値については【Codecov】codecov.ymlの設定についてのあれこれが参考になりました。
GitHub Actionで動かすには、Codec GitHub app で自分のリポジトリにインストール。次に、Codecovにログインして、secretsに CODECOV_TOKEN
を登録する必要があります。
ワークフローは以下のようになります。
- uses: actions/checkout@v4
with:
ref: ${{ github.event.pull_request.head.sha }}
- uses: actions/setup-go@v5
with:
go-version-file: go.mod
- name: Run Tests
run: go list -f '{{.Dir}}/...' -m | xargs go test -v -race -coverprofile=coverage.out -covermode=atomic
- name: Upload coverage to Codecov
uses: codecov/codecov-action@v4
with:
fail_ci_if_error: true
token: ${{ secrets.CODECOV_TOKEN }}
また、ログインすると、バッジも取得できます。
k1LoW/octocov-action@v1
シンプルで見やすいコメントをつけてくれます。こちらもGo以外の言語でも使用できます。CodeCovと異なり、外部サイトにログインする必要やsecretsの登録などの手間が必要ないので、簡単に導入できます。
ちなみに、以下は作成者の記事です。
GitHub Actionのワークフローは以下のようになります。
- uses: actions/checkout@v4
with:
ref: ${{ github.event.pull_request.head.sha }}
- uses: actions/setup-go@v5
with:
go-version-file: go.mod
- name: Run Tests
run: go list -f '{{.Dir}}/...' -m | xargs go test -v -race -coverprofile=coverage.out -covermode=atomic
- name: create report
uses: k1LoW/octocov-action@v1
設定ファイルは.octocov.yml
に作成します。
以下は自分の例です。
coverage:
paths:
- coverage.out
codeToTestRatio:
code:
- "**/*.go"
- "!**/*_test.go"
test:
- "**/*_test.go"
testExecutionTime:
if: true
comment:
if: is_pull_request
report:
if: is_default_branch
datastores:
- artifact://${GITHUB_REPOSITORY}
diff:
datastores:
- artifact://${GITHUB_REPOSITORY}