/
markdown.go
175 lines (143 loc) · 4.05 KB
/
markdown.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
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
package encoder
import (
"bytes"
"fmt"
"os"
"path/filepath"
"regexp"
"strings"
"text/template"
yaml "gopkg.in/yaml.v3"
)
var markdownTemplate = `
{{ .Description }}
{{- $anchors := .Anchors -}}
{{- $tick := "` + "`" + `" -}}
{{ range $struct := .Structs }}
---
## {{ $struct.Type }}
{{ if $struct.Description -}}
{{ $struct.Description }}
{{ end }}
{{ if $struct.AppearsIn -}}
Appears in:
{{ range $appearance := $struct.AppearsIn -}}
- <code>{{ encodeType $appearance.TypeName }}.{{ $appearance.FieldName }}</code>
{{ end -}}
{{ end }}
{{ range $example := $struct.Examples }}
{{ yaml $example.GetValue "" }}
{{ end }}
{{ if $struct.Fields -}}
| Field | Type | Description | Value(s) |
|-------|------|-------------|----------|
{{ range $field := $struct.Fields -}}
{{ if $field.Name -}}
| {{- $tick }}{{ $field.Name }}{{ $tick }} |
{{- encodeType $field.Type }} |
{{- fmtDesc $field.Description }} {{ with $field.Examples }}<details><summary>Show example(s)</summary>{{ range . }}{{ yaml .GetValue $field.Name }}{{ end }}</details>{{ end }} |
{{- range $value := $field.Values }}{{ $tick }}{{ $value }}{{ $tick }}<br />{{ end }} |
{{ end -}}
{{ end }}
{{ end }}
{{ end }}`
// FileDoc represents a single go file documentation.
type FileDoc struct {
// Name will be used in md file name pattern.
Name string
// Description file description, supports markdown.
Description string
// Structs structs defined in the file.
Structs []*Doc
Anchors map[string]string
t *template.Template
}
// Encode encodes file documentation as MD file.
func (fd *FileDoc) Encode() ([]byte, error) {
anchors := map[string]string{}
for _, t := range fd.Structs {
anchors[t.Type] = strings.ToLower(t.Type)
}
fd.Anchors = anchors
fd.t = template.Must(template.New("file_markdown.tpl").
Funcs(template.FuncMap{
"yaml": encodeYaml,
"fmtDesc": formatDescription,
"encodeType": fd.encodeType,
}).
Parse(markdownTemplate))
buf := bytes.Buffer{}
if err := fd.t.Execute(&buf, fd); err != nil {
return nil, err
}
return buf.Bytes(), nil
}
// Write dumps documentation string to folder.
func (fd *FileDoc) Write(path, frontmatter string) error {
data, err := fd.Encode()
if err != nil {
return err
}
if stat, e := os.Stat(path); !os.IsNotExist(e) {
if !stat.IsDir() {
return fmt.Errorf("destination path should be a directory")
}
} else {
if e := os.MkdirAll(path, 0o777); e != nil {
return e
}
}
f, err := os.Create(filepath.Join(path, fmt.Sprintf("%s.%s", strings.ToLower(fd.Name), "md")))
if err != nil {
return err
}
if _, err := f.Write([]byte(frontmatter)); err != nil {
return err
}
if _, err := f.Write(data); err != nil {
return err
}
return nil
}
func (fd *FileDoc) encodeType(t string) string {
re := regexp.MustCompile(`\w+`)
for _, s := range re.FindAllString(t, -1) {
if anchor, ok := fd.Anchors[s]; ok {
t = strings.ReplaceAll(t, s, formatLink(s, "#"+anchor))
}
}
return t
}
func encodeYaml(in interface{}, name string) string {
if name != "" {
in = map[string]interface{}{
name: in,
}
}
node, err := toYamlNode(in, newOptions(WithComments(CommentsAll)))
if err != nil {
return fmt.Sprintf("yaml encoding failed %s", err)
}
data, err := yaml.Marshal(node)
if err != nil {
return fmt.Sprintf("yaml encoding failed %s", err)
}
lines := strings.Split(string(data), "\n")
for i, line := range lines {
lines[i] = strings.TrimRight(line, " ")
}
return fmt.Sprintf("{{< highlight yaml >}}\n%s{{< /highlight >}}", strings.Join(lines, "\n"))
}
func formatLink(text, link string) string {
return fmt.Sprintf(`<a href="%s">%s</a>`, link, text)
}
func formatDescription(description string) string {
lines := strings.Split(description, "\n")
if len(lines) <= 1 {
return strings.Join(lines, "<br />")
}
return fmt.Sprintf("<details><summary>%s</summary>%s</details>", lines[0], strings.Join(lines[1:], "<br />"))
}