-
Notifications
You must be signed in to change notification settings - Fork 0
/
parser.go
68 lines (60 loc) · 1.78 KB
/
parser.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
package parser
import (
"fmt"
"regexp"
"strings"
"time"
"github.com/LouisBrunner/gofixit/src/contracts"
"github.com/LouisBrunner/gofixit/src/utils"
"github.com/sirupsen/logrus"
)
const maxPreAllocated = 100
type parserImpl struct {
contracts.ParsingConfig
re regexp.Regexp
order ordering
logger *logrus.Logger
}
func New(logger *logrus.Logger, config contracts.ParsingConfig) (contracts.Parser, error) {
re, order, err := buildRE(logger, config)
if err != nil {
return nil, fmt.Errorf("cannot build internal matcher: %w", err)
}
return &parserImpl{
ParsingConfig: config,
re: *re,
order: *order,
logger: logger,
}, nil
}
func (me *parserImpl) Parse(fileContent string) ([]contracts.ParsedComment, error) {
lines := strings.Split(fileContent, "\n")
results := make([]contracts.ParsedComment, 0, utils.Min(len(lines)/10, maxPreAllocated))
for num, line := range lines {
me.logger.Debugf("parsing line %q", line)
matches := me.re.FindStringSubmatch(line)
me.logger.Debugf("found matches %+v", matches)
if len(matches) < expectedMatches {
continue
}
me.logger.Infof("line matched %+v", matches)
var expiry *time.Time
if matches[me.order.matchExpiry] != "" {
expiryValue, err := time.Parse(me.DateLayout, matches[me.order.matchExpiry])
if err != nil {
me.logger.Errorf("invalid date layout %q: %v", matches[me.order.matchExpiry], err)
continue
}
expiry = &expiryValue
}
results = append(results, contracts.ParsedComment{
CommentPrefix: matches[me.order.matchComment],
Prefix: matches[me.order.matchPrefix],
Content: matches[me.order.matchContent],
Expiry: expiry,
LineNumber: uint(num) + 1,
OriginalLine: matches[me.order.matchEverything],
})
}
return results, nil
}