-
Notifications
You must be signed in to change notification settings - Fork 2
/
comment.go
115 lines (104 loc) · 2.39 KB
/
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
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
package main
import (
"go/ast"
"go/token"
"html/template"
"regexp"
"strings"
)
type AllComments struct {
Source *token.FileSet
Comments []*ast.CommentGroup
}
type CommentStruct struct {
Description string
Params []Param
Returns []Return
}
func IsParamSpec(line string) bool {
matched, err := regexp.MatchString("^ @param", line)
if err != nil {
panic(err)
}
return matched
}
func IsReturnSpec(line string) bool {
matched, err := regexp.MatchString("^ @return", line)
if err != nil {
panic(err)
}
return matched
}
func (a *AllComments) findCommentFor(i int) CommentStruct {
var methodComments CommentStruct
var comments *ast.CommentGroup
var result []string
found := false
for _, group := range a.Comments {
for _, comment := range group.List {
line := a.Source.Position(comment.Slash).Line
if line == (i - 1) {
comments = group
found = true
}
}
if found {
break
}
}
if found {
for _, comment := range comments.List {
comment.Text = strings.Replace(comment.Text, "//", "", 1)
if IsParamSpec(comment.Text) {
param := ExtractParam(comment.Text)
if param.Name != "" {
methodComments.Params = append(methodComments.Params, param)
}
} else if IsReturnSpec(comment.Text) {
r := ExtractReturn(comment.Text)
if r.Class != "" {
methodComments.Returns = append(methodComments.Returns, r)
}
} else {
result = append(result, comment.Text)
}
}
}
methodComments.Description = strings.Join(result, "\n")
return methodComments
}
func ExtractParam(line string) Param {
param := Param{}
words := strings.Split(line, " ")
words = words[1:len(words)]
if len(words) > 1 {
param.Name = words[1]
}
if len(words) > 2 {
class := words[2]
class = strings.Replace(class, "[", "", 1)
class = strings.Replace(class, "]", "", 1)
param.Class = template.HTML(class)
}
if len(words) > 3 {
theRest := strings.Join(words[3:len(words)], " ")
param.Description = template.HTML(theRest)
}
return param
}
func ExtractReturn(line string) Return {
r := Return{}
words := strings.Split(line, " ")
words = words[1:len(words)]
if len(words) > 1 {
class := words[1]
class = strings.Replace(class, "[", "", 1)
class = strings.Replace(class, "]", "", 1)
r.Class = template.HTML(class)
}
if len(words) > 2 {
theRest := strings.Join(words[3:len(words)], " ")
r.Description = template.HTML(theRest)
}
return r
}