~abentley/bzrtools/bzrtools.dev

« back to all changes in this revision

Viewing changes to graph.py

  • Committer: Aaron Bentley
  • Date: 2006-06-18 01:24:25 UTC
  • mfrom: (0.3.3 shelf-dev)
  • Revision ID: aaron.bentley@utoronto.ca-20060618012425-61c3d9d62a2cc971
Merged the latest Shelf changes, patches.py no longer needed.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2005 Aaron Bentley
 
2
# <aaron.bentley@utoronto.ca>
 
3
#
 
4
#    This program is free software; you can redistribute it and/or modify
 
5
#    it under the terms of the GNU General Public License as published by
 
6
#    the Free Software Foundation; either version 2 of the License, or
 
7
#    (at your option) any later version.
 
8
#
 
9
#    This program is distributed in the hope that it will be useful,
 
10
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
 
11
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
12
#    GNU General Public License for more details.
 
13
#
 
14
#    You should have received a copy of the GNU General Public License
 
15
#    along with this program; if not, write to the Free Software
 
16
#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
17
from bzrtools import short_committer
1
18
from dotgraph import Node, dot_output, invoke_dot, invoke_dot_aa, NoDot, NoRsvg
2
 
from dotgraph import mail_map, RSVG_OUTPUT_TYPES, DOT_OUTPUT_TYPES
 
19
from dotgraph import RSVG_OUTPUT_TYPES, DOT_OUTPUT_TYPES, Edge, invoke_dot_html
3
20
from bzrlib.branch import Branch
4
21
from bzrlib.errors import BzrCommandError, NoCommonRoot, NoSuchRevision
5
 
from bzrlib.fetch import greedy_fetch
6
22
from bzrlib.graph import node_distances, select_farthest
7
 
from bzrlib.revision import combined_graph, MultipleRevisionSources
 
23
from bzrlib.revision import combined_graph, revision_graph
 
24
from bzrlib.revision import MultipleRevisionSources
8
25
import bzrlib.errors
9
26
import re
10
27
import os.path
 
28
import time
11
29
 
12
 
mail_map.update({'aaron.bentley@utoronto.ca'     : 'Aaron Bentley',
13
 
                 'abentley@panoramicfeedback.com': 'Aaron Bentley',
14
 
                 'abentley@lappy'                : 'Aaron Bentley',
15
 
                 'john@arbash-meinel.com'        : 'John Arbash Meinel',
16
 
                 'mbp@sourcefrog.net'            : 'Martin Pool',
17
 
                 'robertc@robertcollins.net'     : 'Robert Collins',
18
 
                })
 
30
mail_map = {'aaron.bentley@utoronto.ca'     : 'Aaron Bentley',
 
31
            'abentley@panoramicfeedback.com': 'Aaron Bentley',
 
32
            'abentley@lappy'                : 'Aaron Bentley',
 
33
            'john@arbash-meinel.com'        : 'John Arbash Meinel',
 
34
            'mbp@sourcefrog.net'            : 'Martin Pool',
 
35
            'robertc@robertcollins.net'     : 'Robert Collins',
 
36
            }
19
37
 
20
38
committer_alias = {'abentley': 'Aaron Bentley'}
21
 
def add_relations(rev_id):
22
 
    if rev_id in ancestors:
23
 
        return
24
 
    print rev_id
25
 
    if rev_id not in nodes:
26
 
        nodes[rev_id] = Node("n%d" % counter, label = rev_id)
27
 
        counter += 1
28
 
    revision = branch.get_revision(rev_id)
29
 
    ancestors [rev_id] = []
30
 
    for p in (p.revision_id for p in revision.parents):
31
 
        add_relations(p)
32
 
        if p not in descendants:
33
 
            descendants[p] = []
34
 
        descendants[p].append(rev_id)
35
 
        ancestors [rev_id].append(rev_id)
36
 
 
37
 
def short_committer(committer):
38
 
    new_committer = re.sub('<.*>', '', committer).strip(' ')
39
 
    if len(new_committer) < 2:
40
 
        return committer
41
 
    return new_committer
42
 
 
43
39
def can_skip(rev_id, descendants, ancestors):
44
40
    if rev_id not in descendants:
45
41
        return False
 
42
    elif rev_id not in ancestors:
 
43
        return False
46
44
    elif len(ancestors[rev_id]) != 1:
47
45
        return False
48
 
    elif len(descendants[ancestors[rev_id][0]]) != 1:
 
46
    elif len(descendants[list(ancestors[rev_id])[0]]) != 1:
49
47
        return False
50
48
    elif len(descendants[rev_id]) != 1:
51
49
        return False
52
50
    else:
53
51
        return True
54
52
 
55
 
def compact_descendants(descendants, ancestors):
56
 
    new_descendants={}
 
53
def compact_ancestors(descendants, ancestors, exceptions=()):
 
54
    new_ancestors={}
57
55
    skip = set()
58
 
    for me, my_descendants in descendants.iteritems():
 
56
    for me, my_parents in ancestors.iteritems():
59
57
        if me in skip:
60
58
            continue
61
 
        new_descendants[me] = []
62
 
        for descendant in my_descendants:
63
 
            new_descendant = descendant
64
 
            while can_skip(new_descendant, descendants, ancestors):
65
 
                skip.add(new_descendant)
66
 
                if new_descendant in new_descendants:
67
 
                    del new_descendants[new_descendant]
68
 
                new_descendant = descendants[new_descendant][0]
69
 
            new_descendants[me].append(new_descendant)
70
 
    return new_descendants    
71
 
 
72
 
 
73
 
def graph_ancestry(branch, collapse=True):
74
 
    nodes = {}
75
 
    q = ((i+1, n) for (i, n) in enumerate(branch.revision_history()))
76
 
    r = 1
77
 
    try:
78
 
        branch_name = os.path.basename(branch.base)
79
 
    except AttributeError:
80
 
        branch_name = "main"
81
 
    for (revno, rev_id) in q:
82
 
        nodes[rev_id] = Node("R%d" % revno, color="#ffff00", rev_id=rev_id, 
83
 
                             cluster=branch_name)
84
 
 
85
 
    ancestors = {} 
86
 
    descendants = {}
87
 
    counter = 0
88
 
    lines = [branch.last_patch()]
89
 
    while len(lines) > 0:
90
 
        new_lines = set()
91
 
        for rev_id in lines:
92
 
            if rev_id not in nodes:
93
 
                nodes[rev_id] = Node("n%d" % counter, label=rev_id, 
94
 
                                     rev_id=rev_id)
95
 
                counter+=1
96
 
                
97
 
            try:
98
 
                revision = branch.get_revision(rev_id)
99
 
            except bzrlib.errors.NoSuchRevision:
100
 
                nodes[rev_id].node_style.append('dotted')
101
 
                continue
102
 
            if nodes[rev_id].committer is None:
103
 
                nodes[rev_id].committer = short_committer(revision.committer)
104
 
            parent_ids = [r.revision_id for r in revision.parents]
105
 
            ancestors [rev_id] = parent_ids
106
 
            for parent in parent_ids:
107
 
                if parent not in ancestors:
108
 
                    new_lines.add(parent)
109
 
                    descendants[parent] = []
110
 
                descendants[parent].append(rev_id)
111
 
        lines = new_lines
112
 
    node_relations = []
113
 
 
114
 
    for node in nodes.itervalues():
115
 
        node.label = node.get_label()
116
 
    if collapse:
117
 
        visible_descendants = compact_descendants(descendants, ancestors)
118
 
    else:
119
 
        visible_descendants = descendants
120
 
                
121
 
    for key, values in visible_descendants.iteritems():
122
 
        for value in values:
123
 
            node_relations.append((nodes[key], nodes[value]))
124
 
    return node_relations
125
 
 
126
 
def get_committer(rev_id, source):
127
 
    try:
128
 
        committer = short_committer(source.get_revision(rev_id).committer)
 
59
        new_ancestors[me] = {} 
 
60
        for parent in my_parents:
 
61
            new_parent = parent 
 
62
            distance = 0
 
63
            while can_skip(new_parent, descendants, ancestors):
 
64
                if new_parent in exceptions:
 
65
                    break
 
66
                skip.add(new_parent)
 
67
                if new_parent in new_ancestors:
 
68
                    del new_ancestors[new_parent]
 
69
                new_parent = list(ancestors[new_parent])[0]
 
70
                distance += 1
 
71
            new_ancestors[me][new_parent] = distance
 
72
    return new_ancestors    
 
73
 
 
74
def get_rev_info(rev_id, source):
 
75
    """Return the committer, message, and date of a revision."""
 
76
    committer = None
 
77
    message = None
 
78
    date = None
 
79
    if rev_id == 'null:':
 
80
        return None, 'Null Revision', None
 
81
    try:
 
82
        rev = source.get_revision(rev_id)
129
83
    except NoSuchRevision:
130
84
        try:
131
 
            committer = '-'.join(rev_id.split('-')[:-2])\
132
 
                .strip(' ')
 
85
            committer = '-'.join(rev_id.split('-')[:-2]).strip(' ')
 
86
            if committer == '':
 
87
                return None, None, None
133
88
        except ValueError:
134
 
            committer = '' 
 
89
            return None, None, None
 
90
    else:
 
91
        committer = short_committer(rev.committer)
 
92
        if rev.message is not None:
 
93
            message = rev.message.split('\n')[0]
 
94
        gmtime = time.gmtime(rev.timestamp + (rev.timezone or 0))
 
95
        date = time.strftime('%Y/%m/%d', gmtime)
135
96
    if '@' in committer:
136
97
        try:
137
98
            committer = mail_map[committer]
141
102
        committer = committer_alias[committer]
142
103
    except KeyError:
143
104
        pass
144
 
    return committer
145
 
 
146
 
 
147
 
def graph_merge_pick(branch, other_branch):
148
 
    greedy_fetch(branch, other_branch)
149
 
    revision_a = branch.last_patch()
150
 
    revision_b = other_branch.last_patch()
151
 
    try:
152
 
        root, ancestors, descendants, common = \
153
 
            combined_graph(revision_a, revision_b, branch)
154
 
    except bzrlib.errors.NoCommonRoot:
155
 
        raise bzrlib.errors.NoCommonAncestor(revision_a, revision_b)
156
 
    distances = node_distances(descendants, ancestors, root)
157
 
    base = select_farthest(distances, common)
158
 
    n_history = branch.revision_history()
159
 
    m_history = []
160
 
    dot_nodes = {}
161
 
    def dot_node(node, num):
 
105
    return committer, message, date
 
106
 
 
107
class Grapher(object):
 
108
    def __init__(self, branch, other_branch=None):
 
109
        object.__init__(self)
 
110
        self.branch = branch
 
111
        self.other_branch = other_branch
 
112
        revision_a = self.branch.last_revision()
 
113
        if other_branch is not None:
 
114
            branch.fetch(other_branch)
 
115
            revision_b = self.other_branch.last_revision()
 
116
            try:
 
117
                self.root, self.ancestors, self.descendants, self.common = \
 
118
                    combined_graph(revision_a, revision_b,
 
119
                                   self.branch.repository)
 
120
            except bzrlib.errors.NoCommonRoot:
 
121
                raise bzrlib.errors.NoCommonAncestor(revision_a, revision_b)
 
122
        else:
 
123
            self.root, self.ancestors, self.descendants = \
 
124
                revision_graph(revision_a, branch.repository)
 
125
            self.common = []
 
126
 
 
127
        self.n_history = branch.revision_history()
 
128
        self.distances = node_distances(self.descendants, self.ancestors, 
 
129
                                        self.root)
 
130
        if other_branch is not None:
 
131
            self.base = select_farthest(self.distances, self.common)
 
132
            self.m_history = other_branch.revision_history() 
 
133
        else:
 
134
            self.base = None
 
135
            self.m_history = []
 
136
 
 
137
    def dot_node(self, node, num):
162
138
        try:
163
 
            n_rev = n_history.index(node) + 1
 
139
            n_rev = self.n_history.index(node) + 1
164
140
        except ValueError:
165
141
            n_rev = None
166
142
        try:
167
 
            m_rev = m_history.index(node) + 1
 
143
            m_rev = self.m_history.index(node) + 1
168
144
        except ValueError:
169
145
            m_rev = None
170
146
        if (n_rev, m_rev) == (None, None):
171
 
            name = node[-4:]
 
147
            name = node[-5:]
172
148
            cluster = None
173
149
        elif n_rev == m_rev:
174
150
            name = "rR%d" % n_rev
183
159
            color = "#ff9900"
184
160
        elif (None, None) == (n_rev, m_rev):
185
161
            cluster = None
186
 
            if node in common:
 
162
            if node in self.common:
187
163
                color = "#6699ff"
188
164
            else:
189
 
                color = None
 
165
                color = "white"
190
166
        elif n_rev is not None:
191
167
            cluster = "my_history"
192
168
            color = "#ffff00"
194
170
            assert m_rev is not None
195
171
            cluster = "other_history"
196
172
            color = "#ff0000"
197
 
        if node == base:
 
173
        if node == self.base:
198
174
            color = "#33ff99"
199
175
 
200
176
        label = [name]
201
 
        committer = get_committer(node, branch)
 
177
        committer, message, date = get_rev_info(node, self.branch.repository)
202
178
        if committer is not None:
203
179
            label.append(committer)
204
180
 
205
 
        if node in distances:
206
 
            label.append('d%d' % distances[node])
207
 
        return Node("n%d" % num, color=color, label="\\n".join(label), 
208
 
                    rev_id=node, cluster=cluster)
209
 
            
210
 
            
211
 
    for num,node in enumerate(descendants):
212
 
        dot_nodes[node] = dot_node(node, num)
213
 
 
214
 
    node_relations = []
215
 
    for node, parents in ancestors.iteritems():
216
 
        if node not in dot_nodes:
217
 
            dot_nodes[node] = dot_node(node, 100000)
218
 
        for parent in parents:
219
 
            node_relations.append((dot_nodes[parent], dot_nodes[node]))
220
 
    return node_relations
 
181
        if date is not None:
 
182
            label.append(date)
 
183
 
 
184
        if node in self.distances:
 
185
            rank = self.distances[node]
 
186
            label.append('d%d' % self.distances[node])
 
187
        else:
 
188
            rank = None
 
189
 
 
190
        d_node = Node("n%d" % num, color=color, label="\\n".join(label), 
 
191
                    rev_id=node, cluster=cluster, message=message,
 
192
                    date=date)
 
193
        d_node.rank = rank
 
194
 
 
195
        if node not in self.ancestors:
 
196
            d_node.node_style.append('dotted')
 
197
 
 
198
        return d_node
 
199
        
 
200
    def get_relations(self, collapse=False):
 
201
        dot_nodes = {}
 
202
        node_relations = []
 
203
        num = 0
 
204
        if collapse:
 
205
            visible_ancestors = compact_ancestors(self.descendants, 
 
206
                                                  self.ancestors, (self.base,))
 
207
        else:
 
208
            visible_ancestors = self.ancestors
 
209
        for node, parents in visible_ancestors.iteritems():
 
210
            if node not in dot_nodes:
 
211
                dot_nodes[node] = self.dot_node(node, num)
 
212
                num += 1
 
213
            if visible_ancestors is self.ancestors:
 
214
                parent_iter = ((f, 0) for f in parents)
 
215
            else:
 
216
                parent_iter = (f for f in parents.iteritems())
 
217
            for parent, skipped in parent_iter:
 
218
                if parent not in dot_nodes:
 
219
                    dot_nodes[parent] = self.dot_node(parent, num)
 
220
                    num += 1
 
221
                edge = Edge(dot_nodes[parent], dot_nodes[node])
 
222
                if skipped != 0:
 
223
                    edge.label = "%d" % skipped
 
224
                node_relations.append(edge)
 
225
        return node_relations
221
226
 
222
227
 
223
228
def write_ancestry_file(branch, filename, collapse=True, antialias=True,
224
 
                        merge_branch=None):
225
 
    b = Branch.open_containing(branch)
226
 
    if merge_branch is None:
227
 
        relations = graph_ancestry(b, collapse)
 
229
                        merge_branch=None, ranking="forced"):
 
230
    b = Branch.open_containing(branch)[0]
 
231
    if merge_branch is not None:
 
232
        m = Branch.open_containing(merge_branch)[0]
228
233
    else:
229
 
        m = Branch.open_containing(merge_branch)
230
 
        relations = graph_merge_pick(b, m)
 
234
        m = None
 
235
    b.lock_write()
 
236
    try:
 
237
        if m is not None:
 
238
            m.lock_read()
 
239
        try:
 
240
            grapher = Grapher(b, m)
 
241
            relations = grapher.get_relations(collapse)
 
242
        finally:
 
243
            if m is not None:
 
244
                m.unlock()
 
245
    finally:
 
246
        b.unlock()
231
247
 
232
248
    ext = filename.split('.')[-1]
233
 
    if antialias and ext in RSVG_OUTPUT_TYPES:
 
249
    output = dot_output(relations, ranking)
 
250
    done = False
 
251
    if ext not in RSVG_OUTPUT_TYPES:
 
252
        antialias = False
 
253
    if antialias: 
 
254
        output = list(output)
234
255
        try:
235
 
            invoke_dot_aa(dot_output(relations), filename, ext)
 
256
            invoke_dot_aa(output, filename, ext)
 
257
            done = True
236
258
        except NoDot, e:
237
259
            raise BzrCommandError("Can't find 'dot'.  Please ensure Graphviz"\
238
260
                " is installed correctly.")
239
261
        except NoRsvg, e:
240
 
            raise BzrCommandError("Can't find 'rsvg'.  Please ensure "\
241
 
                "librsvg-bin is installed correctly, or use --noantialias.")
242
 
    elif ext in DOT_OUTPUT_TYPES:
243
 
        try:
244
 
            invoke_dot(dot_output(relations), filename, ext)
245
 
        except NoDot, e:
246
 
            raise BzrCommandError("Can't find 'dot'.  Please ensure Graphviz"\
247
 
                " is installed correctly, or use --noantialias")
248
 
    elif ext=='dot':
249
 
        file(filename, 'wb').write("".join(list(dot_output(relations))))
250
 
    else:
 
262
            print "Not antialiasing because rsvg (from librsvg-bin) is not"\
 
263
                " installed."
 
264
            antialias = False
 
265
    if ext in DOT_OUTPUT_TYPES and not antialias and not done:
 
266
        try:
 
267
            invoke_dot(output, filename, ext)
 
268
            done = True
 
269
        except NoDot, e:
 
270
            raise BzrCommandError("Can't find 'dot'.  Please ensure Graphviz"\
 
271
                " is installed correctly, or use --noantialias")
 
272
    elif ext == 'dot' and not done:
 
273
        my_file = file(filename, 'wb')
 
274
        for fragment in output:
 
275
            my_file.write(fragment.encode('utf-8'))
 
276
    elif ext == 'html':
 
277
        try:
 
278
            invoke_dot_html(output, filename)
 
279
        except NoDot, e:
 
280
            raise BzrCommandError("Can't find 'dot'.  Please ensure Graphviz"\
 
281
                " is installed correctly, or use --noantialias")
 
282
    elif not done:
251
283
        print "Unknown file extension: %s" % ext
252
284