...
1 package systemdconfig
2
3 import (
4 "strings"
5 )
6
7 type Section struct {
8 fields map[string]*Field
9 orderedFieldKeys []string
10 }
11
12
13 func (section *Section) Field(targetKey string) *Field {
14 return section.fields[targetKey]
15 }
16
17
18 func (section *Section) ListFields() []string {
19 fieldKeys := []string{}
20 for _, key := range section.orderedFieldKeys {
21 if !strings.HasPrefix(key, "!") {
22 fieldKeys = append(fieldKeys, key)
23 }
24 }
25 return fieldKeys
26 }
27
28
29 func (section *Section) SetField(targetKey string, value string) error {
30 if !valueIsValid(value) {
31 return &SyntaxError{value, errValueSyntax}
32 }
33 if strings.HasSuffix(value, "\\") {
34 return &UnsupportedError{value, errMultiLineValuesUnsupported}
35 }
36 key := strings.TrimSpace(targetKey)
37 if _, ok := section.fields[targetKey]; !ok {
38 if !keyIsValid(key) {
39 return &SyntaxError{targetKey, errKeySyntax}
40 }
41 targetKey = generateKeyForField(key, 0)
42 section.orderedFieldKeys = append(section.orderedFieldKeys, targetKey)
43 }
44 section.fields[targetKey] = &Field{key, value, ""}
45 return nil
46 }
47
48
49 func (section *Section) RemoveField(targetKey string) error {
50 if !keyIsValid(targetKey) {
51 return &SyntaxError{targetKey, errKeySyntax}
52 }
53 if _, ok := section.fields[targetKey]; ok {
54 delete(section.fields, targetKey)
55 updatedKeys := []string{}
56 for _, key := range section.orderedFieldKeys {
57 if key != targetKey {
58 updatedKeys = append(updatedKeys, key)
59 }
60 }
61 section.orderedFieldKeys = updatedKeys
62 }
63 return nil
64 }
65
66
67 func (section *Section) HasField(targetKey string) bool {
68 _, ok := section.fields[targetKey]
69 return ok
70 }
71
View as plain text