summaryrefslogtreecommitdiff
path: root/umlpy.py
blob: 0a3cd48a9a3393bbc916815878f6ff36e5245684 (plain)
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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
#!/usr/bin/env python
# coding=utf-8

'''
 umlpy
 Author : Guillaume "iXce" Seguin
 Email  : guillaume@segu.in (or guillaume.seguin@ens.fr)

 # UML-like graph produced for Python #

 Copyright (C) 2009 Guillaume Seguin

 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., 51 Franklin Street, Fifth Floor,
 Boston, MA  02110-1301, USA.
'''

import epydoc.docparser
import epydoc.docstringparser
import epydoc.apidoc

import gv

import sys
import os
import re

from optparse import OptionParser

parser = OptionParser()
parser.add_option("-v", dest = "debug", action = "store_true",
                  default = False,
                  help = "enables debug output")
parser.add_option("-e", "--exclude", dest = "excludes", action = "append",
                  default = [],
                  help = "classes matching this regexp will be excluded \
                          from display")
parser.add_option("-i", "--include", dest = "includes", action = "append",
                  default = [],
                  help = "classes matching this regexp will be included \
                          in display even if they were excluded by exclude \
                          regexps")
parser.add_option("-p", "--prefix", dest = "prefix", action = "store",
                  default = "",
                  help = "prefix which will be stripped of class names")
parser.add_option("-f", "--force", dest = "forces", action = "append",
                  default = [],
                  help = "classes matching this regexp will be forced into \
                          display")
parser.add_option("--all-methods", dest = "all_methods",
                  action = "store_true", default = False,
                  help = "shows all methods")
parser.add_option("--all-properties", dest = "all_properties",
                  action = "store_true", default = False,
                  help = "shows all properties")
parser.add_option("--no-method", dest = "no_method",
                  action = "store_true", default = False,
                  help = "shows no method")
parser.add_option("--no-property", dest = "no_property",
                  action = "store_true", default = False,
                  help = "shows no property")
parser.add_option("-o", "--output", dest = "output", action = "store",
                  default = "uml.png",
                  help = "output file")

(options, args) = parser.parse_args ()

excludes = reduce (lambda x, y: x + y,
                   map (lambda s: s.split(","), options.excludes), [])
includes = reduce (lambda x, y: x + y,
                   map (lambda s: s.split(","), options.includes), [])
forces = reduce (lambda x, y: x + y,
                 map (lambda s: s.split(","), options.forces), [])
prefix = options.prefix
all_methods = options.all_methods
all_properties = options.all_properties
no_method = options.no_method
no_property = options.no_property
output = options.output

print "Settings"
print "--------"
print "Output file :", output
print "Prefix :", prefix
print "Show all methods :", all_methods
print "Show all properties :", all_properties
print "Show no method :", no_method
print "Show no propertie :", no_property
print "Excludes :", excludes
print "Includes :", includes
print "Forces :", forces

excludes = [re.compile (exp)
            for exp in excludes]
includes = [re.compile (exp)
            for exp in includes]
forces = [re.compile (exp)
            for exp in forces]

def is_excluded (class_name):
  for exp in excludes:
    if exp.match (class_name):
      for exp in includes:
        if exp.match (class_name):
          return False
      for exp in forces:
        if exp.match (class_name):
          return False
      return True
  else:
    return False

docs = []

def get_var_type (var):
  if var.type_descr != None:
    return str (var.type_descr.to_plaintext ("").strip ())
  else:
    return None

for path in args:
  if os.path.isdir (path):
    paths = [os.path.join (path, file)
             for file in os.listdir (path) if file.endswith (".py")]
  else:
    paths = [path]
  for path in paths:
    docs.append (epydoc.docparser.parse_docs (path))

classes = []
bases_dict = {}
uses_dict = {}
methods_dict = {}
vars_dict = {}

for doc in docs:
  for var in doc.variables.values ():
    if type (var.value) != epydoc.apidoc.ClassDoc:
      continue
    var_val = var.value
    var_name = str (var_val.canonical_name)
    var_name = var_name.replace (prefix, "")
    classes.append (var_name)
    if options.debug:
      print var_name
    var_vars = var_val.variables.values ()
    vars_dict[var_name] = []
    methods_dict[var_name] = []
    uses_dict[var_name] = []
    if str (var_val.docstring) != "<UNKNOWN>":
      bits = str (var_val.docstring).split ("\n")
      for bit in bits:
        if bit.strip ().startswith ("@uses:"):
          bit = bit.replace ("@uses:", "").strip ()
          uses_dict[var_name].append (bit)
    for var_var in var_vars:
      if type (var_var.value) == epydoc.apidoc.GenericValueDoc:
        if no_property:
            continue
        epydoc.docstringparser.parse_docstring (var_var, None)
        if options.debug:
          print var_name, var_var.name, get_var_type (var_var)
        var_type = get_var_type (var_var)
        if all_properties or "@doc" in str (var_var.docstring) or var_type:
            var_var_name = str (var_var.name.replace (prefix, ""))
            vars_dict[var_name].append ((var_var_name, get_var_type (var_var)))
      elif type (var_var.value) in (epydoc.apidoc.RoutineDoc,
                                    epydoc.apidoc.StaticMethodDoc):
        if no_method:
            continue
        if (all_methods or "@doc" in str (var_var.value.docstring)) \
           and not "@nodoc" in str (var_var.value.docstring):
          methods_dict[var_name].append (str (var_var.name))
      else:
        print type (var_var.value)
    bases = [str (base.canonical_name).replace (prefix, "")
             for base in var_val.bases
             if str (base.canonical_name) not in ("object", "<UNKNOWN>")]
    if options.debug:
      print bases
    bases_dict[var_name] = bases

nodes_dict = {}
var_fields_dict = {}
method_fields_dict = {}
graph = gv.digraph ('g')
gv.setv (graph, 'charset', 'utf-8')
gv.setv (graph, 'overlap', 'false')
gv.setv (graph, 'splines', 'true')
gv.setv (graph, 'rankdir', 'BT')
item = gv.protoedge (graph)
gv.setv (item, 'len', '2')
item = gv.protonode (graph)
gv.setv (item, 'shape', 'plaintext')

CLASS_COLOR = "#FF6262"
VAR_FIELD_COLOR = "#63BDFF"
METHOD_FIELD_COLOR = "#6EFF62"

SUPER_EDGE_COLOR = "#AD0006"
VAR_EDGE_COLOR = "#002990"
USE_EDGE_COLOR = "#05C800"

LABEL_BASE = """<
<TABLE BORDER="0" CELLBORDER="1" CELLSPACING="0">
  <TR>
    <TD BGCOLOR="%s" PORT="%s">%s</TD>
  </TR>
%s
</TABLE>
>"""
FIELD_FORMATTER = """  <TR>
    <TD BGCOLOR="%s" PORT="%s">%s</TD>
  </TR>"""

def build_record_label (class_name):
  fields = "".join ([FIELD_FORMATTER % (VAR_FIELD_COLOR, field, field)
                    for field in sorted (var_fields_dict[class_name])])
  fields += "".join ([FIELD_FORMATTER % (METHOD_FIELD_COLOR, field, field)
                     for field in sorted (method_fields_dict[class_name])])
  return LABEL_BASE % (CLASS_COLOR, class_name, class_name, fields)

def build_simple_label (class_name):
  return LABEL_BASE % (CLASS_COLOR, class_name, class_name, "")

def check_class_node (name):
  if name not in nodes_dict:
    node = gv.node (graph, name)
    gv.setv (node, 'shape', 'plaintext')
    gv.setv (node, 'style', 'invis')
    if name in var_fields_dict or name in method_fields_dict:
      gv.setv (node, 'label', build_record_label (name))
    else:
      gv.setv (node, 'label', build_simple_label (name))
    nodes_dict[name] = node
  return nodes_dict[name]

def add_super_edge (class_name, base_name):
  check_class_node (class_name)
  check_class_node (base_name)
  edge = gv.edge (graph, class_name, base_name)
  gv.setv (edge, 'arrowhead', 'normal')
  gv.setv (edge, 'color', SUPER_EDGE_COLOR)
  # FIXME: edge style

def add_var_edge (class_name, var_name, type_name):
  check_class_node (class_name)
  check_class_node (type_name)
  edge = gv.edge (graph, type_name, class_name)
  gv.setv (edge, 'headport', "%s:e" % var_name)
  gv.setv (edge, 'arrowhead', 'diamond')
  gv.setv (edge, 'color', VAR_EDGE_COLOR)
  # FIXME: edge style

def add_use_edge (class_name, base_name):
  check_class_node (class_name)
  check_class_node (base_name)
  edge = gv.edge (graph, class_name, base_name)
  gv.setv (edge, 'arrowhead', 'box')
  gv.setv (edge, 'color', USE_EDGE_COLOR)
  # FIXME: edge style

for class_name in classes:
  if is_excluded (class_name):
    continue
  for (var_name, type_name) in vars_dict[class_name]:
    if class_name not in var_fields_dict:
        var_fields_dict[class_name] = []
        method_fields_dict[class_name] = []
    var_fields_dict[class_name].append (var_name)
  for method_name in methods_dict[class_name]:
    if class_name not in var_fields_dict:
        var_fields_dict[class_name] = []
        method_fields_dict[class_name] = []
    method_fields_dict[class_name].append (method_name)

for class_name in classes:
  if is_excluded (class_name):
    continue
  for (var_name, type_name) in vars_dict[class_name]:
    if not type_name or is_excluded (type_name):
      continue
    add_var_edge (class_name, var_name, type_name)
  for base_name in bases_dict[class_name]:
    if is_excluded (base_name):
      continue
    add_super_edge (class_name, base_name)
  for used_name in uses_dict[class_name]:
    if is_excluded (used_name):
      continue
    add_use_edge (class_name, used_name)

for class_name in classes:
    for exp in forces:
        if exp.match (class_name):
            check_class_node (class_name)
            break

gv.layout (graph, 'dot')
gv.render (graph, 'png', output)