-
Notifications
You must be signed in to change notification settings - Fork 96
/
syntax.go
99 lines (82 loc) · 1.84 KB
/
syntax.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
package confgov2
import (
"fmt"
"regexp"
"strings"
"github.com/douyu/juno/pkg/model"
"github.com/link-duan/toml"
"gopkg.in/yaml.v3"
)
type (
syntaxChecker func(content string) error
SyntaxError struct {
LineNumber int
Message string
}
)
var (
syntaxCheckers = map[model.ConfigFormat]syntaxChecker{
model.ConfigFormatToml: tomlChecker,
model.ConfigFormatYaml: yamlChecker,
model.ConfigFormatIni: iniChecker,
}
)
func (s SyntaxError) Error() string {
return fmt.Sprintf("syntax error. near line %d. %s", s.LineNumber, s.Message)
}
func CheckSyntax(format model.ConfigFormat, content string) error {
checker, ok := syntaxCheckers[format]
if !ok {
return nil
}
return checker(content)
}
func tomlChecker(content string) error {
var target interface{}
_, err := toml.Decode(content, &target)
if err != nil {
if parseErr, ok := err.(toml.ParseError); ok {
return SyntaxError{
LineNumber: parseErr.Line,
Message: fmt.Sprintf("last key is %s", parseErr.LastKey),
}
}
return err
}
return nil
}
func yamlChecker(content string) error {
var target interface{}
decoder := yaml.NewDecoder(strings.NewReader(content))
err := decoder.Decode(&target)
if err != nil {
return err
}
return nil
}
func iniChecker(content string) error {
sectionRegex := regexp.MustCompile("^\\[[^\\[]+]$")
keyValueRegex := regexp.MustCompile("\\w+[\\s]*=[\\s]*.*")
lines := strings.Split(content, "\n")
for lineNumber, line := range lines {
line = strings.Trim(line, " \\r\\n\\t")
// skip blank line
if line == "" {
continue
}
// check if section
matched := sectionRegex.MatchString(line)
if matched {
continue
}
// check key value syntax
matched = keyValueRegex.MatchString(line)
if !matched {
return SyntaxError{
LineNumber: lineNumber,
Message: "invalid syntax",
}
}
}
return nil
}