Ejemplo n.º 1
0
def _patch_python_domain():
    import sphinx.domains.python
    from sphinx.domains.python import PyTypedField
    import sphinx.locale
    l_ = sphinx.locale.lazy_gettext
    for doc_field in sphinx.domains.python.PyObject.doc_field_types:
        if doc_field.name == 'parameter':
            doc_field.names = ('param', 'parameter', 'arg', 'argument')
            break
    sphinx.domains.python.PyObject.doc_field_types.append(
        PyTypedField('keyword',
                     label=l_('Keyword Arguments'),
                     names=('keyword', 'kwarg', 'kwparam'),
                     typerolename='obj',
                     typenames=('paramtype', 'kwtype'),
                     can_collapse=True), )
Ejemplo n.º 2
0
def _patch_python_domain() -> None:
    try:
        from sphinx.domains.python import PyTypedField
    except ImportError:
        pass
    else:
        import sphinx.domains.python
        from sphinx.locale import _
        for doc_field in sphinx.domains.python.PyObject.doc_field_types:
            if doc_field.name == 'parameter':
                doc_field.names = ('param', 'parameter', 'arg', 'argument')
                break
        sphinx.domains.python.PyObject.doc_field_types.append(
            PyTypedField('keyword', label=_('Keyword Arguments'),
                         names=('keyword', 'kwarg', 'kwparam'),
                         typerolename='obj', typenames=('paramtype', 'kwtype'),
                         can_collapse=True))
Ejemplo n.º 3
0
def _patch_python_domain():
    # type: () -> None
    try:
        from sphinx.domains.python import PyTypedField
    except ImportError:
        pass
    else:
        import sphinx.domains.python
        from sphinx.locale import _

        for doc_field in sphinx.domains.python.PyObject.doc_field_types:
            if doc_field.name == "parameter":
                doc_field.names = ("param", "parameter", "arg", "argument")
                break
        sphinx.domains.python.PyObject.doc_field_types.append(
            PyTypedField(
                "keyword",
                label=_("Keyword Arguments"),
                names=("keyword", "kwarg", "kwparam"),
                typerolename="obj",
                typenames=("paramtype", "kwtype"),
                can_collapse=True,
            ))
Ejemplo n.º 4
0
"""

from sphinx.domains.python import PyObject, PyTypedField
from sphinx.ext.napoleon.docstring import GoogleDocstring

# Extend the python sphinx domain with support for :field: and :relation: directives,
# as well as their related type directives. These then get used by DjangoGoogleDocstring.
# Using the 'data' role for the :field: and :relation: directives prevents sphinx from trying
# cross-reference them. This role is intended to be used at the module level, but renders
# correctly when used in Model definitions and prevents warnings from sphinx about duplicate
# cross-reference targets on something that shouldn't be cross-referenced.
PyObject.doc_field_types.extend([
    PyTypedField('field',
                 label=('Fields'),
                 rolename='data',
                 names=('field', ),
                 typerolename='obj',
                 typenames=('fieldtype', ),
                 can_collapse=True),
    PyTypedField('relation',
                 label=('Relations'),
                 rolename='data',
                 names=('relation', ),
                 typerolename='obj',
                 typenames=('reltype', ),
                 can_collapse=True),
])

# Similar to the extensions above, but this rewrites the 'variable' type used for class attrs to
# use the data rolename, which prevents sphinx from attempting to cross-reference class attrs.
for field in PyObject.doc_field_types:
Ejemplo n.º 5
0
class HTTPResource(ObjectDescription):

    doc_field_types = [
        PyTypedField('parameter',
                     label='Parameters',
                     names=('param', 'parameter', 'arg', 'argument'),
                     typerolename='obj',
                     typenames=('paramtype', 'type')),
        PyTypedField('jsonparameter',
                     label='JSON Parameters',
                     names=('jsonparameter', 'jsonparam', 'json'),
                     typerolename='obj',
                     typenames=('jsonparamtype', 'jsontype')),
        PyTypedField('requestjsonobject',
                     label='Request JSON Object',
                     names=('reqjsonobj', 'reqjson', '<jsonobj', '<json'),
                     typerolename='obj',
                     typenames=('reqjsonobj', '<jsonobj')),
        PyTypedField('requestjsonarray',
                     label='Request JSON Array of Objects',
                     names=('reqjsonarr', '<jsonarr'),
                     typerolename='obj',
                     typenames=('reqjsonarrtype', '<jsonarrtype')),
        PyTypedField('responsejsonobject',
                     label='Response JSON Object',
                     names=('resjsonobj', 'resjson', '>jsonobj', '>json'),
                     typerolename='obj',
                     typenames=('resjsonobj', '>jsonobj')),
        Field('singlejsonvalue',
              label='Response JSON Object',
              has_arg=False,
              names=('returns', 'return')),
        PyField('singlejsontype',
                label='Response JSON type',
                has_arg=False,
                names=('rtype', ),
                bodyrolename='obj'),
        PyTypedField('responsejsonarray',
                     label='Response JSON Array of Objects',
                     names=('resjsonarr', '>jsonarr'),
                     typerolename='obj',
                     typenames=('resjsonarrtype', '>jsonarrtype')),
        PyTypedField('queryparameter',
                     label='Query Parameters',
                     names=('queryparameter', 'queryparam', 'qparam', 'query'),
                     typerolename='obj',
                     typenames=('queryparamtype', 'querytype', 'qtype')),
        GroupedField('formparameter',
                     label='Form Parameters',
                     names=('formparameter', 'formparam', 'fparam', 'form')),
        GroupedField('requestheader',
                     label='Request Headers',
                     rolename='header',
                     names=('<header', 'reqheader', 'requestheader')),
        GroupedField('responseheader',
                     label='Response Headers',
                     rolename='header',
                     names=('>header', 'resheader', 'responseheader')),
        GroupedField('statuscode',
                     label='Status Codes',
                     rolename='statuscode',
                     names=('statuscode', 'status', 'code')),
        PyGroupedField('exceptions',
                       label='Possible error responses',
                       rolename='exc',
                       names=('raises', 'raise', 'exception', 'except'),
                       can_collapse=True),
    ]

    option_spec = {
        'deprecated': directives.flag,
        'noindex': directives.flag,
        'synopsis': lambda x: x,
    }

    method = NotImplemented

    def handle_signature(self, sig, signode):
        method = self.method.upper() + ' '
        signode += addnodes.desc_name(method, method)
        offset = 0
        path = None
        for match in http_sig_param_re.finditer(sig):
            path = sig[offset:match.start()]
            signode += addnodes.desc_name(path, path)
            params = addnodes.desc_parameterlist()
            typ = match.group('type')
            if typ:
                typ += ': '
                params += addnodes.desc_annotation(typ, typ)
            name = match.group('name')
            params += addnodes.desc_parameter(name, name)
            signode += params
            offset = match.end()
        if offset < len(sig):
            path = sig[offset:len(sig)]
            signode += addnodes.desc_name(path, path)
        assert path is not None, 'no matches for sig: %s' % sig
        fullname = self.method.upper() + ' ' + path
        signode['method'] = self.method
        signode['path'] = sig
        signode['fullname'] = fullname
        return (fullname, self.method, sig)

    def needs_arglist(self):
        return False

    def add_target_and_index(self, name_cls, sig, signode):
        signode['ids'].append(http_resource_anchor(*name_cls[1:]))
        if 'noindex' not in self.options:
            self.env.domaindata['http'][self.method][sig] = (self.env.docname,
                                                             self.options.get(
                                                                 'synopsis',
                                                                 ''),
                                                             'deprecated'
                                                             in self.options)

    def get_index_text(self, modname, name):
        return ''
Ejemplo n.º 6
0
#
# All configuration values have a default; values that are commented out
# serve to show the default.

# Monkey patch in a field type for columns.

# try:
from sphinx.util.docfields import Field, GroupedField, TypedField
from sphinx.domains.python import PythonDomain, PyObject, l_, PyField, PyTypedField

PyObject.doc_field_types += [
    GroupedField('modelparam', label='Model Parameters', names=('modelparam', ), can_collapse=True,
        rolename='math'
    ),
    PyTypedField('expparam', 
        label=l_('Experiment Parameters'), names=('expparam', ), can_collapse=False,
        rolename='obj'
    ),
    PyField('scalar-expparam',
        label=l_('Experiment Parameter'), names=('scalar-expparam', ),
        has_arg=True, rolename='obj'
    ),
    GroupedField('columns', label=l_('Columns'), names=('column', ), can_collapse=True),
]
# except:
#   pass

###############################################################################

import sys, os

# If extensions (or modules to document with autodoc) are in another directory,
Ejemplo n.º 7
0
class JSONObject(directives.ObjectDescription):
    """
    Implementation of ``json:object``.

    The :meth:`run` method is called to process each ``.. json:object::``
    directive.  It builds the docutil nodes that the builder uses to
    generate the output.  We don't do anything that is too complex
    with formatting.  Cross-references and examples are a different
    story.  The :class:`JSONDomain` instance is responsible for
    creating the examples since we have to wait until all of the JSON
    objects have been parsed to do that.

    Cross-references are generated using the :meth:`JSONDomain.add_object`
    method of the Domain instance.  This stores the JSON object definition
    so that we can access it via the ``:json:object:`` role as well.
    Take a look at :class:`JSONXRef` and :meth:`JSONDomain.resolve_xref`
    for the implementation of the lookup.

    """

    doc_field_types = [
        PyTypedField('property',
                     label='Object Properties',
                     names=('property', 'member'),
                     rolename='prop',
                     typerolename='jsonprop',
                     typenames=('proptype', 'type'))
    ]
    """A list of fields that are implemented."""

    option_spec = {
        'noindex': rst_directives.flag,
        'showexample': rst_directives.unchanged,
    }
    """Mapping from supported option to an option processor."""

    has_content = True
    """JSONObject directives accept content."""

    # Inherited Attribute Notes
    # --------- --------- -----
    # self.name - directive name ... probably `object'
    # self.arguments - pos args as list of strings
    # self.options - mapping of name -> value after passing thru option_spec
    # self.content - content as a list of lines (strings)
    # self.lineno - input line number
    # self.src - input file/path
    # self.srcline - input line number in source file
    # self.content_offset - line offset of the first line
    # self.block_text - raw text
    # self.state - `state' which called the directive (?)
    # self.state_machine - `state machine' that controls the state (?)
    #
    # NB self.domain is required to be the name of the sphinx domain
    # inside of DocFieldTransformer

    def run(self):
        """
        Process a ``json:object`` directive.

        This method parses the property definitions and generates a
        single :class:`sphinx.addnodes.desc` element to hold the
        generated docutils tree.  The structure is::

            <sphinx.addnodes.desc>
                <sphinx.addnodes.desc_signature>name
                <sphinx.addnodes.desc_name>name
                <sphinx.addnodes.desc_content>
                    # sub-tree generated from parsing content
                <sphinx.addnodes.compact_paragraph>
                    <docutils.nodes.strong>"JSON Example"
                    <docutils.nodes.literal_block>{...}

        The example block is generated when :meth:`JSONDomain.process_doc`
        is called.  We create the ``compact_paragraph`` node, add it to the
        ``desc`` node and tell the Domain instance to populate the
        ``compact_paragraph`` later on.

        """
        self.domain, sep, objtype = self.name.partition(':')
        if not objtype:  # swap domain and objtype
            objtype = self.domain
            self.domain = ''

        env = self.state.document.settings.env
        self.names = []
        self.indexnode = addnodes.index(entries=[])
        self.domain_obj = env.domains['json']

        node = addnodes.desc()
        node.document = self.state.document
        node['domain'] = self.domain
        node['objtype'] = node['desctype'] = objtype
        noindex = node['noindex'] = 'noindex' in self.options

        name = self.arguments[0]
        signode = addnodes.desc_signature(name)
        node.append(signode)
        signode += addnodes.desc_name(text=name)

        contentnode = addnodes.desc_content()
        node.append(contentnode)
        self.before_content()
        self.state.nested_parse(self.content, self.content_offset, contentnode)

        props = self.domain_obj.get_object(name)
        if props:
            env.warn(
                env.docname, 'JSON type {} already documented in {}'.format(
                    name, env.doc2path(props.docname)), self.lineno)
        else:
            self.domain_obj.add_object(name, env, contentnode)
            if not noindex:
                self.add_target_and_index(name, node, signode)

        docfields.DocFieldTransformer(self).transform_all(contentnode)

        if 'showexample' in self.options:
            paragraph = addnodes.compact_paragraph()
            contentnode.append(paragraph)
            self.domain_obj.data['examples'].append(
                (name, self.options['showexample'] or 'json', paragraph))

        self.after_content()

        return [self.indexnode, node]

    def add_target_and_index(self, name, sig, signode):
        """
        Add an entry for ``name`` to the general index.

        :param str name: name to insert into the index.
        :param docutils.nodes.Element sig: unused
        :param docutils.nodes.Element signode: node to index

        The entry is stored as a child of the ``JSON Objects`` index
        entry.

        """
        key = normalize_object_name(name)
        if key in self.state.document.ids:
            return

        signode['names'].append(name)
        signode['ids'].append(key)
        signode['first'] = not self.names
        self.indexnode['entries'].append(
            ('single', 'JSON Objects; {}'.format(name), key, '', None))