Skip to content

Commit

Permalink
graph/encoding/dot: allow unmarshalling of DOT IDs
Browse files Browse the repository at this point in the history
  • Loading branch information
kortschak committed Jun 9, 2017
1 parent 9e16ba4 commit 2ec089c
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 6 deletions.
12 changes: 12 additions & 0 deletions graph/encoding/dot/decode.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,12 @@ type UnmarshalerAttr interface {
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) error
}

// Unmarshal parses the Graphviz DOT-encoded data and stores the result in dst.
func Unmarshal(data []byte, dst Builder) error {
file, err := dot.ParseBytes(data)
Expand Down Expand Up @@ -100,6 +106,12 @@ func (gen *generator) node(dst Builder, id string) graph.Node {
return n
}
n := dst.NewNode()
if n, ok := n.(UnmarshalerID); ok {
err := n.UnmarshalDOTID(id)
if err != nil {
panic(err)
}
}
gen.ids[id] = n
// Check if within the context of a subgraph, that is to be used as a vertex
// of an edge.
Expand Down
24 changes: 18 additions & 6 deletions graph/encoding/dot/decode_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,11 +65,11 @@ const directed = `digraph {
];
// Node definitions.
0 [label="foo 2"];
1 [label="bar 2"];
A [label="foo 2"];
B [label="bar 2"];
// Edge definitions.
0 -> 1 [label="baz 2"];
A -> B [label="baz 2"];
}`

const undirected = `graph {
Expand All @@ -86,11 +86,11 @@ const undirected = `graph {
];
// Node definitions.
0 [label="foo 2"];
1 [label="bar 2"];
A [label="foo 2"];
B [label="bar 2"];
// Edge definitions.
0 -- 1 [label="baz 2"];
A -- B [label="baz 2"];
}`

// Below follows a minimal implementation of a graph capable of validating the
Expand Down Expand Up @@ -187,10 +187,22 @@ func (g *dotUndirectedGraph) DOTUnmarshalerAttrs() (graph, node, edge Unmarshale
// and decoding of node DOT label attributes.
type dotNode struct {
simple.Node
dotID string
// Node label.
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) error {
n.dotID = id
return nil
}

// UnmarshalDOTAttr decodes a single DOT attribute.
func (n *dotNode) UnmarshalDOTAttr(attr Attribute) error {
if attr.Key != "label" {
Expand Down

0 comments on commit 2ec089c

Please sign in to comment.