File: codegrab.py

package info (click to toggle)
python-reportlab 3.1.8-3%2Bdeb8u1
  • links: PTS
  • area: main
  • in suites: jessie
  • size: 6,996 kB
  • ctags: 9,483
  • sloc: python: 69,727; ansic: 19,108; xml: 1,494; makefile: 416; java: 193; sh: 100
file content (228 lines) | stat: -rw-r--r-- 7,818 bytes parent folder | download | duplicates (3)
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
#Copyright ReportLab Europe Ltd. 2000-2012
#see license.txt for license details
#history http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportlab/tools/docco/codegrab.py
#codegrab.py
"""
This grabs various Python class, method and function
headers and their doc strings to include in documents
"""

import imp
import types
import string
import os
import sys

class Struct:
    pass

def getObjectsDefinedIn(modulename, directory=None):
    """Returns two tuple of (functions, classes) defined
    in the given module.  'directory' must be the directory
    containing the script; modulename should not include
    the .py suffix"""

    if directory:
        searchpath = [directory]
    else:
        searchpath = sys.path   # searches usual Python path

    #might be a package.  If so, check the top level
    #package is there, then recalculate the path needed
    words = modulename.split('.')
    if len(words) > 1:
        packagename = words[0]
        packagefound = imp.find_module(packagename, searchpath)
        assert packagefound, "Package %s not found" % packagename
        (file, packagepath, description) = packagefound
        #now the full path should be known, if it is in the
        #package

        directory = os.path.join(*([packagepath] + words[1:-1]))
        modulename = words[-1]
        searchpath = [directory]



    #find and import the module.
    found = imp.find_module(modulename, searchpath)
    assert found, "Module %s not found" % modulename
    (file, pathname, description) = found
    mod = imp.load_module(modulename, file, pathname, description)

    #grab the code too, minus trailing newlines
    lines = open(pathname, 'r').readlines()
    lines = list(map(str.rstrip, lines))

    result = Struct()
    result.functions = []
    result.classes = []
    result.doc = mod.__doc__
    for name in dir(mod):
        value = getattr(mod, name)
        if type(value) is types.FunctionType:
            path, file = os.path.split(value.__code__.co_filename)
            root, ext = os.path.splitext(file)
            #we're possibly interested in it
            if root == modulename:
                #it was defined here
                funcObj = value
                fn = Struct()
                fn.name = name
                fn.proto = getFunctionPrototype(funcObj, lines)
                if funcObj.__doc__:
                    fn.doc = dedent(funcObj.__doc__)
                else:
                    fn.doc = '(no documentation string)'
                #is it official?
                if name[0:1] == '_':
                    fn.status = 'private'
                elif name[-1] in '0123456789':
                    fn.status = 'experimental'
                else:
                    fn.status = 'official'

                result.functions.append(fn)
        elif type(value) == type:
            if value.__module__ == modulename:
                cl = Struct()
                cl.name = name
                if value.__doc__:
                    cl.doc = dedent(value.__doc__)
                else:
                    cl.doc = "(no documentation string)"

                cl.bases = []
                for base in value.__bases__:
                    cl.bases.append(base.__name__)
                if name[0:1] == '_':
                    cl.status = 'private'
                elif name[-1] in '0123456789':
                    cl.status = 'experimental'
                else:
                    cl.status = 'official'

                cl.methods = []
                #loop over dict finding methods defined here
                # Q - should we show all methods?
                # loop over dict finding methods defined here
                items = list(value.__dict__.items())
                items.sort()
                for (key2, value2) in items:
                    if type(value2) != types.FunctionType:
                        continue # not a method
                    elif os.path.splitext(value2.__code__.co_filename)[0] == modulename:
                        continue # defined in base class
                    else:
                        #we want it
                        meth = Struct()
                        meth.name = key2
                        name2 = value2.__code__.co_name
                        meth.proto = getFunctionPrototype(value2, lines)
                        if name2!=key2:
                            meth.doc = 'pointer to '+name2
                            meth.proto = meth.proto.replace(name2,key2)
                        else:
                            if value2.__doc__:
                                meth.doc = dedent(value2.__doc__)
                            else:
                                meth.doc = "(no documentation string)"
                        #is it official?
                        if key2[0:1] == '_':
                            meth.status = 'private'
                        elif key2[-1] in '0123456789':
                            meth.status = 'experimental'
                        else:
                            meth.status = 'official'
                        cl.methods.append(meth)
                result.classes.append(cl)
    return result

def getFunctionPrototype(f, lines):
    """Pass in the function object and list of lines;
    it extracts the header as a multiline text block."""
    firstLineNo = f.__code__.co_firstlineno - 1
    lineNo = firstLineNo
    brackets = 0
    while 1:
        line = lines[lineNo]
        for char in line:
            if char == '(':
                brackets = brackets + 1
            elif char == ')':
                brackets = brackets - 1
        if brackets == 0:
            break
        else:
            lineNo = lineNo + 1

    usefulLines = lines[firstLineNo:lineNo+1]
    return '\n'.join(usefulLines)


def dedent(comment):
    """Attempts to dedent the lines to the edge. Looks at no.
    of leading spaces in line 2, and removes up to that number
    of blanks from other lines."""
    commentLines = comment.split('\n')
    if len(commentLines) < 2:
        cleaned = list(map(str.lstrip, commentLines))
    else:
        spc = 0
        for char in commentLines[1]:
            if char in string.whitespace:
                spc = spc + 1
            else:
                break
        #now check other lines
        cleaned = []
        for line in commentLines:
            for i in range(min(len(line),spc)):
                if line[0] in string.whitespace:
                    line = line[1:]
            cleaned.append(line)
    return '\n'.join(cleaned)



def dumpDoc(modulename, directory=None):
    """Test support.  Just prints docco on the module
    to standard output."""
    docco = getObjectsDefinedIn(modulename, directory)
    print('codegrab.py - ReportLab Documentation Utility')
    print('documenting', modulename + '.py')
    print('-------------------------------------------------------')
    print()
    if docco.functions == []:
        print('No functions found')
    else:
        print('Functions:')
        for f in docco.functions:
            print(f.proto)
            print('    ' + f.doc)

    if docco.classes == []:
        print('No classes found')
    else:
        print('Classes:')
        for c in docco.classes:
            print(c.name)
            print('    ' + c.doc)
            for m in c.methods:
                print(m.proto)  # it is already indented in the file!
                print('        ' + m.doc)
            print()

def test(m='reportlab.platypus.paragraph'):
    dumpDoc(m)

if __name__=='__main__':
    import sys
    print('Path to search:')
    for line in sys.path:
        print('   ',line)
    M = sys.argv[1:]
    if M==[]:
        M.append('reportlab.platypus.paragraph')
    for m in M:
        test(m)