/
utilities.py
380 lines (303 loc) · 11.5 KB
/
utilities.py
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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
##############################################################################
#
# Copyright (c) 2004 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Utilties to make the life of Documentation Modules easier.
"""
__docformat__ = 'restructuredtext'
import re
import sys
import types
import inspect
from os.path import dirname
import six
from zope.component import createObject, getMultiAdapter
from zope.interface import implementer, implementedBy
from zope.publisher.browser import TestRequest
from zope.security.checker import getCheckerForInstancesOf, Global
from zope.security.interfaces import INameBasedChecker
from zope.security.proxy import isinstance, removeSecurityProxy
import zope.app
import zope.i18nmessageid
from zope.container.interfaces import IReadContainer
from zope.app.apidoc.classregistry import safe_import, IGNORE_MODULES
_ = zope.i18nmessageid.MessageFactory("zope")
_remove_html_overhead = re.compile(
r'(?sm)^<html.*<body.*?>\n(.*)</body>\n</html>\n')
space_re = re.compile(r'\n^( *)\S', re.M)
_marker = object()
try:
_path = zope.app.__file__
except AttributeError:
try:
_path = zope.app.__path__[0]
except TypeError:
# "_NamespacePath" object does not support indexing
_path = list(zope.app.__path__)[0]
BASEDIR = dirname(dirname(dirname(dirname(_path))))
del _path
def relativizePath(path):
return path.replace(BASEDIR, 'Zope3')
def truncateSysPath(path):
"""Remove the system path prefix from the path."""
for syspath in sys.path:
if syspath and path.startswith(syspath):
return path.replace(syspath, '')[1:]
return path
@implementer(IReadContainer)
class ReadContainerBase(object):
"""Base for `IReadContainer` objects."""
def __repr__(self):
if getattr(self, '__name__', None) is None:
return super(ReadContainerBase, self).__repr__()
c = type(self)
return "<%s.%s '%s' at 0x%x>" % (c.__module__, c.__name__, self.__name__, id(self))
def get(self, key, default=None):
raise NotImplementedError()
def items(self):
raise NotImplementedError()
def __getitem__(self, key):
default = object()
obj = self.get(key, default)
if obj is default:
raise KeyError(key)
return obj
def __contains__(self, key):
return self.get(key) is not None
def keys(self):
return [x[0] for x in self.items()]
def __iter__(self):
return self.values().__iter__()
def values(self):
return [x[1] for x in self.items()]
def __len__(self):
return len(self.items())
class DocumentationModuleBase(ReadContainerBase):
"""Support for implementing a documentation module."""
__parent__ = None
__name__ = None
def withParentAndName(self, parent, name):
"Subclasses need to override this if they are stateful."
located = type(self)()
located.__parent__ = parent
located.__name__ = name
return located
def getPythonPath(obj):
"""Return the path of the object in standard Python notation.
This method should try very hard to return a string, even if it is not a
valid Python path.
"""
if obj is None:
return None
# Even for methods `im_class` and `__module__` is not allowed to be
# accessed (which is probably not a bad idea). So, we remove the security
# proxies for this check.
naked = removeSecurityProxy(obj)
qname = ''
if hasattr(naked, '__qualname__'):
# Python 3. This makes unbound functions inside classes
# do the same thing as they do an Python 2: return just their
# class name.
qname = naked.__qualname__
qname = qname.split('.')[0]
if hasattr(naked, 'im_class'):
# Python 2, unbound methods
naked = naked.im_class
if isinstance(naked, types.MethodType):
naked = type(naked.__self__)
module = getattr(naked, '__module__', _marker)
if module is _marker:
return naked.__name__
return '%s.%s' %(module, qname or naked.__name__)
def isReferencable(path):
"""Return whether the Python path is referencable."""
# Sometimes no path exists, so make a simple check first; example: None
if path is None:
return False
# There are certain paths that we do not want to reference, most often
# because they are outside the scope of this documentation
for exclude_name in IGNORE_MODULES:
if path.startswith(exclude_name):
return False
split_path = path.rsplit('.', 1)
if len(split_path) == 2:
module_name, obj_name = split_path
else:
module_name, obj_name = split_path[0], None
# Do not allow private attributes to be accessible
if (obj_name is not None and
obj_name.startswith('_') and
not (obj_name.startswith('__') and obj_name.endswith('__'))):
return False
module = safe_import(module_name)
if module is None:
return False
# If the module imported correctly and no name is provided, then we are
# all good.
if obj_name is None:
return True
obj = getattr(module, obj_name, _marker)
if obj is _marker:
return False
# Detect singeltons; those are not referencable in apidoc (yet)
if hasattr(obj, '__class__') and getPythonPath(obj.__class__) == path:
return False
return True
def _evalId(id):
if isinstance(id, Global):
id = id.__name__
if id == 'CheckerPublic':
id = 'zope.Public'
return id
def getPermissionIds(name, checker=_marker, klass=_marker):
"""Get the permissions of an attribute."""
assert (klass is _marker) != (checker is _marker)
entry = {}
if klass is not _marker:
checker = getCheckerForInstancesOf(klass)
if checker is not None and INameBasedChecker.providedBy(checker):
entry['read_perm'] = _evalId(checker.permission_id(name)) \
or _('n/a')
entry['write_perm'] = _evalId(checker.setattr_permission_id(name)) \
or _('n/a')
else:
entry['read_perm'] = entry['write_perm'] = None
return entry
def getFunctionSignature(func, ignore_self=False):
"""Return the signature of a function or method."""
if not callable(func): #isinstance(func, (types.FunctionType, types.MethodType)):
raise TypeError("func must be a function or method not a %s (%r)" % (type(func), func))
try:
args, varargs, varkw, defaults = inspect.getargspec(func)
except TypeError:
# On Python 2, inspect.getargspec can't handle certain types
# of callable things, like object.__init__ (<slot wrapper '__init__'> is not
# a python function), but it *can* handle them on Python 3.
# Punt on Python 2
return '(<unknown>)'
placeholder = object()
sig = '('
# By filling up the default tuple, we now have equal indeces for args and
# default.
if defaults is not None:
defaults = (placeholder,)*(len(args)-len(defaults)) + defaults
else:
defaults = (placeholder,)*len(args)
str_args = []
for name, default in zip(args, defaults):
# Neglect self, since it is always there and not part of the signature.
# This way the implementation and interface signatures should match.
if name == 'self' and (isinstance(func, types.MethodType) or ignore_self):
continue
# Make sure the name is a string
if isinstance(name, (tuple, list)):
name = '(' + ', '.join(name) + ')'
elif not isinstance(name, str): # pragma: no cover
name = repr(name)
if default is placeholder:
str_args.append(name)
else:
str_args.append(name + '=' + repr(default))
if varargs:
str_args.append('*'+varargs)
if varkw:
str_args.append('**'+varkw)
sig += ', '.join(str_args)
return sig + ')'
def getPublicAttributes(obj):
"""Return a list of public attribute names."""
attrs = []
for attr in dir(obj):
if attr.startswith('_'):
continue
try:
getattr(obj, attr)
except AttributeError:
continue
attrs.append(attr)
return attrs
def getInterfaceForAttribute(name, interfaces=_marker, klass=_marker,
asPath=True):
"""Determine the interface in which an attribute is defined."""
if (interfaces is _marker) and (klass is _marker):
raise ValueError("need to specify interfaces or klass")
if (interfaces is not _marker) and (klass is not _marker):
raise ValueError("must specify only one of interfaces and klass")
if interfaces is _marker:
direct_interfaces = list(implementedBy(klass))
interfaces = {}
for interface in direct_interfaces:
interfaces[interface] = 1
for base in interface.getBases():
interfaces[base] = 1
interfaces = interfaces.keys()
for interface in interfaces:
if name in interface.names():
if asPath:
return getPythonPath(interface)
return interface
return None
def columnize(entries, columns=3):
"""Place a list of entries into columns."""
if len(entries) % columns == 0:
per_col = len(entries) // columns
last_full_col = columns
else:
per_col = len(entries) // columns + 1
last_full_col = len(entries) % columns
columns = []
col = []
in_col = 0
for entry in entries:
if in_col < per_col - int(len(columns) + 1 > last_full_col):
col.append(entry)
in_col += 1
else:
columns.append(col)
col = [entry]
in_col = 1
if col:
columns.append(col)
return columns
_format_dict = {
'plaintext': 'zope.source.plaintext',
'structuredtext': 'zope.source.stx',
'restructuredtext': 'zope.source.rest'
}
def getDocFormat(module):
"""Convert a module's __docformat__ specification to a renderer source
id"""
format = getattr(module, '__docformat__', 'structuredtext').lower()
# The format can also contain the language, so just get the first part
format = format.split(' ')[0]
return _format_dict.get(format, 'zope.source.stx')
def dedentString(text):
"""Dedent the docstring, so that docutils can correctly render it."""
dedent = min([len(match) for match in space_re.findall(text)] or [0])
return re.compile('\n {%i}' % dedent, re.M).sub('\n', text)
def renderText(text, module=None, format=None, dedent=True):
if not text:
return u''
if module is not None:
if isinstance(module, six.string_types):
module = sys.modules.get(module, None)
if format is None:
format = getDocFormat(module)
if format is None:
format = 'zope.source.rest'
assert format in _format_dict.values()
if isinstance(text, bytes):
text = text.decode('latin-1', 'replace')
text = dedentString(text)
source = createObject(format, text)
renderer = getMultiAdapter((source, TestRequest()))
return renderer.render()