~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tsort.py

  • Committer: Canonical.com Patch Queue Manager
  • Date: 2007-08-09 15:19:06 UTC
  • mfrom: (2681.1.7 send-bundle)
  • Revision ID: pqm@pqm.ubuntu.com-20070809151906-hdn9oyslf2qib2op
Allow omitting -o for bundle, add --format

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2006, 2008 Canonical Ltd
 
1
# Copyright (C) 2005, 2006 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
12
12
#
13
13
# You should have received a copy of the GNU General Public License
14
14
# along with this program; if not, write to the Free Software
15
 
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
16
 
17
17
 
18
18
"""Topological sorting routines."""
19
19
 
20
20
 
21
21
from bzrlib import errors
22
 
import bzrlib.revision as _mod_revision
23
22
 
24
23
 
25
24
__all__ = ["topo_sort", "TopoSorter", "merge_sort", "MergeSorter"]
42
41
 
43
42
    def __init__(self, graph):
44
43
        """Topological sorting of a graph.
45
 
 
 
44
    
46
45
        :param graph: sequence of pairs of node_name->parent_names_list.
47
46
                      i.e. [('C', ['B']), ('B', ['A']), ('A', [])]
48
47
                      For this input the output from the sort or
49
48
                      iter_topo_order routines will be:
50
49
                      'A', 'B', 'C'
51
 
 
 
50
        
52
51
        node identifiers can be any hashable object, and are typically strings.
53
52
 
54
53
        If you have a graph like [('a', ['b']), ('a', ['c'])] this will only use
57
56
        The graph is sorted lazily: until you iterate or sort the input is
58
57
        not processed other than to create an internal representation.
59
58
 
60
 
        iteration or sorting may raise GraphCycleError if a cycle is present
 
59
        iteration or sorting may raise GraphCycleError if a cycle is present 
61
60
        in the graph.
62
61
        """
63
62
        # a dict of the graph.
65
64
        self._visitable = set(self._graph)
66
65
        ### if debugging:
67
66
        # self._original_graph = dict(graph)
68
 
 
 
67
        
69
68
        # this is a stack storing the depth first search into the graph.
70
69
        self._node_name_stack = []
71
70
        # at each level of 'recursion' we have to check each parent. This
72
 
        # stack stores the parents we have not yet checked for the node at the
 
71
        # stack stores the parents we have not yet checked for the node at the 
73
72
        # matching depth in _node_name_stack
74
73
        self._pending_parents_stack = []
75
74
        # this is a set of the completed nodes for fast checking whether a
79
78
 
80
79
    def sorted(self):
81
80
        """Sort the graph and return as a list.
82
 
 
 
81
        
83
82
        After calling this the sorter is empty and you must create a new one.
84
83
        """
85
84
        return list(self.iter_topo_order())
96
95
 
97
96
    def iter_topo_order(self):
98
97
        """Yield the nodes of the graph in a topological order.
99
 
 
 
98
        
100
99
        After finishing iteration the sorter is empty and you cannot continue
101
100
        iteration.
102
101
        """
116
115
                    yield self._pop_node()
117
116
                else:
118
117
                    while self._pending_parents_stack[-1]:
119
 
                        # recurse depth first into a single parent
 
118
                        # recurse depth first into a single parent 
120
119
                        next_node_name = self._pending_parents_stack[-1].pop()
121
120
                        if next_node_name in self._completed_node_names:
122
121
                            # this parent was completed by a child on the
136
135
                            # this indicates a cycle.
137
136
                            raise errors.GraphCycleError(self._node_name_stack)
138
137
                        self._push_node(next_node_name, parents)
139
 
                        # and do not continue processing parents until this 'call'
 
138
                        # and do not continue processing parents until this 'call' 
140
139
                        # has recursed.
141
140
                        break
142
141
 
143
142
    def _push_node(self, node_name, parents):
144
143
        """Add node_name to the pending node stack.
145
 
 
 
144
        
146
145
        Names in this stack will get emitted into the output as they are popped
147
146
        off the stack.
148
147
        """
150
149
        self._pending_parents_stack.append(list(parents))
151
150
 
152
151
    def _pop_node(self):
153
 
        """Pop the top node off the stack
 
152
        """Pop the top node off the stack 
154
153
 
155
154
        The node is appended to the sorted output.
156
155
        """
167
166
    """Topological sort a graph which groups merges.
168
167
 
169
168
    :param graph: sequence of pairs of node->parents_list.
170
 
    :param branch_tip: the tip of the branch to graph. Revisions not
 
169
    :param branch_tip: the tip of the branch to graph. Revisions not 
171
170
                       reachable from branch_tip are not included in the
172
171
                       output.
173
172
    :param mainline_revisions: If not None this forces a mainline to be
193
192
    __slots__ = ['_node_name_stack',
194
193
                 '_node_merge_depth_stack',
195
194
                 '_pending_parents_stack',
196
 
                 '_first_child_stack',
 
195
                 '_assigned_sequence_stack',
197
196
                 '_left_subtree_pushed_stack',
198
197
                 '_generate_revno',
199
198
                 '_graph',
201
200
                 '_stop_revision',
202
201
                 '_original_graph',
203
202
                 '_revnos',
204
 
                 '_revno_to_branch_count',
 
203
                 '_root_sequence',
205
204
                 '_completed_node_names',
206
205
                 '_scheduled_nodes',
207
206
                ]
209
208
    def __init__(self, graph, branch_tip, mainline_revisions=None,
210
209
        generate_revno=False):
211
210
        """Merge-aware topological sorting of a graph.
212
 
 
 
211
    
213
212
        :param graph: sequence of pairs of node_name->parent_names_list.
214
213
                      i.e. [('C', ['B']), ('B', ['A']), ('A', [])]
215
214
                      For this input the output from the sort or
216
215
                      iter_topo_order routines will be:
217
216
                      'A', 'B', 'C'
218
 
        :param branch_tip: the tip of the branch to graph. Revisions not
 
217
        :param branch_tip: the tip of the branch to graph. Revisions not 
219
218
                       reachable from branch_tip are not included in the
220
219
                       output.
221
220
        :param mainline_revisions: If not None this forces a mainline to be
233
232
        The result is a list sorted so that all parents come before
234
233
        their children. Each element of the list is a tuple containing:
235
234
        (sequence_number, node_name, merge_depth, end_of_merge)
236
 
         * sequence_number: The sequence of this row in the output. Useful for
 
235
         * sequence_number: The sequence of this row in the output. Useful for 
237
236
           GUIs.
238
237
         * node_name: The node name: opaque text to the merge routine.
239
238
         * merge_depth: How many levels of merging deep this node has been
240
239
           found.
241
240
         * revno_sequence: When requested this field provides a sequence of
242
241
             revision numbers for all revisions. The format is:
243
 
             (REVNO, BRANCHNUM, BRANCHREVNO). BRANCHNUM is the number of the
 
242
             REVNO[[.BRANCHREVNO.REVNO] ...]. BRANCHREVNO is the number of the
244
243
             branch that the revno is on. From left to right the REVNO numbers
245
244
             are the sequence numbers within that branch of the revision.
246
245
             For instance, the graph {A:[], B:['A'], C:['A', 'B']} will get
250
249
             second commit in the trunk'.
251
250
         * end_of_merge: When True the next node is part of a different merge.
252
251
 
253
 
 
 
252
        
254
253
        node identifiers can be any hashable object, and are typically strings.
255
254
 
256
255
        If you have a graph like [('a', ['b']), ('a', ['c'])] this will only use
259
258
        The graph is sorted lazily: until you iterate or sort the input is
260
259
        not processed other than to create an internal representation.
261
260
 
262
 
        iteration or sorting may raise GraphCycleError if a cycle is present
 
261
        iteration or sorting may raise GraphCycleError if a cycle is present 
263
262
        in the graph.
264
263
 
265
264
        Background information on the design:
284
283
              E  1   [F]
285
284
              F 0
286
285
              C is the end of a cluster due to rule 1.
287
 
              D is not the end of a cluster from rule 1, but is from rule 2: E
 
286
              D is not the end of a cluster from rule 1, but is from rule 2: E 
288
287
                is not its left most ancestor
289
288
              E is the end of a cluster due to rule 1
290
289
              F might be but we need more data.
291
 
 
 
290
              
292
291
        we show connecting lines to a parent when:
293
292
         - The parent is the start of a merge within this cluster.
294
 
           That is, the merge was not done to the mainline before this cluster
 
293
           That is, the merge was not done to the mainline before this cluster 
295
294
           was merged to the mainline.
296
295
           This can be detected thus:
297
 
            * The parent has a higher merge depth and is the next revision in
 
296
            * The parent has a higher merge depth and is the next revision in 
298
297
              the list.
299
 
 
 
298
          
300
299
          The next revision in the list constraint is needed for this case:
301
 
          A 0   [D, B]
302
 
          B  1  [C, F]   # we do not want to show a line to F which is depth 2
 
300
          A 0   [D, B]   
 
301
          B  1  [C, F]   # we do not want to show a line to F which is depth 2 
303
302
                           but not a merge
304
 
          C  1  [H]      # note that this is a long line to show back to the
 
303
          C  1  [H]      # note that this is a long line to show back to the 
305
304
                           ancestor - see the end of merge rules.
306
305
          D 0   [G, E]
307
306
          E  1  [G, F]
342
341
        else:
343
342
            self._mainline_revisions = list(mainline_revisions)
344
343
            self._stop_revision = self._mainline_revisions[0]
345
 
        # skip the first revision, its what we reach and its parents are
 
344
        # skip the first revision, its what we reach and its parents are 
346
345
        # therefore irrelevant
347
346
        for index, revision in enumerate(self._mainline_revisions[1:]):
348
347
            # NB: index 0 means self._mainline_revisions[1]
351
350
            if parent is None:
352
351
                # end of mainline_revisions history
353
352
                continue
354
 
            graph_parent_ids = self._graph[revision]
355
 
            if not graph_parent_ids:
356
 
                # We ran into a ghost, skip over it, this is a workaround for
357
 
                # bug #243536, the _graph has had ghosts stripped, but the
358
 
                # mainline_revisions have not
359
 
                continue
360
 
            if graph_parent_ids[0] == parent:
 
353
            if self._graph[revision][0] == parent:
361
354
                continue
362
355
            # remove it from its prior spot
363
356
            self._graph[revision].remove(parent)
369
362
        self._original_graph = dict(self._graph.items())
370
363
        # we need to know the revision numbers of revisions to determine
371
364
        # the revision numbers of their descendants
372
 
        # this is a graph from node to [revno_tuple, first_child]
373
 
        # where first_child is True if no other children have seen this node
 
365
        # this is a graph from node to [revno_tuple, sequence_number]
 
366
        # where sequence is the number of branches made from the node,
374
367
        # and revno_tuple is the tuple that was assigned to the node.
375
368
        # we dont know revnos to start with, so we start it seeded with
376
 
        # [None, True]
377
 
        self._revnos = dict((revision, [None, True])
378
 
                            for revision in self._graph)
379
 
        # Each mainline revision counts how many child branches have spawned from it.
380
 
        self._revno_to_branch_count = {}
381
 
 
 
369
        # [None, 0]
 
370
        self._revnos = dict((revision, [None, 0]) for revision in self._graph)
 
371
        # the global implicit root node has revno 0, but we need to know
 
372
        # the sequence number for it too:
 
373
        self._root_sequence = 0
 
374
        
382
375
        # this is a stack storing the depth first search into the graph.
383
376
        self._node_name_stack = []
384
377
        # at each level of recursion we need the merge depth this node is at:
385
378
        self._node_merge_depth_stack = []
386
379
        # at each level of 'recursion' we have to check each parent. This
387
 
        # stack stores the parents we have not yet checked for the node at the
 
380
        # stack stores the parents we have not yet checked for the node at the 
388
381
        # matching depth in _node_name_stack
389
382
        self._pending_parents_stack = []
390
383
        # When we first look at a node we assign it a seqence number from its
391
384
        # leftmost parent.
392
 
        self._first_child_stack = []
 
385
        self._assigned_sequence_stack = []
393
386
        # this is a set of the nodes who have been completely analysed for fast
394
387
        # membership checking
395
388
        self._completed_node_names = set()
402
395
        # D 0  [F, E]
403
396
        # E  1 [F]
404
397
        # F 0
405
 
        # the scheduling order is: F, E, D, C, B, A
 
398
        # the scheduling order is: F, E, D, C, B, A 
406
399
        # that is - 'left subtree, right subtree, node'
407
400
        # which would mean that when we schedule A we can emit the entire tree.
408
401
        self._scheduled_nodes = []
409
 
        # This records for each node when we have processed its left most
 
402
        # This records for each node when we have processed its left most 
410
403
        # unmerged subtree. After this subtree is scheduled, all other subtrees
411
404
        # have their merge depth increased by one from this nodes merge depth.
412
405
        # it contains tuples - name, merge_depth
413
406
        self._left_subtree_pushed_stack = []
414
407
 
415
408
        # seed the search with the tip of the branch
416
 
        if (branch_tip is not None and
417
 
            branch_tip != _mod_revision.NULL_REVISION):
 
409
        if branch_tip is not None:
418
410
            parents = self._graph.pop(branch_tip)
419
411
            self._push_node(branch_tip, 0, parents)
420
412
 
421
413
    def sorted(self):
422
414
        """Sort the graph and return as a list.
423
 
 
 
415
        
424
416
        After calling this the sorter is empty and you must create a new one.
425
417
        """
426
418
        return list(self.iter_topo_order())
427
419
 
428
420
    def iter_topo_order(self):
429
421
        """Yield the nodes of the graph in a topological order.
430
 
 
 
422
        
431
423
        After finishing iteration the sorter is empty and you cannot continue
432
424
        iteration.
433
425
        """
447
439
                      node_merge_depth_stack_append=node_merge_depth_stack.append,
448
440
                      left_subtree_pushed_stack_append=left_subtree_pushed_stack.append,
449
441
                      pending_parents_stack_append=pending_parents_stack.append,
450
 
                      first_child_stack_append=self._first_child_stack.append,
 
442
                      assigned_sequence_stack_append=self._assigned_sequence_stack.append,
 
443
                      original_graph=self._original_graph,
451
444
                      revnos=self._revnos,
452
445
                      ):
453
446
            """Add node_name to the pending node stack.
462
455
            node_merge_depth_stack_append(merge_depth)
463
456
            left_subtree_pushed_stack_append(False)
464
457
            pending_parents_stack_append(list(parents))
465
 
            # as we push it, check if it is the first child
 
458
            # as we push it, assign it a sequence number against its parent:
 
459
            parents = original_graph[node_name]
466
460
            if parents:
467
461
                # node has parents, assign from the left most parent.
468
 
                parent_info = revnos[parents[0]]
469
 
                first_child = parent_info[1]
470
 
                parent_info[1] = False
 
462
                parent_revno = revnos[parents[0]]
 
463
                sequence = parent_revno[1]
 
464
                parent_revno[1] += 1
471
465
            else:
472
 
                # We don't use the same algorithm here, but we need to keep the
473
 
                # stack in line
474
 
                first_child = None
475
 
            first_child_stack_append(first_child)
 
466
                # no parents, use the root sequence
 
467
                sequence = self._root_sequence
 
468
                self._root_sequence +=1
 
469
            assigned_sequence_stack_append(sequence)
476
470
 
477
471
        def pop_node(node_name_stack_pop=node_name_stack.pop,
478
472
                     node_merge_depth_stack_pop=node_merge_depth_stack.pop,
479
 
                     first_child_stack_pop=self._first_child_stack.pop,
 
473
                     assigned_sequence_stack_pop=self._assigned_sequence_stack.pop,
480
474
                     left_subtree_pushed_stack_pop=left_subtree_pushed_stack.pop,
481
475
                     pending_parents_stack_pop=pending_parents_stack.pop,
482
476
                     original_graph=self._original_graph,
483
477
                     revnos=self._revnos,
484
478
                     completed_node_names_add=self._completed_node_names.add,
485
479
                     scheduled_nodes_append=scheduled_nodes.append,
486
 
                     revno_to_branch_count=self._revno_to_branch_count,
487
480
                    ):
488
481
            """Pop the top node off the stack
489
482
 
493
486
            # pop off the local variables
494
487
            node_name = node_name_stack_pop()
495
488
            merge_depth = node_merge_depth_stack_pop()
496
 
            first_child = first_child_stack_pop()
 
489
            sequence = assigned_sequence_stack_pop()
497
490
            # remove this node from the pending lists:
498
491
            left_subtree_pushed_stack_pop()
499
492
            pending_parents_stack_pop()
501
494
            parents = original_graph[node_name]
502
495
            if parents:
503
496
                # node has parents, assign from the left most parent.
504
 
                parent_revno = revnos[parents[0]][0]
505
 
                if not first_child:
 
497
                parent_revno = revnos[parents[0]]
 
498
                if sequence:
506
499
                    # not the first child, make a new branch
507
 
                    base_revno = parent_revno[0]
508
 
                    branch_count = revno_to_branch_count.get(base_revno, 0)
509
 
                    branch_count += 1
510
 
                    revno_to_branch_count[base_revno] = branch_count
511
 
                    revno = (parent_revno[0], branch_count, 1)
512
 
                    # revno = (parent_revno[0], branch_count, parent_revno[-1]+1)
 
500
                    revno = parent_revno[0] + (sequence, 1)
513
501
                else:
514
 
                    # as the first child, we just increase the final revision
515
 
                    # number
516
 
                    revno = parent_revno[:-1] + (parent_revno[-1] + 1,)
 
502
                    # increment the sequence number within the branch
 
503
                    revno = parent_revno[0][:-1] + (parent_revno[0][-1] + 1,)
517
504
            else:
518
505
                # no parents, use the root sequence
519
 
                root_count = revno_to_branch_count.get(0, -1)
520
 
                root_count += 1
521
 
                if root_count:
522
 
                    revno = (0, root_count, 1)
 
506
                if sequence:
 
507
                    # make a parallel import revision number
 
508
                    revno = (0, sequence, 1)
523
509
                else:
524
510
                    revno = (1,)
525
 
                revno_to_branch_count[0] = root_count
526
511
 
527
512
            # store the revno for this node for future reference
528
513
            revnos[node_name][0] = revno
548
533
                    else:
549
534
                        # place any merges in right-to-left order for scheduling
550
535
                        # which gives us left-to-right order after we reverse
551
 
                        # the scheduled queue. XXX: This has the effect of
 
536
                        # the scheduled queue. XXX: This has the effect of 
552
537
                        # allocating common-new revisions to the right-most
553
 
                        # subtree rather than the left most, which will
 
538
                        # subtree rather than the left most, which will 
554
539
                        # display nicely (you get smaller trees at the top
555
540
                        # of the combined merge).
556
541
                        next_node_name = pending_parents_stack[-1].pop()
582
567
                        next_node_name,
583
568
                        next_merge_depth,
584
569
                        parents)
585
 
                    # and do not continue processing parents until this 'call'
 
570
                    # and do not continue processing parents until this 'call' 
586
571
                    # has recursed.
587
572
                    break
588
573
 
617
602
 
618
603
    def _push_node(self, node_name, merge_depth, parents):
619
604
        """Add node_name to the pending node stack.
620
 
 
 
605
        
621
606
        Names in this stack will get emitted into the output as they are popped
622
607
        off the stack.
623
608
        """
625
610
        self._node_merge_depth_stack.append(merge_depth)
626
611
        self._left_subtree_pushed_stack.append(False)
627
612
        self._pending_parents_stack.append(list(parents))
628
 
        # as we push it, figure out if this is the first child
 
613
        # as we push it, assign it a sequence number against its parent:
629
614
        parents = self._original_graph[node_name]
630
615
        if parents:
631
616
            # node has parents, assign from the left most parent.
632
 
            parent_info = self._revnos[parents[0]]
633
 
            first_child = parent_info[1]
634
 
            parent_info[1] = False
 
617
            parent_revno = self._revnos[parents[0]]
 
618
            sequence = parent_revno[1]
 
619
            parent_revno[1] += 1
635
620
        else:
636
 
            # We don't use the same algorithm here, but we need to keep the
637
 
            # stack in line
638
 
            first_child = None
639
 
        self._first_child_stack.append(first_child)
 
621
            # no parents, use the root sequence
 
622
            sequence = self._root_sequence
 
623
            self._root_sequence +=1
 
624
        self._assigned_sequence_stack.append(sequence)
640
625
 
641
626
    def _pop_node(self):
642
 
        """Pop the top node off the stack
 
627
        """Pop the top node off the stack 
643
628
 
644
629
        The node is appended to the sorted output.
645
630
        """
647
632
        # pop off the local variables
648
633
        node_name = self._node_name_stack.pop()
649
634
        merge_depth = self._node_merge_depth_stack.pop()
650
 
        first_child = self._first_child_stack.pop()
 
635
        sequence = self._assigned_sequence_stack.pop()
651
636
        # remove this node from the pending lists:
652
637
        self._left_subtree_pushed_stack.pop()
653
638
        self._pending_parents_stack.pop()
655
640
        parents = self._original_graph[node_name]
656
641
        if parents:
657
642
            # node has parents, assign from the left most parent.
658
 
            parent_revno = self._revnos[parents[0]][0]
659
 
            if not first_child:
 
643
            parent_revno = self._revnos[parents[0]]
 
644
            if sequence:
660
645
                # not the first child, make a new branch
661
 
                base_revno = parent_revno[0]
662
 
                branch_count = self._revno_to_branch_count.get(base_revno, 0)
663
 
                branch_count += 1
664
 
                self._revno_to_branch_count[base_revno] = branch_count
665
 
                revno = (parent_revno[0], branch_count, 1)
666
 
                # revno = (parent_revno[0], branch_count, parent_revno[-1]+1)
 
646
                revno = parent_revno[0] + (sequence, 1)
667
647
            else:
668
 
                # as the first child, we just increase the final revision
669
 
                # number
670
 
                revno = parent_revno[:-1] + (parent_revno[-1] + 1,)
 
648
                # increment the sequence number within the branch
 
649
                revno = parent_revno[0][:-1] + (parent_revno[0][-1] + 1,)
671
650
        else:
672
651
            # no parents, use the root sequence
673
 
            root_count = self._revno_to_branch_count.get(0, 0)
674
 
            if root_count:
675
 
                revno = (0, root_count, 1)
 
652
            if sequence:
 
653
                # make a parallel import revision number
 
654
                revno = (0, sequence, 1)
676
655
            else:
677
656
                revno = (1,)
678
 
            root_count += 1
679
 
            self._revno_to_branch_count[0] = root_count
680
657
 
681
658
        # store the revno for this node for future reference
682
659
        self._revnos[node_name][0] = revno