~ubuntu-branches/ubuntu/hardy/bzr/hardy-updates

« back to all changes in this revision

Viewing changes to bzrlib/tsort.py

  • Committer: Bazaar Package Importer
  • Author(s): Jeff Bailey
  • Date: 2005-11-07 13:17:53 UTC
  • Revision ID: james.westby@ubuntu.com-20051107131753-qsy145z1rfug5i27
Tags: upstream-0.6.2
ImportĀ upstreamĀ versionĀ 0.6.2

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# (C) 2005 Canonical
 
2
#
 
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.
 
7
#
 
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.
 
12
#
 
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
 
16
 
 
17
import pdb
 
18
 
 
19
from bzrlib.errors import GraphCycleError
 
20
 
 
21
def topo_sort(graph):
 
22
    """Topological sort a graph.
 
23
 
 
24
    graph -- sequence of pairs of node->parents_list.
 
25
 
 
26
    The result is a list of node names, such that all parents come before
 
27
    their children.
 
28
 
 
29
    Nodes at the same depth are returned in sorted order.
 
30
 
 
31
    node identifiers can be any hashable object, and are typically strings.
 
32
    """
 
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)
 
44
            else:
 
45
                children[parent] = set([node])
 
46
    result = []
 
47
    while parents:
 
48
        # find nodes with no parents, and take them now
 
49
        no_parents = [n for n in parents if len(parents[n]) == 0]
 
50
        no_parents.sort()
 
51
        if not no_parents:
 
52
            raise GraphCycleError(parents)
 
53
        for n in no_parents:
 
54
            result.append(n)
 
55
            for child in children[n]:
 
56
                assert n in parents[child]
 
57
                parents[child].remove(n)
 
58
            del children[n]
 
59
            del parents[n]
 
60
    return result