これは、なにをしたくて書いたもの?
Goで書いたソースコードを、ディレクトリ内を再帰的にフォーマットしたいということで。
どうも、gofmtとgo fmtを使う場合で違うようです。
今回は、カレントディレクトリ(.)に考えます。
環境
今回の環境は、こちらです。
$ go version go version go1.15.6 linux/amd64
gofmtを使う場合
.を指定して実行すればいいみたいです。再帰的に見てくれます。
$ gofmt -w .
-wオプションは、ソースコードを書き換えてしまうオプションです。これを指定しない場合は、フォーマットされた結果が
標準出力に書き出されるだけで、ソースコード自体は変わりません。
個人的には、こんな感じで良いのではと。
$ gofmt -d -w .
-dは差分表示です。
$ gofmt -h
usage: gofmt [flags] [path ...]
-cpuprofile string
write cpu profile to this file
-d display diffs instead of rewriting files
-e report all errors (not just the first 10 on different lines)
-l list files whose formatting differs from gofmt's
-r string
rewrite rule (e.g., 'a[b:len(a)] -> a[b:]')
-s simplify code
-w write result to (source) file instead of stdout
go fmtを使う場合
go fmtを使う場合は、...記法を使います。
$ go fmt ./...
なお、go fmtの正体は、ヘルプを見るとわかりますがgofmt -l -wです。
$ 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. The -mod flag's value sets which module download mode to use: readonly or vendor. See 'go help modules' for more. To run gofmt with specific options, run gofmt itself. See also: go fix, go vet.
ちなみに、gofmtで同様の記法を使うとエラーになります…。
$ gofmt ./... stat ./...: no such file or directory
まあ、gofmtを使う、で良いような気はしますね。