Exemple #1
0
    def getMethods(self):
        """Get all methods of this class."""
        methods = []
        # remove the security proxy, so that `attr` is not proxied. We could
        # unproxy `attr` for each turn, but that would be less efficient.
        #
        # `getPermissionIds()` also expects the class's security checker not
        # to be proxied.
        klass = removeSecurityProxy(self.context)
        for name, attr, iface in klass.getMethodDescriptors():
            entry = {'name': name,
                     'signature': "(...)",
                     'doc': renderText(attr.__doc__ or '',
                                       inspect.getmodule(attr)),
                     'interface': getInterfaceInfo(iface)}
            entry.update(getPermissionIds(name, klass.getSecurityChecker()))
            methods.append(entry)

        for name, attr, iface in klass.getMethods():
            entry = {'name': name,
                     'signature': getFunctionSignature(attr),
                     'doc': renderText(attr.__doc__ or '',
                                       inspect.getmodule(attr)),
                     'interface': getInterfaceInfo(iface)}
            entry.update(getPermissionIds(name, klass.getSecurityChecker()))
            methods.append(entry)
        return methods
Exemple #2
0
 def renderedContent(self):
     """Render the file content to HTML."""
     if self.context.path.endswith('.stx'):
         format = 'zope.source.stx'
     else:
         format = 'zope.source.rest'
     return renderText(self.context.getContent(), format=format)
Exemple #3
0
 def getMethods(self):
     methods = self.context.getMethods()
     for m in methods:
         m['doc'] = renderText(m['attr'].__doc__ or '',
                               inspect.getmodule(m['attr']))
         m['interface'] = self._listClasses([m['interface']])
     return methods
    def test_renderText_non_text(self):
        # If we pass something that isn't actually text, we get a
        # descriptive error back.
        from zope.app.apidoc.utilities import renderText

        text = renderText(self)
        self.assertIn("Failed to render non-text", text)
Exemple #5
0
 def getContent(self):
     lines = self.context.getContent()
     if self.context.path.endswith('.stx'):
         format = 'zope.source.stx'
     else:
         format = 'zope.source.rest'
     return renderText(lines, format=format)
Exemple #6
0
 def getDoc(self):
     """Get the doc string of the module STX formatted."""
     text = self.context.getDocString()
     if text is None:
         return None
     lines = text.strip().split('\n')
     # Get rid of possible CVS id.
     lines = [line for line in lines if not line.startswith('$Id')]
     return renderText('\n'.join(lines), self.context.getPath())
Exemple #7
0
 def getConstructor(self):
     """Get info about the constructor, or None if there isn't one."""
     attr = self.context.getConstructor()
     if attr is None:
         return None
     attr = removeSecurityProxy(attr)
     return {
         'signature': getFunctionSignature(attr),
         'doc': renderText(attr.__doc__ or '', inspect.getmodule(attr)),
         }
 def getModuleList(self):
     """Get a list of all available documentation modules."""
     items = sorted(self.context.items())
     result = []
     for name, module in items:
         description = removeSecurityProxy(module.description)
         description = translate(description, context=self.request,
                                 default=description)
         description = renderText(description, module.__class__.__module__)
         assert not isinstance(description, bytes)
         result.append({'name': name,
                        'title': module.title,
                        'description': description})
     return result
Exemple #9
0
    def getDoc(self):
        r"""Return the main documentation string of the interface.

        Example::

          >>> from tests import getInterfaceDetails
          >>> details = getInterfaceDetails()
          >>> details.getDoc()[:55]
          u'<div class="document">\n<p>This is the Foo interface</p>'
        """
        # We must remove all proxies here, so that we get the context's
        # __module__ attribute. If we only remove security proxies, the
        # location proxy's module will be returned.
        iface = removeAllProxies(self.context)
        return renderText(iface.__doc__, inspect.getmodule(iface))
def getFactoryInfoDictionary(reg):
    """Return a PT-friendly info dictionary for a factory."""
    factory = reg.component
    callable = factory

    # Usually only zope.component.factory.Factory instances have this attribute
    if IFactory.providedBy(factory) and hasattr(factory, '_callable'):
        callable = factory._callable
    elif hasattr(callable, '__class__'):
        callable = callable.__class__

    path = getPythonPath(callable)

    return {'name': six.text_type(reg.name) or _('<i>no name</i>'),
            'title': getattr(factory, 'title', u''),
            'description': renderText(getattr(factory, 'description', u''),
                                      module=callable.__module__),
            'url': isReferencable(path) and path.replace('.', '/') or None}
Exemple #11
0
 def getDoc(self, heading_only=False):
     """Get the doc string of the module STX formatted.
     """
     if hasattr(self, "apidoc") and hasattr(self.apidoc, "getDocString"):
         text = self.apidoc.getDocString()
     else:
         return None
     if text is None:
         return None
     lines = text.strip().split('\n')
     if len(lines) and heading_only:
         # Find first empty line to separate heading from trailing text.
         headlines = []
         for line in lines:
             if line.strip() == "":
                 break
             headlines.append(line)
         lines = headlines
     # Get rid of possible CVS id.
     lines = [line for line in lines if not line.startswith('$Id')]
     return renderText('\n'.join(lines), self.path)
Exemple #12
0
def formatDocString(text, module=None, summary=False):
    """Format a doc string for display.

    module is either a Python module (from sys.modules) or the dotted name
    of a module.

    If summary is true, the result is plain text and includes only
    the summary part of the doc string.
    If summary is false, the result is HTML and includes the whole doc string.
    """
    if text is None:
        return None
    lines = text.strip().split('\n')
    # Get rid of possible CVS id.
    lines = [line for line in lines if not line.startswith('$Id')]
    if summary:
        for i in range(len(lines)):
            if not lines[i].strip():
                del lines[i:]
                break
        return '\n'.join(lines)
    return renderText('\n'.join(lines), module)
Exemple #13
0
def getFieldInfoDictionary(field, format=None):
    """Return a page-template-friendly information dictionary."""
    format = format or _getDocFormat(field)

    info = {'name': field.getName(),
            'required': field.required,
            'required_string': field.required and u'required' or u'optional',
            'default': repr(field.default),
            'title': field.title}

    # Determine the interface of the field
    iface = getFieldInterface(field)
    info['iface'] = {'name': iface.getName(), 'id': getPythonPath(iface)}

    # Determine the field class
    class_ = field.__class__
    info['class'] = {'name': class_.__name__,
                     'path': getPythonPath(class_).replace('.', '/')}

    # Render the field description
    info['description'] = renderText(field.description or u'', format=format)

    return info
Exemple #14
0
 def getDoc(self):
     """Get the doc string of the class STX formatted."""
     return renderText(self.context.getDocString() or '',
                       zapi.getParent(self.context).getPath())
Exemple #15
0
 def getDocString(self):
     """Get the doc string of the function in a rendered format."""
     return renderText(self.context.getDocString() or '',
                       getParent(self.context).getPath())
Exemple #16
0
    def update(self, show_private=False, *args, **kw):
        obj = self.context
        if isinstance(self.context, ZopeObjectInfo):
            # When the docgrok-object traverser delivers content, then
            # we get a wrapped context: the meant object is wrapped
            # into a ZopeObjectInfo.
            obj = self.context.obj

        self.ob_info = ZopeObjectInfo(obj)
        ob_info = self.ob_info
        self.show_private = show_private
        root_url = self.root_url()
        parent = ob_info.getParent()
        parent = {
            'class_link': parent and getPathLinksForObject(parent) or '',
            'obj_link': getItemLink('', getParentURL(self.url(''))),
            'obj': parent
        }
        bases = [getPathLinksForClass(x) for x in ob_info.getBases()]
        bases.sort()

        ifaces = [
            getPathLinksForClass(x) for x in ob_info.getProvidedInterfaces()
        ]
        ifaces.sort()

        methods = [
            x for x in list(ob_info.getMethods())
            if self.show_private or not x['name'].startswith('_')
        ]
        for method in methods:
            if method['interface']:
                method['interface'] = getPathLinksForDottedName(
                    method['interface'], root_url)
            if method['doc']:
                method['doc'] = renderText(method['doc'],
                                           getattr(obj, '__module__', None))

        attrs = [
            x for x in list(ob_info.getAttributes())
            if self.show_private or not x['name'].startswith('_')
        ]
        for attr in attrs:
            if '.' in str(attr['type']):
                attr['type'] = getPathLinksForClass(attr['type'], root_url)
            else:
                attr['type'] = attrEscape(str(attr['type']))
            if attr['interface']:
                attr['interface'] = getPathLinksForDottedName(
                    attr['interface'], root_url)
            attr['obj'] = getattr(obj, attr['name'], None)
            attr['docgrok_link'] = getItemLink(attr['name'], self.url(''))
        attrs.sort(lambda x, y: x['name'] > y['name'])

        seqitems = ob_info.getSequenceItems() or []
        for item in seqitems:
            if '.' in str(item['value_type']):
                item['value_type'] = getPathLinksForClass(
                    item['value_type'], root_url)
            else:
                item['value_type'] = attrEscape(str(item['value_type']))
            item['obj'] = obj[item['index']]
            item['docgrok_link'] = getItemLink(item['index'], self.url(''))
        seqitems.sort()

        mapitems = [
            x for x in ob_info.getMappingItems()
            if self.show_private or not x['key'].startswith('_')
        ]
        for item in mapitems:
            if '.' in str(item['value_type']):
                item['value_type'] = getPathLinksForClass(
                    item['value_type'], root_url)
            else:
                item['value_type'] = attrEscape(str(item['value_type']))
            item['obj'] = obj[item['key']]
            item['docgrok_link'] = getItemLink(item['key'], self.url(''))
        mapitems.sort(lambda x, y: x['key'] > y['key'])

        annotations = [
            x for x in ob_info.getAnnotationsInfo()
            if self.show_private or not x['key'].startswith('_')
        ]
        for item in annotations:
            if '.' in str(item['value_type']):
                item['value_type'] = getPathLinksForClass(
                    item['value_type'], root_url)
            else:
                item['value_type'] = attrEscape(str(item['value_type']))
            item['docgrok_link'] = getItemLink(item['key'], self.url(''))
        annotations.sort(lambda x, y: x['key'] > y['key'])

        self.info = {
            'name':
            ob_info.getId() or u'<unnamed object>',
            'type':
            getPathLinksForClass(
                (getattr(obj, '__class__', None) or type(obj)), root_url),
            'obj_link':
            getPathLinksForObject(obj, root_url),
            'moduleinfo':
            ob_info.getmoduleinfo(),
            'modulename':
            ob_info.getmodulename(),
            'ismodule':
            ob_info.ismodule(),
            'isclass':
            ob_info.isclass(),
            'ismethod':
            ob_info.ismethod(),
            'isfunction':
            ob_info.isfunction(),
            'iscode':
            ob_info.iscode(),
            'isbuiltin':
            ob_info.isbuiltin(),
            'isroutine':
            ob_info.isroutine(),
            'issequence':
            ob_info.isSequence(),
            'ismapping':
            ob_info.isMapping(),
            'isannotatable':
            ob_info.isAnnotatable(),
            'doc':
            renderText(ob_info.getdoc(), None),
            'comments':
            ob_info.getcomments(),
            'module':
            ob_info.getmodule(),
            'sourcefile':
            ob_info.getsourcefile(),
            'source':
            ob_info.getsource(),
            'parent':
            parent,
            'dotted_path':
            ob_info.getPythonPath(),
            'provided_interfaces':
            ob_info.getDirectlyProvidedInterfaces(),
            'interfaces':
            ifaces,
            'bases':
            bases,
            'attributes':
            attrs,
            'methods':
            methods,
            'sequenceitems':
            seqitems,
            'mappingitems':
            mapitems,
            'annotations':
            annotations
        }
Exemple #17
0
def getMethodInfoDictionary(method, format=None):
    """Return a page-template-friendly information dictionary."""
    format = format or _getDocFormat(method)
    return {'name': method.getName(),
            'signature': method.getSignatureString(),
            'doc': renderText(method.getDoc() or u'', format=format)}
Exemple #18
0
def getAttributeInfoDictionary(attr, format=None):
    """Return a page-template-friendly information dictionary."""
    format = format or _getDocFormat(attr)
    return {'name': attr.getName(),
            'doc': renderText(attr.getDoc() or u'', format=format)}