1
# Copyright (C) 2005, 2006 Canonical Ltd
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
18
"""Topological sorting routines."""
21
from bzrlib import errors
24
__all__ = ["topo_sort", "TopoSorter", "merge_sort", "MergeSorter"]
28
"""Topological sort a graph.
30
graph -- sequence of pairs of node->parents_list.
32
The result is a list of node names, such that all parents come before
35
node identifiers can be any hashable object, and are typically strings.
37
return TopoSorter(graph).sorted()
40
class TopoSorter(object):
42
def __init__(self, graph):
43
"""Topological sorting of a graph.
45
:param graph: sequence of pairs of node_name->parent_names_list.
46
i.e. [('C', ['B']), ('B', ['A']), ('A', [])]
47
For this input the output from the sort or
48
iter_topo_order routines will be:
51
node identifiers can be any hashable object, and are typically strings.
53
If you have a graph like [('a', ['b']), ('a', ['c'])] this will only use
54
one of the two values for 'a'.
56
The graph is sorted lazily: until you iterate or sort the input is
57
not processed other than to create an internal representation.
59
iteration or sorting may raise GraphCycleError if a cycle is present
62
# a dict of the graph.
63
self._graph = dict(graph)
64
self._visitable = set(self._graph)
66
# self._original_graph = dict(graph)
68
# this is a stack storing the depth first search into the graph.
69
self._node_name_stack = []
70
# at each level of 'recursion' we have to check each parent. This
71
# stack stores the parents we have not yet checked for the node at the
72
# matching depth in _node_name_stack
73
self._pending_parents_stack = []
74
# this is a set of the completed nodes for fast checking whether a
75
# parent in a node we are processing on the stack has already been
76
# emitted and thus can be skipped.
77
self._completed_node_names = set()
80
"""Sort the graph and return as a list.
82
After calling this the sorter is empty and you must create a new one.
84
return list(self.iter_topo_order())
86
### Useful if fiddling with this code.
88
### sorted_names = list(self.iter_topo_order())
89
### for index in range(len(sorted_names)):
90
### rev = sorted_names[index]
91
### for left_index in range(index):
92
### if rev in self.original_graph[sorted_names[left_index]]:
93
### print "revision in parent list of earlier revision"
94
### import pdb;pdb.set_trace()
96
def iter_topo_order(self):
97
"""Yield the nodes of the graph in a topological order.
99
After finishing iteration the sorter is empty and you cannot continue
103
# now pick a random node in the source graph, and transfer it to the
104
# top of the depth first search stack.
105
node_name, parents = self._graph.popitem()
106
self._push_node(node_name, parents)
107
while self._node_name_stack:
108
# loop until this call completes.
109
parents_to_visit = self._pending_parents_stack[-1]
110
# if all parents are done, the revision is done
111
if not parents_to_visit:
112
# append the revision to the topo sorted list
113
# all the nodes parents have been added to the output, now
114
# we can add it to the output.
115
yield self._pop_node()
117
while self._pending_parents_stack[-1]:
118
# recurse depth first into a single parent
119
next_node_name = self._pending_parents_stack[-1].pop()
120
if next_node_name in self._completed_node_names:
121
# this parent was completed by a child on the
122
# call stack. skip it.
124
if next_node_name not in self._visitable:
126
# otherwise transfer it from the source graph into the
127
# top of the current depth first search stack.
129
parents = self._graph.pop(next_node_name)
131
# if the next node is not in the source graph it has
132
# already been popped from it and placed into the
133
# current search stack (but not completed or we would
134
# have hit the continue 4 lines up.
135
# this indicates a cycle.
136
raise errors.GraphCycleError(self._node_name_stack)
137
self._push_node(next_node_name, parents)
138
# and do not continue processing parents until this 'call'
142
def _push_node(self, node_name, parents):
143
"""Add node_name to the pending node stack.
145
Names in this stack will get emitted into the output as they are popped
148
self._node_name_stack.append(node_name)
149
self._pending_parents_stack.append(list(parents))
152
"""Pop the top node off the stack
154
The node is appended to the sorted output.
156
# we are returning from the flattened call frame:
157
# pop off the local variables
158
node_name = self._node_name_stack.pop()
159
self._pending_parents_stack.pop()
161
self._completed_node_names.add(node_name)
165
def merge_sort(graph, branch_tip, mainline_revisions=None, generate_revno=False):
166
"""Topological sort a graph which groups merges.
168
:param graph: sequence of pairs of node->parents_list.
169
:param branch_tip: the tip of the branch to graph. Revisions not
170
reachable from branch_tip are not included in the
172
:param mainline_revisions: If not None this forces a mainline to be
173
used rather than synthesised from the graph.
174
This must be a valid path through some part
175
of the graph. If the mainline does not cover all
176
the revisions, output stops at the start of the
177
old revision listed in the mainline revisions
179
The order for this parameter is oldest-first.
180
:param generate_revno: Optional parameter controlling the generation of
181
revision number sequences in the output. See the output description of
182
the MergeSorter docstring for details.
183
:result: See the MergeSorter docstring for details.
184
node identifiers can be any hashable object, and are typically strings.
186
return MergeSorter(graph, branch_tip, mainline_revisions,
187
generate_revno).sorted()
190
class MergeSorter(object):
192
__slots__ = ['_node_name_stack',
193
'_node_merge_depth_stack',
194
'_pending_parents_stack',
195
'_first_child_stack',
196
'_left_subtree_pushed_stack',
199
'_mainline_revisions',
203
'_revno_to_branch_count',
204
'_completed_node_names',
208
def __init__(self, graph, branch_tip, mainline_revisions=None,
209
generate_revno=False):
210
"""Merge-aware topological sorting of a graph.
212
:param graph: sequence of pairs of node_name->parent_names_list.
213
i.e. [('C', ['B']), ('B', ['A']), ('A', [])]
214
For this input the output from the sort or
215
iter_topo_order routines will be:
217
:param branch_tip: the tip of the branch to graph. Revisions not
218
reachable from branch_tip are not included in the
220
:param mainline_revisions: If not None this forces a mainline to be
221
used rather than synthesised from the graph.
222
This must be a valid path through some part
223
of the graph. If the mainline does not cover all
224
the revisions, output stops at the start of the
225
old revision listed in the mainline revisions
227
The order for this parameter is oldest-first.
228
:param generate_revno: Optional parameter controlling the generation of
229
revision number sequences in the output. See the output description
232
The result is a list sorted so that all parents come before
233
their children. Each element of the list is a tuple containing:
234
(sequence_number, node_name, merge_depth, end_of_merge)
235
* sequence_number: The sequence of this row in the output. Useful for
237
* node_name: The node name: opaque text to the merge routine.
238
* merge_depth: How many levels of merging deep this node has been
240
* revno_sequence: When requested this field provides a sequence of
241
revision numbers for all revisions. The format is:
242
(REVNO, BRANCHNUM, BRANCHREVNO). BRANCHNUM is the number of the
243
branch that the revno is on. From left to right the REVNO numbers
244
are the sequence numbers within that branch of the revision.
245
For instance, the graph {A:[], B:['A'], C:['A', 'B']} will get
246
the following revno_sequences assigned: A:(1,), B:(1,1,1), C:(2,).
247
This should be read as 'A is the first commit in the trunk',
248
'B is the first commit on the first branch made from A', 'C is the
249
second commit in the trunk'.
250
* end_of_merge: When True the next node is part of a different merge.
253
node identifiers can be any hashable object, and are typically strings.
255
If you have a graph like [('a', ['b']), ('a', ['c'])] this will only use
256
one of the two values for 'a'.
258
The graph is sorted lazily: until you iterate or sort the input is
259
not processed other than to create an internal representation.
261
iteration or sorting may raise GraphCycleError if a cycle is present
264
Background information on the design:
265
-------------------------------------
266
definition: the end of any cluster or 'merge' occurs when:
267
1 - the next revision has a lower merge depth than we do.
274
C, D are the ends of clusters, E might be but we need more data.
275
2 - or the next revision at our merge depth is not our left most
277
This is required to handle multiple-merges in one commit.
285
C is the end of a cluster due to rule 1.
286
D is not the end of a cluster from rule 1, but is from rule 2: E
287
is not its left most ancestor
288
E is the end of a cluster due to rule 1
289
F might be but we need more data.
291
we show connecting lines to a parent when:
292
- The parent is the start of a merge within this cluster.
293
That is, the merge was not done to the mainline before this cluster
294
was merged to the mainline.
295
This can be detected thus:
296
* The parent has a higher merge depth and is the next revision in
299
The next revision in the list constraint is needed for this case:
301
B 1 [C, F] # we do not want to show a line to F which is depth 2
303
C 1 [H] # note that this is a long line to show back to the
304
ancestor - see the end of merge rules.
310
- Part of this merges 'branch':
311
The parent has the same merge depth and is our left most parent and we
312
are not the end of the cluster.
313
A 0 [C, B] lines: [B, C]
314
B 1 [E, C] lines: [C]
316
D 0 [F, E] lines: [E, F]
319
- The end of this merge/cluster:
320
we can ONLY have multiple parents at the end of a cluster if this
321
branch was previously merged into the 'mainline'.
322
- if we have one and only one parent, show it
323
Note that this may be to a greater merge depth - for instance if
324
this branch continued from a deeply nested branch to add something
326
- if we have more than one parent - show the second oldest (older ==
327
further down the list) parent with
328
an equal or lower merge depth
329
XXXX revisit when awake. ddaa asks about the relevance of each one
330
- maybe more than one parent is relevant
332
self._generate_revno = generate_revno
333
# a dict of the graph.
334
self._graph = dict(graph)
335
# if there is an explicit mainline, alter the graph to match. This is
336
# easier than checking at every merge whether we are on the mainline and
337
# if so which path to take.
338
if mainline_revisions is None:
339
self._mainline_revisions = []
340
self._stop_revision = None
342
self._mainline_revisions = list(mainline_revisions)
343
self._stop_revision = self._mainline_revisions[0]
344
# skip the first revision, its what we reach and its parents are
345
# therefore irrelevant
346
for index, revision in enumerate(self._mainline_revisions[1:]):
347
# NB: index 0 means self._mainline_revisions[1]
348
# if the mainline matches the graph, nothing to do.
349
parent = self._mainline_revisions[index]
351
# end of mainline_revisions history
353
if self._graph[revision][0] == parent:
355
# remove it from its prior spot
356
self._graph[revision].remove(parent)
357
# insert it into the start of the mainline
358
self._graph[revision].insert(0, parent)
359
# we need to do a check late in the process to detect end-of-merges
360
# which requires the parents to be accessible: its easier for now
361
# to just keep the original graph around.
362
self._original_graph = dict(self._graph.items())
363
# we need to know the revision numbers of revisions to determine
364
# the revision numbers of their descendants
365
# this is a graph from node to [revno_tuple, first_child]
366
# where first_child is True if no other children have seen this node
367
# and revno_tuple is the tuple that was assigned to the node.
368
# we dont know revnos to start with, so we start it seeded with
370
self._revnos = dict((revision, [None, True])
371
for revision in self._graph)
372
# Each mainline revision counts how many child branches have spawned from it.
373
self._revno_to_branch_count = {}
375
# this is a stack storing the depth first search into the graph.
376
self._node_name_stack = []
377
# at each level of recursion we need the merge depth this node is at:
378
self._node_merge_depth_stack = []
379
# at each level of 'recursion' we have to check each parent. This
380
# stack stores the parents we have not yet checked for the node at the
381
# matching depth in _node_name_stack
382
self._pending_parents_stack = []
383
# When we first look at a node we assign it a seqence number from its
385
self._first_child_stack = []
386
# this is a set of the nodes who have been completely analysed for fast
387
# membership checking
388
self._completed_node_names = set()
389
# this is the scheduling of nodes list.
390
# Nodes are scheduled
391
# from the bottom left of the tree: in the tree
398
# the scheduling order is: F, E, D, C, B, A
399
# that is - 'left subtree, right subtree, node'
400
# which would mean that when we schedule A we can emit the entire tree.
401
self._scheduled_nodes = []
402
# This records for each node when we have processed its left most
403
# unmerged subtree. After this subtree is scheduled, all other subtrees
404
# have their merge depth increased by one from this nodes merge depth.
405
# it contains tuples - name, merge_depth
406
self._left_subtree_pushed_stack = []
408
# seed the search with the tip of the branch
409
if branch_tip is not None:
410
parents = self._graph.pop(branch_tip)
411
self._push_node(branch_tip, 0, parents)
414
"""Sort the graph and return as a list.
416
After calling this the sorter is empty and you must create a new one.
418
return list(self.iter_topo_order())
420
def iter_topo_order(self):
421
"""Yield the nodes of the graph in a topological order.
423
After finishing iteration the sorter is empty and you cannot continue
426
# These are safe to offload to local variables, because they are used
427
# as a stack and modified in place, never assigned to.
428
node_name_stack = self._node_name_stack
429
node_merge_depth_stack = self._node_merge_depth_stack
430
pending_parents_stack = self._pending_parents_stack
431
left_subtree_pushed_stack = self._left_subtree_pushed_stack
432
completed_node_names = self._completed_node_names
433
scheduled_nodes = self._scheduled_nodes
435
graph_pop = self._graph.pop
437
def push_node(node_name, merge_depth, parents,
438
node_name_stack_append=node_name_stack.append,
439
node_merge_depth_stack_append=node_merge_depth_stack.append,
440
left_subtree_pushed_stack_append=left_subtree_pushed_stack.append,
441
pending_parents_stack_append=pending_parents_stack.append,
442
first_child_stack_append=self._first_child_stack.append,
445
"""Add node_name to the pending node stack.
447
Names in this stack will get emitted into the output as they are popped
450
This inlines a lot of self._variable.append functions as local
453
node_name_stack_append(node_name)
454
node_merge_depth_stack_append(merge_depth)
455
left_subtree_pushed_stack_append(False)
456
pending_parents_stack_append(list(parents))
457
# as we push it, check if it is the first child
459
# node has parents, assign from the left most parent.
460
parent_info = revnos[parents[0]]
461
first_child = parent_info[1]
462
parent_info[1] = False
464
# We don't use the same algorithm here, but we need to keep the
467
first_child_stack_append(first_child)
469
def pop_node(node_name_stack_pop=node_name_stack.pop,
470
node_merge_depth_stack_pop=node_merge_depth_stack.pop,
471
first_child_stack_pop=self._first_child_stack.pop,
472
left_subtree_pushed_stack_pop=left_subtree_pushed_stack.pop,
473
pending_parents_stack_pop=pending_parents_stack.pop,
474
original_graph=self._original_graph,
476
completed_node_names_add=self._completed_node_names.add,
477
scheduled_nodes_append=scheduled_nodes.append,
478
revno_to_branch_count=self._revno_to_branch_count,
480
"""Pop the top node off the stack
482
The node is appended to the sorted output.
484
# we are returning from the flattened call frame:
485
# pop off the local variables
486
node_name = node_name_stack_pop()
487
merge_depth = node_merge_depth_stack_pop()
488
first_child = first_child_stack_pop()
489
# remove this node from the pending lists:
490
left_subtree_pushed_stack_pop()
491
pending_parents_stack_pop()
493
parents = original_graph[node_name]
495
# node has parents, assign from the left most parent.
496
parent_revno = revnos[parents[0]][0]
498
# not the first child, make a new branch
499
base_revno = parent_revno[0]
500
branch_count = revno_to_branch_count.get(base_revno, 0)
502
revno_to_branch_count[base_revno] = branch_count
503
revno = (parent_revno[0], branch_count, 1)
504
# revno = (parent_revno[0], branch_count, parent_revno[-1]+1)
506
# as the first child, we just increase the final revision
508
revno = parent_revno[:-1] + (parent_revno[-1] + 1,)
510
# no parents, use the root sequence
511
root_count = revno_to_branch_count.get(0, 0)
513
revno = (0, root_count, 1)
517
revno_to_branch_count[0] = root_count
519
# store the revno for this node for future reference
520
revnos[node_name][0] = revno
521
completed_node_names_add(node_name)
522
scheduled_nodes_append((node_name, merge_depth, revno))
526
while node_name_stack:
527
# loop until this call completes.
528
parents_to_visit = pending_parents_stack[-1]
529
# if all parents are done, the revision is done
530
if not parents_to_visit:
531
# append the revision to the topo sorted scheduled list:
532
# all the nodes parents have been scheduled added, now
533
# we can add it to the output.
536
while pending_parents_stack[-1]:
537
if not left_subtree_pushed_stack[-1]:
538
# recurse depth first into the primary parent
539
next_node_name = pending_parents_stack[-1].pop(0)
541
# place any merges in right-to-left order for scheduling
542
# which gives us left-to-right order after we reverse
543
# the scheduled queue. XXX: This has the effect of
544
# allocating common-new revisions to the right-most
545
# subtree rather than the left most, which will
546
# display nicely (you get smaller trees at the top
547
# of the combined merge).
548
next_node_name = pending_parents_stack[-1].pop()
549
if next_node_name in completed_node_names:
550
# this parent was completed by a child on the
551
# call stack. skip it.
553
# otherwise transfer it from the source graph into the
554
# top of the current depth first search stack.
556
parents = graph_pop(next_node_name)
558
# if the next node is not in the source graph it has
559
# already been popped from it and placed into the
560
# current search stack (but not completed or we would
561
# have hit the continue 4 lines up.
562
# this indicates a cycle.
563
raise errors.GraphCycleError(node_name_stack)
565
if left_subtree_pushed_stack[-1]:
566
# a new child branch from name_stack[-1]
570
left_subtree_pushed_stack[-1] = True
572
node_merge_depth_stack[-1] + next_merge_depth)
577
# and do not continue processing parents until this 'call'
581
# We have scheduled the graph. Now deliver the ordered output:
583
stop_revision = self._stop_revision
584
generate_revno = self._generate_revno
585
original_graph = self._original_graph
587
while scheduled_nodes:
588
node_name, merge_depth, revno = scheduled_nodes.pop()
589
if node_name == stop_revision:
591
if not len(scheduled_nodes):
592
# last revision is the end of a merge
594
elif scheduled_nodes[-1][1] < merge_depth:
595
# the next node is to our left
597
elif (scheduled_nodes[-1][1] == merge_depth and
598
(scheduled_nodes[-1][0] not in
599
original_graph[node_name])):
600
# the next node was part of a multiple-merge.
605
yield (sequence_number, node_name, merge_depth, revno, end_of_merge)
607
yield (sequence_number, node_name, merge_depth, end_of_merge)
610
def _push_node(self, node_name, merge_depth, parents):
611
"""Add node_name to the pending node stack.
613
Names in this stack will get emitted into the output as they are popped
616
self._node_name_stack.append(node_name)
617
self._node_merge_depth_stack.append(merge_depth)
618
self._left_subtree_pushed_stack.append(False)
619
self._pending_parents_stack.append(list(parents))
620
# as we push it, figure out if this is the first child
621
parents = self._original_graph[node_name]
623
# node has parents, assign from the left most parent.
624
parent_info = self._revnos[parents[0]]
625
first_child = parent_info[1]
626
parent_info[1] = False
628
# We don't use the same algorithm here, but we need to keep the
631
self._first_child_stack.append(first_child)
634
"""Pop the top node off the stack
636
The node is appended to the sorted output.
638
# we are returning from the flattened call frame:
639
# pop off the local variables
640
node_name = self._node_name_stack.pop()
641
merge_depth = self._node_merge_depth_stack.pop()
642
first_child = self._first_child_stack.pop()
643
# remove this node from the pending lists:
644
self._left_subtree_pushed_stack.pop()
645
self._pending_parents_stack.pop()
647
parents = self._original_graph[node_name]
649
# node has parents, assign from the left most parent.
650
parent_revno = self._revnos[parents[0]][0]
652
# not the first child, make a new branch
653
base_revno = parent_revno[0]
654
branch_count = self._revno_to_branch_count.get(base_revno, 0)
656
self._revno_to_branch_count[base_revno] = branch_count
657
revno = (parent_revno[0], branch_count, 1)
658
# revno = (parent_revno[0], branch_count, parent_revno[-1]+1)
660
# as the first child, we just increase the final revision
662
revno = parent_revno[:-1] + (parent_revno[-1] + 1,)
664
# no parents, use the root sequence
665
root_count = self._revno_to_branch_count.get(0, 0)
667
revno = (0, root_count, 1)
671
self._revno_to_branch_count[0] = root_count
673
# store the revno for this node for future reference
674
self._revnos[node_name][0] = revno
675
self._completed_node_names.add(node_name)
676
self._scheduled_nodes.append((node_name, merge_depth, self._revnos[node_name][0]))