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 // actual section stack
stack := make([]*Line, 0) stack := make([]*Line, 0)
eof := false
for { for {
n++ n++
if eof {
break
}
l := &Line{Type: NONE} l := &Line{Type: NONE}
// 1. read line // 1. read line
notrim, err := r.ReadString('\n') notrim, err := r.ReadString('\n')
if err == io.EOF { if err == io.EOF {
break if len(notrim) > 0 {
eof = true
} else {
break
}
} else if err != nil { } else if err != nil {
return &LineError{n, err} return &LineError{n, err}
} }
notrim = strings.Trim(notrim, "\r\n") notrim = strings.Trim(notrim, "\r\n")
// 2. ignore empty // 2. ignore empty
line := strings.Trim(notrim, " \t") line := strings.Trim(notrim, " \t\r\n")
if len(line) < 1 { if len(line) < 1 {
continue continue
} }

View File

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