Skip to content

proposal: cmd/gofmt: add option to insert missing end-of-line commas in program #18939

@rhysd

Description

@rhysd

Please answer these questions before submitting your issue. Thanks!

What version of Go are you using (go version)?

go version go1.7.4 darwin/amd64

What operating system and processor architecture are you using (go env)?

GOARCH="amd64"
GOBIN=""
GOEXE=""
GOHOSTARCH="amd64"
GOHOSTOS="darwin"
GOOS="darwin"
GOPATH="/Users/rhysd/.go"
GORACE=""
GOROOT="/usr/local/Cellar/go/1.7.4_1/libexec"
GOTOOLDIR="/usr/local/Cellar/go/1.7.4_1/libexec/pkg/tool/darwin_amd64"
CC="clang"
GOGCCFLAGS="-fPIC -m64 -pthread -fno-caret-diagnostics -Qunused-arguments -fmessage-length=0 -fdebug-prefix-map=/var/folders/sv/mr3y8ytd7gzfdww8gxx568z80000gn/T/go-build764880956=/tmp/go-build -gno-record-gcc-switches -fno-common"
CXX="clang++"
CGO_ENABLED="1"

What did you do?

If possible, provide a recipe for reproducing the error.
A complete runnable program is good.
A link on play.golang.org is best.

First, save below code as blah.go

package main

func main() {
	a := []int{
		1,
		2
	}
}

Then execute below command

$ gofmt blah.go

What did you expect to see?

Automatically fix trailing comma at 2 (line 6, column 9) and formatting has been done successfully.

What did you see instead?

Formatting failed with below error

blah.go:6:4: missing ',' before newline in composite literal

I believe this is because gofmt can't format a code which contains syntax error. Trailing comma such as line 6 in above is a syntax error in Go. So gofmt cannot fix this. However, we tend to forget adding trailing comma when expose one line code to multi-line code. If gofmt can fix it automatically, we no longer need to take care about trailing commas.

I guess implementing this is not so difficult. When parsing failed, then fix the source and retry to parse it again.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions