-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
211 lines (193 loc) · 5.3 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
package main
import (
"embed"
"fmt"
"io/ioutil"
"log"
"os"
"path"
"sort"
"strings"
"text/template"
sprig "github.com/go-task/slim-sprig"
"github.com/jessevdk/go-flags"
"github.com/pb33f/libopenapi"
validator "github.com/pb33f/libopenapi-validator"
"github.com/pb33f/libopenapi/datamodel"
"github.com/pb33f/libopenapi/datamodel/high/base"
v3 "github.com/pb33f/libopenapi/datamodel/high/v3"
"github.com/pb33f/libopenapi/renderer"
"golang.org/x/exp/slog"
)
//go:embed templates/*
var templates embed.FS
type endpoint struct {
Name string
Resource *v3.PathItem
Weight int
}
type schemaData struct {
Name string
Schema *base.Schema
Weight int
}
type config struct {
Dir string `long:"dir" short:"d" description:"The directory in which to place the cfg.Dir files" required:"true"`
Spec string `long:"spec" short:"s" description:"The OpenAPI spec file to laod" required:"true"`
SinglePage bool `short:"1" description:"Create a single output page of the entire API"`
Github bool `short:"g" description:"Create Github compatible markdown"`
}
func main() {
cfg := &config{}
_, err := flags.Parse(cfg)
if err != nil {
log.Fatalf("Cannot parse command arguments: %v", err)
}
fInfo, err := os.Stat(cfg.Dir)
if err != nil {
log.Fatalf("Error getting output dir info: %v", err)
}
if !fInfo.IsDir() {
log.Fatalf("%s is not a directory", cfg.Dir)
}
prefix := ""
if !cfg.Github {
prefix = "hugo"
}
mg := renderer.NewMockGenerator(renderer.JSON)
mg.SetPretty()
indextmpl, err := template.New("base").Funcs(sprig.FuncMap()).Funcs(
template.FuncMap{
"renderExample": func(obj any) string {
defer func() {
if r := recover(); r != nil {
slog.Error(fmt.Sprintf("Could not render example: %v", r))
}
}()
result, err := mg.GenerateMock(obj, "")
if err != nil {
return fmt.Sprintf("Could not render example: %v", err)
}
return string(result)
},
},
).ParseFS(templates, "templates/*.tmpl")
if err != nil {
panic(err)
}
fd, err := ioutil.ReadFile(cfg.Spec)
if err != nil {
panic(err)
}
apicfg := datamodel.DocumentConfiguration{
AllowFileReferences: true,
AllowRemoteReferences: true,
}
document, err := libopenapi.NewDocumentWithConfiguration(fd, &apicfg)
if err != nil {
panic(err)
}
highLevelValidator, validatorErrs := validator.NewValidator(document)
if validatorErrs != nil {
slog.Error("Please fix validation errors:")
for _, ve := range validatorErrs {
slog.Error(ve.Error())
}
log.Fatal("")
}
if ok, vErrs := highLevelValidator.ValidateDocument(); !ok {
slog.Error("OpenAPI document is not valid:")
for _, ve := range vErrs {
slog.Error(fmt.Sprintf("%s: %s", ve.Message, ve.HowToFix))
}
log.Fatal()
}
oapi, errors := document.BuildV3Model()
// if anything went wrong when building the v3 model, a slice of errors will be returned
if len(errors) > 0 {
for i := range errors {
fmt.Printf("error: %e\n", errors[i])
}
panic(fmt.Sprintf("cannot create v3 model from document: %d errors reported",
len(errors)))
}
indexName := "_index.md"
if cfg.SinglePage || cfg.Github {
indexName = "README.md"
}
out, err := os.Create(path.Join(cfg.Dir, indexName))
err = indextmpl.ExecuteTemplate(out, fmt.Sprintf("%s%s", prefix, "index"), oapi.Model)
if err != nil {
panic(err)
}
if !cfg.SinglePage {
out.Close()
}
if oapi.Model.Paths != nil {
paths := make([]string, 0, len(oapi.Model.Paths.PathItems))
for k := range oapi.Model.Paths.PathItems {
paths = append(paths, k)
}
sort.Strings(paths)
for x, name := range paths {
resource := oapi.Model.Paths.PathItems[name]
if !cfg.SinglePage {
out, err = os.Create(path.Join(cfg.Dir, fileName(name)))
if err != nil {
panic(err)
}
}
endpoint := &endpoint{Name: name, Resource: resource, Weight: (x + 1) * 10}
err = indextmpl.ExecuteTemplate(out, fmt.Sprintf("%s%s", prefix, "resource"), endpoint)
if err != nil {
slog.Error(fmt.Sprintf("Error rendering %s%s (%s): %v", prefix, "resource", endpoint.Name, err))
}
if !cfg.SinglePage {
out.Close()
}
}
}
/* For generating separate schema pages
if oapi.Model.Components != nil && oapi.Model.Components.Schemas != nil {
if !cfg.SinglePage {
out, err = os.Create(path.Join(cfg.Dir, "schemas", indexName))
if err != nil {
panic(err)
}
}
err = indextmpl.ExecuteTemplate(out, fmt.Sprintf("%sschema%s", prefix, "index"), oapi.Model)
if err != nil {
panic(err)
}
if !cfg.SinglePage {
out.Close()
}
schemas := make([]string, 0, len(oapi.Model.Components.Schemas))
for k := range oapi.Model.Components.Schemas {
schemas = append(schemas, k)
}
sort.Strings(schemas)
for x, sName := range schemas {
schema := oapi.Model.Components.Schemas[sName]
data := &schemaData{Name: sName, Schema: schema.Schema(), Weight: (x + 1) * 10}
if !cfg.SinglePage {
out, err = os.Create(path.Join(cfg.Dir, "schemas", fileName(sName)))
if err != nil {
panic(err)
}
}
err = indextmpl.ExecuteTemplate(out, fmt.Sprintf("%s%s", prefix, "schema"), data)
if err != nil {
slog.Error(fmt.Sprintf("Error rendering %s%s (%s): %v", prefix, "schema", sName, err))
}
if !cfg.SinglePage {
out.Close()
}
}
}
*/
out.Close()
}
func fileName(name string) string {
return strings.Replace(name, "/", "_", -1) + ".md"
}