...

Source file src/edge-infra.dev/pkg/sds/lib/systemd/systemdconfig/section.go

Documentation: edge-infra.dev/pkg/sds/lib/systemd/systemdconfig

     1  package systemdconfig
     2  
     3  import (
     4  	"strings"
     5  )
     6  
     7  type Section struct {
     8  	fields           map[string]*Field // fields in the section, mapping keys to fields
     9  	orderedFieldKeys []string          // keys, ordered as they appear in the section
    10  }
    11  
    12  // Gets the field for a given key
    13  func (section *Section) Field(targetKey string) *Field {
    14  	return section.fields[targetKey]
    15  }
    16  
    17  // Lists the fields which have key:values
    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  // Sets the field for a given key, adds it if it doesn't exist
    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) // idx is ignored
    42  		section.orderedFieldKeys = append(section.orderedFieldKeys, targetKey)
    43  	}
    44  	section.fields[targetKey] = &Field{key, value, ""}
    45  	return nil
    46  }
    47  
    48  // Removes the field for a given key, if it exists
    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  // Returns if the section has a field for a given key
    67  func (section *Section) HasField(targetKey string) bool {
    68  	_, ok := section.fields[targetKey]
    69  	return ok
    70  }
    71  

View as plain text