~abentley/bzrtools/bzrtools.dev

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
# Copyright (C) 2004, 2005 Aaron Bentley
# <aaron@aaronbentley.com>
#
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program; if not, write to the Free Software
#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

from subprocess import Popen, PIPE
import os.path
import errno
import tempfile
import shutil

RSVG_OUTPUT_TYPES = ('png', 'jpg')
DOT_OUTPUT_TYPES = ('svg', 'svgz', 'gif', 'jpg', 'ps', 'fig', 'mif', 'png',
                    'cmapx')

class NoDot(Exception):
    def __init__(self):
        Exception.__init__(self, "Can't find dot!")

class NoRsvg(Exception):
    def __init__(self):
        Exception.__init__(self, "Can't find rsvg!")

class Node(object):
    def __init__(self, name, color=None, label=None, rev_id=None,
                 cluster=None, node_style=None, date=None, message=None):
        self.name = name
        self.color = color
        self.label = label
        self.committer = None
        self.rev_id = rev_id
        if node_style is None:
            self.node_style = []
        self.cluster = cluster
        self.rank = None
        self.date = date
        self.message = message
        self.href = None

    def define(self):
        attributes = []
        style = []
        if self.color is not None:
            attributes.append('fillcolor="%s"' % self.color)
            style.append('filled')
        style.extend(self.node_style)
        if len(style) > 0:
            attributes.append('style="%s"' % ",".join(style))
        label = self.label
        if label is not None:
            attributes.append('label="%s"' % label)
        attributes.append('shape="box"')
        tooltip = ''
        if self.message is not None:
            tooltip += self.message.replace('"', '\\"')
        if tooltip:
            attributes.append('tooltip="%s"' % tooltip)
        if self.href is not None:
            attributes.append('href="%s"' % self.href)
        elif tooltip:
            attributes.append('href="#"')
        if len(attributes) > 0:
            return '%s[%s]' % (self.name, " ".join(attributes))

    def __str__(self):
        return self.name

class Edge(object):
    def __init__(self, start, end, label=None):
        object.__init__(self)
        self.start = start
        self.end = end
        self.label = label

    def dot(self, do_weight=False):
        attributes = []
        if self.label is not None:
            attributes.append(('label', self.label))
        if do_weight:
            weight = '0'
            if self.start.cluster == self.end.cluster:
                weight = '1'
            elif self.start.rank is None:
                weight = '1'
            elif self.end.rank is None:
                weight = '1'
            attributes.append(('weight', weight))
        if len(attributes) > 0:
            atlist = []
            for key, value in attributes:
                atlist.append("%s=\"%s\"" % (key, value))
            pq = ' '.join(atlist)
            op = "[%s]" % pq
        else:
            op = ""
        return "%s->%s%s;" % (self.start.name, self.end.name, op)

def make_edge(relation):
    if hasattr(relation, 'start') and hasattr(relation, 'end'):
        return relation
    return Edge(relation[0], relation[1])

def dot_output(relations, ranking="forced"):
    defined = {}
    yield "digraph G\n"
    yield "{\n"
    clusters = set()
    edges = [make_edge(f) for f in relations]
    def rel_appropriate(start, end, cluster):
        if cluster is None:
            return (start.cluster is None and end.cluster is None) or \
                start.cluster != end.cluster
        else:
            return start.cluster==cluster and end.cluster==cluster

    for edge in edges:
        if edge.start.cluster is not None:
            clusters.add(edge.start.cluster)
        if edge.end.cluster is not None:
            clusters.add(edge.end.cluster)
    clusters = list(clusters)
    clusters.append(None)
    for index, cluster in enumerate(clusters):
        if cluster is not None and ranking == "cluster":
            yield "subgraph cluster_%s\n" % index
            yield "{\n"
            yield '    label="%s"\n' % cluster
        for edge in edges:
            if edge.start.name not in defined and edge.start.cluster == cluster:
                defined[edge.start.name] = edge.start
                my_def = edge.start.define()
                if my_def is not None:
                    yield "    %s\n" % my_def
            if edge.end.name not in defined and edge.end.cluster == cluster:
                defined[edge.end.name] = edge.end
                my_def = edge.end.define()
                if my_def is not None:
                    yield "    %s;\n" % my_def
            if rel_appropriate(edge.start, edge.end, cluster):
                yield "    %s\n" % edge.dot(do_weight=ranking=="forced")
        if cluster is not None and ranking == "cluster":
            yield "}\n"

    if ranking == "forced":
        ranks = {}
        for node in defined.itervalues():
            if node.rank not in ranks:
                ranks[node.rank] = set()
            ranks[node.rank].add(node.name)
        sorted_ranks = [n for n in ranks.iteritems()]
        sorted_ranks.sort()
        last_rank = None
        for rank, nodes in sorted_ranks:
            if rank is None:
                continue
            yield 'rank%d[style="invis"];\n' % rank
            if last_rank is not None:
                yield 'rank%d -> rank%d[style="invis"];\n' % (last_rank, rank)
            last_rank = rank
        for rank, nodes in ranks.iteritems():
            if rank is None:
                continue
            node_text = "; ".join('"%s"' % n for n in nodes)
            yield ' {rank = same; "rank%d"; %s}\n' % (rank, node_text)
    yield "}\n"

def invoke_dot_aa(input, out_file, file_type='png'):
    """\
    Produce antialiased Dot output, invoking rsvg on an intermediate file.
    rsvg only supports png, jpeg and .ico files."""
    tempdir = tempfile.mkdtemp()
    try:
        temp_file = os.path.join(tempdir, 'temp.svg')
        invoke_dot(input, temp_file, 'svg')
        cmdline = ['rsvg', temp_file, out_file]
        try:
            rsvg_proc = Popen(cmdline)
        except OSError, e:
            if e.errno == errno.ENOENT:
                raise NoRsvg()
        status = rsvg_proc.wait()
    finally:
        shutil.rmtree(tempdir)
    return status

def invoke_dot(input, out_file=None, file_type='svg', antialias=None,
               fontname="Helvetica", fontsize=11):
    cmdline = ['dot', '-T%s' % file_type, '-Nfontname=%s' % fontname,
               '-Efontname=%s' % fontname, '-Nfontsize=%d' % fontsize,
               '-Efontsize=%d' % fontsize]
    if out_file is not None:
        cmdline.extend(('-o', out_file))
    try:
        dot_proc = Popen(cmdline, stdin=PIPE)
    except OSError, e:
        if e.errno == errno.ENOENT:
            raise NoDot()
        else:
            raise
    for line in input:
        dot_proc.stdin.write(line.encode('utf-8'))
    dot_proc.stdin.close()
    return dot_proc.wait()

def invoke_dot_html(input, out_file):
    """\
    Produce an html file, which uses a .png file, and a cmap to provide
    annotated revisions.
    """
    tempdir = tempfile.mkdtemp()
    try:
        temp_dot = os.path.join(tempdir, 'temp.dot')
        status = invoke_dot(input, temp_dot, file_type='dot')

        dot = open(temp_dot)
        temp_file = os.path.join(tempdir, 'temp.cmapx')
        status = invoke_dot(dot, temp_file, 'cmapx')

        png_file = '.'.join(out_file.split('.')[:-1] + ['png'])
        dot.seek(0)
        status = invoke_dot(dot, png_file, 'png')

        png_relative = png_file.split('/')[-1]
        html = open(out_file, 'wb')
        w = html.write
        w('<html><head><title></title></head>\n')
        w('<body>\n')
        w('<img src="%s" usemap="#G" border=0/>' % png_relative)
        w(open(temp_file).read())
        w('</body></html>\n')
    finally:
        shutil.rmtree(tempdir)
    return status