14
14
# along with this program; if not, write to the Free Software
15
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
from bzrlib.tsort import topo_sort
21
17
def max_distance(node, ancestors, distances, root_descendants):
22
18
"""Calculate the max distance to an ancestor.
23
19
Return None if not all possible ancestors have known distances"""
106
102
new_lines.add(descendant)
107
103
lines = new_lines
112
"""A graph object which can memoise and cache results for performance."""
115
super(Graph, self).__init__()
117
self.ghosts = set([])
118
self._graph_ancestors = {}
119
self._graph_descendants = {}
121
def add_ghost(self, node_id):
122
"""Add a ghost to the graph."""
123
self.ghosts.add(node_id)
124
self._ensure_descendant(node_id)
126
def add_node(self, node_id, parent_ids):
127
"""Add node_id to the graph with parent_ids as its parents."""
129
self.roots.add(node_id)
130
self._graph_ancestors[node_id] = list(parent_ids)
131
self._ensure_descendant(node_id)
132
for parent in parent_ids:
133
self._ensure_descendant(parent)
134
self._graph_descendants[parent][node_id] = 1
136
def _ensure_descendant(self, node_id):
137
"""Ensure that a descendant lookup for node_id will work."""
138
if not node_id in self._graph_descendants:
139
self._graph_descendants[node_id] = {}
141
def get_ancestors(self):
142
"""Return a dictionary of graph node:ancestor_list entries."""
143
return dict(self._graph_ancestors.items())
145
def get_ancestry(self, node_id):
146
"""Return the inclusive ancestors of node_id in topological order."""
147
# maybe optimise this ?
149
pending = set([node_id])
151
current = pending.pop()
152
parents = self._graph_ancestors[current]
153
parents = [parent for parent in parents if parent not in self.ghosts]
154
result[current] = parents
155
for parent in parents:
156
if parent not in result and parent not in pending:
158
return topo_sort(result.items())
160
def get_descendants(self):
161
"""Return a dictionary of graph node:child_node:distance entries."""
162
return dict(self._graph_descendants.items())