给定此代码,我如何在不破坏注释节点的情况下使用额外的导入规范打印它。
https://play.golang.org/p/N6_y1ehM1Qc
package main
import (
"go/ast"
"go/parser"
"go/printer"
"go/token"
"log"
"os"
"golang.org/x/tools/go/loader"
)
func main() {
var conf loader.Config
conf.ParserMode = parser.ParseComments
f, err := conf.ParseFile("main.go", `// some comment goes here
package main
// some comment here.
// main comment here.
func main(){
}
`)
if err != nil {
log.Fatal(err)
}
conf.CreateFromFiles("main", f)
prog, err := conf.Load()
if err != nil {
log.Println(err)
}
g := &ast.GenDecl{}
g.Tok = token.IMPORT
spec := &ast.ImportSpec{
Path: &ast.BasicLit{Value: "package/path"},
}
g.Specs = append(g.Specs, spec)
f.Decls = append([]ast.Decl{g}, f.Decls...)
_ = prog
printer.Fprint(os.Stdout, token.NewFileSet(), f)
//printer.Fprint(os.Stdout, prog.Fset, f)
}
该程序显示
package main // some comment goes here
// some comment here.
// main comment here.
import package/path
func main() {
}
我期望得到类似的输出(不确定
import
语句是在单独的第二个注释行之前还是之后)// some comment goes here
package main
// some comment here.
import package/path
// main comment here.
func main() {
}
在更复杂的程序中,输出中断。我得到了混乱的go代码,例如
// some comment goes here
package main
import // some comment here.
package/path
// main comment here.
func main() {
}
最佳答案
对于我的特定用例,添加一个import语句,解决方案是使用astutil.AddImport,如@mkopriva所建议
astutil.AddImport(prog.Fset, f, "package/path")
关于go - 使用包加载器,如何更新包含注释的ast并打印结果代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58955135/