-
Notifications
You must be signed in to change notification settings - Fork 7
/
godoc.go
101 lines (87 loc) · 1.83 KB
/
godoc.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
package main
import (
"bytes"
"go/ast"
"go/doc"
"go/doc/comment"
"go/format"
"go/token"
"strings"
)
func Synopsis(text string) string {
d := ParseDoc(text)
text = string(newPrinter(1).Text(d))
var p doc.Package
return p.Synopsis(text)
}
func ParseDoc(text string) *comment.Doc {
p := &comment.Parser{
LookupPackage: func(string) (string, bool) {
return "", true
},
LookupSym: func(string, string) bool {
return true
},
}
return p.Parse(text)
}
type Doc struct {
Empty bool
Synopsis string
*comment.Doc
}
func NewDoc(text string) *Doc {
return &Doc{
Empty: strings.TrimSpace(strings.ReplaceAll(text, "\n", "")) == "",
Synopsis: Synopsis(text),
Doc: ParseDoc(text),
}
}
func epsilon(*comment.Heading) string {
return ""
}
func noLink(*comment.DocLink) string {
return ""
}
func newPrinter(headingLevel int) *comment.Printer {
return &comment.Printer{
HeadingLevel: headingLevel,
HeadingID: epsilon,
DocLinkURL: noLink,
}
}
func (d *Doc) Markdown(headingLevel int) string {
p := newPrinter(headingLevel)
return string(p.Markdown(d.Doc))
}
func renderExample(buf *bytes.Buffer, fset *token.FileSet, in *doc.Example) Example {
out := Example{
Name: in.Name,
Documentation: NewDoc(in.Doc),
Playable: in.Play != nil,
Unordered: in.Unordered,
EmptyOutput: in.EmptyOutput,
}
code := []any{in.Play}
if !out.Playable {
code = []any{}
for _, line := range in.Code.(*ast.BlockStmt).List {
code = append(code, line)
}
}
buf.Reset()
buf.WriteString("```go\n")
for _, line := range code {
format.Node(buf, fset, line)
// playable examples end with a newline already
if !out.Playable {
buf.WriteString("\n")
}
}
buf.WriteString("```\n")
out.Code = buf.String()
if in.Output != "" {
out.Output = "```\n" + in.Output + "```\n"
}
return out
}