...
1 package systemdconfig
2
3 import (
4 "fmt"
5 "strings"
6 )
7
8 type Field struct {
9 key string
10 value string
11 comment string
12 }
13
14
15 func (field *Field) GetKey() string {
16 return field.key
17 }
18
19
20 func (field *Field) HasKey() bool {
21 return field.GetKey() != ""
22 }
23
24
25 func (field *Field) CommentKey() {
26 if field.KeyIsCommented() {
27 return
28 }
29 field.key = "#" + field.GetKey()
30 }
31
32
33 func (field *Field) UncommentKey() {
34 if !field.KeyIsCommented() {
35 return
36 }
37 field.key = strings.TrimSpace(field.GetKey()[1:])
38 }
39
40
41 func (field *Field) KeyIsCommented() bool {
42 return isCommented(field.GetKey())
43 }
44
45
46 func (field *Field) GetValue() string {
47 return field.value
48 }
49
50
51 func (field *Field) SetValue(value string) error {
52 if !valueIsValid(value) {
53 return &SyntaxError{value, errValueSyntax}
54 }
55 if strings.HasSuffix(value, "\\") {
56 return &UnsupportedError{value, errMultiLineValuesUnsupported}
57 }
58 field.value = value
59 return nil
60 }
61
62
63 func (field *Field) RemoveValue() {
64 field.value = ""
65 }
66
67
68 func (field *Field) HasValue() bool {
69 return field.GetValue() != ""
70 }
71
72
73 func (field *Field) GetComment() string {
74 return field.comment
75 }
76
77
78 func (field *Field) SetComment(comment string) {
79 if !isCommented(comment) {
80 comment = "# " + comment
81 }
82 field.comment = comment
83 }
84
85
86 func (field *Field) RemoveComment() {
87 field.comment = ""
88 }
89
90
91 func (field *Field) HasComment() bool {
92 return field.GetComment() != ""
93 }
94
95
96 func (field *Field) IsCommentLine() bool {
97 return !field.HasKey() && !field.HasValue() && field.HasComment()
98 }
99
100
101 func (field *Field) IsEmptyLine() bool {
102 return !field.HasKey() && !field.HasValue() && !field.HasComment()
103 }
104
105
106 func (field *Field) ToFileLine() string {
107 if field.IsEmptyLine() {
108 return ""
109 } else if field.IsCommentLine() {
110 return field.GetComment()
111 } else if field.HasComment() {
112 return fmt.Sprintf("%s=%s %s", field.GetKey(), field.GetValue(), field.GetComment())
113 }
114 return fmt.Sprintf("%s=%s", field.GetKey(), field.GetValue())
115 }
116
View as plain text