github.com/jsoriano/terraform@v0.6.7-0.20151026070445-8b70867fdd95/dag/graph.go (about)

     1  package dag
     2  
     3  import (
     4  	"bytes"
     5  	"fmt"
     6  	"sort"
     7  	"sync"
     8  )
     9  
    10  // Graph is used to represent a dependency graph.
    11  type Graph struct {
    12  	vertices  *Set
    13  	edges     *Set
    14  	downEdges map[Vertex]*Set
    15  	upEdges   map[Vertex]*Set
    16  	once      sync.Once
    17  }
    18  
    19  // Vertex of the graph.
    20  type Vertex interface{}
    21  
    22  // NamedVertex is an optional interface that can be implemented by Vertex
    23  // to give it a human-friendly name that is used for outputting the graph.
    24  type NamedVertex interface {
    25  	Vertex
    26  	Name() string
    27  }
    28  
    29  // Vertices returns the list of all the vertices in the graph.
    30  func (g *Graph) Vertices() []Vertex {
    31  	list := g.vertices.List()
    32  	result := make([]Vertex, len(list))
    33  	for i, v := range list {
    34  		result[i] = v.(Vertex)
    35  	}
    36  
    37  	return result
    38  }
    39  
    40  // Edges returns the list of all the edges in the graph.
    41  func (g *Graph) Edges() []Edge {
    42  	list := g.edges.List()
    43  	result := make([]Edge, len(list))
    44  	for i, v := range list {
    45  		result[i] = v.(Edge)
    46  	}
    47  
    48  	return result
    49  }
    50  
    51  // Add adds a vertex to the graph. This is safe to call multiple time with
    52  // the same Vertex.
    53  func (g *Graph) Add(v Vertex) Vertex {
    54  	g.once.Do(g.init)
    55  	g.vertices.Add(v)
    56  	return v
    57  }
    58  
    59  // Remove removes a vertex from the graph. This will also remove any
    60  // edges with this vertex as a source or target.
    61  func (g *Graph) Remove(v Vertex) Vertex {
    62  	// Delete the vertex itself
    63  	g.vertices.Delete(v)
    64  
    65  	// Delete the edges to non-existent things
    66  	for _, target := range g.DownEdges(v).List() {
    67  		g.RemoveEdge(BasicEdge(v, target))
    68  	}
    69  	for _, source := range g.UpEdges(v).List() {
    70  		g.RemoveEdge(BasicEdge(source, v))
    71  	}
    72  
    73  	return nil
    74  }
    75  
    76  // Replace replaces the original Vertex with replacement. If the original
    77  // does not exist within the graph, then false is returned. Otherwise, true
    78  // is returned.
    79  func (g *Graph) Replace(original, replacement Vertex) bool {
    80  	// If we don't have the original, we can't do anything
    81  	if !g.vertices.Include(original) {
    82  		return false
    83  	}
    84  
    85  	// If they're the same, then don't do anything
    86  	if original == replacement {
    87  		return true
    88  	}
    89  
    90  	// Add our new vertex, then copy all the edges
    91  	g.Add(replacement)
    92  	for _, target := range g.DownEdges(original).List() {
    93  		g.Connect(BasicEdge(replacement, target))
    94  	}
    95  	for _, source := range g.UpEdges(original).List() {
    96  		g.Connect(BasicEdge(source, replacement))
    97  	}
    98  
    99  	// Remove our old vertex, which will also remove all the edges
   100  	g.Remove(original)
   101  
   102  	return true
   103  }
   104  
   105  // RemoveEdge removes an edge from the graph.
   106  func (g *Graph) RemoveEdge(edge Edge) {
   107  	g.once.Do(g.init)
   108  
   109  	// Delete the edge from the set
   110  	g.edges.Delete(edge)
   111  
   112  	// Delete the up/down edges
   113  	if s, ok := g.downEdges[edge.Source()]; ok {
   114  		s.Delete(edge.Target())
   115  	}
   116  	if s, ok := g.upEdges[edge.Target()]; ok {
   117  		s.Delete(edge.Source())
   118  	}
   119  }
   120  
   121  // DownEdges returns the outward edges from the source Vertex v.
   122  func (g *Graph) DownEdges(v Vertex) *Set {
   123  	g.once.Do(g.init)
   124  	return g.downEdges[v]
   125  }
   126  
   127  // UpEdges returns the inward edges to the destination Vertex v.
   128  func (g *Graph) UpEdges(v Vertex) *Set {
   129  	g.once.Do(g.init)
   130  	return g.upEdges[v]
   131  }
   132  
   133  // Connect adds an edge with the given source and target. This is safe to
   134  // call multiple times with the same value. Note that the same value is
   135  // verified through pointer equality of the vertices, not through the
   136  // value of the edge itself.
   137  func (g *Graph) Connect(edge Edge) {
   138  	g.once.Do(g.init)
   139  
   140  	source := edge.Source()
   141  	target := edge.Target()
   142  
   143  	// Do we have this already? If so, don't add it again.
   144  	if s, ok := g.downEdges[source]; ok && s.Include(target) {
   145  		return
   146  	}
   147  
   148  	// Add the edge to the set
   149  	g.edges.Add(edge)
   150  
   151  	// Add the down edge
   152  	s, ok := g.downEdges[source]
   153  	if !ok {
   154  		s = new(Set)
   155  		g.downEdges[source] = s
   156  	}
   157  	s.Add(target)
   158  
   159  	// Add the up edge
   160  	s, ok = g.upEdges[target]
   161  	if !ok {
   162  		s = new(Set)
   163  		g.upEdges[target] = s
   164  	}
   165  	s.Add(source)
   166  }
   167  
   168  // String outputs some human-friendly output for the graph structure.
   169  func (g *Graph) String() string {
   170  	var buf bytes.Buffer
   171  
   172  	// Build the list of node names and a mapping so that we can more
   173  	// easily alphabetize the output to remain deterministic.
   174  	vertices := g.Vertices()
   175  	names := make([]string, 0, len(vertices))
   176  	mapping := make(map[string]Vertex, len(vertices))
   177  	for _, v := range vertices {
   178  		name := VertexName(v)
   179  		names = append(names, name)
   180  		mapping[name] = v
   181  	}
   182  	sort.Strings(names)
   183  
   184  	// Write each node in order...
   185  	for _, name := range names {
   186  		v := mapping[name]
   187  		targets := g.downEdges[v]
   188  
   189  		buf.WriteString(fmt.Sprintf("%s\n", name))
   190  
   191  		// Alphabetize dependencies
   192  		deps := make([]string, 0, targets.Len())
   193  		for _, target := range targets.List() {
   194  			deps = append(deps, VertexName(target))
   195  		}
   196  		sort.Strings(deps)
   197  
   198  		// Write dependencies
   199  		for _, d := range deps {
   200  			buf.WriteString(fmt.Sprintf("  %s\n", d))
   201  		}
   202  	}
   203  
   204  	return buf.String()
   205  }
   206  
   207  func (g *Graph) init() {
   208  	g.vertices = new(Set)
   209  	g.edges = new(Set)
   210  	g.downEdges = make(map[Vertex]*Set)
   211  	g.upEdges = make(map[Vertex]*Set)
   212  }
   213  
   214  // VertexName returns the name of a vertex.
   215  func VertexName(raw Vertex) string {
   216  	switch v := raw.(type) {
   217  	case NamedVertex:
   218  		return v.Name()
   219  	case fmt.Stringer:
   220  		return fmt.Sprintf("%s", v)
   221  	default:
   222  		return fmt.Sprintf("%v", v)
   223  	}
   224  }