forked from bukalapak/snowboard
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
468 lines (387 loc) · 9.01 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
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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
package main
//go:generate esc -o templates.go ./templates
import (
"bytes"
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"strings"
"text/tabwriter"
"github.com/bukalapak/snowboard/adapter/drafter"
"github.com/bukalapak/snowboard/adapter/drafterc"
"github.com/bukalapak/snowboard/mock"
snowboard "github.com/bukalapak/snowboard/parser"
"github.com/bukalapak/snowboard/render"
"github.com/fsnotify/fsnotify"
xerrors "github.com/pkg/errors"
cli "gopkg.in/urfave/cli.v1"
)
var versionStr string
var (
engine snowboard.Parser
engineC snowboard.Parser
)
func main() {
engine = drafter.Engine{}
engineC = drafterc.Engine{}
cli.VersionPrinter = func(c *cli.Context) {
fmt.Fprintf(c.App.Writer, "Snowboard version: %s\n", c.App.Version)
fmt.Fprintf(c.App.Writer, "Drafter version: %s\n", engine.Version())
}
if versionStr == "" {
versionStr = "HEAD"
}
app := cli.NewApp()
app.Name = "snowboard"
app.Usage = "API blueprint toolkit"
app.Version = versionStr
app.Before = func(c *cli.Context) error {
if c.Args().Present() && c.Args().Get(1) == "" {
cli.ShowCommandHelp(c, c.Args().Get(0))
}
return nil
}
app.Commands = []cli.Command{
{
Name: "lint",
Usage: "Validate API blueprint",
Flags: []cli.Flag{
cli.BoolFlag{
Name: "c",
Usage: "Use character index instead of line and row number",
},
},
Action: func(c *cli.Context) error {
if c.Args().Get(0) == "" {
return nil
}
if err := validate(c, c.Args().Get(0), c.Bool("c")); err != nil {
if strings.Contains(err.Error(), "read failed") {
return xerrors.Cause(err)
}
return cli.NewExitError(err.Error(), 1)
}
return nil
},
},
{
Name: "html",
Usage: "Render HTML documentation",
Flags: []cli.Flag{
cli.StringFlag{
Name: "o",
Usage: "HTML file",
},
cli.StringFlag{
Name: "t",
Value: "alpha",
Usage: "Template for HTML documentation",
},
cli.BoolFlag{
Name: "s",
Usage: "Serve HTML via HTTP server",
},
cli.StringFlag{
Name: "b",
Value: "127.0.0.1:8088",
Usage: "HTTP server listen address",
},
},
Action: func(c *cli.Context) error {
if c.Args().Get(0) == "" {
return nil
}
if c.Bool("s") {
if err := watchHTML(c, c.Args().Get(0), c.String("o"), c.String("t"), c.String("b")); err != nil {
return cli.NewExitError(err.Error()+"\n", 1)
}
}
if err := renderHTML(c, c.Args().Get(0), c.String("o"), c.String("t")); err != nil {
return cli.NewExitError(err.Error(), 1)
}
return nil
},
},
{
Name: "apib",
Usage: "Render API blueprint",
Flags: []cli.Flag{
cli.StringFlag{
Name: "o",
Usage: "API blueprint output file",
},
},
Action: func(c *cli.Context) error {
if c.Args().Get(0) == "" {
return nil
}
if err := renderAPIB(c, c.Args().Get(0), c.String("o")); err != nil {
return cli.NewExitError(err.Error(), 1)
}
return nil
},
},
{
Name: "json",
Usage: "Render API element json",
Flags: []cli.Flag{
cli.StringFlag{
Name: "o",
Usage: "API element output file",
},
},
Action: func(c *cli.Context) error {
if c.Args().Get(0) == "" {
return nil
}
if err := renderJSON(c, c.Args().Get(0), c.String("o")); err != nil {
return cli.NewExitError(err.Error(), 1)
}
return nil
},
},
{
Name: "mock",
Usage: "Run Mock server",
Flags: []cli.Flag{
cli.StringFlag{
Name: "b",
Value: "127.0.0.1:8087",
Usage: "HTTP server listen address",
},
},
Action: func(c *cli.Context) error {
if c.Args().Get(0) == "" {
return nil
}
if err := serveMock(c, c.String("b"), c.Args().Get(0)); err != nil {
return cli.NewExitError(err.Error(), 1)
}
return nil
},
},
}
app.Run(os.Args)
}
func readFile(fn string) ([]byte, error) {
info, err := os.Stat(fn)
if err != nil {
return nil, errors.New("File is not exist")
}
if info.IsDir() {
return nil, errors.New("File is a directory")
}
return ioutil.ReadFile(fn)
}
func readTemplate(fn string) ([]byte, error) {
tf, err := readFile(fn)
if err == nil {
return tf, nil
}
fs := FS(false)
ff, err := fs.Open("/templates/" + fn + ".html")
if err != nil {
return nil, err
}
defer ff.Close()
return ioutil.ReadAll(ff)
}
func renderHTML(c *cli.Context, input, output, tplFile string) error {
bp, err := snowboard.Load(input, engine)
if err != nil {
return err
}
tf, err := readTemplate(tplFile)
if err != nil {
return err
}
if output == "" {
var bf bytes.Buffer
if err := render.HTML(string(tf), &bf, bp); err != nil {
return err
}
fmt.Fprintln(c.App.Writer, bf.String())
return nil
}
of, err := os.Create(output)
if err != nil {
return err
}
defer of.Close()
err = render.HTML(string(tf), of, bp)
if err != nil {
return err
}
fmt.Fprintf(c.App.Writer, "%s: HTML has been generated!\n", of.Name())
return nil
}
func renderAPIB(c *cli.Context, input, output string) error {
b, err := snowboard.Read(input)
if err != nil {
return err
}
if output == "" {
fmt.Fprintln(c.App.Writer, string(b))
return nil
}
of, err := os.Create(output)
if err != nil {
return err
}
defer of.Close()
_, err = io.Copy(of, bytes.NewReader(b))
if err != nil {
return err
}
fmt.Fprintf(c.App.Writer, "%s: API blueprint has been generated!\n", of.Name())
return nil
}
func renderJSON(c *cli.Context, input, output string) error {
b, err := snowboard.LoadAsJSON(input, engine)
if err != nil {
return err
}
if output == "" {
fmt.Fprintln(c.App.Writer, string(b))
return nil
}
of, err := os.Create(output)
if err != nil {
return err
}
defer of.Close()
_, err = io.Copy(of, bytes.NewReader(b))
if err != nil {
return err
}
fmt.Fprintf(c.App.Writer, "%s: API element JSON has been generated!\n", of.Name())
return nil
}
func validate(c *cli.Context, input string, charIdx bool) error {
b, err := readFile(input)
if err != nil {
return xerrors.Wrap(err, "read failed")
}
bf := bytes.NewReader(b)
if charIdx {
out, err := snowboard.Validate(bf, engine)
if err != nil {
return err
}
if out == nil {
fmt.Fprintln(c.App.Writer, "OK")
return nil
}
var buf bytes.Buffer
s := "--------"
w := tabwriter.NewWriter(&buf, 8, 0, 0, ' ', tabwriter.Debug)
fmt.Fprintln(w, "Char Index\tDescription")
fmt.Fprintf(w, "%s\t%s\n", s, strings.Repeat(s, 8))
for _, n := range out.Annotations {
for _, m := range n.SourceMaps {
fmt.Fprintf(w, "%d:%d\t%s\n", m.Row, m.Col, n.Description)
}
}
w.Flush()
if len(out.Annotations) > 0 {
return errors.New(buf.String())
}
} else {
b, err := engineC.Validate(bf)
if err != nil {
return err
}
var buf bytes.Buffer
w := tabwriter.NewWriter(&buf, 8, 0, 0, ' ', tabwriter.Debug)
fmt.Fprintln(w, "Location\tSeverity\tDescription")
fmt.Fprintf(w, "%s\t%s\t%s\n", dash(42), dash(16), dash(80))
if string(b) == "" {
fmt.Fprintln(c.App.Writer, "OK")
return nil
}
ns := strings.Split(string(b), "\n")
for _, n := range ns {
nn := strings.SplitN(n, "; ", 2)
mm := strings.SplitN(nn[0], " ", 2)
fmt.Fprintf(w, "%s\t%s\t%s\n", nn[1], mm[0], mm[1])
}
w.Flush()
return errors.New(buf.String())
}
return nil
}
func dash(n int) string {
return strings.Repeat("-", n)
}
func watchHTML(c *cli.Context, input, output, tplFile, bind string) error {
if output == "" {
output = "index.html"
}
watcher, err := fsnotify.NewWatcher()
if err != nil {
return err
}
defer watcher.Close()
done := make(chan bool)
go func() {
for {
select {
case event := <-watcher.Events:
if event.Op&fsnotify.Write == fsnotify.Write {
if err := renderHTML(c, input, output, tplFile); err != nil {
fmt.Fprintln(c.App.Writer, err)
}
}
case err := <-watcher.Errors:
if err != nil {
fmt.Fprintln(c.App.Writer, err)
}
}
}
}()
if err = watcher.Add(input); err != nil {
return err
}
if _, err = os.Stat(tplFile); err == nil {
if err = watcher.Add(tplFile); err != nil {
return err
}
}
if err := renderHTML(c, input, output, tplFile); err != nil {
return err
}
for _, s := range snowboard.Seeds(input) {
if err = watcher.Add(s); err != nil {
return err
}
}
fmt.Fprintf(c.App.Writer, "snowboard: listening on %s\n", bind)
if err := serveHTML(bind, output); err != nil {
return err
}
<-done
return nil
}
func serveHTML(bind, output string) error {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, output)
})
return http.ListenAndServe(bind, nil)
}
func serveMock(c *cli.Context, bind, input string) error {
bp, err := snowboard.Load(input, engine)
if err != nil {
return err
}
fmt.Fprintf(c.App.Writer, "Mock server is ready. Use %s\n", bind)
fmt.Fprintln(c.App.Writer, "Available Routes:")
ms := mock.Mock(bp)
for _, m := range ms {
fmt.Fprintf(c.App.Writer, "%s\t%d\t%s\n", m.Method, m.StatusCode, m.Pattern)
}
h := mock.MockHandler(ms)
return http.ListenAndServe(bind, h)
}