fix yaml decode issue

This commit is contained in:
AdoHe 2016-10-07 11:22:44 +08:00
parent 56be1976fc
commit 919bb01b04
2 changed files with 23 additions and 11 deletions

View File

@ -137,7 +137,7 @@ func (d *YAMLDecoder) Close() error {
} }
const yamlSeparator = "\n---" const yamlSeparator = "\n---"
const separator = "---\n" const separator = "---"
// splitYAMLDocument is a bufio.SplitFunc for splitting YAML streams into individual documents. // splitYAMLDocument is a bufio.SplitFunc for splitting YAML streams into individual documents.
func splitYAMLDocument(data []byte, atEOF bool) (advance int, token []byte, err error) { func splitYAMLDocument(data []byte, atEOF bool) (advance int, token []byte, err error) {
@ -246,16 +246,28 @@ func (r *YAMLReader) Read() ([]byte, error) {
return nil, err return nil, err
} }
if string(line) == separator || err == io.EOF { sep := len([]byte(separator))
if i := bytes.Index(line, []byte(separator)); i == 0 {
// We have a potential document terminator
i += sep
after := line[i:]
if len(strings.TrimRightFunc(string(after), unicode.IsSpace)) == 0 {
if buffer.Len() != 0 {
return buffer.Bytes(), nil
}
if err == io.EOF {
return nil, err
}
}
}
if err == io.EOF {
if buffer.Len() != 0 { if buffer.Len() != 0 {
// If we're at EOF, we have a final, non-terminated line. Return it.
return buffer.Bytes(), nil return buffer.Bytes(), nil
} }
if err == io.EOF { return nil, err
return nil, err
}
} else {
buffer.Write(line)
} }
buffer.Write(line)
} }
} }

View File

@ -138,11 +138,11 @@ stuff: 1
obj := generic{} obj := generic{}
err := s.Decode(&obj) err := s.Decode(&obj)
if err == nil { if err == nil {
t.Fatal("expected error with yaml: prefix, got no error") t.Fatal("expected error with yaml: violate, got no error")
} }
fmt.Printf("err: %s\n", err.Error()) fmt.Printf("err: %s\n", err.Error())
if !strings.HasPrefix(err.Error(), "yaml: line 1:") { if !strings.HasPrefix(err.Error(), "yaml: line 2:") {
t.Fatalf("expected %q to have 'yaml: line 1:' prefix", err.Error()) t.Fatalf("expected %q to have 'yaml: line 2:' found a tab character", err.Error())
} }
} }