nodes.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. //Copyright 2013 GoGraphviz Authors
  2. //
  3. //Licensed under the Apache License, Version 2.0 (the "License");
  4. //you may not use this file except in compliance with the License.
  5. //You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. //Unless required by applicable law or agreed to in writing, software
  10. //distributed under the License is distributed on an "AS IS" BASIS,
  11. //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. //See the License for the specific language governing permissions and
  13. //limitations under the License.
  14. package gographviz
  15. import (
  16. "fmt"
  17. "sort"
  18. )
  19. // Node represents a Node.
  20. type Node struct {
  21. Name string
  22. Attrs Attrs
  23. }
  24. // Nodes represents a set of Nodes.
  25. type Nodes struct {
  26. Lookup map[string]*Node
  27. Nodes []*Node
  28. }
  29. // NewNodes creates a new set of Nodes.
  30. func NewNodes() *Nodes {
  31. return &Nodes{make(map[string]*Node), make([]*Node, 0)}
  32. }
  33. // Remove removes a node
  34. func (nodes *Nodes) Remove(name string) error {
  35. for i := 0; i < len(nodes.Nodes); i++ {
  36. if nodes.Nodes[i].Name != name {
  37. continue
  38. }
  39. nodes.Nodes = append(nodes.Nodes[:i], nodes.Nodes[i+1:]...)
  40. delete(nodes.Lookup, name)
  41. return nil
  42. }
  43. return fmt.Errorf("node %s not found", name)
  44. }
  45. // Add adds a Node to the set of Nodes, extending the attributes of an already existing node.
  46. func (nodes *Nodes) Add(node *Node) {
  47. n, ok := nodes.Lookup[node.Name]
  48. if ok {
  49. n.Attrs.Extend(node.Attrs)
  50. return
  51. }
  52. nodes.Lookup[node.Name] = node
  53. nodes.Nodes = append(nodes.Nodes, node)
  54. }
  55. // Sorted returns a sorted list of nodes.
  56. func (nodes Nodes) Sorted() []*Node {
  57. keys := make([]string, 0, len(nodes.Lookup))
  58. for key := range nodes.Lookup {
  59. keys = append(keys, key)
  60. }
  61. sort.Strings(keys)
  62. nodeList := make([]*Node, len(keys))
  63. for i := range keys {
  64. nodeList[i] = nodes.Lookup[keys[i]]
  65. }
  66. return nodeList
  67. }