package systemdconfig import ( "strings" ) type Section struct { fields map[string]*Field // fields in the section, mapping keys to fields orderedFieldKeys []string // keys, ordered as they appear in the section } // Gets the field for a given key func (section *Section) Field(targetKey string) *Field { return section.fields[targetKey] } // Lists the fields which have key:values func (section *Section) ListFields() []string { fieldKeys := []string{} for _, key := range section.orderedFieldKeys { if !strings.HasPrefix(key, "!") { fieldKeys = append(fieldKeys, key) } } return fieldKeys } // Sets the field for a given key, adds it if it doesn't exist func (section *Section) SetField(targetKey string, value string) error { if !valueIsValid(value) { return &SyntaxError{value, errValueSyntax} } if strings.HasSuffix(value, "\\") { return &UnsupportedError{value, errMultiLineValuesUnsupported} } key := strings.TrimSpace(targetKey) if _, ok := section.fields[targetKey]; !ok { if !keyIsValid(key) { return &SyntaxError{targetKey, errKeySyntax} } targetKey = generateKeyForField(key, 0) // idx is ignored section.orderedFieldKeys = append(section.orderedFieldKeys, targetKey) } section.fields[targetKey] = &Field{key, value, ""} return nil } // Removes the field for a given key, if it exists func (section *Section) RemoveField(targetKey string) error { if !keyIsValid(targetKey) { return &SyntaxError{targetKey, errKeySyntax} } if _, ok := section.fields[targetKey]; ok { delete(section.fields, targetKey) updatedKeys := []string{} for _, key := range section.orderedFieldKeys { if key != targetKey { updatedKeys = append(updatedKeys, key) } } section.orderedFieldKeys = updatedKeys } return nil } // Returns if the section has a field for a given key func (section *Section) HasField(targetKey string) bool { _, ok := section.fields[targetKey] return ok }