3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
# GNU General Public License for more details.
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19
from bzrlib.errors import GraphCycleError
22
"""Topological sort a graph.
24
graph -- sequence of pairs of node->parents_list.
26
The result is a list of node names, such that all parents come before
29
Nodes at the same depth are returned in sorted order.
31
node identifiers can be any hashable object, and are typically strings.
33
parents = {} # node -> list of parents
34
children = {} # node -> list of children
35
for node, node_parents in graph:
36
assert node not in parents, \
37
('node %r repeated in graph' % node)
38
parents[node] = set(node_parents)
39
if node not in children:
40
children[node] = set()
41
for parent in node_parents:
42
if parent in children:
43
children[parent].add(node)
45
children[parent] = set([node])
48
# find nodes with no parents, and take them now
49
no_parents = [n for n in parents if len(parents[n]) == 0]
52
raise GraphCycleError(parents)
55
for child in children[n]:
56
assert n in parents[child]
57
parents[child].remove(n)