go-zero/tools/goctl/api/docgen/doc.go

110 lines
2.5 KiB
Go
Raw Normal View History

2020-07-29 17:11:41 +08:00
package docgen
import (
"bytes"
_ "embed"
2020-07-29 17:11:41 +08:00
"fmt"
"go/format"
2020-07-29 17:11:41 +08:00
"html/template"
"strconv"
"strings"
"github.com/zeromicro/go-zero/core/stringx"
"github.com/zeromicro/go-zero/tools/goctl/api/gogen"
"github.com/zeromicro/go-zero/tools/goctl/api/spec"
"github.com/zeromicro/go-zero/tools/goctl/api/util"
2020-07-29 17:11:41 +08:00
)
//go:embed markdown.tpl
var markdownTemplate string
2020-07-29 17:11:41 +08:00
func genDoc(api *spec.ApiSpec, dir, filename string) error {
if len(api.Service.Routes()) == 0 {
return nil
}
2020-07-29 17:11:41 +08:00
fp, _, err := util.MaybeCreateFile(dir, "", filename)
if err != nil {
return err
}
defer fp.Close()
2020-07-29 17:11:41 +08:00
var builder strings.Builder
for index, route := range api.Service.Routes() {
routeComment := route.JoinedDoc()
2020-07-29 17:11:41 +08:00
if len(routeComment) == 0 {
routeComment = "N/A"
}
requestContent, err := buildDoc(route.RequestType, api)
if err != nil {
return err
}
responseContent, err := buildDoc(route.ResponseType, api)
2020-07-29 17:11:41 +08:00
if err != nil {
return err
}
t := template.Must(template.New("markdownTemplate").Parse(markdownTemplate))
var tmplBytes bytes.Buffer
err = t.Execute(&tmplBytes, map[string]string{
"index": strconv.Itoa(index + 1),
"routeComment": routeComment,
"method": strings.ToUpper(route.Method),
"uri": route.Path,
"requestType": "`" + stringx.TakeOne(route.RequestTypeName(), "-") + "`",
"responseType": "`" + stringx.TakeOne(route.ResponseTypeName(), "-") + "`",
"requestContent": requestContent,
2020-07-29 17:11:41 +08:00
"responseContent": responseContent,
})
if err != nil {
return err
}
builder.Write(tmplBytes.Bytes())
}
2020-07-29 17:11:41 +08:00
_, err = fp.WriteString(strings.Replace(builder.String(), """, `"`, -1))
return err
}
func buildDoc(route spec.Type, api *spec.ApiSpec) (string, error) {
if route == nil || len(route.Name()) == 0 {
return "", nil
}
2021-04-15 19:49:17 +08:00
tps := make([]spec.Type, 0)
tps = append(tps, route)
if definedType, ok := route.(spec.DefineStruct); ok {
associatedTypes(definedType, &tps)
}
value, err := gogen.BuildTypes(tps, api)
2020-07-29 17:11:41 +08:00
if err != nil {
return "", err
}
formatted, err := format.Source([]byte(value))
if err != nil {
return "", err
}
return fmt.Sprintf("\n\n```golang\n%s\n```\n", string(formatted)), nil
2020-07-29 17:11:41 +08:00
}
func associatedTypes(tp spec.DefineStruct, tps *[]spec.Type) {
2021-04-15 19:49:17 +08:00
hasAdded := false
for _, item := range *tps {
if item.Name() == tp.Name() {
hasAdded = true
break
}
}
if !hasAdded {
*tps = append(*tps, tp)
}
for _, item := range tp.Members {
if definedType, ok := item.Type.(spec.DefineStruct); ok {
associatedTypes(definedType, tps)
}
}
}