-
Notifications
You must be signed in to change notification settings - Fork 0
/
Documentation.go
324 lines (285 loc) · 7.5 KB
/
Documentation.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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
// Godoc2API
// todo
// Fix: combinable enums is not RAML 1.0 compliant
// Features: Annotations
// Features: Traits
// Improvement: Handle array type definitions like: (string | Person)[] (https://github.com/raml-org/raml-spec/blob/master/versions/raml-10/raml-10.md/#type-expressions)
// Improvement: Create files for types to include
// Tests/examples: SecuritySchemes
package godoc2api
import (
"errors"
"fmt"
"io/ioutil"
"log"
"os"
"path/filepath"
"regexp"
"strings"
"github.com/florenthobein/godoc2api/raml"
)
// Default settings used for rendering the RAML root document
const (
_DEFAULT_TITLE = "Your API"
_DEFAULT_VERSION = "v1"
_DEFAULT_URL = "http://localhost/{v1}"
_DEFAULT_MEDIA_TYPE = "application/json"
_DEFAULT_OUTPUT_DIR = "raml"
)
// The tag that is used to parse an evenutal input struct that describes a route
const _MAIN_TAG_NAME = "raml"
// Main documentation struct, used to render a complete RAML documentation.
type Documentation struct {
Title string
Description string
Version string
URL string
MediaType string
UserDocumentation []map[string]string
routes map[string]Route
types map[string]Type
traits map[string]Trait
annotations map[string]Annotation
}
// Add a route to the documentation.
//
// Adding a route via a handler function
//
// A route can be registered throught its http handler function, in that case the function should be fully documented, including with the tag `@resource` and `@method` (cf Reserved tags https://godoc.org/github.com/florenthobein/godoc2api/#pkg-constants).
//
// Example:
// // Define a http handler
// // @resource GET /myroute
// // @response {MyObject}
// func MyHandler(http.ResponseWriter, *http.Request) { ... }
//
// ...
//
// // Register the route
// d := godoc2api.Documentation{}
// d.AddRoute(MyHandler)
//
// Adding a route via a struct
//
// A route can also be registered via a struct which fields use the tag `raml`, matching the reserved tags (cf Reserved tags https://godoc.org/github.com/florenthobein/godoc2api/#pkg-constants).
//
// Example:
// // Define a http handler
// func MyHandler(http.ResponseWriter, *http.Request) { ... }
//
// ...
//
// // Custom route definition struct
// type MyRouteDefinition struct {
// Resource string `raml:"resource"`
// Resp string `raml:"response"`
// }
//
// ...
//
// // Register the route
// d := godoc2api.Documentation{}
// d.AddRoute(MyRouteDefinition{ "GET /myroute", "MyObject" })
func (d *Documentation) AddRoute(user_route interface{}) error {
r := Route{_documentation: d}
// Read the comment
c, extra, err := readComment(user_route)
if err != nil {
warn("%v (%v)", err, user_route)
return err
}
// If `user_route` is a struct and tags are already defined inside,
// fill the route with it
if extra != nil {
for k, v := range extra {
err := r.addTag(k, v)
if err != nil {
warn("%v (%v)", err, user_route)
}
}
}
// Parse the comment to extract tags and add it to the route
tags := parseComment(c)
for keyword, values := range tags {
for _, fields := range values {
err := r.addTag(keyword, fields)
if err != nil {
warn("%v (%v)", err, user_route)
}
}
}
// Check if the route can be used
if err := r.checkViability(); err != nil {
warn("unusable route: %v (%v)", err, user_route)
return err
}
// Check if the route is coherent
if err := r.checkURIParameters(); err != nil {
warn("uncoherent route: %v (%s)", err, r.Resource)
}
// Store the route
if d.routes == nil {
d.routes = make(map[string]Route)
}
d.routes[r.signature()] = r
return nil
}
// Add an external documentation to describe the API
func (d *Documentation) AddUserDocumentation(title, content string) error {
if title == "" || content == "" {
return errors.New("empty title or content")
}
if d.UserDocumentation == nil {
d.UserDocumentation = []map[string]string{}
}
d.UserDocumentation = append(d.UserDocumentation, map[string]string{
"title": title,
"content": content,
})
return nil
}
// Generate the documentation
func (d *Documentation) toString() (string, error) {
// Fill the empty fields
if d.Title == "" {
d.Title = _DEFAULT_TITLE
}
if d.Version == "" {
d.Version = _DEFAULT_VERSION
}
if d.URL == "" {
d.URL = _DEFAULT_URL
}
if d.MediaType == "" {
d.MediaType = _DEFAULT_MEDIA_TYPE
}
// Format the document to a RAML structure
api, err := d.toRAML()
if err != nil {
problem(err.Error())
return "", err
}
// Transform the RAML into a string
s := api.String()
return s, nil
}
// Print the documentation
func (d *Documentation) Print() error {
s, err := d.toString()
if err != nil {
return err
}
log.Println(s)
return nil
}
// Render the documentation into a RAML file in the designated directory.
func (d *Documentation) Save(dirname string) error {
sep := string(filepath.Separator)
if dirname == "" {
warn("no output directory specified, rendering to default %s", _DEFAULT_OUTPUT_DIR)
dirname = _DEFAULT_OUTPUT_DIR
} else {
dirname = strings.Trim(dirname, " "+sep)
}
s, err := d.toString()
if err != nil {
return err
}
// Get the filename
filename := fmt.Sprintf(
"%s_%s.raml",
regexp.MustCompile(`[^0-9a-z]`).ReplaceAllString(strings.ToLower(d.Title), "_"),
d.Version,
)
// Create the directory
dirpath := fmt.Sprintf(".%s%s",
sep,
dirname,
)
os.Mkdir(dirpath, 0777)
// Create the file
filepath := fmt.Sprintf("%s%s%s",
dirpath,
sep,
filename,
)
err = ioutil.WriteFile(filepath, []byte(s), 0644)
if err != nil {
problem(err.Error())
}
return err
}
// The Types to add in the RAML document when rendering
func (d *Documentation) addType(t Type) bool {
if d.types == nil {
d.types = make(map[string]Type)
}
if _, ok := d.types[string(t)]; ok {
return false
}
d.types[string(t)] = t
other_ts := extractTypes(string(t))
for _, t := range other_ts {
d.addType(t)
}
return true
}
// Transform the documentation into a RAML structure
func (d *Documentation) toRAML() (raml.Root, error) {
api := raml.Root{
Title: d.Title,
Description: d.Description,
Version: d.Version,
BaseURI: d.URL,
MediaType: d.MediaType,
Documentation: d.UserDocumentation,
}
// Create the resources
if d.routes != nil {
api.Resources = make(map[string]raml.Resource)
for _, r := range d.routes {
err := r.fillToRAML(&api.Resources)
if err != nil {
return api, fmt.Errorf("error while RAMLing resource %s: %v", r.Resource, err)
}
}
// Pile the resources
api.PileResources()
}
// Create the types
if d.types != nil {
api.Types = make(map[string]raml.Type)
for _, t := range d.types {
err := t.fillToRAML(&api.Types)
if err != nil {
return api, fmt.Errorf("error while RAMLing type %s: %v", t, err)
}
}
}
// Create the annotation types
if d.annotations != nil {
api.AnnotationTypes = make(map[string]raml.AnnotationType)
for _, a := range d.annotations {
err := a.fillToRAML(&api.AnnotationTypes)
if err != nil {
return api, fmt.Errorf("error while RAMLing annotation %s: %v", a, err)
}
}
}
// Create the traits
if d.traits != nil {
api.Traits = make(map[string]raml.Trait)
for _, t := range d.traits {
err := t.fillToRAML(&api.Traits)
if err != nil {
return api, fmt.Errorf("error while RAMLing trait %s: %v", t, err)
}
}
}
// Create the security schemes globaly defined
if hasReservedSecurity() {
api.SecuritySchemes = make(map[string]raml.SecurityScheme)
securitiesToRAML(&api.SecuritySchemes)
}
return api, nil
}