update cnf/parser/nginx encoder+decoder to read the last line even if no newline '\n' char

This commit is contained in:
xdrm-brackets 2018-11-12 19:38:24 +01:00
parent 78d8d9a7a2
commit c27ab45bc2
2 changed files with 25 additions and 8 deletions

View File

@ -32,23 +32,31 @@ func (d *decoder) Decode(v interface{}) error {
// actual section stack
stack := make([]*Line, 0)
eof := false
for {
n++
if eof {
break
}
l := &Line{Type: NONE}
// 1. read line
notrim, err := r.ReadString('\n')
if err == io.EOF {
break
if len(notrim) > 0 {
eof = true
} else {
break
}
} else if err != nil {
return &LineError{n, err}
}
notrim = strings.Trim(notrim, "\r\n")
// 2. ignore empty
line := strings.Trim(notrim, " \t")
line := strings.Trim(notrim, " \t\r\n")
if len(line) < 1 {
continue
}

View File

@ -7,22 +7,31 @@ import (
var (
defaultPrefix = ""
defaultIndent = " "
defaultIndent = "\t"
)
// encoder implements parser.Encoder
type encoder struct {
writer io.Writer
prefix string
indent string
prefix []byte
indent []byte
}
func (e *encoder) SetIndent(prefix, indent string) {
e.prefix = prefix
e.indent = indent
e.prefix = make([]byte, 0)
e.prefix = append(e.prefix, []byte(prefix)...)
e.indent = make([]byte, 0)
e.indent = append(e.indent, []byte(indent)...)
}
func (e *encoder) Encode(v interface{}) error {
// default indentation
if e.prefix == nil || e.indent == nil {
e.SetIndent(defaultPrefix, defaultIndent)
}
// check 'v'
vcast, ok := v.(*Line)
if !ok {
@ -78,7 +87,7 @@ func (e *encoder) Encode(v interface{}) error {
// 4.assignments
} else if line.Type == ASSIGNMENT {
repr = append(repr, []byte(fmt.Sprintf("%s %s;\n", line.Components[0], line.Components[1]))...)
repr = append(repr, []byte(fmt.Sprintf("%s\t\t%s;\n", line.Components[0], line.Components[1]))...)
// 5. include
} else if line.Type == INCLUDE {