~abentley/bzrtools/bzrtools.dev

« back to all changes in this revision

Viewing changes to dotgraph.py

Update for integration move of read_working_inventory from Branch to WorkingTree.

Show diffs side-by-side

added added

removed removed

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