package systemdconfig import ( "fmt" "strings" ) type Field struct { key string // key as output to file (can be commented out) value string // value for a key in the section, must have associated key if set comment string // in-line comment if key is present, comment line if not } // Gets the key for the field func (field *Field) GetKey() string { return field.key } // Returns if the field has a key func (field *Field) HasKey() bool { return field.GetKey() != "" } // Commented out the fields key, if uncommented func (field *Field) CommentKey() { if field.KeyIsCommented() { return } field.key = "#" + field.GetKey() } // Uncomments the fields key, if commented func (field *Field) UncommentKey() { if !field.KeyIsCommented() { return } field.key = strings.TrimSpace(field.GetKey()[1:]) } // Returns if the key is commented out func (field *Field) KeyIsCommented() bool { return isCommented(field.GetKey()) } // Gets the value for the field func (field *Field) GetValue() string { return field.value } // Sets the value for the field func (field *Field) SetValue(value string) error { if !valueIsValid(value) { return &SyntaxError{value, errValueSyntax} } if strings.HasSuffix(value, "\\") { return &UnsupportedError{value, errMultiLineValuesUnsupported} } field.value = value return nil } // Removes the value from the field, if it exists func (field *Field) RemoveValue() { field.value = "" } // Returns if the field has a value set func (field *Field) HasValue() bool { return field.GetValue() != "" } // Gets the comment string for the field func (field *Field) GetComment() string { return field.comment } // Sets the comment string for the field func (field *Field) SetComment(comment string) { if !isCommented(comment) { comment = "# " + comment } field.comment = comment } // Removes the comment from the field, if it exists func (field *Field) RemoveComment() { field.comment = "" } // Returns if a field has a comment func (field *Field) HasComment() bool { return field.GetComment() != "" } // Returns if the line is a comment, i.e. comment with no key:value func (field *Field) IsCommentLine() bool { return !field.HasKey() && !field.HasValue() && field.HasComment() } // Returns if the line is empty func (field *Field) IsEmptyLine() bool { return !field.HasKey() && !field.HasValue() && !field.HasComment() } // Gets the string line output to the file for a field func (field *Field) ToFileLine() string { if field.IsEmptyLine() { return "" } else if field.IsCommentLine() { return field.GetComment() } else if field.HasComment() { return fmt.Sprintf("%s=%s %s", field.GetKey(), field.GetValue(), field.GetComment()) } return fmt.Sprintf("%s=%s", field.GetKey(), field.GetValue()) }