1
# Copyright (C) 2005, 2006, 2008 Canonical Ltd
1
# Copyright (C) 2005, 2006 Canonical Ltd
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
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
18
18
"""Topological sorting routines."""
21
21
from bzrlib import errors
22
import bzrlib.revision as _mod_revision
25
24
__all__ = ["topo_sort", "TopoSorter", "merge_sort", "MergeSorter"]
43
42
def __init__(self, graph):
44
43
"""Topological sorting of a graph.
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:
52
51
node identifiers can be any hashable object, and are typically strings.
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.
60
iteration or sorting may raise GraphCycleError if a cycle is present
59
iteration or sorting may raise GraphCycleError if a cycle is present
63
62
# a dict of the graph.
65
64
self._visitable = set(self._graph)
67
66
# self._original_graph = dict(graph)
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
116
115
yield self._pop_node()
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'
143
142
def _push_node(self, node_name, parents):
144
143
"""Add node_name to the pending node stack.
146
145
Names in this stack will get emitted into the output as they are popped
167
166
"""Topological sort a graph which groups merges.
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
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',
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.
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:
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
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
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
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.
254
253
node identifiers can be any hashable object, and are typically strings.
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.
262
iteration or sorting may raise GraphCycleError if a cycle is present
261
iteration or sorting may raise GraphCycleError if a cycle is present
265
264
Background information on the design:
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.
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
300
299
The next revision in the list constraint is needed for this case:
302
B 1 [C, F] # we do not want to show a line to F which is depth 2
301
B 1 [C, F] # we do not want to show a line to F which is depth 2
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.
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
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
360
if graph_parent_ids[0] == parent:
353
if self._graph[revision][0] == parent:
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
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 = {}
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
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()
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 = []
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)
421
413
def sorted(self):
422
414
"""Sort the graph and return as a list.
424
416
After calling this the sorter is empty and you must create a new one.
426
418
return list(self.iter_topo_order())
428
420
def iter_topo_order(self):
429
421
"""Yield the nodes of the graph in a topological order.
431
423
After finishing iteration the sorter is empty and you cannot continue
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,
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]
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]
472
# We don't use the same algorithm here, but we need to keep the
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)
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,
488
481
"""Pop the top node off the stack
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]
503
496
# node has parents, assign from the left most parent.
504
parent_revno = revnos[parents[0]][0]
497
parent_revno = revnos[parents[0]]
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)
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)
514
# as the first child, we just increase the final revision
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,)
518
505
# no parents, use the root sequence
519
root_count = revno_to_branch_count.get(0, -1)
522
revno = (0, root_count, 1)
507
# make a parallel import revision number
508
revno = (0, sequence, 1)
525
revno_to_branch_count[0] = root_count
527
512
# store the revno for this node for future reference
528
513
revnos[node_name][0] = revno
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()
618
603
def _push_node(self, node_name, merge_depth, parents):
619
604
"""Add node_name to the pending node stack.
621
606
Names in this stack will get emitted into the output as they are popped
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]
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]
636
# We don't use the same algorithm here, but we need to keep the
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)
641
626
def _pop_node(self):
642
"""Pop the top node off the stack
627
"""Pop the top node off the stack
644
629
The node is appended to the sorted output.
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]
657
642
# node has parents, assign from the left most parent.
658
parent_revno = self._revnos[parents[0]][0]
643
parent_revno = self._revnos[parents[0]]
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)
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)
668
# as the first child, we just increase the final revision
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,)
672
651
# no parents, use the root sequence
673
root_count = self._revno_to_branch_count.get(0, 0)
675
revno = (0, root_count, 1)
653
# make a parallel import revision number
654
revno = (0, sequence, 1)
679
self._revno_to_branch_count[0] = root_count
681
658
# store the revno for this node for future reference
682
659
self._revnos[node_name][0] = revno