diff --git a/cgraph/attribute.go b/cgraph/attribute.go index 2b66b2d..fd07889 100644 --- a/cgraph/attribute.go +++ b/cgraph/attribute.go @@ -2912,3 +2912,19 @@ func (n *Node) SetZ(v float64) *Node { n.SafeSet(string(zAttr), fmt.Sprint(v), "0.0") return n } + +type Kind int + +const ( + KindGraph Kind = iota + KindNode + KindEdge +) + +// SetDefaultAttr +// +// Set default attribute for the graph, node, or edge. +func (g *Graph) SetDefaultAttr(kind Kind, attr string, value string) error { + _, err := g.Attr(int(kind), attr, value) + return err +} diff --git a/graphviz_test.go b/graphviz_test.go index 15b634e..9f88822 100644 --- a/graphviz_test.go +++ b/graphviz_test.go @@ -10,6 +10,7 @@ import ( "testing" "github.com/goccy/go-graphviz" + "github.com/goccy/go-graphviz/cgraph" ) func TestGraphviz_Image(t *testing.T) { @@ -350,3 +351,54 @@ func TestEdgeSourceAndTarget(t *testing.T) { t.Fatalf("Expected target name to be 'a', got '%s'", tailName) } } + +func TestDefaultNodeAttr(t *testing.T) { + ctx := context.Background() + graph, err := graphviz.New(ctx) + if err != nil { + t.Fatalf("Error: %+v", err) + } + + g, err := graph.Graph() + if err != nil { + t.Fatalf("Error: %+v", err) + } + + err = g.SetDefaultAttr(cgraph.KindGraph, "bgcolor", "red") + if err != nil { + t.Fatalf("Error: %+v", err) + } + + err = g.SetDefaultAttr(cgraph.KindNode, "shape", "box") + if err != nil { + t.Fatalf("Error: %+v", err) + } + + err = g.SetDefaultAttr(cgraph.KindEdge, "color", "blue") + if err != nil { + t.Fatalf("Error: %+v", err) + } + + bgcolor := g.GetStr("bgcolor") + if bgcolor != "red" { + t.Fatalf("Expected bgcolor to be 'red', got '%s'", bgcolor) + } + + n, err := g.CreateNodeByName("n") + if err != nil { + t.Fatalf("Error: %+v", err) + } + shape := n.GetStr("shape") + if shape != "box" { + t.Fatalf("Expected shape to be 'box', got '%s'", shape) + } + + e, err := g.CreateEdgeByName("e", n, n) + if err != nil { + t.Fatalf("Error: %+v", err) + } + color := e.GetStr("color") + if color != "blue" { + t.Fatalf("Expected color to be 'blue', got '%s'", color) + } +}