~abentley/bzrtools/bzrtools.dev

« back to all changes in this revision

Viewing changes to graph.py

  • Committer: Aaron Bentley
  • Date: 2005-09-22 18:12:30 UTC
  • Revision ID: abentley@panoramicfeedback.com-20050922181230-4ef95c7a832bd760
Use Grapher for both kinds of graphs

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
18
1
from dotgraph import Node, dot_output, invoke_dot, invoke_dot_aa, NoDot, NoRsvg
19
 
from dotgraph import RSVG_OUTPUT_TYPES, DOT_OUTPUT_TYPES, Edge, invoke_dot_html
 
2
from dotgraph import mail_map, RSVG_OUTPUT_TYPES, DOT_OUTPUT_TYPES, Edge
20
3
from bzrlib.branch import Branch
21
4
from bzrlib.errors import BzrCommandError, NoCommonRoot, NoSuchRevision
 
5
from bzrlib.fetch import greedy_fetch
22
6
from bzrlib.graph import node_distances, select_farthest
23
7
from bzrlib.revision import combined_graph, revision_graph
24
8
from bzrlib.revision import MultipleRevisionSources
25
9
import bzrlib.errors
26
10
import re
27
11
import os.path
28
 
import time
29
12
 
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
 
            }
 
13
mail_map.update({'aaron.bentley@utoronto.ca'     : 'Aaron Bentley',
 
14
                 'abentley@panoramicfeedback.com': 'Aaron Bentley',
 
15
                 'abentley@lappy'                : 'Aaron Bentley',
 
16
                 'john@arbash-meinel.com'        : 'John Arbash Meinel',
 
17
                 'mbp@sourcefrog.net'            : 'Martin Pool',
 
18
                 'robertc@robertcollins.net'     : 'Robert Collins',
 
19
                })
37
20
 
38
21
committer_alias = {'abentley': 'Aaron Bentley'}
 
22
def short_committer(committer):
 
23
    new_committer = re.sub('<.*>', '', committer).strip(' ')
 
24
    if len(new_committer) < 2:
 
25
        return committer
 
26
    return new_committer
 
27
 
39
28
def can_skip(rev_id, descendants, ancestors):
40
29
    if rev_id not in descendants:
41
30
        return False
56
45
    for me, my_parents in ancestors.iteritems():
57
46
        if me in skip:
58
47
            continue
59
 
        new_ancestors[me] = {}
 
48
        new_ancestors[me] = {} 
60
49
        for parent in my_parents:
61
 
            new_parent = parent
 
50
            new_parent = parent 
62
51
            distance = 0
63
52
            while can_skip(new_parent, descendants, ancestors):
64
53
                if new_parent in exceptions:
69
58
                new_parent = list(ancestors[new_parent])[0]
70
59
                distance += 1
71
60
            new_ancestors[me][new_parent] = distance
72
 
    return new_ancestors
 
61
    return new_ancestors    
73
62
 
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, None
 
63
def get_committer(rev_id, source):
81
64
    try:
82
 
        rev = source.get_revision(rev_id)
 
65
        committer = short_committer(source.get_revision(rev_id).committer)
83
66
    except NoSuchRevision:
84
67
        try:
85
68
            committer = '-'.join(rev_id.split('-')[:-2]).strip(' ')
86
69
            if committer == '':
87
 
                return None, None, None, None
 
70
                return None
88
71
        except ValueError:
89
 
            return None, 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)
96
 
        nick = rev.properties.get('branch-nick')
 
72
            return None
97
73
    if '@' in committer:
98
74
        try:
99
75
            committer = mail_map[committer]
103
79
        committer = committer_alias[committer]
104
80
    except KeyError:
105
81
        pass
106
 
    return committer, message, nick, date
 
82
    return committer
107
83
 
108
84
class Grapher(object):
109
85
    def __init__(self, branch, other_branch=None):
110
86
        object.__init__(self)
111
87
        self.branch = branch
112
88
        self.other_branch = other_branch
113
 
        revision_a = self.branch.last_revision()
 
89
        revision_a = self.branch.last_patch()
114
90
        if other_branch is not None:
115
 
            branch.fetch(other_branch)
116
 
            revision_b = self.other_branch.last_revision()
 
91
            greedy_fetch(branch, other_branch)
 
92
            revision_b = self.other_branch.last_patch()
117
93
            try:
118
94
                self.root, self.ancestors, self.descendants, self.common = \
119
 
                    combined_graph(revision_a, revision_b,
120
 
                                   self.branch.repository)
 
95
                    combined_graph(revision_a, revision_b, self.branch)
121
96
            except bzrlib.errors.NoCommonRoot:
122
97
                raise bzrlib.errors.NoCommonAncestor(revision_a, revision_b)
123
98
        else:
124
99
            self.root, self.ancestors, self.descendants = \
125
 
                revision_graph(revision_a, branch.repository)
 
100
                revision_graph(revision_a, branch)
126
101
            self.common = []
127
102
 
128
103
        self.n_history = branch.revision_history()
129
 
        self.distances = node_distances(self.descendants, self.ancestors,
 
104
        self.distances = node_distances(self.descendants, self.ancestors, 
130
105
                                        self.root)
131
106
        if other_branch is not None:
132
107
            self.base = select_farthest(self.distances, self.common)
133
 
            self.m_history = other_branch.revision_history()
134
 
            new_graph = getattr(branch.repository, 'get_graph', lambda: None)()
135
 
            if new_graph is None:
136
 
                self.new_base = None
137
 
                self.lcas = set()
138
 
            else:
139
 
                self.new_base = new_graph.find_unique_lca(revision_a,
140
 
                                                          revision_b)
141
 
                self.lcas = new_graph.find_lca(revision_a, revision_b)
 
108
            self.m_history = other_branch.revision_history() 
142
109
        else:
143
110
            self.base = None
144
 
            self.new_base = None
145
 
            self.lcas = set()
146
111
            self.m_history = []
147
112
 
148
113
    def dot_node(self, node, num):
173
138
            if node in self.common:
174
139
                color = "#6699ff"
175
140
            else:
176
 
                color = "white"
 
141
                color = None
177
142
        elif n_rev is not None:
178
143
            cluster = "my_history"
179
144
            color = "#ffff00"
181
146
            assert m_rev is not None
182
147
            cluster = "other_history"
183
148
            color = "#ff0000"
184
 
        if node in self.lcas:
185
 
            color = "#9933cc"
186
149
        if node == self.base:
187
 
            color = "#669933"
188
 
            if node == self.new_base:
189
 
                color = "#33ff33"
190
 
        if node == self.new_base:
191
 
            color = '#33cc99'
 
150
            color = "#33ff99"
192
151
 
193
152
        label = [name]
194
 
        committer, message, nick, date = get_rev_info(node,
195
 
                                                      self.branch.repository)
 
153
        committer = get_committer(node, self.branch)
196
154
        if committer is not None:
197
155
            label.append(committer)
198
156
 
199
 
        if nick is not None:
200
 
            label.append(nick)
201
 
 
202
 
        if date is not None:
203
 
            label.append(date)
204
 
 
205
157
        if node in self.distances:
206
158
            rank = self.distances[node]
207
159
            label.append('d%d' % self.distances[node])
208
160
        else:
209
161
            rank = None
210
162
 
211
 
        d_node = Node("n%d" % num, color=color, label="\\n".join(label),
212
 
                    rev_id=node, cluster=cluster, message=message,
213
 
                    date=date)
 
163
        d_node = Node("n%d" % num, color=color, label="\\n".join(label), 
 
164
                    rev_id=node, cluster=cluster)
214
165
        d_node.rank = rank
215
166
 
216
167
        if node not in self.ancestors:
217
168
            d_node.node_style.append('dotted')
218
169
 
219
170
        return d_node
220
 
 
221
 
    def get_relations(self, collapse=False, max_distance=None):
 
171
        
 
172
    def get_relations(self, collapse=False):
222
173
        dot_nodes = {}
223
174
        node_relations = []
224
175
        num = 0
225
176
        if collapse:
226
 
            exceptions = self.lcas.union([self.base, self.new_base])
227
 
            visible_ancestors = compact_ancestors(self.descendants,
228
 
                                                  self.ancestors,
229
 
                                                  exceptions)
 
177
            visible_ancestors = compact_ancestors(self.descendants, 
 
178
                                                  self.ancestors, (self.base,))
230
179
        else:
231
 
            visible_ancestors = {}
232
 
            for revision, parents in self.ancestors.iteritems():
233
 
                visible_ancestors[revision] = dict((p, 0) for p in parents)
234
 
        if max_distance is not None:
235
 
            min_distance = max(self.distances.values()) - max_distance
236
 
            visible_ancestors = dict((n, p) for n, p in
237
 
                                     visible_ancestors.iteritems() if
238
 
                                     self.distances[n] >= min_distance)
 
180
            visible_ancestors = self.ancestors
239
181
        for node, parents in visible_ancestors.iteritems():
240
182
            if node not in dot_nodes:
241
183
                dot_nodes[node] = self.dot_node(node, num)
242
184
                num += 1
243
 
            for parent, skipped in parents.iteritems():
 
185
            if visible_ancestors is self.ancestors:
 
186
                parent_iter = ((f, 0) for f in parents)
 
187
            else:
 
188
                parent_iter = (f for f in parents.iteritems())
 
189
            for parent, skipped in parent_iter:
244
190
                if parent not in dot_nodes:
245
191
                    dot_nodes[parent] = self.dot_node(parent, num)
246
192
                    num += 1
252
198
 
253
199
 
254
200
def write_ancestry_file(branch, filename, collapse=True, antialias=True,
255
 
                        merge_branch=None, ranking="forced", max_distance=None):
256
 
    b = Branch.open_containing(branch)[0]
 
201
                        merge_branch=None, ranking="forced"):
 
202
    b = Branch.open_containing(branch)
257
203
    if merge_branch is not None:
258
 
        m = Branch.open_containing(merge_branch)[0]
 
204
        m = Branch.open_containing(merge_branch)
259
205
    else:
260
206
        m = None
261
 
    b.lock_write()
262
 
    try:
263
 
        if m is not None:
264
 
            m.lock_read()
265
 
        try:
266
 
            grapher = Grapher(b, m)
267
 
            relations = grapher.get_relations(collapse, max_distance)
268
 
        finally:
269
 
            if m is not None:
270
 
                m.unlock()
271
 
    finally:
272
 
        b.unlock()
 
207
    grapher = Grapher(b, m)
 
208
    relations = grapher.get_relations(collapse)
273
209
 
274
210
    ext = filename.split('.')[-1]
275
211
    output = dot_output(relations, ranking)
276
 
    done = False
277
 
    if ext not in RSVG_OUTPUT_TYPES:
278
 
        antialias = False
279
 
    if antialias:
280
 
        output = list(output)
 
212
    if antialias and ext in RSVG_OUTPUT_TYPES:
281
213
        try:
282
214
            invoke_dot_aa(output, filename, ext)
283
 
            done = True
284
215
        except NoDot, e:
285
216
            raise BzrCommandError("Can't find 'dot'.  Please ensure Graphviz"\
286
217
                " is installed correctly.")
287
218
        except NoRsvg, e:
288
 
            print "Not antialiasing because rsvg (from librsvg-bin) is not"\
289
 
                " installed."
290
 
            antialias = False
291
 
    if ext in DOT_OUTPUT_TYPES and not antialias and not done:
 
219
            raise BzrCommandError("Can't find 'rsvg'.  Please ensure "\
 
220
                "librsvg-bin is installed correctly, or use --noantialias.")
 
221
    elif ext in DOT_OUTPUT_TYPES:
292
222
        try:
293
223
            invoke_dot(output, filename, ext)
294
 
            done = True
295
224
        except NoDot, e:
296
225
            raise BzrCommandError("Can't find 'dot'.  Please ensure Graphviz"\
297
226
                " is installed correctly, or use --noantialias")
298
 
    elif ext == 'dot' and not done:
 
227
    elif ext=='dot':
299
228
        my_file = file(filename, 'wb')
300
229
        for fragment in output:
301
 
            my_file.write(fragment.encode('utf-8'))
302
 
    elif ext == 'html':
303
 
        try:
304
 
            invoke_dot_html(output, filename)
305
 
        except NoDot, e:
306
 
            raise BzrCommandError("Can't find 'dot'.  Please ensure Graphviz"\
307
 
                " is installed correctly, or use --noantialias")
308
 
    elif not done:
 
230
            my_file.write(fragment)
 
231
    else:
309
232
        print "Unknown file extension: %s" % ext
310
233