~abentley/bzrtools/bzrtools.dev

125 by Aaron Bentley
Added pastegraph
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
139 by Aaron Bentley
Tweaked missing-dot handling
6
import errno
143 by Aaron Bentley
Used rsvga for nice antialiasing
7
import tempfile
8
import shutil
189.1.1 by John Arbash Meinel
Adding an html target.
9
import time
139 by Aaron Bentley
Tweaked missing-dot handling
10
167 by Aaron Bentley
Moved extention lists to dotgraph
11
RSVG_OUTPUT_TYPES = ('png', 'jpg')
189 by Aaron Bentley
Enabled client-side imagemaps
12
DOT_OUTPUT_TYPES = ('svg', 'svgz', 'gif', 'jpg', 'ps', 'fig', 'mif', 'png', 
13
                    'cmapx')
140 by Aaron Bentley
Mapped some email addresses to names
14
139 by Aaron Bentley
Tweaked missing-dot handling
15
class NoDot(Exception):
16
    def __init__(self):
17
        Exception.__init__(self, "Can't find dot!")
125 by Aaron Bentley
Added pastegraph
18
143 by Aaron Bentley
Used rsvga for nice antialiasing
19
class NoRsvg(Exception):
20
    def __init__(self):
21
        Exception.__init__(self, "Can't find rsvg!")
22
125 by Aaron Bentley
Added pastegraph
23
class Node(object):
142 by Aaron Bentley
Clustered the branch revision history
24
    def __init__(self, name, color=None, label=None, rev_id=None,
189.1.1 by John Arbash Meinel
Adding an html target.
25
                 cluster=None, node_style=None, date=None, message=None):
125 by Aaron Bentley
Added pastegraph
26
        self.name = name
27
        self.color = color
128 by Aaron Bentley
Got initial graphing functionality working
28
        self.label = label
130 by Aaron Bentley
Added committer to revisions
29
        self.committer = None
137 by Aaron Bentley
Put dotted outlines on missing revisions
30
        self.rev_id = rev_id
172 by Aaron Bentley
Marked missing nodes
31
        if node_style is None:
32
            self.node_style = []
142 by Aaron Bentley
Clustered the branch revision history
33
        self.cluster = cluster
178 by Aaron Bentley
Switched from clusters to forced ranking
34
        self.rank = None
189.1.1 by John Arbash Meinel
Adding an html target.
35
        self.date = date
36
        self.message = message
189 by Aaron Bentley
Enabled client-side imagemaps
37
        self.href = None
135 by Aaron Bentley
Enhanced revision-crediting
38
125 by Aaron Bentley
Added pastegraph
39
    def define(self):
137 by Aaron Bentley
Put dotted outlines on missing revisions
40
        attributes = []
130 by Aaron Bentley
Added committer to revisions
41
        style = []
125 by Aaron Bentley
Added pastegraph
42
        if self.color is not None:
137 by Aaron Bentley
Put dotted outlines on missing revisions
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))
157 by Aaron Bentley
Got graph showing merge selection decently
48
        label = self.label
135 by Aaron Bentley
Enhanced revision-crediting
49
        if label is not None:
137 by Aaron Bentley
Put dotted outlines on missing revisions
50
            attributes.append('label="%s"' % label)
141 by Aaron Bentley
Switched to use boxes
51
        attributes.append('shape="box"')
189.1.1 by John Arbash Meinel
Adding an html target.
52
        tooltip = ''
53
        if self.message is not None:
54
            tooltip += self.message.replace('"', '\\"')
55
        if tooltip:
56
            attributes.append('tooltip="%s"' % tooltip)
189 by Aaron Bentley
Enabled client-side imagemaps
57
        if self.href is not None:
58
            attributes.append('href="%s"' % self.href)
189.1.1 by John Arbash Meinel
Adding an html target.
59
        elif tooltip:
60
            attributes.append('href="#"')
137 by Aaron Bentley
Put dotted outlines on missing revisions
61
        if len(attributes) > 0:
62
            return '%s[%s]' % (self.name, " ".join(attributes))
125 by Aaron Bentley
Added pastegraph
63
64
    def __str__(self):
65
        return self.name
66
175 by Aaron Bentley
Added edges
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
178 by Aaron Bentley
Switched from clusters to forced ranking
74
    def dot(self, do_weight=False):
175 by Aaron Bentley
Added edges
75
        attributes = []
76
        if self.label is not None:
77
            attributes.append(('label', self.label))
178 by Aaron Bentley
Switched from clusters to forced ranking
78
        if do_weight:
182 by Aaron Bentley
Set edge weight to 1 for missing revisions
79
            weight = '0'
178 by Aaron Bentley
Switched from clusters to forced ranking
80
            if self.start.cluster == self.end.cluster:
182 by Aaron Bentley
Set edge weight to 1 for missing revisions
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))
175 by Aaron Bentley
Added edges
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):
176 by Aaron Bentley
Added skip labels to edges
98
    if hasattr(relation, 'start') and hasattr(relation, 'end'):
99
        return relation
175 by Aaron Bentley
Added edges
100
    return Edge(relation[0], relation[1])
101
178 by Aaron Bentley
Switched from clusters to forced ranking
102
def dot_output(relations, ranking="forced"):
103
    defined = {}
125 by Aaron Bentley
Added pastegraph
104
    yield "digraph G\n"
105
    yield "{\n"
142 by Aaron Bentley
Clustered the branch revision history
106
    clusters = set()
175 by Aaron Bentley
Added edges
107
    edges = [make_edge(f) for f in relations]
142 by Aaron Bentley
Clustered the branch revision history
108
    def rel_appropriate(start, end, cluster):
109
        if cluster is None:
169 by Aaron Bentley
Got ancestry-graph showing common and revision-history nodes properly
110
            return (start.cluster is None and end.cluster is None) or \
111
                start.cluster != end.cluster
142 by Aaron Bentley
Clustered the branch revision history
112
        else:
113
            return start.cluster==cluster and end.cluster==cluster
114
175 by Aaron Bentley
Added edges
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)
142 by Aaron Bentley
Clustered the branch revision history
120
    clusters = list(clusters)
121
    clusters.append(None)
122
    for index, cluster in enumerate(clusters):
178 by Aaron Bentley
Switched from clusters to forced ranking
123
        if cluster is not None and ranking == "cluster":
142 by Aaron Bentley
Clustered the branch revision history
124
            yield "subgraph cluster_%s\n" % index
125
            yield "{\n"
126
            yield '    label="%s"\n' % cluster
175 by Aaron Bentley
Added edges
127
        for edge in edges:
128
            if edge.start.name not in defined and edge.start.cluster == cluster:
178 by Aaron Bentley
Switched from clusters to forced ranking
129
                defined[edge.start.name] = edge.start
175 by Aaron Bentley
Added edges
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:
178 by Aaron Bentley
Switched from clusters to forced ranking
134
                defined[edge.end.name] = edge.end
175 by Aaron Bentley
Added edges
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):
178 by Aaron Bentley
Switched from clusters to forced ranking
139
                yield "    %s\n" % edge.dot(do_weight=ranking=="forced")
140
        if cluster is not None and ranking == "cluster":
142 by Aaron Bentley
Clustered the branch revision history
141
            yield "}\n"
178 by Aaron Bentley
Switched from clusters to forced ranking
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)
125 by Aaron Bentley
Added pastegraph
164
    yield "}\n"
165
143 by Aaron Bentley
Used rsvga for nice antialiasing
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
179 by Aaron Bentley
Enforced a font and size
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]
125 by Aaron Bentley
Added pastegraph
190
    if out_file is not None:
191
        cmdline.extend(('-o', out_file))
138 by Aaron Bentley
Handle systems without dot (the horror!). From Magnus Therning.
192
    try:
193
        dot_proc = Popen(cmdline, stdin=PIPE)
194
    except OSError, e:
139 by Aaron Bentley
Tweaked missing-dot handling
195
        if e.errno == errno.ENOENT:
196
            raise NoDot()
197
        else:
198
            raise
125 by Aaron Bentley
Added pastegraph
199
    for line in input:
200
        dot_proc.stdin.write(line)
201
    dot_proc.stdin.close()
202
    return dot_proc.wait()
189.1.1 by John Arbash Meinel
Adding an html target.
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')
189.1.2 by John Arbash Meinel
Fix datestamp, reuse pre-layed out dot file.
212
        status = invoke_dot(input, temp_dot, file_type='dot')
213
189.1.1 by John Arbash Meinel
Adding an html target.
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