From 9368d6ccbfe57bc54b433b22b2008d3c4faf086d Mon Sep 17 00:00:00 2001 From: Dmitri Shuralyov Date: Fri, 22 Aug 2014 10:18:00 -0700 Subject: [PATCH] cmd/gofmt: fix error on partial Go code ending with line comment. Fix issue by always appending newline after user input, before the closing curly bracket. The adjust func is modified to remove this new newline. Add test case (it fails before CL, passes after). Fixes #8411. LGTM=gri R=golang-codereviews, bradfitz, josharian, gri CC=golang-codereviews https://golang.org/cl/124700043 --- src/cmd/gofmt/gofmt.go | 4 ++-- src/cmd/gofmt/testdata/stdin5.golden | 3 +++ src/cmd/gofmt/testdata/stdin5.input | 3 +++ 3 files changed, 8 insertions(+), 2 deletions(-) create mode 100644 src/cmd/gofmt/testdata/stdin5.golden create mode 100644 src/cmd/gofmt/testdata/stdin5.input diff --git a/src/cmd/gofmt/gofmt.go b/src/cmd/gofmt/gofmt.go index 576cae5228e..f7d30d84052 100644 --- a/src/cmd/gofmt/gofmt.go +++ b/src/cmd/gofmt/gofmt.go @@ -277,14 +277,14 @@ func parse(fset *token.FileSet, filename string, src []byte, stdin bool) (*ast.F // into a function body. This handles expressions too. // Insert using a ;, not a newline, so that the line numbers // in fsrc match the ones in src. - fsrc := append(append([]byte("package p; func _() {"), src...), '}') + fsrc := append(append([]byte("package p; func _() {"), src...), '\n', '}') file, err = parser.ParseFile(fset, filename, fsrc, parserMode) if err == nil { adjust := func(orig, src []byte) []byte { // Remove the wrapping. // Gofmt has turned the ; into a \n\n. src = src[len("package p\n\nfunc _() {"):] - src = src[:len(src)-len("}\n")] + src = src[:len(src)-len("\n}\n")] // Gofmt has also indented the function body one level. // Remove that indent. src = bytes.Replace(src, []byte("\n\t"), []byte("\n"), -1) diff --git a/src/cmd/gofmt/testdata/stdin5.golden b/src/cmd/gofmt/testdata/stdin5.golden new file mode 100644 index 00000000000..31ce6b24852 --- /dev/null +++ b/src/cmd/gofmt/testdata/stdin5.golden @@ -0,0 +1,3 @@ +//gofmt -stdin + +i := 5 // Line comment without newline. \ No newline at end of file diff --git a/src/cmd/gofmt/testdata/stdin5.input b/src/cmd/gofmt/testdata/stdin5.input new file mode 100644 index 00000000000..0a7c97d180c --- /dev/null +++ b/src/cmd/gofmt/testdata/stdin5.input @@ -0,0 +1,3 @@ +//gofmt -stdin + +i :=5// Line comment without newline. \ No newline at end of file