-
Notifications
You must be signed in to change notification settings - Fork 8
/
write_comment.go
66 lines (53 loc) · 1.39 KB
/
write_comment.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
package tygoja
import (
"go/ast"
"strings"
)
func (g *PackageGenerator) writeCommentGroup(s *strings.Builder, f *ast.CommentGroup, depth int) {
if f == nil {
return
}
docLines := strings.Split(f.Text(), "\n")
g.writeIndent(s, depth)
s.WriteString("/**\n")
lastLineIdx := len(docLines) - 1
var isCodeBlock bool
emptySB := new(strings.Builder)
for i, c := range docLines {
isEndLine := i == lastLineIdx
isEmpty := len(strings.TrimSpace(c)) == 0
isIndented := strings.HasPrefix(c, "\t") || strings.HasPrefix(c, " ")
// end code block
if isCodeBlock && (isEndLine || (!isIndented && !isEmpty)) {
g.writeIndent(s, depth)
s.WriteString(" * ```\n")
isCodeBlock = false
}
// accumulate empty comment lines
// (this is done to properly enclose code blocks with new lines)
if isEmpty {
g.writeIndent(emptySB, depth)
emptySB.WriteString(" * \n")
} else {
// write all empty lines
s.WriteString(emptySB.String())
emptySB.Reset()
}
// start code block
if isIndented && !isCodeBlock && !isEndLine {
g.writeIndent(s, depth)
s.WriteString(" * ```\n")
isCodeBlock = true
}
// write comment line
if !isEmpty {
g.writeIndent(s, depth)
s.WriteString(" * ")
c = strings.ReplaceAll(c, "*/", "*\\/") // An edge case: a // comment can contain */
s.WriteString(c)
s.WriteByte('\n')
}
}
g.writeIndent(s, depth)
s.WriteString(" */\n")
}