Skip to content

Commit

Permalink
feat: groups and apis can sort with order attr, api version attr outp…
Browse files Browse the repository at this point in the history
…ut, remove main file args
  • Loading branch information
alovn committed May 16, 2022
1 parent 913e9d9 commit 6d1a7ba
Show file tree
Hide file tree
Showing 12 changed files with 170 additions and 117 deletions.
12 changes: 4 additions & 8 deletions cmd/apidoc/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,33 +11,29 @@ import (
func main() {
var searchDir string
var outputDir string
var mainFile string
var isSingle bool
var isHelp bool
flag.StringVar(&searchDir, "dir", ".", "--dir")
flag.StringVar(&outputDir, "output", "./docs/", "--output")
flag.StringVar(&mainFile, "main", "main.go", "--main")
flag.BoolVar(&isSingle, "single", false, "--single")
flag.BoolVar(&isHelp, "help", false, "--help")
flag.Parse()
if isHelp {
fmt.Println(`apidoc is a tool for Go to generate apis markdown docs.
Usage:
apidoc --dir= --output= --main= --single
apidoc --dir= --output= --single
Flags:
--dir: search apis dir, default .
--output: generate markdown files dir, default ./docs/
--main: the path of main go file, default main.go
--single: generate single markdown file, default multi group files`)
return
}
g := gen.New(&gen.Config{
SearchDir: searchDir,
MainFile: mainFile,
OutputDir: outputDir,
IsGenGroupFile: !isSingle,
SearchDir: searchDir,
OutputDir: outputDir,
IsGenSingleFile: isSingle,
})
if err := g.Build(); err != nil {
log.Fatal(err)
Expand Down
8 changes: 4 additions & 4 deletions examples/docs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,13 @@ version: _@1.0.1_

2.5. [获取地址列表](./apis-address.md#5-获取地址列表)(Deprecated)

3. [资料管理](./apis-profile.md)
3. [菜单管理](./apis-menu.md)

3.1. [获取用户资料](./apis-profile.md#1-获取用户资料)
3.1. [获取菜单节点](./apis-menu.md#1-获取菜单节点)

4. [菜单管理](./apis-menu.md)
4. [资料管理](./apis-profile.md)

4.1. [获取菜单节点](./apis-menu.md#1-获取菜单节点)
4.1. [获取用户资料](./apis-profile.md#1-获取用户资料)

5. [测试示例](./apis-demo.md)

Expand Down
6 changes: 4 additions & 2 deletions examples/docs/apis-demo.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@

### 1. struct数组

version: _1.0.2.1_

```text
GET /user/demo/struct_array
```
Expand Down Expand Up @@ -212,9 +214,9 @@ __Response__:
{ //object(common.Response), 通用返回结果
"code": 0, //int, 返回状态码
"data": { //object(handler.DemoTime)
"time_1": "2022-05-16T11:38:50.59873+08:00", //object(time.Time), example1
"time_1": "2022-05-16T16:47:48.741899+08:00", //object(time.Time), example1
"time_2": "2022-05-14 15:04:05", //object(time.Time), example2
"time_3": "2022-05-16T11:38:50.598876+08:00" //object(time.Time)
"time_3": "2022-05-16T16:47:48.742123+08:00" //object(time.Time)
},
"msg": "success" //string, 返回消息
}
Expand Down
1 change: 1 addition & 0 deletions examples/svc-user/handler/account.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ type RegisterResponse struct {
//@response 200 common.Response{code=10011,msg="password format error"} "密码格式错误"
//@author alovn
//@desc 用户注册接口说明
//@order -1
func (h *AccountHandler) Register(w http.ResponseWriter, r *http.Request) {
res := common.NewResponse(200, "注册成功", &RegisterResponse{
Username: "abc",
Expand Down
1 change: 1 addition & 0 deletions examples/svc-user/handler/demo.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ type DemoMap map[string]DemoData
//@title struct数组
//@group demo
//@response 200 []DemoData "demo struct array"
//@version 1.0.2.1
func (h *DemoHandler) StructArray(w http.ResponseWriter, r *http.Request) {

}
Expand Down
1 change: 1 addition & 0 deletions examples/svc-user/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ func main() {
//@group demo
//@title 测试示例
//@desc 其它一些示例演示
//@order 6
{
demo := handler.NewDemoHandler()
mux.HandleFunc("/user/demo/struct_array", demo.StructArray)
Expand Down
92 changes: 59 additions & 33 deletions gen/gen.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import (
"fmt"
"os"
"path/filepath"
"sort"
"strings"
"text/template"

"github.com/alovn/apidoc"
Expand All @@ -21,35 +23,50 @@ func New(c *Config) *Gen {
}

type Config struct {
SearchDir string
OutputDir string
TemplateFile string
MainFile string
IsGenGroupFile bool
SearchDir string
OutputDir string
TemplateFile string
IsGenSingleFile bool
}

func (g *Gen) Build() error {
if g.c == nil {
return errors.New("error config")
}
p := apidoc.New()
if err := p.Parse(g.c.SearchDir, g.c.MainFile); err != nil {
if err := p.Parse(g.c.SearchDir); err != nil {
return err
}
doc := p.GetApiDoc()
if doc.Title == "" && doc.Service == "" && len(doc.Apis) == 0 {
fmt.Println("can't find apis")
if doc.Service == "" {
fmt.Println("apidoc @service is not set")
return nil
}
if doc.Title == "" {
fmt.Println("apidoc @title is not set")
return nil
}
if doc.TotalCount == 0 {
fmt.Println("apis count is 0")
return nil
}

if len(doc.Apis) > 0 {
if len(doc.UngroupedApis) > 0 {
doc.Groups = append(doc.Groups, &apidoc.ApiGroupSpec{
Group: "ungrouped",
Title: "ungrouped",
Description: "Ungrouped apis",
Apis: doc.Apis,
Apis: doc.UngroupedApis,
})
doc.UngroupedApis = doc.UngroupedApis[:0]
}
sort.Slice(doc.Groups, func(i, j int) bool {
a, b := doc.Groups[i], doc.Groups[j]
if a.Order == b.Order {
return strings.Compare(a.Group, b.Group) < 0
}
return a.Order < b.Order
})

if err := os.MkdirAll(g.c.OutputDir, os.ModePerm); err != nil {
return err
Expand All @@ -60,16 +77,44 @@ func (g *Gen) Build() error {
return a + b
},
}
sortApis := func(apis []*apidoc.ApiSpec) {
less := func(i, j int) bool {
a, b := apis[i], apis[j]
return a.Order < b.Order
}
sort.Slice(apis, less)
}

if g.c.IsGenGroupFile {
if g.c.IsGenSingleFile {
t := template.New("apis-single").Funcs(funcMap)
t, err := t.Parse(singleApisTemplate)
if err != nil {
return err
}
f, err := os.Create(filepath.Join(g.c.OutputDir, "README.md"))
if err != nil {
return err
}
defer f.Close()
for _, g := range doc.Groups {
apis := g.Apis
sortApis(apis)
}

if err = t.Execute(f, doc); err != nil {
return err
}
fmt.Println("generated: README.md")
} else {
//group
t := template.New("group").Funcs(funcMap)
t := template.New("group-apis").Funcs(funcMap)
t, err := t.Parse(groupApisTemplate)
if err != nil {
return err
}
for _, v := range doc.Groups {
group := v
sortApis(group.Apis)
fileName := fmt.Sprintf("apis-%s.md", group.Group)
f, err := os.Create(filepath.Join(g.c.OutputDir, fileName))
if err != nil {
Expand All @@ -83,7 +128,7 @@ func (g *Gen) Build() error {
}

//readme
t = template.New("apis").Funcs(funcMap)
t = template.New("group-readme").Funcs(funcMap)
t, err = t.Parse(groupReadmeTemplate)
if err != nil {
return err
Expand All @@ -97,26 +142,7 @@ func (g *Gen) Build() error {
return err
}
fmt.Println("generated: README.md")

return nil
}

t := template.New("apis-single").Funcs(funcMap)
t, err := t.Parse(singleApisTemplate)
if err != nil {
return err
}
f, err := os.Create(filepath.Join(g.c.OutputDir, "README.md"))
if err != nil {
return err
}
defer f.Close()
for _, g := range doc.Groups {
doc.Apis = append(g.Apis, doc.Apis...)
}
if err = t.Execute(f, doc); err != nil {
return err
}
fmt.Println("generated: README.md")
fmt.Println("apis total count:", doc.TotalCount)
return nil
}
5 changes: 5 additions & 0 deletions gen/template/group_apis.tpl
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,11 @@ ___Deprecated___
author: _{{$v.Author}}_
{{- end}}

{{- if $v.Version}}

version: _{{$v.Version}}_
{{- end}}

```text
{{$v.HTTPMethod}} {{$v.FullURL}}
```
Expand Down
5 changes: 5 additions & 0 deletions gen/template/single.tpl
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,11 @@ ___Deprecated___
author: _{{$v.Author}}_
{{- end}}

{{- if $v.Version}}

version: _{{$v.Version}}_
{{- end}}

```text
{{$v.HTTPMethod}} {{$v.FullURL}}
```
Expand Down
7 changes: 6 additions & 1 deletion operation.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,12 @@ func (operation *Operation) ParseComment(comment string, astFile *ast.File) erro
return operation.ParseParametersComment(strings.TrimPrefix(lowerAttribute, "@"), lineRemainder, astFile)
case deprecatedAttr, "deprecated:":
operation.Deprecated = true
case orderAttr:
if i, err := strconv.Atoi(lineRemainder); err == nil {
operation.Order = i
}
case versionAttr:
operation.Version = lineRemainder
}
return nil
}
Expand Down Expand Up @@ -105,7 +111,6 @@ func (operation *Operation) ParseRouterComment(commentLine string) error {

operation.HTTPMethod = httpMethod
operation.Api = matches[2]
operation.FullURL = fmt.Sprintf("%s/%s", strings.TrimSuffix(operation.parser.doc.BaseURL, "/"), strings.TrimPrefix(operation.Api, "/"))
return nil
}

Expand Down
Loading

0 comments on commit 6d1a7ba

Please sign in to comment.