예제 #1
0
파일: ibkeys.py 프로젝트: eniko1/docs
    def run(self):
        document = self.state.document
        env = document.settings.env
        docname = env.docname

        if ':' in self.name:
            self.domain, self.objtype = self.name.split(':', 1)
        else:
            self.domain, self.objtype = 'py', self.name

        key = self.find_key(self.content.parent)

        targetnode = nodes.target('', '', ids=[key])

        key_elem = keynode(key)

        # Separating argument and content causes two <dd>-s to be generated in
        # the same <dl>
        doc = addnodes.desc_content()
        update_attrs(doc, self)
        txt = '\n'.join(self.arguments)
        self.before_content()
        details = keydoc(self.state, self.content)
        update_attrs(details, self)
        DocFieldTransformer(self).transform_all(details)
        self.after_content()
        doc += nodes.paragraph(txt, txt)
        doc += details

        import os
        source_line = self.lineno
        source, _ = self.state_machine.get_source_and_line(source_line)
        src_file, src_other = source.split(':', 1)
        source_file = os.path.basename(src_file)

        doc_entry = ibkey(self, key, key_elem, doc)
        #doc_entry = make_admonition(dummy, self.name, 'Alma', self.options, self.content, self.lineno, self.content_offset, self.block_text, self.state, self.state_machine)[0]

        catalog_entry = iblist_entry(self, env, docname, src_other,
                                     source_file, source_line, key, key_elem,
                                     doc)

        set_source_info(self, doc_entry)
        set_source_info(self, catalog_entry)
        env.resolve_references(doc_entry, docname, env.app.builder)
        env.resolve_references(catalog_entry, docname, env.app.builder)

        if not hasattr(env, 'ibkey_all_ibkeys'):
            env.ibkey_all_ibkeys = dict()

        env.ibkey_all_ibkeys[key] = dict(docname=docname,
                                         catalog_entry=catalog_entry)

        # - super.run() doesnt't kill the structure, it works fine
        # - returning both superrun and doc_entry does (in any order)
        # - The todo in the method docstring is rendered outside the
        #   method's documentation (?!)
        return [doc_entry]  #[targetnode, doc_entry]
예제 #2
0
 def docstring(self, node, scope):
     docstringlines = node.docstring.split("\n")
     self.env.app.emit('autodoc-process-docstring', 'class', node["ids"][0],
                       node, {}, docstringlines)
     content = ViewList(docstringlines)
     docstringnode = nodes.paragraph()
     self.state.nested_parse(content, self.content_offset, docstringnode)
     DocFieldTransformer(self).transform_all(docstringnode)
     node.insert(0, docstringnode)
예제 #3
0
    def run(self):
        self.env = env = self.state.document.settings.env
        # normalize whitespace in fullname like XRefRole does
        fullname = ws_re.sub(' ', self.arguments[0].strip())
        targetname = '%s-%s' % (self.ref_type, fullname)

        # keep the target; this may be used to generate a BBIndex later
        targets = env.domaindata['bb']['targets'].setdefault(self.ref_type, {})
        targets[fullname] = env.docname, targetname

        # make up the descriptor: a target and potentially an index descriptor
        node = nodes.target('', '', ids=[targetname])
        ret = [node]

        # add the target to the document
        self.state.document.note_explicit_target(node)

        # append the index node if necessary
        entries = []
        for tpl in self.indextemplates:
            colon = tpl.find(':')
            if colon != -1:
                indextype = tpl[:colon].strip()
                indexentry = tpl[colon + 1:].strip() % (fullname, )
            else:
                indextype = 'single'
                indexentry = tpl % (fullname, )
            entries.append(
                (indextype, indexentry, targetname, targetname, None))

        if entries:
            inode = addnodes.index(entries=entries)
            ret.insert(0, inode)

        # if the node has content, set up a signature and parse the content
        if self.has_content:
            descnode = addnodes.desc()
            descnode['domain'] = 'bb'
            descnode['objtype'] = self.ref_type
            descnode['noindex'] = True
            signode = addnodes.desc_signature(fullname, '')

            if self.name_annotation:
                annotation = "%s " % self.name_annotation
                signode += addnodes.desc_annotation(annotation, annotation)
            signode += addnodes.desc_name(fullname, fullname)
            descnode += signode

            contentnode = addnodes.desc_content()
            self.state.nested_parse(self.content, 0, contentnode)
            DocFieldTransformer(self).transform_all(contentnode)
            descnode += contentnode

            ret.append(descnode)

        return ret
예제 #4
0
    def run(self) -> List[nodes.Node]:  # noqa: D102
        if ':' in self.name:
            self.domain, self.objtype = self.name.split(':', 1)
        else:
            self.domain, self.objtype = '', self.name
        self.indexnode = addnodes.index(entries=[])

        node = OptionDesc()
        node.document = self.state.document
        node["domain"] = self.domain
        # 'desctype' is a backwards compatible attribute
        node["objtype"] = node["desctype"] = self.objtype
        node["noindex"] = noindex = ("noindex" in self.options)
        if self.domain:
            node["classes"].append(self.domain)

        self.names: List[Any] = []
        signatures = self.get_signatures()
        for i, sig in enumerate(signatures):
            # add a signature node for each signature in the current unit
            # and add a reference target for it
            signode = addnodes.desc_signature(sig, '')
            self.set_source_info(signode)
            node.append(signode)
            try:
                # name can also be a tuple, e.g. (classname, objname);
                # this is strictly domain-specific (i.e. no assumptions may
                # be made in this base class)
                name = self.handle_signature(sig, signode)
            except ValueError:
                # signature parsing failed
                signode.clear()
                signode += addnodes.desc_name(sig, sig)
                continue  # we don't want an index entry here
            if name not in self.names:
                self.names.append(name)
                if not noindex:
                    # only add target and index entry if this is the first
                    # description of the object with this name in this desc block
                    self.add_target_and_index(name, sig, signode)

        contentnode = addnodes.desc_content()
        node.append(contentnode)
        if self.names:
            # needed for association of version{added,changed} directives
            self.env.temp_data["object"] = self.names[0]
        self.before_content()
        self.state.nested_parse(self.content, self.content_offset, contentnode)
        self.transform_content(contentnode)
        self.env.app.emit("object-description-transform", self.domain,
                          self.objtype, contentnode)
        DocFieldTransformer(self).transform_all(contentnode)
        self.env.temp_data["object"] = None
        self.after_content()

        return [self.indexnode, node]
예제 #5
0
    def run(self):
        if ':' in self.name:
            self.domain, self.objtype = self.name.split(':', 1)
        else:
            self.domain, self.objtype = '', self.name
        self.indexnode = addnodes.index(entries=[])

        node = addnodes.desc()
        node.document = self.state.document
        node['domain'] = self.domain

        node['classes'].append('csharp')

        node['objtype'] = node['desctype'] = self.objtype
        node['noindex'] = noindex = ('noindex' in self.options)

        self.names = []
        signatures = self.get_signatures()
        for i, sig in enumerate(signatures):
            beforesignode = CSNodes.EmptyNode()
            node.append(beforesignode)

            signode = addnodes.desc_signature(sig, '')
            signode['first'] = False
            node.append(signode)
            self.before_sig(beforesignode)
            try:
                name = self.handle_signature(sig, signode)
            except ValueError:
                signode.clear()
                signode += addnodes.desc_name(sig, sig)
                continue
            if name not in self.names:
                self.names.append(name)
                if not noindex:
                    self.add_target_and_index(name, sig, signode)

            aftersignode = CSNodes.EmptyNode()
            node.append(aftersignode)
            self.after_sig(aftersignode)

        contentnode = addnodes.desc_content()
        node.append(contentnode)
        self.before_content_node(contentnode)
        if self.names:
            self.env.temp_data['object'] = self.names[0]
        self.before_content()
        self.state.nested_parse(self.content, self.content_offset, contentnode)
        self.after_content_node(contentnode)
        DocFieldTransformer(self).transform_all(contentnode)
        self.env.temp_data['object'] = None
        self.after_content()
        return [self.indexnode, node]
예제 #6
0
 def run(self):
     if ':' in self.name:
         self.domain, self.objtype = self.name.split(':', 1)
     else:
         self.domain, self.objtype = '', self.name
     self.env = self.state.document.settings.env
     modelnode = self.parse_arguments()
     scope = self.env.ref_context.get('jl:scope', [])
     docname = self.env.docname
     dictionary = self.env.domaindata['jl'][self.objtype]
     modelnode["ids"] = [modelnode.uid(scope)]
     modelnode.register(docname, scope, dictionary)
     self.parse_content(modelnode)
     DocFieldTransformer(self).transform_all(modelnode)
     return [modelnode]
예제 #7
0
    def _render_service(self, service):
        service_id = "service-%d" % self.env.new_serialno('service')
        service_node = nodes.section(ids=[service_id])

        title = '%s service at %s' % (service.name.title(), service.path)
        service_node += nodes.title(text=title)

        if service.description is not None:
            service_node += rst2node(trim(service.description))

        for method, view, args in service.definitions:
            if method == 'HEAD':
                #Skip head - this is essentially duplicating the get docs.
                continue
            method_id = '%s-%s' % (service_id, method)
            method_node = nodes.section(ids=[method_id])
            method_node += nodes.title(text=method)

            if is_string(view):
                if 'klass' in args:
                    ob = args['klass']
                    view_ = getattr(ob, view.lower())
                    docstring = trim(view_.__doc__ or "") + '\n'
            else:
                docstring = trim(view.__doc__ or "") + '\n'

            if 'schema' in args:
                schema = args['schema']

                attrs_node = nodes.inline()
                for location in ('header', 'querystring', 'body'):
                    attributes = schema.get_attributes(location=location)
                    if attributes:
                        attrs_node += nodes.inline(text='values in the %s' %
                                                   location)
                        location_attrs = nodes.bullet_list()

                        for attr in attributes:
                            temp = nodes.list_item()
                            desc = "%s : " % attr.name

                            # Get attribute data-type
                            if hasattr(attr, 'type'):
                                attr_type = attr.type
                            elif hasattr(attr, 'typ'):
                                attr_type = attr.typ.__class__.__name__

                            desc += " %s, " % attr_type

                            if attr.required:
                                desc += "required "
                            else:
                                desc += "optional "

                            temp += nodes.inline(text=desc)
                            location_attrs += temp

                        attrs_node += location_attrs
                method_node += attrs_node

            for validator in args.get('validators', ()):
                if validator.__doc__ is not None:
                    docstring += trim(validator.__doc__)

            if 'accept' in args:
                accept = to_list(args['accept'])

                if callable(accept):
                    if accept.__doc__ is not None:
                        docstring += accept.__doc__.strip()
                else:
                    accept_node = nodes.strong(text='Accepted content types:')
                    node_accept_list = nodes.bullet_list()
                    accept_node += node_accept_list

                    for item in accept:
                        temp = nodes.list_item()
                        temp += nodes.inline(text=item)
                        node_accept_list += temp

                    method_node += accept_node

            node = rst2node(docstring)
            DocFieldTransformer(self).transform_all(node)
            if node is not None:
                method_node += node

            renderer = args['renderer']
            if renderer == 'simplejson':
                renderer = 'json'

            response = nodes.paragraph()

            response += nodes.strong(text='Response: %s' % renderer)
            method_node += response

            service_node += method_node

        return service_node
예제 #8
0
    def run(self):
        # type: () -> List[nodes.Node]
        """
        Main directive entry function, called by docutils upon encountering the
        directive.

        This directive is meant to be quite easily subclassable, so it delegates
        to several additional methods.  What it does:

        * find out if called as a domain-specific directive, set self.domain
        * create a `desc` node to fit all description inside
        * parse standard options, currently `noindex`
        * create an index node if needed as self.indexnode
        * parse all given signatures (as returned by self.get_signatures())
          using self.handle_signature(), which should either return a name
          or raise ValueError
        * add index entries using self.add_target_and_index()
        * parse the content and handle doc fields in it
        """
        if ':' in self.name:
            self.domain, self.objtype = self.name.split(':', 1)
        else:
            self.domain, self.objtype = '', self.name
        self.indexnode = addnodes.index(entries=[])

        node = addnodes.desc()
        node.document = self.state.document
        node['domain'] = self.domain
        # 'desctype' is a backwards compatible attribute
        node['objtype'] = node['desctype'] = self.objtype
        node['noindex'] = noindex = ('noindex' in self.options)

        self.names = []  # type: List[unicode]
        signatures = self.get_signatures()
        for i, sig in enumerate(signatures):
            # add a signature node for each signature in the current unit
            # and add a reference target for it
            signode = addnodes.desc_signature(sig, '')
            signode['first'] = False
            node.append(signode)
            try:
                # name can also be a tuple, e.g. (classname, objname);
                # this is strictly domain-specific (i.e. no assumptions may
                # be made in this base class)
                name = self.handle_signature(sig, signode)
            except ValueError:
                # signature parsing failed
                signode.clear()
                signode += addnodes.desc_name(sig, sig)
                continue  # we don't want an index entry here
            if name not in self.names:
                self.names.append(name)
                if not noindex:
                    # only add target and index entry if this is the first
                    # description of the object with this name in this desc block
                    self.add_target_and_index(name, sig, signode)

        contentnode = addnodes.desc_content()
        node.append(contentnode)
        if self.names:
            # needed for association of version{added,changed} directives
            self.env.temp_data['object'] = self.names[0]
        self.before_content()
        self.state.nested_parse(self.content, self.content_offset, contentnode)
        DocFieldTransformer(self).transform_all(contentnode)
        self.env.temp_data['object'] = None
        self.after_content()
        return [self.indexnode, node]
예제 #9
0
    def _render_service(self, path, service, methods):
        env = self.state.document.settings.env
        service_id = "service-%d" % env.new_serialno('service')
        service_node = nodes.section(ids=[service_id])
        service_node += nodes.title(text='Service at %s' % service.route_name)

        if service.description is not None:
            service_node += rst2node(trim(service.description))

        for method, info in methods.items():
            method_id = '%s-%s' % (service_id, method)
            method_node = nodes.section(ids=[method_id])
            method_node += nodes.title(text=method)

            if 'attr' in info:
                docstring = getattr(info['func'], info['attr']).__doc__ or ""
            else:
                docstring = info['func'].__doc__ or ""

            docstring = trim(docstring) + '\n'

            if method in service.schemas:
                schema = service.schemas[method]

                attrs_node = nodes.inline()
                for location in ('headers', 'querystring', 'body'):
                    attributes = schema.get_attributes(location=location)
                    if attributes:
                        attrs_node += nodes.inline(text='values in the %s' %
                                                   location)
                        location_attrs = nodes.bullet_list()

                        for attr in attributes:
                            temp = nodes.list_item()
                            desc = "%s : " % attr.name

                            if hasattr(attr, 'type'):
                                desc += " %s, " % attr.type

                            if attr.required:
                                desc += "required "
                            else:
                                desc += "optional "

                            temp += nodes.inline(text=desc)
                            location_attrs += temp

                        attrs_node += location_attrs
                method_node += attrs_node

            if 'validators' in info:
                for validator in info['validators']:
                    if validator.__doc__ is not None:
                        if docstring is not None:
                            doc = trim(validator.__doc__)
                            docstring += '\n' + doc

            if 'accept' in info:
                accept = info['accept']

                if callable(accept):
                    if accept.__doc__ is not None:
                        docstring += accept.__doc__.strip()
                else:
                    accept = to_list(accept)

                    accept_node = nodes.strong(text='Accepted content types:')
                    node_accept_list = nodes.bullet_list()
                    accept_node += node_accept_list

                    for item in accept:
                        temp = nodes.list_item()
                        temp += nodes.inline(text=item)
                        node_accept_list += temp

                    method_node += accept_node

            node = rst2node(docstring)
            DocFieldTransformer(self).transform_all(node)
            if node is not None:
                method_node += node

            renderer = info['renderer']
            if renderer == 'simplejson':
                renderer = 'json'

            response = nodes.paragraph()

            response += nodes.strong(text='Response: %s' % renderer)
            method_node += response

            service_node += method_node

        return service_node
예제 #10
0
    def _render_service(self, service):
        service_id = "service-%d" % self.env.new_serialno('service')
        service_node = nodes.section(ids=[service_id])

        title = '%s service at %s' % (service.name.title(), service.path)
        service_node += nodes.title(text=title)

        if service.description is not None:
            service_node += rst2node(trim(service.description), self.env)

        for method, view, args in service.definitions:
            if method == 'HEAD':
                # Skip head - this is essentially duplicating the get docs.
                continue
            method_id = '%s-%s' % (service_id, method)
            method_node = nodes.section(ids=[method_id])
            method_node += nodes.title(text=method)

            docstring = self._resolve_obj_to_docstring(view, args)

            if 'schema' in args:
                schema = args['schema']

                attrs_node = nodes.inline()
                for location in ('header', 'querystring', 'body'):
                    attributes = self._get_attributes(schema,
                                                      location=location)
                    if attributes:
                        attrs_node += nodes.inline(
                            text='values in the %s' % location)
                        location_attrs = nodes.bullet_list()

                        for attr in attributes:
                            temp = nodes.list_item()

                            # Get attribute data-type
                            if hasattr(attr, 'type'):
                                attr_type = attr.type
                            elif hasattr(attr, 'typ'):
                                attr_type = attr.typ.__class__.__name__
                            else:
                                attr_type = None

                            temp += nodes.strong(text=attr.name)
                            if attr_type is not None:
                                temp += nodes.inline(text=' (%s)' % attr_type)
                            if not attr.required or attr.description:
                                temp += nodes.inline(text=' - ')
                                if not attr.required:
                                    if attr.missing is not None:
                                        default = json.dumps(attr.missing)
                                        temp += nodes.inline(
                                            text='(default: %s) ' % default)
                                    else:
                                        temp += nodes.inline(
                                            text='(optional) ')
                                if attr.description:
                                    temp += nodes.inline(text=attr.description)

                            location_attrs += temp

                        attrs_node += location_attrs
                method_node += attrs_node

            for validator in args.get('validators', ()):
                docstring += self._resolve_obj_to_docstring(validator, args)

            if 'accept' in args:
                accept = to_list(args['accept'])

                if callable(accept):
                    if accept.__doc__ is not None:
                        docstring += accept.__doc__.strip()
                else:
                    accept_node = nodes.strong(text='Accepted content types:')
                    node_accept_list = nodes.bullet_list()
                    accept_node += node_accept_list

                    for item in accept:
                        temp = nodes.list_item()
                        temp += nodes.inline(text=item)
                        node_accept_list += temp

                    method_node += accept_node

            node = rst2node(docstring, self.env)
            DocFieldTransformer(self).transform_all(node)
            if node is not None:
                method_node += node

            renderer = args['renderer']
            if renderer == 'simplejson':
                renderer = 'json'

            response = nodes.paragraph()

            response += nodes.strong(text='Response: %s' % renderer)
            method_node += response

            service_node += method_node
        return service_node
예제 #11
0
    def run(self) -> List[Node]:
        """
        Main directive entry function, called by docutils upon encountering the
        directive.

        This directive is meant to be quite easily subclassable, so it
        delegates to several additional methods.  What it does:

        * find out if called as a domain-specific directive, set self.domain
        * create a `desc` node to fit all description inside
        * parse standard options, currently `noindex`
        * create an index node if needed as self.indexnode
        * parse all given signatures (as returned by self.get_signatures())
          using self.handle_signature(), which should either return a name
          or raise ValueError
        * add index entries using self.add_target_and_index()
        * parse the content and handle doc fields in it

        """
        if ":" in self.name:
            self.domain, self.objtype = self.name.split(":", 1)
        else:
            self.domain, self.objtype = "", self.name
        self.indexnode = addnodes.index(entries=[])

        nest_depth = "nested-%d" % self.get_nesting_depth()
        node = nodes.admonition(classes=["toggle", self.objtype, nest_depth])
        node.document = self.state.document
        node["domain"] = self.domain
        # 'desctype' is a backwards compatible attribute
        node["objtype"] = node["desctype"] = self.objtype
        node["noindex"] = noindex = "noindex" in self.options
        if self.domain:
            node["classes"].append(self.domain)

        self.names = []  # type: List[Any]
        signatures = self.get_signatures()
        assert len(signatures) == 1, "only assuming 1 signature can be given"
        for i, sig in enumerate(signatures):
            # add a signature node for each signature in the current unit
            # and add a reference target for it
            signode = nodes.title(sig, "")
            self.set_source_info(signode)
            node.append(signode)
            try:
                # name can also be a tuple, e.g. (classname, objname);
                # this is strictly domain-specific (i.e. no assumptions may
                # be made in this base class)
                name = self.handle_signature(sig, signode)
            except ValueError:
                # signature parsing failed
                signode.clear()
                signode += addnodes.desc_name(sig, sig)
                continue  # we don't want an index entry here
            if name not in self.names:
                self.names.append(name)
                if not noindex:
                    # only add target and index entry if this is the first
                    # description of the object with this name in this desc
                    # block
                    self.add_target_and_index(name, sig, signode)

        contentnode = nodes.paragraph()
        node.append(contentnode)
        if self.names:
            # needed for association of version{added,changed} directives
            self.env.temp_data["object"] = self.names[0]
        self.before_content()
        self.state.nested_parse(self.content, self.content_offset, contentnode)
        self.transform_content(contentnode)
        self.env.app.emit("object-description-transform", self.domain,
                          self.objtype, contentnode)
        DocFieldTransformer(self).transform_all(contentnode)
        self.env.temp_data["object"] = None
        self.after_content()

        # Do this here so `become_parent` hasn't taken effect too early
        self.define_graph(signatures[0])

        return [self.indexnode, node]
예제 #12
0
    def _render_service(self, service):
        service_id = "service-%d" % self.env.new_serialno("service")
        service_node = nodes.section(ids=[service_id])

        title = "%s service at %s" % (service.name.title(), service.path)
        service_node += nodes.title(text=title)

        if service.description is not None:
            service_node += rst2node(trim(service.description), self.env)

        for method, view, args in service.definitions:
            if method == "HEAD":
                # Skip head - this is essentially duplicating the get docs.
                continue
            method_id = "%s-%s" % (service_id, method)
            method_node = nodes.section(ids=[method_id])
            method_node += nodes.title(text=method)

            docstring = self._resolve_obj_to_docstring(view, args)

            if "schema" in args:
                schema = args["schema"]

                attrs_node = nodes.inline()
                for location in ("header", "querystring", "body"):
                    attributes = self._get_attributes(schema,
                                                      location=location)
                    if attributes:
                        attrs_node += nodes.inline(text="values in the %s" %
                                                   location)
                        location_attrs = nodes.bullet_list()

                        for attr in attributes:
                            location_attrs += self._render_element_recursively(
                                attr)

                        attrs_node += location_attrs
                method_node += attrs_node

            for validator in args.get("validators", ()):
                docstring += self._resolve_obj_to_docstring(validator, args)

            if "accept" in args:
                accept = to_list(args["accept"])

                if callable(accept):
                    if accept.__doc__ is not None:
                        docstring += accept.__doc__.strip()
                else:
                    accept_node = nodes.strong(text="Accepted content types:")
                    node_accept_list = nodes.bullet_list()
                    accept_node += node_accept_list

                    for item in accept:
                        temp = nodes.list_item()
                        temp += nodes.inline(text=item)
                        node_accept_list += temp

                    method_node += accept_node

            node = rst2node(docstring, self.env)
            DocFieldTransformer(self).transform_all(node)
            if node is not None:
                method_node += node

            renderer = args["renderer"]
            if renderer == "simplejson":
                renderer = "json"

            response = nodes.paragraph()

            response += nodes.strong(text="Response: %s" % renderer)
            method_node += response

            service_node += method_node
        return service_node