github.com/eliastor/durgaform@v0.0.0-20220816172711-d0ab2d17673e/internal/dag/graph.go (about) 1 package dag 2 3 import ( 4 "bytes" 5 "fmt" 6 "sort" 7 ) 8 9 // Graph is used to represent a dependency graph. 10 type Graph struct { 11 vertices Set 12 edges Set 13 downEdges map[interface{}]Set 14 upEdges map[interface{}]Set 15 } 16 17 // Subgrapher allows a Vertex to be a Graph itself, by returning a Grapher. 18 type Subgrapher interface { 19 Subgraph() Grapher 20 } 21 22 // A Grapher is any type that returns a Grapher, mainly used to identify 23 // dag.Graph and dag.AcyclicGraph. In the case of Graph and AcyclicGraph, they 24 // return themselves. 25 type Grapher interface { 26 DirectedGraph() Grapher 27 } 28 29 // Vertex of the graph. 30 type Vertex interface{} 31 32 // NamedVertex is an optional interface that can be implemented by Vertex 33 // to give it a human-friendly name that is used for outputting the graph. 34 type NamedVertex interface { 35 Vertex 36 Name() string 37 } 38 39 func (g *Graph) DirectedGraph() Grapher { 40 return g 41 } 42 43 // Vertices returns the list of all the vertices in the graph. 44 func (g *Graph) Vertices() []Vertex { 45 result := make([]Vertex, 0, len(g.vertices)) 46 for _, v := range g.vertices { 47 result = append(result, v.(Vertex)) 48 } 49 50 return result 51 } 52 53 // Edges returns the list of all the edges in the graph. 54 func (g *Graph) Edges() []Edge { 55 result := make([]Edge, 0, len(g.edges)) 56 for _, v := range g.edges { 57 result = append(result, v.(Edge)) 58 } 59 60 return result 61 } 62 63 // EdgesFrom returns the list of edges from the given source. 64 func (g *Graph) EdgesFrom(v Vertex) []Edge { 65 var result []Edge 66 from := hashcode(v) 67 for _, e := range g.Edges() { 68 if hashcode(e.Source()) == from { 69 result = append(result, e) 70 } 71 } 72 73 return result 74 } 75 76 // EdgesTo returns the list of edges to the given target. 77 func (g *Graph) EdgesTo(v Vertex) []Edge { 78 var result []Edge 79 search := hashcode(v) 80 for _, e := range g.Edges() { 81 if hashcode(e.Target()) == search { 82 result = append(result, e) 83 } 84 } 85 86 return result 87 } 88 89 // HasVertex checks if the given Vertex is present in the graph. 90 func (g *Graph) HasVertex(v Vertex) bool { 91 return g.vertices.Include(v) 92 } 93 94 // HasEdge checks if the given Edge is present in the graph. 95 func (g *Graph) HasEdge(e Edge) bool { 96 return g.edges.Include(e) 97 } 98 99 // Add adds a vertex to the graph. This is safe to call multiple time with 100 // the same Vertex. 101 func (g *Graph) Add(v Vertex) Vertex { 102 g.init() 103 g.vertices.Add(v) 104 return v 105 } 106 107 // Remove removes a vertex from the graph. This will also remove any 108 // edges with this vertex as a source or target. 109 func (g *Graph) Remove(v Vertex) Vertex { 110 // Delete the vertex itself 111 g.vertices.Delete(v) 112 113 // Delete the edges to non-existent things 114 for _, target := range g.downEdgesNoCopy(v) { 115 g.RemoveEdge(BasicEdge(v, target)) 116 } 117 for _, source := range g.upEdgesNoCopy(v) { 118 g.RemoveEdge(BasicEdge(source, v)) 119 } 120 121 return nil 122 } 123 124 // Replace replaces the original Vertex with replacement. If the original 125 // does not exist within the graph, then false is returned. Otherwise, true 126 // is returned. 127 func (g *Graph) Replace(original, replacement Vertex) bool { 128 // If we don't have the original, we can't do anything 129 if !g.vertices.Include(original) { 130 return false 131 } 132 133 // If they're the same, then don't do anything 134 if original == replacement { 135 return true 136 } 137 138 // Add our new vertex, then copy all the edges 139 g.Add(replacement) 140 for _, target := range g.downEdgesNoCopy(original) { 141 g.Connect(BasicEdge(replacement, target)) 142 } 143 for _, source := range g.upEdgesNoCopy(original) { 144 g.Connect(BasicEdge(source, replacement)) 145 } 146 147 // Remove our old vertex, which will also remove all the edges 148 g.Remove(original) 149 150 return true 151 } 152 153 // RemoveEdge removes an edge from the graph. 154 func (g *Graph) RemoveEdge(edge Edge) { 155 g.init() 156 157 // Delete the edge from the set 158 g.edges.Delete(edge) 159 160 // Delete the up/down edges 161 if s, ok := g.downEdges[hashcode(edge.Source())]; ok { 162 s.Delete(edge.Target()) 163 } 164 if s, ok := g.upEdges[hashcode(edge.Target())]; ok { 165 s.Delete(edge.Source()) 166 } 167 } 168 169 // UpEdges returns the vertices connected to the outward edges from the source 170 // Vertex v. 171 func (g *Graph) UpEdges(v Vertex) Set { 172 return g.upEdgesNoCopy(v).Copy() 173 } 174 175 // DownEdges returns the vertices connected from the inward edges to Vertex v. 176 func (g *Graph) DownEdges(v Vertex) Set { 177 return g.downEdgesNoCopy(v).Copy() 178 } 179 180 // downEdgesNoCopy returns the outward edges from the source Vertex v as a Set. 181 // This Set is the same as used internally bu the Graph to prevent a copy, and 182 // must not be modified by the caller. 183 func (g *Graph) downEdgesNoCopy(v Vertex) Set { 184 g.init() 185 return g.downEdges[hashcode(v)] 186 } 187 188 // upEdgesNoCopy returns the inward edges to the destination Vertex v as a Set. 189 // This Set is the same as used internally bu the Graph to prevent a copy, and 190 // must not be modified by the caller. 191 func (g *Graph) upEdgesNoCopy(v Vertex) Set { 192 g.init() 193 return g.upEdges[hashcode(v)] 194 } 195 196 // Connect adds an edge with the given source and target. This is safe to 197 // call multiple times with the same value. Note that the same value is 198 // verified through pointer equality of the vertices, not through the 199 // value of the edge itself. 200 func (g *Graph) Connect(edge Edge) { 201 g.init() 202 203 source := edge.Source() 204 target := edge.Target() 205 sourceCode := hashcode(source) 206 targetCode := hashcode(target) 207 208 // Do we have this already? If so, don't add it again. 209 if s, ok := g.downEdges[sourceCode]; ok && s.Include(target) { 210 return 211 } 212 213 // Add the edge to the set 214 g.edges.Add(edge) 215 216 // Add the down edge 217 s, ok := g.downEdges[sourceCode] 218 if !ok { 219 s = make(Set) 220 g.downEdges[sourceCode] = s 221 } 222 s.Add(target) 223 224 // Add the up edge 225 s, ok = g.upEdges[targetCode] 226 if !ok { 227 s = make(Set) 228 g.upEdges[targetCode] = s 229 } 230 s.Add(source) 231 } 232 233 // String outputs some human-friendly output for the graph structure. 234 func (g *Graph) StringWithNodeTypes() string { 235 var buf bytes.Buffer 236 237 // Build the list of node names and a mapping so that we can more 238 // easily alphabetize the output to remain deterministic. 239 vertices := g.Vertices() 240 names := make([]string, 0, len(vertices)) 241 mapping := make(map[string]Vertex, len(vertices)) 242 for _, v := range vertices { 243 name := VertexName(v) 244 names = append(names, name) 245 mapping[name] = v 246 } 247 sort.Strings(names) 248 249 // Write each node in order... 250 for _, name := range names { 251 v := mapping[name] 252 targets := g.downEdges[hashcode(v)] 253 254 buf.WriteString(fmt.Sprintf("%s - %T\n", name, v)) 255 256 // Alphabetize dependencies 257 deps := make([]string, 0, targets.Len()) 258 targetNodes := make(map[string]Vertex) 259 for _, target := range targets { 260 dep := VertexName(target) 261 deps = append(deps, dep) 262 targetNodes[dep] = target 263 } 264 sort.Strings(deps) 265 266 // Write dependencies 267 for _, d := range deps { 268 buf.WriteString(fmt.Sprintf(" %s - %T\n", d, targetNodes[d])) 269 } 270 } 271 272 return buf.String() 273 } 274 275 // String outputs some human-friendly output for the graph structure. 276 func (g *Graph) String() string { 277 var buf bytes.Buffer 278 279 // Build the list of node names and a mapping so that we can more 280 // easily alphabetize the output to remain deterministic. 281 vertices := g.Vertices() 282 names := make([]string, 0, len(vertices)) 283 mapping := make(map[string]Vertex, len(vertices)) 284 for _, v := range vertices { 285 name := VertexName(v) 286 names = append(names, name) 287 mapping[name] = v 288 } 289 sort.Strings(names) 290 291 // Write each node in order... 292 for _, name := range names { 293 v := mapping[name] 294 targets := g.downEdges[hashcode(v)] 295 296 buf.WriteString(fmt.Sprintf("%s\n", name)) 297 298 // Alphabetize dependencies 299 deps := make([]string, 0, targets.Len()) 300 for _, target := range targets { 301 deps = append(deps, VertexName(target)) 302 } 303 sort.Strings(deps) 304 305 // Write dependencies 306 for _, d := range deps { 307 buf.WriteString(fmt.Sprintf(" %s\n", d)) 308 } 309 } 310 311 return buf.String() 312 } 313 314 func (g *Graph) init() { 315 if g.vertices == nil { 316 g.vertices = make(Set) 317 } 318 if g.edges == nil { 319 g.edges = make(Set) 320 } 321 if g.downEdges == nil { 322 g.downEdges = make(map[interface{}]Set) 323 } 324 if g.upEdges == nil { 325 g.upEdges = make(map[interface{}]Set) 326 } 327 } 328 329 // Dot returns a dot-formatted representation of the Graph. 330 func (g *Graph) Dot(opts *DotOpts) []byte { 331 return newMarshalGraph("", g).Dot(opts) 332 } 333 334 // VertexName returns the name of a vertex. 335 func VertexName(raw Vertex) string { 336 switch v := raw.(type) { 337 case NamedVertex: 338 return v.Name() 339 case fmt.Stringer: 340 return v.String() 341 default: 342 return fmt.Sprintf("%v", v) 343 } 344 }