github.com/tushar-armorcode/terraform@v0.11.12-beta1/digraph/basic.go (about) 1 package digraph 2 3 import ( 4 "fmt" 5 "strings" 6 ) 7 8 // BasicNode is a digraph Node that has a name and out edges 9 type BasicNode struct { 10 Name string 11 NodeEdges []Edge 12 } 13 14 func (b *BasicNode) Edges() []Edge { 15 return b.NodeEdges 16 } 17 18 func (b *BasicNode) AddEdge(edge Edge) { 19 b.NodeEdges = append(b.NodeEdges, edge) 20 } 21 22 func (b *BasicNode) String() string { 23 if b.Name == "" { 24 return "Node" 25 } 26 return fmt.Sprintf("%v", b.Name) 27 } 28 29 // BasicEdge is a digraph Edge that has a name, head and tail 30 type BasicEdge struct { 31 Name string 32 EdgeHead *BasicNode 33 EdgeTail *BasicNode 34 } 35 36 func (b *BasicEdge) Head() Node { 37 return b.EdgeHead 38 } 39 40 // Tail returns the end point of the Edge 41 func (b *BasicEdge) Tail() Node { 42 return b.EdgeTail 43 } 44 45 func (b *BasicEdge) String() string { 46 if b.Name == "" { 47 return "Edge" 48 } 49 return fmt.Sprintf("%v", b.Name) 50 } 51 52 // ParseBasic is used to parse a string in the format of: 53 // a -> b ; edge name 54 // b -> c 55 // Into a series of basic node and basic edges 56 func ParseBasic(s string) map[string]*BasicNode { 57 lines := strings.Split(s, "\n") 58 nodes := make(map[string]*BasicNode) 59 for _, line := range lines { 60 var edgeName string 61 if idx := strings.Index(line, ";"); idx >= 0 { 62 edgeName = strings.Trim(line[idx+1:], " \t\r\n") 63 line = line[:idx] 64 } 65 parts := strings.SplitN(line, "->", 2) 66 if len(parts) != 2 { 67 continue 68 } 69 head_name := strings.Trim(parts[0], " \t\r\n") 70 tail_name := strings.Trim(parts[1], " \t\r\n") 71 head := nodes[head_name] 72 if head == nil { 73 head = &BasicNode{Name: head_name} 74 nodes[head_name] = head 75 } 76 tail := nodes[tail_name] 77 if tail == nil { 78 tail = &BasicNode{Name: tail_name} 79 nodes[tail_name] = tail 80 } 81 edge := &BasicEdge{ 82 Name: edgeName, 83 EdgeHead: head, 84 EdgeTail: tail, 85 } 86 head.AddEdge(edge) 87 } 88 return nodes 89 }