nolintlint

Table of Contents

  1. 解決する問題
  2. 設定
  3. オプション
  4. サンプル
    1. 検出例
    2. 修正例
  5. 注意点
  6. 参考リンク

nolintlint は //nolint ディレクティブの品質をチェックするツールです。

解決する問題

//nolint ディレクティブは Linter の警告を抑制する便利な仕組みですが、乱用すると問題が隠蔽されます。対象の Linter 名が指定されていない、理由が書かれていない、既に不要になったディレクティブが残っている、といった問題を検出します。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// Before: 質の低い nolint ディレクティブ

//nolint
func BadExample() error {
// どの Linter を抑制しているか不明、理由もない
fmt.Println("debug")
return nil
}

//nolint:errcheck
func AnotherBad() {
// errcheck を抑制しているが、実際にはエラーチェック違反がない(不要な nolint)
fmt.Println("hello")
}
1
2
3
4
5
6
7
// After: 適切な nolint ディレクティブ

//nolint:forbidigo // デバッグ出力が本番で必要なため
func GoodExample() error {
fmt.Println("startup message")
return nil
}

設定

公式ドキュメント

1
2
3
4
5
6
7
8
9
10
11
# .golangci.yml 設定例
version: "2"

linters:
enable:
- nolintlint
settings:
nolintlint:
require-explanation: true
require-specific: true
allow-unused: false

オプション

オプション デフォルト 説明
allow-unused bool false 効果のない(不要な)//nolint ディレクティブを許可する
require-explanation bool false //nolint ディレクティブに理由の記載を必須にする
require-specific bool false 抑制対象の Linter 名の指定を必須にする
allow-no-explanation []string [] 理由の記載を免除する Linter のリスト

サンプル

検出例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// nolintlint が警告するパターン

// 1. require-specific: true の場合 → Linter 名がない
//nolint // directive `//nolint` should mention specific linter
func example1() {}

// 2. require-explanation: true の場合 → 理由がない
//nolint:gosec // directive `//nolint:gosec` should provide explanation
func example2() {
_ = exec.Command("sh", "-c", userInput)
}

// 3. allow-unused: false の場合 → 効果のない nolint
//nolint:errcheck // directive `//nolint:errcheck` is unused
func example3() {
// errcheck の違反がないため nolint は不要
return
}

修正例

1
2
3
4
5
6
7
8
9
10
// Linter 名と理由を明記
//nolint:gosec // ユーザー入力は事前にバリデーション済み
func example2() {
_ = exec.Command("sh", "-c", validatedInput)
}

// 不要な nolint を削除
func example3() {
return
}

注意点

  • require-specific: truerequire-explanation: true を併用するのが推奨。//nolint:linter // 理由 の形式を強制できる
  • allow-unused: false(デフォルト)にすると、Linter のルール変更やコード修正で不要になった //nolint を自動的に検出できる
  • allow-no-explanation に特定の Linter を指定すると、その Linter については理由の記載を免除できる

参考リンク