いろいろ備忘録日記

主に .NET とか Go とか Flutter とか Python絡みのメモを公開しています。

go fmt をプロジェクト配下の全ファイルに対して実行したい

概要

Go言語勉強中です。これも忘れないようメモ。基本的なことばかりですが・・w

go fmt をプロジェクト配下の全ファイルに一発で適用したいって話です。

勉強になったのは、以下の内容。

stackoverflow.com

ソース構成

以下のようになってるとします。

$ tree
.
├── go.mod
├── main.go
└── pkg
    └── lib
        └── lib.go

go fmt をそのまま実行する

ソースツリーのトップディレクトリに今いるとして、go fmt ってすると

$ go fmt
main.go

って感じで、実行したディレクトリの go ファイルだけがフォーマットされます。

サブディレクトリも含めて全部 go fmt したい

... という記法を使うと、それ以下のファイルを対象にできます。

$ go fmt ./...
pkg/lib/lib.go
main.go

それか、パッケージ指定して ... をつける

$ go fmt github.com/devlights/go-pkg-dir/...
main.go
pkg/lib/lib.go 

なお、今いるディレクトリのパッケージ表記は go list ってやれば取れるので

$ go fmt $(go list)/...
main.go
pkg/lib/lib.go

でもオッケイ。

gofmt コマンド使っても良い

go fmt のヘルプ見ると分かりますが、go fmt は、内部で gofmt を呼び出しています。

$ go help fmt
usage: go fmt [-n] [-x] [packages]

Fmt runs the command 'gofmt -l -w' on the packages named
by the import paths. It prints the names of the files that are modified.

For more about gofmt, see 'go doc cmd/gofmt'.
For more about specifying packages, see 'go help packages'.

The -n flag prints commands that would be executed.
The -x flag prints commands as they are executed.

To run gofmt with specific options, run gofmt itself.

gofmt コマンドの方は、再帰でファイルを見てくれます。さらにこっちの方が多機能。

ってことで、gofmt を使うと以下で同じ結果となります。

$ gofmt -l -w .
main.go
pkg/lib/lib.go

どうせなら、コードのシンプル化のオプションもあるのでつけてしまって

$ gofmt -l -s -w .
main.go
pkg/lib/lib.go

でもいいですね。

-s を付与したときの挙動は、以下に記載されています。

golang.org


過去の記事については、以下のページからご参照下さい。

  • いろいろ備忘録日記まとめ

devlights.github.io

サンプルコードは、以下の場所で公開しています。

  • いろいろ備忘録日記サンプルソース置き場

github.com

github.com

github.com