forbidigo

Table of Contents

  1. 解決する問題
  2. 設定
  3. オプション
  4. サンプル
    1. 検出例
    2. 修正例
    3. カスタムパターンの活用
  5. 注意点
  6. 参考リンク

forbidigo は特定の識別子(関数呼び出しなど)の使用を正規表現で禁止するツールです。

解決する問題

デバッグ用の fmt.Println や一時的なテストヘルパー(Ginkgo の FItFDescribe など)がコードに残ったままコミットされることがあります。コードレビューで見落とすと、本番環境で不要な出力やテストスキップが発生します。

1
2
3
4
5
6
7
// Before: デバッグ用の print がそのまま残っている
func ProcessOrder(ctx context.Context, order Order) error {
fmt.Println("debug:", order.ID) // 本番に残ってしまう
fmt.Printf("order: %+v\n", order)

return processInternal(ctx, order)
}
1
2
3
4
5
6
// After: slog による構造化ログに置き換え
func ProcessOrder(ctx context.Context, order Order) error {
slog.Debug("process order", "order_id", order.ID)

return processInternal(ctx, order)
}

設定

公式ドキュメント

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

linters:
enable:
- forbidigo
settings:
forbidigo:
forbid:
- pattern: ^print(ln)?$
- pattern: ^fmt\.Print.*
msg: Do not commit print statements. Use slog instead.
analyze-types: true

オプション

オプション デフォルト 説明
forbid []pattern [^(fmt\.Print(|f|ln)|print|println)$] 禁止する識別子の正規表現パターンのリスト
forbid[].pattern string - 禁止する識別子の正規表現
forbid[].msg string "" エラーレポートに含めるカスタムメッセージ
forbid[].pkg string "" パッケージのインポートパスを正規表現で絞り込む(analyze-types が必要)
exclude-godoc-examples bool true godoc の Example 関数をチェック対象から除外する
analyze-types bool false 型情報を使用して解析する。import のリネームやメソッド・フィールドの禁止が可能になる

サンプル

検出例

1
2
3
4
5
6
7
8
9
// forbidigo が警告するパターン

func example() {
// デフォルト設定で検出される
fmt.Println("debug output") // use of `fmt.Println` is forbidden
fmt.Printf("value: %v\n", v) // use of `fmt.Printf` is forbidden
print("hello") // use of `print` is forbidden
println("world") // use of `println` is forbidden
}

修正例

1
2
3
4
5
func example() {
// 構造化ログを使用
slog.Debug("debug output")
slog.Info("processing", "value", v)
}

カスタムパターンの活用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# spew.Dump やテスト用の FIt/FDescribe も禁止する例
linters:
settings:
forbidigo:
forbid:
- pattern: ^fmt\.Print.*
msg: Use slog instead of fmt.Print.
- pattern: ^spew\.(ConfigState\.)?Dump$
msg: Do not commit spew.Dump calls.
- pattern: ^ginkgo\.FIt$
msg: Do not commit focused tests.
- pattern: ^ginkgo\.FDescribe$
msg: Do not commit focused tests.
analyze-types: true

注意点

  • デフォルトで fmt.Printlnfmt.Printffmt.Printprintprintln が禁止される。forbid を明示的に指定するとデフォルトは上書きされるため、必要に応じてデフォルトのパターンも含める
  • analyze-types: true にすると import エイリアスを変えても検出できる(例: import f "fmt"f.Println も検出)
  • godoc の Example 関数では fmt.Println が慣例的に使われるため、デフォルトで除外される

参考リンク