I'm trying to add an import "C"
to the AST at the begining. I want to add also some doc comment to the import node. want to look like this:
package main
/*
#include "postgres.h"
#include "fmgr.h"
*/
import "C"
func main() {}
Doing this:
//parse the file
fset := token.NewFileSet()
f, err := parser.ParseDir(fset, dir, nil, parser.ParseComments)
if err != nil {
panic(err)
}
//get the package main
packageAst, ok := f["main"]
if !ok {
fmt.Println("No package main in", dir)
return
}
//add the import "C" with the comment
for _, file := range packageAst.Files {
comment := &ast.CommentGroup{
List: []*ast.Comment{
&ast.Comment{
Slash: file.Package,
Text: "/*
#include \"postgres.h\"
#include \"fmgr.h\"
*/",
},
},
}
importC := &ast.GenDecl{
TokPos: file.Package,
Tok: token.IMPORT,
Specs: []ast.Spec{&ast.ImportSpec{Doc: comment, Path: &ast.BasicLit{Kind: token.STRING, Value: "\"C\""}}},
}
file.Decls = append([]ast.Decl{importC}, file.Decls...)
break
}
And the output is this:
package main
import "C"
func main() {}
The comment is not there. What I'm doing wrong?