-
Notifications
You must be signed in to change notification settings - Fork 18
/
section.go
79 lines (65 loc) · 1.77 KB
/
section.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 configparser
import "strings"
// Section represent each section of the configuration file.
type Section struct {
Name string
options Dict
lookup Dict
}
// Add adds new key-value pair to the section.
func (s *Section) Add(key, value string) error {
lookupKey := s.safeKey(key)
s.options[key] = s.safeValue(value)
s.lookup[lookupKey] = key
return nil
}
// Get returns value of an option with the given key.
//
// Returns an error if the option does not exist either in the section or in
// the defaults.
func (s *Section) Get(key string) (string, error) {
lookupKey, present := s.lookup[s.safeKey(key)]
if !present {
return "", getNoOptionError(s.Name, key)
}
if value, present := s.options[lookupKey]; present {
return value, nil
}
return "", getNoOptionError(s.Name, key)
}
// Options returns a slice of option names.
func (s *Section) Options() []string {
return s.options.Keys()
}
// Items returns a Dict with the key-value pairs.
func (s *Section) Items() Dict {
return s.options
}
func (s *Section) safeValue(in string) string {
return strings.TrimSpace(in)
}
func (s *Section) safeKey(in string) string {
return strings.ToLower(strings.TrimSpace(in))
}
// Remove removes option with the given name from the section.
//
// Returns an error if the option does not exist either in the section or in
// the defaults.
func (s *Section) Remove(key string) error {
_, present := s.options[key]
if !present {
return getNoOptionError(s.Name, key)
}
// delete doesn't return anything, but this does require
// that the passed key to be removed matches the options key.
delete(s.lookup, s.safeKey(key))
delete(s.options, key)
return nil
}
func newSection(name string) *Section {
return &Section{
Name: name,
options: make(Dict),
lookup: make(Dict),
}
}