/
ramblon.go
657 lines (599 loc) · 18.7 KB
/
ramblon.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
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
package main
import (
"encoding/json"
"fmt"
"github.com/Jumpscale/go-raml/raml"
"github.com/beatrichartz/martini-sockets"
"github.com/go-martini/martini"
"github.com/howeyc/fsnotify"
"github.com/kr/pretty"
"github.com/martini-contrib/render"
"github.com/pierrre/archivefile/zip"
"github.com/satori/go.uuid"
"github.com/tsaikd/KDGoLib/jsonex"
"gopkg.in/urfave/cli.v1"
"html/template"
"io/ioutil"
"log"
"os"
"path/filepath"
"regexp"
"sort"
"strings"
"sync"
"time"
parser "github.com/mattbaird/RAMbLOn/ramlv1.0"
"github.com/mattbaird/RAMbLOn/ramlv1.0/parserConfig"
)
var projects *Projects = newProjects()
var watchers map[string]*fsnotify.Watcher = make(map[string]*fsnotify.Watcher)
var configuration Configuration
func main() {
var err error
configuration, err = ReadConfiguration()
if err != nil {
log.Printf("Error loading configuration:%v\n", err)
os.Exit(-1)
}
log.Printf("configuration is:%v\n", configuration)
var outputdir string
var ramlFile string
var zipOutput bool
var isLocal bool
app := cli.NewApp()
app.HelpName = "RamblOn"
app.Usage = "Generate or Live Preview HTML based API Documentation from RAML v1.0"
app.Version = "0.0.1"
app.Commands = []cli.Command{
{
Name: "Preview",
Aliases: []string{"p", "preview"},
Usage: "Live Preview HTML based documentation from RAML v1.0",
Action: func(c *cli.Context) error {
m := martini.Classic()
m.Use(martini.Static("public")) // serve from the "static" directory
templateFuncs := getTemplateFuncs()
m.Use(render.Renderer(render.Options{
Directory: "templates", // Specify what path to load the templates from.
// Layout: "layout", // Specify a layout template. Layouts can call {{ yield }} to render the current template.
Extensions: []string{".tmpl"}, // Specify extensions to load for templates.
Funcs: []template.FuncMap{templateFuncs}, // Specify helper function maps for templates to access.
Delims: render.Delims{"{{", "}}"}, // Sets delimiters to the specified strings.
Charset: "UTF-8", // Sets encoding for json and html content-types. Default is "UTF-8".
IndentJSON: true, // Output human readable JSON
IndentXML: true, // Output human readable XML
HTMLContentType: "text/html", // Output XHTML content type instead of default "text/html"
}))
m.Get("/", func(r render.Render) {
r.Redirect("/browse")
})
m.Get("/browse", func(r render.Render, params martini.Params) {
files, err := ioutil.ReadDir(configuration.Root)
if err != nil {
log.Printf("error:%v\n", err)
}
var directories []os.FileInfo
for _, file := range files {
if file.IsDir() {
directories = append(directories, file)
}
}
r.HTML(200, "browse", directories)
})
m.Get("/browse/:directory", func(r render.Render, params martini.Params) {
directory := params["directory"]
files, err := ioutil.ReadDir(fmt.Sprintf("%s%s", configuration.Root, directory))
if err != nil {
log.Printf("error:%v\n", err)
}
var apis []os.FileInfo
for _, file := range files {
if !file.IsDir() {
apis = append(apis, file)
}
}
r.HTML(200, "browseapi", map[string]interface{}{
"directory": directory,
"apis": apis})
})
m.NotFound(func(r render.Render) {
r.HTML(404, "404", nil)
})
m.Get("/api/:directory/:name", func(r render.Render, params martini.Params) {
directory := params["directory"]
name := params["name"]
fullDirectory, err := getDirectory(directory)
if err != nil {
pretty.Printf("error during PWD lookup:%v\n", err)
r.HTML(500, "500", err)
return
}
ramlFile := fmt.Sprintf("%s/%s", fullDirectory, name)
log.Printf("file is:%s\n", ramlFile)
project := Project{directory: fullDirectory}
projects.projects = append(projects.projects, &project)
shutdownWatchers() // reset them so they don't eat all file handles
err = watch(fullDirectory, name)
if err != nil {
pretty.Printf("error during File Watch:%v\n", err)
r.HTML(500, "500", err)
return
}
var checkRAMLVersion bool
var allowIntToBeNum bool
var checkOptions = []parser.CheckValueOption{}
ramlParser := parser.NewParser()
if allowIntToBeNum {
checkOptions = append(checkOptions, parser.CheckValueOptionAllowIntegerToBeNumber(true))
}
if err = ramlParser.Config(parserConfig.CheckRAMLVersion, checkRAMLVersion); err != nil {
pretty.Printf("error during config[CheckRAMLVersion]:%v", err)
r.HTML(500, "500", err)
return
}
if err = ramlParser.Config(parserConfig.CheckValueOptions, checkOptions); err != nil {
pretty.Printf("error during config[CheckValueOptions]:%v", err)
r.HTML(500, "500", err)
return
}
rootdoc := new(raml.APIDefinition)
err = raml.ParseFile(ramlFile, rootdoc)
if err != nil {
pretty.Printf("error during ParseFile:%v", err)
r.HTML(500, "500", err)
return
}
jsonBytes, err := jsonex.MarshalIndent(rootdoc, "", " ")
if err != nil {
pretty.Printf("error during MarshalIndent:%v", err)
r.HTML(500, "500", err)
return
}
if false {
log.Printf("json:%v\n", string(jsonBytes))
}
u1, _ := uuid.NewV4()
clientUUID := u1.String()
r.HTML(200, "index", map[string]interface{}{
"preview": true,
"directory": directory,
"name": name,
"raml": rootdoc,
"prefix": "",
"clientUUID": clientUUID})
})
// This is the sockets connection for the project, it is a json mapping to sockets.
m.Get("/sockets/projects/:directory/:project/:clientUUID", sockets.JSON(Message{}, websocketOptions()), func(params martini.Params,
receiver <-chan *Message, sender chan<- *Message, done <-chan bool, disconnect chan<- int, err <-chan error) (int, string) {
client := &Client{params["clientUUID"], receiver, sender, done, err, disconnect}
directory, e := getDirectory(params["directory"])
if e != nil {
pretty.Printf("error during File Watch:%v\n", err)
return 500, e.Error()
}
projects := projects.getProject(directory)
projects.appendClient(client)
// A single select can be used to do all the messaging
for {
select {
case <-client.err:
// Don't try to do this:
// client.out <- &Message{"system", "system", "There has been an error with your connection"}
// The socket connection is already long gone.
// Use the error for statistics etc
case msg := <-client.in:
log.Printf("client message:%v\n", msg)
case <-client.done:
projects.removeClient(client)
return 200, "OK"
}
}
})
m.RunOnAddr(fmt.Sprintf(":%v", configuration.Port))
return nil
},
},
{
Name: "Generate",
Aliases: []string{"g", "generate"},
Usage: "Generate HTML based documentation from RAML v1.0",
Flags: []cli.Flag{
cli.StringFlag{
Name: "outputdir, o",
Value: "./tmp",
Usage: "Directory to output generated documentation to.",
Destination: &outputdir,
},
cli.BoolFlag{
Name: "zip, z",
Usage: "Create ZIP of Documentation",
Destination: &zipOutput,
},
cli.StringFlag{
Name: "raml, r",
Usage: "path to raml file",
Destination: &ramlFile,
},
cli.BoolFlag{
Name: "local, l",
Usage: "If serving from local files vs. http server",
Destination: &isLocal,
},
},
Action: func(c *cli.Context) error {
outputdir := c.String("outputdir")
err := os.MkdirAll(outputdir, os.ModeDir|0777)
if err != nil {
pretty.Printf("Error Creating Output Directory [%s]: %v\n", outputdir, err)
return nil
}
filename := "index.html"
fullPathAndDir := fmt.Sprintf("%s/%s", outputdir, filename)
if strings.HasSuffix(outputdir, "/") {
fullPathAndDir = fmt.Sprintf("%s%s", outputdir, filename)
}
f, err := os.Create(fullPathAndDir)
if err != nil {
pretty.Printf("Error Creating file [%s]: %v\n", fullPathAndDir, err)
return nil
}
defer f.Close()
t := template.Must(template.New("index.tmpl").Funcs(getTemplateFuncs()).ParseFiles("./templates/index.tmpl"))
var checkRAMLVersion bool
var allowIntToBeNum bool
var checkOptions = []parser.CheckValueOption{}
ramlParser := parser.NewParser()
if allowIntToBeNum {
checkOptions = append(checkOptions, parser.CheckValueOptionAllowIntegerToBeNumber(true))
}
if err = ramlParser.Config(parserConfig.CheckRAMLVersion, checkRAMLVersion); err != nil {
pretty.Printf("error during config[CheckRAMLVersion]:%v", err)
return err
}
if err = ramlParser.Config(parserConfig.CheckValueOptions, checkOptions); err != nil {
pretty.Printf("error during config[CheckValueOptions]:%v", err)
return err
}
rootdoc := new(raml.APIDefinition)
err = raml.ParseFile(ramlFile, rootdoc)
if err != nil {
pretty.Printf("error during ParseFile:%v", err)
return err
}
prefix := ""
pretty.Printf("zip:%v\n", zipOutput)
pretty.Printf("isLocal:%v\n", isLocal)
if isLocal {
pretty.Printf("Generating document for local:%v\n", isLocal)
prefix = "."
}
directory, err := filepath.Abs(filepath.Dir(ramlFile))
stuff := map[string]interface{}{
"directory": directory,
"name": rootdoc.Title,
"raml": rootdoc,
"prefix": prefix,
"clientUUID": "na"}
err = t.Execute(f, stuff)
if err != nil {
pretty.Printf("Error executing template: %v\n", err)
return err
}
// now copy the directories (CSS and IMAGES)
err = CopyDir("./public/", outputdir)
if err != nil {
pretty.Printf("Error copying static files: %v\n", err)
return err
}
if zipOutput {
tmpDir, err := ioutil.TempDir("", "test_zip")
if err != nil {
panic(err)
}
defer func() {
_ = os.RemoveAll(tmpDir)
}()
outFilePath := filepath.Join(tmpDir, "design-center-api-docs.zip")
progress := func(archivePath string) {
pretty.Printf("Adding %s to archive\n", archivePath)
}
pretty.Printf("I am going to archive:%v\n", outputdir)
if !strings.HasSuffix(outputdir, "/") {
outputdir = outputdir + "/"
}
finalDestination := filepath.Join(outputdir, "design-center-api-docs.zip")
// delete if exists:
os.Remove(finalDestination)
err = zip.ArchiveFile(outputdir, outFilePath, progress)
if err != nil {
panic(err)
}
err = CopyFile(outFilePath, finalDestination)
if err != nil {
panic(err)
}
pretty.Printf("Wrote Archive to %s\n", finalDestination)
}
return nil
},
},
}
app.Run(os.Args)
}
func getTemplateFuncs() map[string]interface{} {
var templateFuncs = make(map[string]interface{})
templateFuncs["toUpper"] = func(s string) string {
return strings.ToUpper(s)
}
templateFuncs["properties"] = func(v parser.Value) map[string]*parser.Value {
return v.Map["properties"].Map
}
templateFuncs["mapValue"] = func(v parser.Value, key string) string {
if val, ok := v.Map[key]; ok {
return val.String
}
return ""
}
templateFuncs["example"] = func(v parser.Value) string {
var jsonStr string
if val, ok := v.Map["example"]; ok {
jsonBytes, err := json.MarshalIndent(val, "", "\t")
//jsonBytes, err := val.MarshalJSON()
if err != nil {
return fmt.Sprintf("Error Marshalling Example:%v\n", err)
}
jsonStr = string(jsonBytes)
}
return jsonStr
}
templateFuncs["safe"] = func(s string) template.HTML { return template.HTML(s) }
templateFuncs["underscore"] = func(s string) string {
return strings.Replace(s, " ", "_", -1)
}
templateFuncs["uriParameterHighlight"] = func(s string) string {
log.Printf("replacing %s\n", s)
if len(s) > 0 {
temp := s
var params = regexp.MustCompile(`\{([^}]+)\}`)
replace := params.FindAllString(s, -1)
for _, r := range replace {
temp = strings.Replace(temp, r, fmt.Sprintf("<b>%s</b>", r), -1)
}
log.Printf("replaced %s\n", temp)
return temp
}
return s
}
// need to sort by displayName
templateFuncs["sortedMap"] = func(m map[string]raml.Resource) []container {
var displayNameToKeys = map[string]string{}
var displayNames []string
var values []container
for k, v := range m {
displayNameToKeys[v.DisplayName] = k
displayNames = append(displayNames, v.DisplayName)
}
sort.Strings(displayNames)
for _, k := range displayNames {
key := displayNameToKeys[k]
values = append(values, container{Method: key, Value: m[key]})
}
return values
}
return templateFuncs
}
type container struct {
Method string
Value interface{}
}
func getDirectory(directory string) (string, error) {
retval := directory
if strings.HasPrefix(configuration.Root, "./") {
rootDir, err := filepath.Abs(filepath.Dir(os.Args[0]))
if err != nil {
return "", err
}
if strings.HasSuffix(configuration.Root, "/") {
retval = fmt.Sprintf("%s/%s%s/", rootDir, configuration.Root[2:], directory)
} else {
retval = fmt.Sprintf("%s/%s/%s/", rootDir, configuration.Root[2:], directory)
}
} else {
if strings.HasSuffix(configuration.Root, "/") {
retval = fmt.Sprintf("%s%s/", configuration.Root, directory)
} else {
retval = fmt.Sprintf("%s/%s/", configuration.Root, directory)
}
}
return retval, nil
}
var watching = false
var quit = make(chan bool)
func watch(directory, project string) error {
var mutex = &sync.Mutex{}
mutex.Lock()
defer mutex.Unlock()
// quit if already running
if watching {
quit <- true
watching = false
}
dirAndProject := fmt.Sprintf("%s%s", directory, project)
// don't double watch
if _, ok := watchers[dirAndProject]; ok {
log.Printf("dir [%s] already being watched\n", dirAndProject)
return nil
}
watcher, err := fsnotify.NewWatcher()
if err != nil {
return err
}
// Process events
lastEventAt := time.Now()
var event *fsnotify.FileEvent = &fsnotify.FileEvent{}
go func() {
watching = true
for {
time.Sleep(10 * time.Millisecond)
select {
case <-quit:
return
case ev := <-watcher.Event:
if ev != nil && event != nil {
sameEvent := ev.Name == event.Name
recent := time.Since(lastEventAt) < 2*time.Second
notifyClients := false
switch sameEvent {
case true:
if !recent {
notifyClients = true
}
case false:
notifyClients = true
}
if notifyClients {
log.Printf("Notifying\n")
lastEventAt = time.Now()
event = ev
for _, project := range projects.projects {
if project.directory == directory {
project.messageClients(NewMessage("update", dirAndProject, "updated"))
}
}
}
}
case err := <-watcher.Error:
if err != nil {
log.Printf("error:%v\n", err)
}
}
}
}()
err = watcher.Watch(dirAndProject)
if err != nil {
log.Printf("error:%v\n", err)
return err
}
proj := projects.getProject(dirAndProject)
if proj != nil {
proj.messageClients(NewMessage("confirmation", "system", fmt.Sprintf("watching %s", dirAndProject)))
}
log.Printf("[%s] being watched\n", dirAndProject)
watchers[directory] = watcher
watching = true
return nil
}
func shutdownWatchers() {
for _, watcher := range watchers {
watcher.Close()
}
}
type Projects struct {
sync.Mutex
projects []*Project
}
type Project struct {
sync.Mutex
directory string
clients []*Client
}
type Client struct {
Name string
in <-chan *Message
out chan<- *Message
done <-chan bool
err <-chan error
disconnect chan<- int
}
func newProjects() *Projects {
return &Projects{sync.Mutex{}, make([]*Project, 0)}
}
// A simple Message struct
type Message struct {
Typ string `json:"typ"`
From string `json:"from"`
Text string `json:"text"`
}
func NewMessage(t, f, text string) *Message {
return &Message{Typ: t, From: f, Text: text}
}
// Get the project for the given directory
func (p *Projects) getProject(directory string) *Project {
p.Lock()
defer p.Unlock()
for _, project := range p.projects {
if project.directory == directory {
return project
}
}
r := &Project{sync.Mutex{}, directory, make([]*Client, 0)}
p.projects = append(p.projects, r)
return r
}
func (p *Project) appendClient(client *Client) {
p.Lock()
p.clients = append(p.clients, client)
for _, c := range p.clients {
if c != client {
c.out <- &Message{"status", client.Name, "Is watching Project"}
}
}
p.Unlock()
}
// Remove a client from a room
func (p *Project) removeClient(client *Client) {
p.Lock()
defer p.Unlock()
for index, c := range p.clients {
if c == client {
p.clients = append(p.clients[:index], p.clients[(index+1):]...)
} else {
c.out <- &Message{"status", client.Name, "Is not watching Project"}
}
}
}
// Message all clients watching the project
func (p *Project) messageClients(msg *Message) {
p.Lock()
for _, c := range p.clients {
c.out <- msg
}
defer p.Unlock()
}
func websocketOptions() *sockets.Options {
// websockets stuff
return &sockets.Options{
// The logger to use for socket logging
Logger: log.New(os.Stdout, "[sockets] ", 0), // *log.Logger
// The LogLevel for socket logging, possible values:
// sockets.LogLevelError (0)
// sockets.LogLevelWarning (1)
// sockets.LogLevelInfo (2)
// sockets.LogLevelDebug (3)
LogLevel: sockets.LogLevelInfo, // int
// Set to true if you want to skip logging
SkipLogging: false, // bool
// The time to wait between writes before timing out the connection
// When this is a zero value time instance, write will never time out
WriteWait: 60 * time.Second, // time.Duration
// The time to wait at maximum between receiving pings from the client.
PongWait: 60 * time.Second, // time.Duration
// The time to wait between sending pings to the client
// Attention, this does have to be shorter than PongWait and WriteWait
// unless you want connections to constantly time out.
PingPeriod: (60 * time.Second * 8 / 10), // time.Duration
// The maximum messages size for receiving and sending in bytes
// Messages bigger than this will lead to panic and disconnect
MaxMessageSize: 65536, // int64
// The send channel buffer
// How many messages can be asynchronously held before the channel blocks
SendChannelBuffer: 10, // int
// The receiving channel buffer
// How many messages can be asynchronously held before the channel blocks
RecvChannelBuffer: 10, // int
// The allowed origin
// Must be compileable as regexp. {{host}} will be replaced with the current
// request host if given.
AllowedOrigin: "https?://{{host}}$", // string
}
}