def test_new_documenter(): class MyDocumenter(ModuleLevelDocumenter): objtype = "integer" directivetype = "data" priority = 100 @classmethod def can_document_member(cls, member, membername, isattr, parent): return isinstance(member, int) def document_members(self, all_members=False): return add_documenter(MyDocumenter) def assert_result_contains(item, objtype, name, **kw): inst = AutoDirective._registry[objtype](directive, name) inst.generate(**kw) # print '\n'.join(directive.result) assert len(_warnings) == 0, _warnings assert item in directive.result del directive.result[:] options.members = ["integer"] assert_result_contains(".. py:data:: integer", "module", "test_autodoc")
def add_autodocumenter(self, cls): # type: (Any) -> None logger.debug('[app] adding autodocumenter: %r', cls) from sphinx.ext import autodoc from sphinx.ext.autodoc.directive import AutodocDirective autodoc.add_documenter(cls) self.add_directive('auto' + cls.objtype, AutodocDirective)
def test_new_documenter(): logging.setup(app, app._status, app._warning) class MyDocumenter(ModuleLevelDocumenter): objtype = 'integer' directivetype = 'data' priority = 100 @classmethod def can_document_member(cls, member, membername, isattr, parent): return isinstance(member, int) def document_members(self, all_members=False): return add_documenter(MyDocumenter) def assert_result_contains(item, objtype, name, **kw): app._warning.truncate(0) inst = app.registry.documenters[objtype](directive, name) inst.generate(**kw) # print '\n'.join(directive.result) assert app._warning.getvalue() == '' assert item in directive.result del directive.result[:] options.members = ['integer'] assert_result_contains('.. py:data:: integer', 'module', 'target')
def setup(app): app.add_config_value('autoc_base_path', False, True) autodoc.add_documenter(CFileDocumenter) # add_directive_to_domain was added in Sphinx 1.0, use add_directive instead. #app.add_directive_to_domain('c', 'autofile', autodoc.AutoDirective) app.add_directive('autocfile', autodoc.AutoDirective)
def test_new_documenter(): class MyDocumenter(ModuleLevelDocumenter): objtype = 'integer' directivetype = 'data' priority = 100 @classmethod def can_document_member(cls, member, membername, isattr, parent): return isinstance(member, int) def document_members(self, all_members=False): return add_documenter(MyDocumenter) def assert_result_contains(item, objtype, name, **kw): inst = AutoDirective._registry[objtype](directive, name) inst.generate(**kw) # print '\n'.join(directive.result) assert len(_warnings) == 0, _warnings assert item in directive.result del directive.result[:] options.members = ['integer'] assert_result_contains('.. py:data:: integer', 'module', 'target')
def add_autodocumenter(app, cls): app.debug('[app] adding autodocumenter: %r', cls) from sphinx.ext import autodoc autodoc.add_documenter(cls) app.add_directive('auto' + cls.objtype, DispatcherDirective)
def add_autodocumenter(app, cls): logger.debug('[app] adding autodocumenter: %r', cls) try: from sphinx.ext.autodoc.directive import AutodocDirective app.registry.add_documenter(cls.objtype, cls) except AttributeError: from sphinx.ext import autodoc autodoc.add_documenter(cls) app.add_directive('auto' + cls.objtype, DispatcherDirective)
def setup(app): # NOTE: the "correct", forward compatible call to make here is # app.add_autodocumenter() - because as of Sphinx 1.7, the inner API we are # manipulating here got changed around a bunch (but the outer # API of add_autodocumenter() remained the same, on purpose). # Unfortunately, in both cases add_autodocumenter() both registers the # documenter AND adds an `auto<type>` directive - meaning it's not possible # to register a "acts kinda like another" Documenter or you double-define # e.g. autofunction, which Sphinx warns about and also presumably kills # real function documenting. # NOTE: sooo for now, since a bunch of our other shit breaks on Sphinx 1.7, # we are just explicitly calling autodoc's add_documenter. Sadface. autodoc.add_documenter(TaskDocumenter)
def setup(app): global sphinxapp sphinxapp = app autodoc.setup(app) autodoc.add_documenter(FieldDocumenter) autodoc.add_documenter(SettingsDocumenter) autodoc.add_documenter(SignalDocumenter) autodoc.add_documenter(EnumDocumenter) app.connect('autodoc-skip-member', skip_member_predicate)
def setup(app): autodoc.add_documenter(FunctionDocumenter) autodoc.add_documenter(MethodDocumenter)
def add_autodocumenter(self, cls): self.debug('[app] adding autodocumenter: %r', cls) from sphinx.ext import autodoc autodoc.add_documenter(cls) self.add_directive('auto' + cls.objtype, autodoc.AutoDirective)
def setup(): autodoc.add_documenter(RestMethodDocumenter) autodoc.add_documenter(RestClassDocumenter)
#print os.path.abspath('canvas') sys.path.append(os.path.abspath('canvas')) import redREnviron directoryNames = redREnviron.__getDirectoryNames(os.path.abspath('')) redREnviron.directoryNames = directoryNames redREnviron.addOrangeDirectoriesToPath(directoryNames) # import orngDlgs # from orngDlgs import SignalDialog from sphinx.ext import autodoc class DocsonlyMethodDocumenter(autodoc.MethodDocumenter): def format_args(self): return None autodoc.add_documenter(DocsonlyMethodDocumenter) # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.coverage', 'sphinx.ext.pngmath', 'sphinx.ext.ifconfig', 'sphinx.ext.viewcode', 'sphinx.ext.graphviz', 'sphinx.ext.inheritance_diagram']
objtype = "task" directivetype = "function" @classmethod def can_document_member(cls, member, membername, isattr, parent): from paver.tasks import Task return isinstance(member, Task) def import_object(self): super(TaskDocumenter, self).import_object() obj = self.object self.object = obj.func return True autodoc.add_documenter(TaskDocumenter) # General configuration # --------------------- # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.autodoc'] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The master toctree document.
#!/usr/bin/env python import sys import auto sys.path.append("..") from jinja2 import FileSystemLoader from jinja2.sandbox import SandboxedEnvironment from sphinx.ext.autodoc import (ModuleDocumenter,ClassDocumenter,ExceptionDocumenter,DataDocumenter,FunctionDocumenter,MethodDocumenter,AttributeDocumenter,InstanceAttributeDocumenter) from sphinx.ext.autodoc import AutoDirective, add_documenter for typ in (ModuleDocumenter,ClassDocumenter,ExceptionDocumenter,DataDocumenter,FunctionDocumenter,MethodDocumenter,AttributeDocumenter,InstanceAttributeDocumenter): add_documenter(typ) from sphinx.ext.autosummary import get_documenter def main (): loader = FileSystemLoader([".templates"]) env = SandboxedEnvironment(loader=loader) done_files = [] for orig_module in auto.modules: output = orig_module + ".rst" f = open(output, "w") try:
def setup(app): from docutils import nodes from sphinx.ext.autodoc import MethodDocumenter, add_documenter from sphinx.domains.python import PyXrefMixin, PyObject from sphinx.locale import _ from sphinx.util.docfields import GroupedField from sphinx.writers.html import SmartyPantsHTMLTranslator class PyXrefGroupedField(PyXrefMixin, GroupedField): pass #-class class MethodDocumenterNoDecoratedPrivateMembers(MethodDocumenter): """Converts names like '_Class__private' to '__private'. """ def format_name(self): objpath = self.objpath[:] if len(objpath) >= 2: class_name = objpath[-2] method_name = objpath[-1] if method_name.startswith("_%s" % class_name): objpath[-1] = method_name[1 + len(class_name):] \ or method_name return '.'.join(objpath) or self.modname #-def #-class add_documenter(MethodDocumenterNoDecoratedPrivateMembers) # Patch PyObject.doc_field_types: item = 0 for field in PyObject.doc_field_types: if field.name == 'exceptions': break item += 1 if item < len(PyObject.doc_field_types): PyObject.doc_field_types[item] = PyXrefGroupedField( field.name, label = field.label, rolename = field.rolename, names = field.names, can_collapse = field.can_collapse ) # Patch Sphinx bug #1788: class CorrectedHTMLTranslator(SmartyPantsHTMLTranslator): def __init__(self, *args, **kwargs): SmartyPantsHTMLTranslator.__init__(self, *args, **kwargs) #-def def depart_caption(self, node): self.body.append('</span>') # append permalink if available if isinstance(node.parent, nodes.container) \ and node.parent.get('literal_block'): self.add_permalink_ref( node.parent, _('Permalink to this code') ) elif isinstance(node.parent, nodes.figure): image_nodes = node.parent.traverse(nodes.image) target_node = image_nodes and image_nodes[0] or node.parent self.add_permalink_ref( target_node, _('Permalink to this image') ) elif node.parent.get('toctree'): self.add_permalink_ref( node.parent.parent, _('Permalink to this toctree') ) if isinstance(node.parent, nodes.container) \ and node.parent.get('literal_block'): self.body.append('</div>\n') else: SmartyPantsHTMLTranslator.__bases__[0].__bases__[0] \ .depart_caption(self, node) #-def #-class def process_signature( app, what, name, obj, options, signature, return_annotation ): if what != 'function': return signature, return_annotation params = [] # We suppose that we have not something like this: # # def fnc(x, y, z = "Hello, World!", g = "== Problem? =="): # ... # for p in [p.strip() for p in signature[1:-1].split(',')]: if '=' not in p: params.append(p) continue key, value = p.split('=') s, e = "<class '", "'>" if not value.startswith(s) or not value.endswith(e): params.append(p) continue value = value[len(s):-len(e)] if '.' not in value or '.' not in name \ or name.split('.')[:-1] != value.split('.')[:-1]: params.append('='.join([key, value])) continue # `value` is from the same module as `name`: params.append('='.join([key, value.split('.')[-1]])) return "(%s)" % ', '.join(params), return_annotation #-def app.set_translator('html', CorrectedHTMLTranslator) app.add_stylesheet('custom.css') app.connect('autodoc-process-signature', process_signature)
def add_autodocumenter(self, cls): """ See :epkg:`class Sphinx`. """ autodoc.add_documenter(cls) self.app.add_directive('auto' + cls.objtype, autodoc.AutoDirective)
from jinja2 import FileSystemLoader, TemplateNotFound from jinja2.sandbox import SandboxedEnvironment from sphinx import package_dir from sphinx.ext.autosummary import import_by_name, get_documenter from sphinx.jinja2glue import BuiltinTemplateLoader from sphinx.util.osutil import ensuredir from sphinx.util.inspect import safe_getattr from sphinx.util.rst import escape as rst_escape # Add documenters to AutoDirective registry from sphinx.ext.autodoc import add_documenter, \ ModuleDocumenter, ClassDocumenter, ExceptionDocumenter, DataDocumenter, \ FunctionDocumenter, MethodDocumenter, AttributeDocumenter, \ InstanceAttributeDocumenter add_documenter(ModuleDocumenter) add_documenter(ClassDocumenter) add_documenter(ExceptionDocumenter) add_documenter(DataDocumenter) add_documenter(FunctionDocumenter) add_documenter(MethodDocumenter) add_documenter(AttributeDocumenter) add_documenter(InstanceAttributeDocumenter) if False: # For type annotation from typing import Any, Callable, Dict, Tuple, List # NOQA from jinja2 import BaseLoader # NOQA from sphinx import addnodes # NOQA from sphinx.builders import Builder # NOQA from sphinx.environment import BuildEnvironment # NOQA
def add_autodocumenter(self, cls): from sphinx.ext import autodoc autodoc.add_documenter(cls) self.add_directive('auto' + cls.objtype, autodoc.AutoDirective)
def make_rst(rootpath, excludes, destdir, header=None, suffix="rst", full=False, author="Author", version="", release="", maxdepth=4, dryrun=False, followlinks=False, includeprivate=False, separatemodules=True, noheadings=False, force=False, notoc=False): """ Make a set of RST files for the modules starting at rootpath """ add_documenter(ModuleDocumenter) add_documenter(ClassDocumenter) add_documenter(ExceptionDocumenter) add_documenter(DataDocumenter) add_documenter(FunctionDocumenter) add_documenter(MethodDocumenter) add_documenter(AttributeDocumenter) add_documenter(InstanceAttributeDocumenter) if header is None: header = path.normpath(rootpath).split(path.sep)[-1] if suffix.startswith('.'): suffix = suffix[1:] if not path.isdir(rootpath): print >>sys.stderr, '%s is not a directory.' % rootpath sys.exit(1) if not path.isdir(destdir): if not dryrun: os.makedirs(destdir) rootpath = path.normpath(path.abspath(rootpath)) excludes = normalize_excludes(rootpath, excludes) modules = recurse_tree(rootpath, excludes, followlinks, includeprivate, separatemodules, noheadings, destdir, dryrun, force, suffix) if full: from sphinx import quickstart as qs modules.sort() prev_module = '' text = '' for module in modules: if module.startswith(prev_module + '.'): continue prev_module = module text += ' %s\n' % module d = dict( path=destdir, sep=False, dot='_', project=header, author=author, version=version, release=release, suffix='.' + suffix, master='index', epub=True, ext_autodoc=True, ext_viewcode=True, makefile=True, batchfile=True, mastertocmaxdepth=maxdepth, mastertoctree=text, ) if not dryrun: qs.generate(d, silent=True, overwrite=force) elif not notoc: create_modules_toc_file(modules, header, maxdepth, destdir, dryrun, force, suffix)
from jinja2 import FileSystemLoader, TemplateNotFound from jinja2.sandbox import SandboxedEnvironment from sphinx import package_dir from sphinx.ext.autosummary import import_by_name, get_documenter from sphinx.jinja2glue import BuiltinTemplateLoader from sphinx.util.osutil import ensuredir from sphinx.util.inspect import safe_getattr # Add documenters to AutoDirective registry from sphinx.ext.autodoc import add_documenter, \ ModuleDocumenter, ClassDocumenter, ExceptionDocumenter, DataDocumenter, \ FunctionDocumenter, MethodDocumenter, AttributeDocumenter, \ InstanceAttributeDocumenter add_documenter(ModuleDocumenter) add_documenter(ClassDocumenter) add_documenter(ExceptionDocumenter) add_documenter(DataDocumenter) add_documenter(FunctionDocumenter) add_documenter(MethodDocumenter) add_documenter(AttributeDocumenter) add_documenter(InstanceAttributeDocumenter) def main(argv=sys.argv): usage = """%prog [OPTIONS] SOURCEFILE ...""" p = optparse.OptionParser(usage.strip()) p.add_option("-o", "--output-dir", action="store",
class TaskDocumenter(autodoc.FunctionDocumenter): objtype = "task" directivetype = "function" @classmethod def can_document_member(cls, member, membername, isattr, parent): from paver.tasks import Task return isinstance(member, Task) def import_object(self): super(TaskDocumenter, self).import_object() obj = self.object self.object = obj.func return True autodoc.add_documenter(TaskDocumenter) # General configuration # --------------------- # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.autodoc'] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The master toctree document.
def setup(app): autodoc.add_documenter(cmdlineFunctionDocumenter)