Replace INI writing function with encoder

This commit is contained in:
kayomn 2022-12-23 13:26:54 +00:00
parent 8a897dbd24
commit 550ed5a8d9
1 changed files with 28 additions and 42 deletions

70
ini.go
View File

@ -2,7 +2,9 @@ package ini
import ( import (
"bufio" "bufio"
"fmt"
"io" "io"
"reflect"
"strings" "strings"
) )
@ -13,6 +15,32 @@ type Entry struct {
Value string Value string
} }
// Attempts to write `value` to `writer` in an INI-encoded format, returning any error that
// occured during writing.
func Encode(writer io.Writer, section string, value any) error {
if _, printError := fmt.Fprintf(writer, "[%s]\n", section); printError != nil {
return printError
}
var valueType = reflect.TypeOf(value)
if valueType.Kind() != reflect.Struct {
return fmt.Errorf("only structs may be encoded")
}
var valueInfo = reflect.ValueOf(value)
for i := 0; i < valueInfo.NumField(); i += 1 {
if _, printError := fmt.Fprintf(writer, "%s = %s\n",
valueType.Field(i).Name, valueInfo.Field(i).Interface()); printError != nil {
return printError
}
}
return nil
}
// Returns the last error that occured during parsing. // Returns the last error that occured during parsing.
func (parser *Parser) Err() error { func (parser *Parser) Err() error {
return parser.err return parser.err
@ -95,48 +123,6 @@ type Parser struct {
isEnd bool isEnd bool
} }
// Attempts to write `entries` to `writer`, returning any error that occured during writing.
func Write(writer io.StringWriter, entries []Entry) error {
// TODO: Not happy with this solution to writing files, needs more revision.
var section = ""
for _, entry := range entries {
if entry.Section != section {
if _, writeError := writer.WriteString("\n["); writeError != nil {
return writeError
}
if _, writeError := writer.WriteString(entry.Section); writeError != nil {
return writeError
}
if _, writeError := writer.WriteString("]\n"); writeError != nil {
return writeError
}
section = entry.Section
}
if _, writeError := writer.WriteString(entry.Key); writeError != nil {
return writeError
}
if _, writeError := writer.WriteString(" = "); writeError != nil {
return writeError
}
if _, writeError := writer.WriteString(entry.Value); writeError != nil {
return writeError
}
if _, writeError := writer.WriteString("\n"); writeError != nil {
return writeError
}
}
return nil
}
// Returns a string with the the outer-most quotes surrounding `s` trimmed, should they exist. // Returns a string with the the outer-most quotes surrounding `s` trimmed, should they exist.
func unquote(s string) string { func unquote(s string) string {
var sLen = len(s) var sLen = len(s)