/
docfmt.go
79 lines (64 loc) · 1.38 KB
/
docfmt.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
package analyzer
import "strings"
const (
newLineChar = '\n'
tabChar = '\t'
)
var (
mdCodeTag = []byte("```\n")
spaceIdent = " "
spaceIdentLen = len(spaceIdent)
)
func isDocLine(line string) bool {
// Source code in Go usually doc starts with tab char
if line[0] == tabChar {
return true
}
// Workaround for some packages with double space as doc indent (line "net/http")
if (len(line) > spaceIdentLen) && (line[:spaceIdentLen] == spaceIdent) {
return true
}
return false
}
func formatDoc(str string) MarkdownString {
if str == "" {
return MarkdownString{Value: str}
}
w := strings.Builder{}
docStart := false
lines := strings.Split(str, "\n")
for _, line := range lines {
if len(line) == 0 {
w.WriteRune(newLineChar)
continue
}
// Source code in Go doc starts with tab char
if isDocLine(line) {
if !docStart {
// Put markdown code section
// if we met first source code line
docStart = true
w.Write(mdCodeTag)
}
w.WriteString(line)
w.WriteRune(newLineChar)
continue
}
// Else - regular text
if docStart {
// Terminate code block if previous
// was open and not terminated
docStart = false
w.Write(mdCodeTag)
}
w.WriteString(line)
w.WriteRune(newLineChar)
}
if docStart {
// close markdown code block if wasn't closed
w.Write(mdCodeTag)
}
return MarkdownString{
Value: w.String(),
}
}