
stackoverflow 地址: https://stackoverflow.com/questions/76947041/code-generation-in-golang-using-the-go-ast-package-to-add-doc-comments-but-comm
当我在 errrmsg 目录中执行 GO GENERATE 时,函数的注释不在正确的位置
// Code generated by gen_code. DO NOT EDIT. // 提示内容:"成功" // 状态码:10000 // 提示内容:"失败" // 状态码:10001 package errmsg const ( TypeCodeSuccess = 10000 TypeCodeFailed = 10001 ) func GetSuccess() Resp { return Resp{Code: TypeCodeSuccess, Msg: TypeMsgSuccess} } func GetFailed() Resp { return Resp{Code: TypeCodeFailed, Msg: TypeMsgFailed} } 这是我的代码地址: https://github.com/KingPuiWong/generrcode/blob/master/gencode/main.go
当我试着这样做,但还是不起作用时,你知道怎么解决它吗?谢谢。
commentMap := ast.NewCommentMap(fset, file, file.Comments) ast.Inspect(file, func(node ast.Node) bool { switch x := node.(type) { case *ast.FuncDecl: if strings.HasPrefix(x.Name.Name, "Get") { commentText := x.Doc.List[0].Text fmt.Println() fmt.Printf("comment:%s", commentText) commentMap[x] = []*ast.CommentGroup{{List: []*ast.Comment{{Text: commentText, Slash: token.Pos(int(x.Pos() - 1))}}}} } } return true }) ast.Print(fset, file) //os.Exit(1) // 保存已分配的错误码 err = saveLastErrorCode(projectName, lastCode) if err != nil { return err } 这是我想要生成的。
// Code generated by gen_code. DO NOT EDIT. package errmsg const ( TypeCodeSuccess = 10000 TypeCodeFailed = 10001 ) // 提示内容:"成功" // 状态码:10000 func GetSuccess() Resp { return Resp{Code: TypeCodeSuccess, Msg: TypeMsgSuccess} } // 提示内容:"失败" // 状态码:10001 func GetFailed() Resp { return Resp{Code: TypeCodeFailed, Msg: TypeMsgFailed} } 1 8520ccc 2023-08-22 01:59:47 +08:00 via iPhone 代码生成推荐用 text/template ,舒服多了 |
2 joesonw 2023-08-22 03:42:19 +08:00 via iPhone ast 包一般都拿来读的,第一次见到写的。 代码生成用 text/template 或者 jennifer 。 |
3 chai2010 2023-08-22 07:14:25 +08:00 感觉 pos 位置计算有点问题,int(x.Pos() - 1) 可能不是前一行。 pos 的定义可参考这里 https://chai2010.cn/go-ast-book/ch1/index.html 的 1.5 Position 位置信息 |
4 joyme 2023-08-22 09:53:18 +08:00 https://go.dev/talks/2015/gofmt-en.slide#14 gofmt 的作者介绍过 comments 处理,不知道对你是否有用。 |
5 japeth OP |
8 harmless 2023-08-23 02:42:20 +08:00 via iPhone 可以试试 github.com/dave/dst ,注释友好,用法与 ast 差不多 |