whitespace

Table of Contents

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

whitespace は関数やブロックの先頭・末尾にある不要な空行を検出するツールです。

解決する問題

関数や iffor などのブロックの先頭・末尾に不要な空行があると、コードの一貫性が損なわれます。チーム内でスタイルがばらつき、差分レビュー時のノイズにもなります。

1
2
3
4
5
6
7
8
9
10
11
12
// Before: 不要な空行がある
func ProcessOrder(ctx context.Context, order Order) error {

if order.ID == "" {

return errors.New("order ID required")

}

return save(ctx, order)

}
1
2
3
4
5
6
7
8
// After: 不要な空行を除去
func ProcessOrder(ctx context.Context, order Order) error {
if order.ID == "" {
return errors.New("order ID required")
}

return save(ctx, order)
}

設定

公式ドキュメント

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

linters:
enable:
- whitespace
settings:
whitespace:
multi-if: false
multi-func: false

オプション

オプション デフォルト 説明
multi-if bool false 複数行の if 文の後に空行を要求する
multi-func bool false 複数行の関数シグネチャの後に空行を要求する

サンプル

検出例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// whitespace が警告するパターン

// 1. 関数の先頭に不要な空行
func example1() {
// ← unnecessary leading newline
doSomething()
}

// 2. 関数の末尾に不要な空行
func example2() {
doSomething()
// ← unnecessary trailing newline
}

// 3. if ブロックの先頭に不要な空行
func example3(ok bool) {
if ok {
// ← unnecessary leading newline
doSomething()
}
}

// 4. for ブロックの末尾に不要な空行
func example4(items []string) {
for _, item := range items {
process(item)
// ← unnecessary trailing newline
}
}

修正例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
func example1() {
doSomething()
}

func example2() {
doSomething()
}

func example3(ok bool) {
if ok {
doSomething()
}
}

func example4(items []string) {
for _, item := range items {
process(item)
}
}

multi-func / multi-if オプション

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// multi-func: true の場合、複数行シグネチャの後に空行を要求
func LongFunction(
ctx context.Context,
userID string,
options Options,
) error {
// ← この空行が必要になる
return process(ctx, userID, options)
}

// multi-if: true の場合、複数行条件の後に空行を要求
if condition1 &&
condition2 &&
condition3 {
// ← この空行が必要になる
doSomething()
}

注意点

  • デフォルトではブロックの先頭・末尾の不要な空行のみを検出する。multi-ifmulti-func はオプトイン
  • ブロック内の中間にある空行(ロジックの区切り)は検出対象外
  • gofmt はこの種の空行を修正しないため、whitespace で補完する

参考リンク