~abentley/bzrtools/bzrtools.dev

« back to all changes in this revision

Viewing changes to graph.py

  • Committer: Aaron Bentley
  • Date: 2008-04-11 00:03:51 UTC
  • Revision ID: aaron@aaronbentley.com-20080411000351-dmbvgmanygnphzgp
Add escaping to HTML output

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
1
# Copyright (C) 2005 Aaron Bentley
2
 
# <aaron.bentley@utoronto.ca>
 
2
# <aaron@aaronbentley.com>
3
3
#
4
4
#    This program is free software; you can redistribute it and/or modify
5
5
#    it under the terms of the GNU General Public License as published by
14
14
#    You should have received a copy of the GNU General Public License
15
15
#    along with this program; if not, write to the Free Software
16
16
#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
17
from bzrtools import short_committer
17
18
from dotgraph import Node, dot_output, invoke_dot, invoke_dot_aa, NoDot, NoRsvg
18
19
from dotgraph import RSVG_OUTPUT_TYPES, DOT_OUTPUT_TYPES, Edge, invoke_dot_html
19
20
from bzrlib.branch import Branch
20
21
from bzrlib.errors import BzrCommandError, NoCommonRoot, NoSuchRevision
21
 
from bzrlib.fetch import greedy_fetch
22
22
from bzrlib.graph import node_distances, select_farthest
23
23
from bzrlib.revision import combined_graph, revision_graph
24
24
from bzrlib.revision import MultipleRevisionSources
36
36
            }
37
37
 
38
38
committer_alias = {'abentley': 'Aaron Bentley'}
39
 
def short_committer(committer):
40
 
    new_committer = re.sub('<.*>', '', committer).strip(' ')
41
 
    if len(new_committer) < 2:
42
 
        return committer
43
 
    return new_committer
44
 
 
45
39
def can_skip(rev_id, descendants, ancestors):
46
40
    if rev_id not in descendants:
47
41
        return False
62
56
    for me, my_parents in ancestors.iteritems():
63
57
        if me in skip:
64
58
            continue
65
 
        new_ancestors[me] = {} 
 
59
        new_ancestors[me] = {}
66
60
        for parent in my_parents:
67
 
            new_parent = parent 
 
61
            new_parent = parent
68
62
            distance = 0
69
63
            while can_skip(new_parent, descendants, ancestors):
70
64
                if new_parent in exceptions:
75
69
                new_parent = list(ancestors[new_parent])[0]
76
70
                distance += 1
77
71
            new_ancestors[me][new_parent] = distance
78
 
    return new_ancestors    
 
72
    return new_ancestors
79
73
 
80
74
def get_rev_info(rev_id, source):
81
75
    """Return the committer, message, and date of a revision."""
83
77
    message = None
84
78
    date = None
85
79
    if rev_id == 'null:':
86
 
        return None, 'Null Revision', None
 
80
        return None, 'Null Revision', None, None
87
81
    try:
88
82
        rev = source.get_revision(rev_id)
89
83
    except NoSuchRevision:
90
84
        try:
91
85
            committer = '-'.join(rev_id.split('-')[:-2]).strip(' ')
92
86
            if committer == '':
93
 
                return None, None, None
 
87
                return None, None, None, None
94
88
        except ValueError:
95
 
            return None, None, None
 
89
            return None, None, None, None
96
90
    else:
97
91
        committer = short_committer(rev.committer)
98
92
        if rev.message is not None:
99
93
            message = rev.message.split('\n')[0]
100
94
        gmtime = time.gmtime(rev.timestamp + (rev.timezone or 0))
101
95
        date = time.strftime('%Y/%m/%d', gmtime)
 
96
        nick = rev.properties.get('branch-nick')
102
97
    if '@' in committer:
103
98
        try:
104
99
            committer = mail_map[committer]
108
103
        committer = committer_alias[committer]
109
104
    except KeyError:
110
105
        pass
111
 
    return committer, message, date
 
106
    return committer, message, nick, date
112
107
 
113
108
class Grapher(object):
114
109
    def __init__(self, branch, other_branch=None):
117
112
        self.other_branch = other_branch
118
113
        revision_a = self.branch.last_revision()
119
114
        if other_branch is not None:
120
 
            greedy_fetch(branch, other_branch)
 
115
            branch.fetch(other_branch)
121
116
            revision_b = self.other_branch.last_revision()
122
117
            try:
123
118
                self.root, self.ancestors, self.descendants, self.common = \
124
 
                    combined_graph(revision_a, revision_b, self.branch)
 
119
                    combined_graph(revision_a, revision_b,
 
120
                                   self.branch.repository)
125
121
            except bzrlib.errors.NoCommonRoot:
126
122
                raise bzrlib.errors.NoCommonAncestor(revision_a, revision_b)
127
123
        else:
128
124
            self.root, self.ancestors, self.descendants = \
129
 
                revision_graph(revision_a, branch)
 
125
                revision_graph(revision_a, branch.repository)
130
126
            self.common = []
131
127
 
132
128
        self.n_history = branch.revision_history()
133
 
        self.distances = node_distances(self.descendants, self.ancestors, 
 
129
        self.n_revnos = branch.get_revision_id_to_revno_map()
 
130
        self.distances = node_distances(self.descendants, self.ancestors,
134
131
                                        self.root)
135
132
        if other_branch is not None:
136
133
            self.base = select_farthest(self.distances, self.common)
137
 
            self.m_history = other_branch.revision_history() 
 
134
            self.m_history = other_branch.revision_history()
 
135
            self.m_revnos = other_branch.get_revision_id_to_revno_map()
 
136
            new_graph = getattr(branch.repository, 'get_graph', lambda: None)()
 
137
            if new_graph is None:
 
138
                self.new_base = None
 
139
                self.lcas = set()
 
140
            else:
 
141
                self.new_base = new_graph.find_unique_lca(revision_a,
 
142
                                                          revision_b)
 
143
                self.lcas = new_graph.find_lca(revision_a, revision_b)
138
144
        else:
139
145
            self.base = None
 
146
            self.new_base = None
 
147
            self.lcas = set()
140
148
            self.m_history = []
 
149
            self.m_revnos = {}
 
150
 
 
151
    @staticmethod
 
152
    def _get_revno_str(prefix, revno_map, revision_id):
 
153
        try:
 
154
            revno = revno_map[revision_id]
 
155
        except KeyError:
 
156
            return None
 
157
        return '%s%s' % (prefix, '.'.join(str(n) for n in revno))
141
158
 
142
159
    def dot_node(self, node, num):
143
160
        try:
149
166
        except ValueError:
150
167
            m_rev = None
151
168
        if (n_rev, m_rev) == (None, None):
152
 
            name = node[-5:]
 
169
            name = self._get_revno_str('r', self.n_revnos, node)
 
170
            if name is None:
 
171
                name = self._get_revno_str('R', self.m_revnos, node)
 
172
            if name is None:
 
173
                name = node[-5:]
153
174
            cluster = None
154
175
        elif n_rev == m_rev:
155
176
            name = "rR%d" % n_rev
175
196
            assert m_rev is not None
176
197
            cluster = "other_history"
177
198
            color = "#ff0000"
 
199
        if node in self.lcas:
 
200
            color = "#9933cc"
178
201
        if node == self.base:
179
 
            color = "#33ff99"
 
202
            color = "#669933"
 
203
            if node == self.new_base:
 
204
                color = "#33ff33"
 
205
        if node == self.new_base:
 
206
            color = '#33cc99'
180
207
 
181
208
        label = [name]
182
 
        committer, message, date = get_rev_info(node, self.branch)
 
209
        committer, message, nick, date = get_rev_info(node,
 
210
                                                      self.branch.repository)
183
211
        if committer is not None:
184
212
            label.append(committer)
185
213
 
 
214
        if nick is not None:
 
215
            label.append(nick)
 
216
 
186
217
        if date is not None:
187
218
            label.append(date)
188
219
 
192
223
        else:
193
224
            rank = None
194
225
 
195
 
        d_node = Node("n%d" % num, color=color, label="\\n".join(label), 
 
226
        d_node = Node("n%d" % num, color=color, label="\\n".join(label),
196
227
                    rev_id=node, cluster=cluster, message=message,
197
228
                    date=date)
198
229
        d_node.rank = rank
201
232
            d_node.node_style.append('dotted')
202
233
 
203
234
        return d_node
204
 
        
205
 
    def get_relations(self, collapse=False):
 
235
 
 
236
    def get_relations(self, collapse=False, max_distance=None):
206
237
        dot_nodes = {}
207
238
        node_relations = []
208
239
        num = 0
209
240
        if collapse:
210
 
            visible_ancestors = compact_ancestors(self.descendants, 
211
 
                                                  self.ancestors, (self.base,))
 
241
            exceptions = self.lcas.union([self.base, self.new_base])
 
242
            visible_ancestors = compact_ancestors(self.descendants,
 
243
                                                  self.ancestors,
 
244
                                                  exceptions)
212
245
        else:
213
 
            visible_ancestors = self.ancestors
 
246
            visible_ancestors = {}
 
247
            for revision, parents in self.ancestors.iteritems():
 
248
                visible_ancestors[revision] = dict((p, 0) for p in parents)
 
249
        if max_distance is not None:
 
250
            min_distance = max(self.distances.values()) - max_distance
 
251
            visible_ancestors = dict((n, p) for n, p in
 
252
                                     visible_ancestors.iteritems() if
 
253
                                     self.distances[n] >= min_distance)
214
254
        for node, parents in visible_ancestors.iteritems():
215
255
            if node not in dot_nodes:
216
256
                dot_nodes[node] = self.dot_node(node, num)
217
257
                num += 1
218
 
            if visible_ancestors is self.ancestors:
219
 
                parent_iter = ((f, 0) for f in parents)
220
 
            else:
221
 
                parent_iter = (f for f in parents.iteritems())
222
 
            for parent, skipped in parent_iter:
 
258
            for parent, skipped in parents.iteritems():
223
259
                if parent not in dot_nodes:
224
260
                    dot_nodes[parent] = self.dot_node(parent, num)
225
261
                    num += 1
231
267
 
232
268
 
233
269
def write_ancestry_file(branch, filename, collapse=True, antialias=True,
234
 
                        merge_branch=None, ranking="forced"):
 
270
                        merge_branch=None, ranking="forced", max_distance=None):
235
271
    b = Branch.open_containing(branch)[0]
236
272
    if merge_branch is not None:
237
273
        m = Branch.open_containing(merge_branch)[0]
238
274
    else:
239
275
        m = None
240
 
    b.lock_read()
 
276
    b.lock_write()
241
277
    try:
242
278
        if m is not None:
243
279
            m.lock_read()
244
280
        try:
245
281
            grapher = Grapher(b, m)
246
 
            relations = grapher.get_relations(collapse)
 
282
            relations = grapher.get_relations(collapse, max_distance)
247
283
        finally:
248
284
            if m is not None:
249
285
                m.unlock()
255
291
    done = False
256
292
    if ext not in RSVG_OUTPUT_TYPES:
257
293
        antialias = False
258
 
    if antialias: 
 
294
    if antialias:
259
295
        output = list(output)
260
296
        try:
261
297
            invoke_dot_aa(output, filename, ext)
273
309
            done = True
274
310
        except NoDot, e:
275
311
            raise BzrCommandError("Can't find 'dot'.  Please ensure Graphviz"\
276
 
                " is installed correctly, or use --noantialias")
 
312
                " is installed correctly.")
277
313
    elif ext == 'dot' and not done:
278
314
        my_file = file(filename, 'wb')
279
315
        for fragment in output:
280
 
            my_file.write(fragment)
 
316
            my_file.write(fragment.encode('utf-8'))
281
317
    elif ext == 'html':
282
318
        try:
283
319
            invoke_dot_html(output, filename)
284
320
        except NoDot, e:
285
321
            raise BzrCommandError("Can't find 'dot'.  Please ensure Graphviz"\
286
 
                " is installed correctly, or use --noantialias")
 
322
                " is installed correctly.")
287
323
    elif not done:
288
324
        print "Unknown file extension: %s" % ext
289
325