golang / go

The Go programming language
https://go.dev
BSD 3-Clause "New" or "Revised" License
122.87k stars 17.52k forks source link

cmd/gofmt: gofmt -r should preserve attached comments through a rewrite #7417

Open griesemer opened 10 years ago

griesemer commented 10 years ago
$ cat test.go
package p

var x = (foo /* foo */ + bar /* bar */)

$ gofmt -r 'foo->bla' test.go 
package p

var x = (bla + bar /* bar */)

Instead it should print:

package p

var x = (bla /* foo */ + bar /* bar */)
mdempsky commented 9 years ago

This just bit me trying to use "gofmt -r" while working on issue #10055:

-       case ld.R_PLT0: // add ip, pc, #0xXX00000
+       case obj.R_PLT0:
dgryski commented 6 years ago

Another test case. I was refactoring an example and the replacement happened on the line just before the // Output: comment, causing the entire output comment block to be removed.

$ cat p_test.go
package main

import (
    "bytes"
    "fmt"
)

func ExampleFoo() {
    var a bytes.Buffer
    fmt.Fprintf(&a, "a123")
    fmt.Println(string(a.Bytes()))

    // Output:
    // a123
}

$ gofmt -d -r 'string(b.Bytes()) -> b.String()' p_test.go
diff -u p_test.go.orig p_test.go
--- p_test.go.orig  2018-02-17 09:52:32.000000000 -0800
+++ p_test.go   2018-02-17 09:52:32.000000000 -0800
@@ -8,8 +8,6 @@
 func ExampleFoo() {
    var a bytes.Buffer
    fmt.Fprintf(&a, "a123")
-   fmt.Println(string(a.Bytes()))
+   fmt.Println(a.String())

-   // Output:
-   // a123
 }
rillig commented 5 years ago

Another test case:

package main

// comment
rillig commented 4 years ago

And another test case, taken from my gobco project:

package main

//go:generate go run build/gen.go

Reproducible with go1.14 bf3ee57d27f7542808f8a153c7b547efaba355b0 from today.