encoding/dot: always allow first graph to be returned

This commit is contained in:
Dan Kortschak
2018-11-25 07:40:00 +10:30
committed by Dan Kortschak
parent b3c4e40467
commit cdf8233f4e

View File

@@ -39,28 +39,34 @@ type PortSetter interface {
} }
// Unmarshal parses the Graphviz DOT-encoded data and stores the result in dst. // Unmarshal parses the Graphviz DOT-encoded data and stores the result in dst.
// If the number of graphs encoded in data is not one, an error is returned and
// dst will hold the first graph in data.
func Unmarshal(data []byte, dst encoding.Builder) error { func Unmarshal(data []byte, dst encoding.Builder) error {
file, err := dot.ParseBytes(data) file, err := dot.ParseBytes(data)
if err != nil { if err != nil {
return err return err
} }
if len(file.Graphs) != 1 { err = copyGraph(dst, file.Graphs[0])
return fmt.Errorf("invalid number of graphs; expected 1, got %d", len(file.Graphs)) if err == nil && len(file.Graphs) != 1 {
err = fmt.Errorf("invalid number of graphs; expected 1, got %d", len(file.Graphs))
} }
return copyGraph(dst, file.Graphs[0]) return err
} }
// UnmarshalMulti parses the Graphviz DOT-encoded data as a multigraph and // UnmarshalMulti parses the Graphviz DOT-encoded data as a multigraph and
// stores the result in dst. // stores the result in dst.
// If the number of graphs encoded in data is not one, an error is returned and
// dst will hold the first graph in data.
func UnmarshalMulti(data []byte, dst encoding.MultiBuilder) error { func UnmarshalMulti(data []byte, dst encoding.MultiBuilder) error {
file, err := dot.ParseBytes(data) file, err := dot.ParseBytes(data)
if err != nil { if err != nil {
return err return err
} }
if len(file.Graphs) != 1 { err = copyMultigraph(dst, file.Graphs[0])
return fmt.Errorf("invalid number of graphs; expected 1, got %d", len(file.Graphs)) if err == nil && len(file.Graphs) != 1 {
err = fmt.Errorf("invalid number of graphs; expected 1, got %d", len(file.Graphs))
} }
return copyMultigraph(dst, file.Graphs[0]) return err
} }
// copyGraph copies the nodes and edges from the Graphviz AST source graph to // copyGraph copies the nodes and edges from the Graphviz AST source graph to