~abentley/bzrtools/bzrtools.dev

« back to all changes in this revision

Viewing changes to dotgraph.py

  • Committer: Robert Collins
  • Date: 2005-09-13 14:14:22 UTC
  • mto: (147.2.6) (364.1.3 bzrtools)
  • mto: This revision was merged to the branch mainline in revision 324.
  • Revision ID: robertc@robertcollins.net-20050913141422-e391cb880f6920df
make feedback be callback based - really

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2004, 2005 Aaron Bentley
2
 
# <aaron@aaronbentley.com>
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
 
 
 
1
#!/usr/bin/env python2.4
18
2
from subprocess import Popen, PIPE
 
3
from urllib import urlencode
 
4
from xml.sax.saxutils import escape
19
5
import os.path
20
6
import errno
21
7
import tempfile
22
8
import shutil
23
9
 
24
 
RSVG_OUTPUT_TYPES = ('png', 'jpg')
25
 
DOT_OUTPUT_TYPES = ('svg', 'svgz', 'gif', 'jpg', 'ps', 'fig', 'mif', 'png',
26
 
                    'cmapx')
 
10
mail_map = {}
27
11
 
28
12
class NoDot(Exception):
29
13
    def __init__(self):
35
19
 
36
20
class Node(object):
37
21
    def __init__(self, name, color=None, label=None, rev_id=None,
38
 
                 cluster=None, node_style=None, date=None, message=None):
 
22
                 cluster=None):
39
23
        self.name = name
40
24
        self.color = color
41
25
        self.label = label
42
26
        self.committer = None
43
27
        self.rev_id = rev_id
44
 
        if node_style is None:
45
 
            self.node_style = []
 
28
        self.node_style = []
46
29
        self.cluster = cluster
47
 
        self.rank = None
48
 
        self.date = date
49
 
        self.message = message
50
 
        self.href = None
 
30
 
 
31
    def get_committer(self):
 
32
        if self.committer is not None:
 
33
            if '@' in self.committer:
 
34
                try:
 
35
                    return mail_map[self.committer]
 
36
                except KeyError:
 
37
                    pass
 
38
            return self.committer
 
39
        elif self.rev_id is not None:
 
40
            try:
 
41
                first_segment = '-'.join(self.rev_id.split('-')[:-2])\
 
42
                    .strip(' ')
 
43
            except ValueError:
 
44
                first_segment = []
 
45
            if '@' in first_segment:
 
46
                try:
 
47
                    return mail_map[first_segment]
 
48
                except KeyError:
 
49
                    return first_segment
 
50
 
 
51
    def get_label(self):
 
52
        label = None
 
53
        committer = self.get_committer()
 
54
        if committer is not None:
 
55
            label = "%s\\n%s" % (self.name, committer)
 
56
        return label
51
57
 
52
58
    def define(self):
53
59
        attributes = []
58
64
        style.extend(self.node_style)
59
65
        if len(style) > 0:
60
66
            attributes.append('style="%s"' % ",".join(style))
61
 
        label = self.label
 
67
        label = self.get_label()
62
68
        if label is not None:
63
69
            attributes.append('label="%s"' % label)
64
70
        attributes.append('shape="box"')
65
 
        tooltip = ''
66
 
        if self.message is not None:
67
 
            tooltip += self.message.replace('"', '\\"')
68
 
        if tooltip:
69
 
            attributes.append('tooltip="%s"' % tooltip)
70
 
        if self.href is not None:
71
 
            attributes.append('href="%s"' % self.href)
72
 
        elif tooltip:
73
 
            attributes.append('href="#"')
74
71
        if len(attributes) > 0:
75
72
            return '%s[%s]' % (self.name, " ".join(attributes))
76
73
 
77
74
    def __str__(self):
78
75
        return self.name
79
76
 
80
 
class Edge(object):
81
 
    def __init__(self, start, end, label=None):
82
 
        object.__init__(self)
83
 
        self.start = start
84
 
        self.end = end
85
 
        self.label = label
86
 
 
87
 
    def dot(self, do_weight=False):
88
 
        attributes = []
89
 
        if self.label is not None:
90
 
            attributes.append(('label', self.label))
91
 
        if do_weight:
92
 
            weight = '0'
93
 
            if self.start.cluster == self.end.cluster:
94
 
                weight = '1'
95
 
            elif self.start.rank is None:
96
 
                weight = '1'
97
 
            elif self.end.rank is None:
98
 
                weight = '1'
99
 
            attributes.append(('weight', weight))
100
 
        if len(attributes) > 0:
101
 
            atlist = []
102
 
            for key, value in attributes:
103
 
                atlist.append("%s=\"%s\"" % (key, value))
104
 
            pq = ' '.join(atlist)
105
 
            op = "[%s]" % pq
106
 
        else:
107
 
            op = ""
108
 
        return "%s->%s%s;" % (self.start.name, self.end.name, op)
109
 
 
110
 
def make_edge(relation):
111
 
    if hasattr(relation, 'start') and hasattr(relation, 'end'):
112
 
        return relation
113
 
    return Edge(relation[0], relation[1])
114
 
 
115
 
def dot_output(relations, ranking="forced"):
116
 
    defined = {}
 
77
def dot_output(relations):
 
78
    defined = set()
117
79
    yield "digraph G\n"
118
80
    yield "{\n"
119
81
    clusters = set()
120
 
    edges = [make_edge(f) for f in relations]
121
82
    def rel_appropriate(start, end, cluster):
122
83
        if cluster is None:
123
 
            return (start.cluster is None and end.cluster is None) or \
124
 
                start.cluster != end.cluster
 
84
            return start.cluster is None or end.cluster is None
125
85
        else:
126
86
            return start.cluster==cluster and end.cluster==cluster
127
87
 
128
 
    for edge in edges:
129
 
        if edge.start.cluster is not None:
130
 
            clusters.add(edge.start.cluster)
131
 
        if edge.end.cluster is not None:
132
 
            clusters.add(edge.end.cluster)
 
88
    for (start, end) in relations:
 
89
        if start.cluster is not None:
 
90
            clusters.add(start.cluster)
 
91
        if end.cluster is not None:
 
92
            clusters.add(end.cluster)
133
93
    clusters = list(clusters)
134
94
    clusters.append(None)
135
95
    for index, cluster in enumerate(clusters):
136
 
        if cluster is not None and ranking == "cluster":
 
96
        if cluster is not None:
137
97
            yield "subgraph cluster_%s\n" % index
138
98
            yield "{\n"
139
99
            yield '    label="%s"\n' % cluster
140
 
        for edge in edges:
141
 
            if edge.start.name not in defined and edge.start.cluster == cluster:
142
 
                defined[edge.start.name] = edge.start
143
 
                my_def = edge.start.define()
144
 
                if my_def is not None:
145
 
                    yield "    %s\n" % my_def
146
 
            if edge.end.name not in defined and edge.end.cluster == cluster:
147
 
                defined[edge.end.name] = edge.end
148
 
                my_def = edge.end.define()
149
 
                if my_def is not None:
150
 
                    yield "    %s;\n" % my_def
151
 
            if rel_appropriate(edge.start, edge.end, cluster):
152
 
                yield "    %s\n" % edge.dot(do_weight=ranking=="forced")
153
 
        if cluster is not None and ranking == "cluster":
 
100
        for (start, end) in relations:
 
101
            if start.name not in defined and start.cluster == cluster:
 
102
                defined.add(start.name)
 
103
                my_def = start.define()
 
104
                if my_def is not None:
 
105
                    yield "    %s;\n" % my_def
 
106
            if end.name not in defined and end.cluster == cluster:
 
107
                defined.add(end.name)
 
108
                my_def = end.define()
 
109
                if my_def is not None:
 
110
                    yield "    %s;\n" % my_def
 
111
            if rel_appropriate(start, end, cluster):
 
112
                yield "    %s->%s;\n" % (start.name, end.name)
 
113
        if cluster is not None:
154
114
            yield "}\n"
155
 
 
156
 
    if ranking == "forced":
157
 
        ranks = {}
158
 
        for node in defined.itervalues():
159
 
            if node.rank not in ranks:
160
 
                ranks[node.rank] = set()
161
 
            ranks[node.rank].add(node.name)
162
 
        sorted_ranks = [n for n in ranks.iteritems()]
163
 
        sorted_ranks.sort()
164
 
        last_rank = None
165
 
        for rank, nodes in sorted_ranks:
166
 
            if rank is None:
167
 
                continue
168
 
            yield 'rank%d[style="invis"];\n' % rank
169
 
            if last_rank is not None:
170
 
                yield 'rank%d -> rank%d[style="invis"];\n' % (last_rank, rank)
171
 
            last_rank = rank
172
 
        for rank, nodes in ranks.iteritems():
173
 
            if rank is None:
174
 
                continue
175
 
            node_text = "; ".join('"%s"' % n for n in nodes)
176
 
            yield ' {rank = same; "rank%d"; %s}\n' % (rank, node_text)
177
115
    yield "}\n"
178
116
 
179
117
def invoke_dot_aa(input, out_file, file_type='png'):
195
133
        shutil.rmtree(tempdir)
196
134
    return status
197
135
 
198
 
def invoke_dot(input, out_file=None, file_type='svg', antialias=None,
199
 
               fontname="Helvetica", fontsize=11):
200
 
    cmdline = ['dot', '-T%s' % file_type, '-Nfontname=%s' % fontname,
201
 
               '-Efontname=%s' % fontname, '-Nfontsize=%d' % fontsize,
202
 
               '-Efontsize=%d' % fontsize]
 
136
def invoke_dot(input, out_file=None, file_type='svg', antialias=None):
 
137
    cmdline = ['dot', '-T%s' % file_type]
203
138
    if out_file is not None:
204
139
        cmdline.extend(('-o', out_file))
205
140
    try:
210
145
        else:
211
146
            raise
212
147
    for line in input:
213
 
        dot_proc.stdin.write(line.encode('utf-8'))
 
148
        dot_proc.stdin.write(line)
214
149
    dot_proc.stdin.close()
215
150
    return dot_proc.wait()
216
 
 
217
 
def invoke_dot_html(input, out_file):
218
 
    """\
219
 
    Produce an html file, which uses a .png file, and a cmap to provide
220
 
    annotated revisions.
221
 
    """
222
 
    tempdir = tempfile.mkdtemp()
223
 
    try:
224
 
        temp_dot = os.path.join(tempdir, 'temp.dot')
225
 
        status = invoke_dot(input, temp_dot, file_type='dot')
226
 
 
227
 
        dot = open(temp_dot)
228
 
        temp_file = os.path.join(tempdir, 'temp.cmapx')
229
 
        status = invoke_dot(dot, temp_file, 'cmapx')
230
 
 
231
 
        png_file = '.'.join(out_file.split('.')[:-1] + ['png'])
232
 
        dot.seek(0)
233
 
        status = invoke_dot(dot, png_file, 'png')
234
 
 
235
 
        png_relative = png_file.split('/')[-1]
236
 
        html = open(out_file, 'wb')
237
 
        w = html.write
238
 
        w('<html><head><title></title></head>\n')
239
 
        w('<body>\n')
240
 
        w('<img src="%s" usemap="#G" border=0/>' % png_relative)
241
 
        w(open(temp_file).read())
242
 
        w('</body></html>\n')
243
 
    finally:
244
 
        shutil.rmtree(tempdir)
245
 
    return status
246