/
example.go
70 lines (53 loc) · 1.19 KB
/
example.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
package go2readme
import (
"bytes"
"go/doc"
"go/format"
"go/printer"
"go/token"
"strings"
)
type Example struct {
fset *token.FileSet
doc *doc.Example
}
func NewExamples(fset *token.FileSet, examples ...*doc.Example) []*Example {
list := make([]*Example, len(examples))
for i, e := range examples {
list[i] = &Example{fset: fset, doc: e}
}
return list
}
func (e *Example) Name() string {
return e.doc.Name
}
func (e *Example) Doc() string {
return e.doc.Doc
}
func (e *Example) Output() string {
return strings.TrimSpace(e.doc.Output)
}
func (e *Example) Code() string {
var buf bytes.Buffer
node := &printer.CommentedNode{Node: e.doc.Code, Comments: e.doc.Comments}
config := &printer.Config{Mode: printer.UseSpaces, Tabwidth: 4}
config.Fprint(&buf, e.fset, node)
code := buf.String()
if n := len(code); n >= 2 && code[0] == '{' && code[n-1] == '}' {
code = code[1 : n-1]
code = strings.Replace(code, "\n ", "\n", -1)
code = strings.TrimSpace(code)
}
return code
}
func (e *Example) Play() string {
if e.doc.Play == nil {
return ""
}
var buf bytes.Buffer
err := format.Node(&buf, e.fset, e.doc.Play)
if err != nil {
return ""
}
return buf.String()
}