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, 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)
}
}
What's the best way to manipulate the AST while preserving comments? Would using