I'm trying to modify a source file and replace some function parameters
based on their names. I was able to get some basics working by following this
tutorial <https://zupzup.org/go-ast-traversal/>, however when I write the
new file, it's deleting the existing comments.
It looks like just the act of reading in the source and rewriting it is
stripping the comments:
func main() {
// --------------- Start test file contents
testFileContents := `
// Licensed under the Apache License...
package main
const (
kMaxRecentSequences = 20 // Maximum number of sequences stored in
RecentSequences before pruning is triggered
)
//////// READING DOCUMENTS:
func fakeFunc(docid string) string {
return docid
}
func main() {
fakeFunc("foo") // Call fakeFunc
}`
// --------------- End test file contents
err := ioutil.WriteFile("/tmp/source.go", []byte(testFileContents),
0644)
if err != nil {
log.Fatal(err)
}
fset := token.NewFileSet()
node, err := parser.ParseFile(fset, "/tmp/source.go", nil, 0)
if err != nil {
log.Fatal(err)
}
ast.Inspect(node, func(n ast.Node) bool {
return true
})
f, err := os.Create("/tmp/source_modified.go")
defer f.Close()
if err := printer.Fprint(f, fset, node); err != nil {
log.Fatal(err)
}
}
The rewritten source code in /tmp/source_modified.go is:
package main
const (
kMaxRecentSequences = 20
)
func fakeFunc(docid string) string {
return docid
}
func main() {
fakeFunc("foo")
}
What's the best way to manipulate the AST while preserving comments? Would
using https://godoc.org/golang.org/x/tools/go/ast/astutil#Apply improve the
situation?
--
You received this message because you are subscribed to the Google Groups
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
For more options, visit https://groups.google.com/d/optout.