graph/encoding/dot: allow unmarshalling of DOT IDs

This commit is contained in:
Dan Kortschak
2017-06-09 20:01:14 +09:30
committed by GitHub
parent 9e16ba4ad2
commit 2942f5c623
2 changed files with 26 additions and 6 deletions

View File

@@ -39,6 +39,12 @@ type UnmarshalerAttr interface {
UnmarshalDOTAttr(attr Attribute) error UnmarshalDOTAttr(attr Attribute) error
} }
// UnmarshalerID is implemented by types that can unmarshal a DOT ID.
type UnmarshalerID interface {
// UnmarshalDOTID decodes a single DOT ID.
UnmarshalDOTID(id string)
}
// 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.
func Unmarshal(data []byte, dst Builder) error { func Unmarshal(data []byte, dst Builder) error {
file, err := dot.ParseBytes(data) file, err := dot.ParseBytes(data)
@@ -100,6 +106,9 @@ func (gen *generator) node(dst Builder, id string) graph.Node {
return n return n
} }
n := dst.NewNode() n := dst.NewNode()
if n, ok := n.(UnmarshalerID); ok {
n.UnmarshalDOTID(id)
}
gen.ids[id] = n gen.ids[id] = n
// Check if within the context of a subgraph, that is to be used as a vertex // Check if within the context of a subgraph, that is to be used as a vertex
// of an edge. // of an edge.

View File

@@ -65,11 +65,11 @@ const directed = `digraph {
]; ];
// Node definitions. // Node definitions.
0 [label="foo 2"]; A [label="foo 2"];
1 [label="bar 2"]; B [label="bar 2"];
// Edge definitions. // Edge definitions.
0 -> 1 [label="baz 2"]; A -> B [label="baz 2"];
}` }`
const undirected = `graph { const undirected = `graph {
@@ -86,11 +86,11 @@ const undirected = `graph {
]; ];
// Node definitions. // Node definitions.
0 [label="foo 2"]; A [label="foo 2"];
1 [label="bar 2"]; B [label="bar 2"];
// Edge definitions. // Edge definitions.
0 -- 1 [label="baz 2"]; A -- B [label="baz 2"];
}` }`
// Below follows a minimal implementation of a graph capable of validating the // Below follows a minimal implementation of a graph capable of validating the
@@ -187,10 +187,21 @@ func (g *dotUndirectedGraph) DOTUnmarshalerAttrs() (graph, node, edge Unmarshale
// and decoding of node DOT label attributes. // and decoding of node DOT label attributes.
type dotNode struct { type dotNode struct {
simple.Node simple.Node
dotID string
// Node label. // Node label.
Label string Label string
} }
// DOTID returns the node's DOT ID.
func (n *dotNode) DOTID() string {
return n.dotID
}
// UnmarshalDOTID decodes a DOT ID.
func (n *dotNode) UnmarshalDOTID(id string) {
n.dotID = id
}
// UnmarshalDOTAttr decodes a single DOT attribute. // UnmarshalDOTAttr decodes a single DOT attribute.
func (n *dotNode) UnmarshalDOTAttr(attr Attribute) error { func (n *dotNode) UnmarshalDOTAttr(attr Attribute) error {
if attr.Key != "label" { if attr.Key != "label" {