Python sphinx.errors.SphinxError() Examples

The following are 13 code examples of sphinx.errors.SphinxError(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module sphinx.errors , or try the search function .
Example #1
Source File: test_publicapi.py    From flocker with Apache License 2.0 6 votes vote down vote up
def test_must_be_documented(self):
        """
        If any route doesn't have documentation, then ``SphinxError`` is
        raised.
        """
        app = Klein()

        @app.route(b"/", methods=[b"GET"])
        def dummy_f():
            """
            Developer docs.
            """

        self.assertRaises(
            SphinxError,
            lambda: list(makeRst(b"/prefix", 'section', app, None, {}))) 
Example #2
Source File: functions.py    From sphinxcontrib-needs with MIT License 6 votes vote down vote up
def register_func(need_function):
    """
    Registers a new sphinx-needs function for the given sphinx environment.
    :param env: Sphinx environment
    :param need_function: Python method
    :return: None
    """

    # if not hasattr(env, 'needs_functions'):
    #     env.needs_functions = {}
    global NEEDS_FUNCTIONS
    if NEEDS_FUNCTIONS is None:
        NEEDS_FUNCTIONS = {}

    func_name = need_function.__name__

    # if func_name in env.needs_functions.keys():
    if func_name in NEEDS_FUNCTIONS.keys():
        raise SphinxError('sphinx-needs: Function name {} already registered.'.format(func_name))

    # env.needs_functions[func_name] = {
    NEEDS_FUNCTIONS[func_name] = {
        'name': func_name,
        'function': need_function
    } 
Example #3
Source File: doclets.py    From sphinx-js with MIT License 6 votes vote down vote up
def analyze_jsdoc(abs_source_paths, app):
    command = Command('jsdoc')
    command.add('-X', *abs_source_paths)
    if app.config.jsdoc_config_path:
        command.add('-c', app.config.jsdoc_config_path)

    # Use a temporary file to handle large output volume. JSDoc defaults to
    # utf8-encoded output.
    with getwriter('utf-8')(TemporaryFile(mode='w+b')) as temp:
        try:
            p = subprocess.Popen(command.make(), cwd=app.confdir, stdout=temp)
        except OSError as exc:
            if exc.errno == ENOENT:
                raise SphinxError('%s was not found. Install it using "npm install -g jsdoc".' % command.program)
            else:
                raise
        p.wait()
        # Once output is finished, move back to beginning of file and load it:
        temp.seek(0)
        try:
            return load(temp)
        except ValueError:
            raise SphinxError('jsdoc found no JS files in the directories %s. Make sure js_source_path is set correctly in conf.py. It is also possible (though unlikely) that jsdoc emitted invalid JSON.' % abs_source_paths) 
Example #4
Source File: doclets.py    From sphinx-js with MIT License 6 votes vote down vote up
def analyze_typescript(abs_source_paths, app):
    command = Command('typedoc')
    if app.config.jsdoc_config_path:
        command.add('--tsconfig', app.config.jsdoc_config_path)

    with getwriter('utf-8')(NamedTemporaryFile(mode='w+b')) as temp:
        command.add('--json', temp.name, *abs_source_paths)
        try:
            subprocess.call(command.make())
        except OSError as exc:
            if exc.errno == ENOENT:
                raise SphinxError('%s was not found. Install it using "npm install -g typedoc".' % command.program)
            else:
                raise
        # typedoc emits a valid JSON file even if it finds no TS files in the dir:
        return parse_typedoc(temp) 
Example #5
Source File: doclets.py    From sphinx-js with MIT License 6 votes vote down vote up
def root_or_fallback(root_for_relative_paths, abs_source_paths):
    """Return the path that relative JS entity paths in the docs are relative to.

    Fall back to the sole JS source path if the setting is unspecified.

    :arg root_for_relative_paths: The raw root_for_relative_js_paths setting.
        None if the user hasn't specified it.
    :arg abs_source_paths: Absolute paths of dirs to scan for JS code

    """
    if root_for_relative_paths:
        return abspath(root_for_relative_paths)
    else:
        if len(abs_source_paths) > 1:
            raise SphinxError('Since more than one js_source_path is specified in conf.py, root_for_relative_js_paths must also be specified. This allows paths beginning with ./ or ../ to be unambiguous.')
        else:
            return abs_source_paths[0] 
Example #6
Source File: conf.py    From callee with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def autodoc_process_docstring(app, what, name, obj, options, lines):
    """Handler for the event emitted when autodoc processes a docstring.
    See http://sphinx-doc.org/ext/autodoc.html#event-autodoc-process-docstring.

    The TL;DR is that we can modify ``lines`` in-place to influence the output.
    """
    # check that only symbols that can be directly imported from ``callee``
    # package are being documented
    _, symbol = name.rsplit('.', 1)
    if symbol not in callee.__all__:
        raise SphinxError(
            "autodoc'd '%s' is not a part of the public API!" % name)

    # for classes exempt from automatic merging of class & __init__ docs,
    # pretend their __init__ methods have no docstring at all,
    # so that nothing will be appended to the class's docstring
    if what == 'class' and name in autoclass_content_exceptions:
        # amusingly, when autodoc reads the constructor's docstring
        # for appending it to class docstring, it will report ``what``
        # as 'class' (again!); hence we must check what it actually read
        ctor_docstring_lines = prepare_docstring(obj.__init__.__doc__)
        if lines == ctor_docstring_lines:
            lines[:] = []


# -- Options for intersphinx extension ------------------------------------ 
Example #7
Source File: functions.py    From sphinxcontrib-needs with MIT License 5 votes vote down vote up
def execute_func(env, need, func_string):
    """
    Executes a given function string.
    :param env: Sphinx environment
    :param need: Actual need, which contains the found function string
    :param func_string: string of the found function. Without [[ ]]
    :return: return value of executed function
    """
    global NEEDS_FUNCTIONS
    func_name, func_args, func_kwargs = _analyze_func_string(func_string, need)

    # if func_name not in env.needs_functions.keys():
    if func_name not in NEEDS_FUNCTIONS.keys():
        raise SphinxError('Unknown dynamic sphinx-needs function: {}. Found in need: {}'.format(func_name, need['id']))

    # func = env.needs_functions[func_name]['function']

    func = NEEDS_FUNCTIONS[func_name]['function']
    func_return = func(env, need, env.needs_all_needs, *func_args, **func_kwargs)

    if not isinstance(func_return, (str, int, float, list, unicode)) and func_return is not None:
        raise SphinxError('Return value of function {} is of type {}. Allowed are str, int, float'.format(
            func_name, type(func_return)))

    if isinstance(func_return, list):
        for element in func_return:
            if not isinstance(element, (str, int, float, unicode)):
                raise SphinxError('Element of return list of function {} is of type {}. '
                                  'Allowed are str, int, float'.format(func_name, type(func_return)))
    return func_return 
Example #8
Source File: lean_sphinx.py    From theorem_proving_in_lean with Apache License 2.0 5 votes vote down vote up
def finish(self):
        for root, _, filenames in os.walk(self.outdir):
            for fn in fnmatch.filter(filenames, '*.lean'):
                fn = os.path.join(root, fn)
                if fn not in self.written_files:
                    os.remove(fn)

        proc = subprocess.Popen(['lean', '--make', self.outdir], stdout=subprocess.PIPE)
        stdout, stderr = proc.communicate()
        errors = '\n'.join(l for l in stdout.decode('utf-8').split('\n') if ': error:' in l)
        if errors != '': raise SphinxError('\nlean exited with errors:\n{0}\n'.format(errors))
        retcode = proc.wait()
        if retcode: raise SphinxError('lean exited with error code {0}'.format(retcode)) 
Example #9
Source File: embed_bibtex.py    From openconcept with MIT License 5 votes vote down vote up
def run(self):
        module_path, class_name = self.arguments
        mod = importlib.import_module(module_path)
        obj = getattr(mod, class_name)()

        if not hasattr(obj, 'cite') or not obj.cite:
            raise SphinxError("Couldn't find 'cite' in class '%s'" % class_name)

        return [bibtex_node(text=obj.cite)] 
Example #10
Source File: renderers.py    From sphinx-js with MIT License 5 votes vote down vote up
def rst_nodes(self):
        """Render into RST nodes a thing shaped like a function, having a name
        and arguments.

        Fill in args, docstrings, and info fields from stored JSDoc output.

        """
        try:
            # Get the relevant documentation together:
            doclet, full_path = self._app._sphinxjs_doclets_by_path.get_with_path(self._partial_path)
        except SuffixNotFound as exc:
            raise SphinxError('No JSDoc documentation was found for object "%s" or any path ending with that.'
                              % ''.join(exc.segments))
        except SuffixAmbiguous as exc:
            raise SphinxError('More than one JS object matches the path suffix "%s". Candidate paths have these segments in front: %s'
                              % (''.join(exc.segments), exc.next_possible_keys))
        else:
            rst = self.rst(self._partial_path,
                           full_path,
                           doclet,
                           use_short_name='short-name' in self._options)

            # Parse the RST into docutils nodes with a fresh doc, and return
            # them.
            #
            # Not sure if passing the settings from the "real" doc is the right
            # thing to do here:
            meta = doclet['meta']
            doc = new_document('%s:%s(%s)' % (meta['filename'],
                                              doclet['longname'],
                                              meta['lineno']),
                               settings=self._directive.state.document.settings)
            RstParser().parse(rst, doc)
            return doc.children
        return [] 
Example #11
Source File: doclets.py    From sphinx-js with MIT License 5 votes vote down vote up
def analyzer_for(language):
    """Return a callable that spits out JSDoc-style doclets from some language:
    JS, TypeScript, or other."""
    try:
        return ANALYZERS[language]
    except KeyError:
        raise SphinxError('Unsupported value of js_language in config: %s' % language) 
Example #12
Source File: automembersummary.py    From python-libjuju with Apache License 2.0 4 votes vote down vote up
def run(self):
        module_name = self.arguments[0]

        try:
            module = importlib.import_module(module_name)
        except ImportError:
            raise SphinxError("Unable to generate reference docs for %s, "
                              "could not import" % (module_name))

        divider = '+{:-<80}+'.format('')
        row = '| {:<78} |'.format
        lines = []
        for member_name, member in inspect.getmembers(module):
            if not self._filter(module_name, member_name, member):
                continue
            summary = textwrap.wrap(self._get_summary(member), 78) or ['']
            link = '`{} <#{}>`_'.format(member_name,
                                        '.'.join([module_name,
                                                  member_name]))
            methods = ['* `{} <#{}>`_'.format(n,
                                              '.'.join([module_name,
                                                        member_name,
                                                        n]))
                       for n, m in inspect.getmembers(member)
                       if not n.startswith('_') and inspect.isfunction(m)]

            lines.append(divider)
            lines.append(row(link))
            lines.append(divider)
            for line in summary:
                lines.append(row(line))
            if methods:
                lines.append(row(''))
                lines.append(row('Methods:'))
                lines.append(row(''))
                for i, method in enumerate(methods):
                    lines.append(row(method))
        lines.append(divider)
        content = '\n'.join(lines)

        result = self._parse(content, '<automembersummary>')
        return result 
Example #13
Source File: embed_shell_cmd.py    From openconcept with MIT License 4 votes vote down vote up
def run(self):
        """
        Create a list of document nodes to return.
        """
        if 'cmd' in self.options:
            cmdstr = self.options['cmd']
            cmd = cmdstr.split()
        else:
            raise SphinxError("'cmd' is not defined for "
                                            "embed-shell-cmd.")

        startdir = os.getcwd()

        if 'dir' in self.options:
            workdir = os.path.abspath(os.path.expandvars(os.path.expanduser(self.options['dir'])))
        else:
            workdir = os.getcwd()

        if 'stderr' in self.options:
            stderr = subprocess.STDOUT
        else:
            stderr = None

        os.chdir(workdir)

        try:
            output = subprocess.check_output(cmd, stderr=stderr).decode('utf-8', 'ignore')
        except subprocess.CalledProcessError as err:
            raise SphinxError("Running of embedded shell command '{}' in docs failed. "
                              "Output was: \n{}".format(cmdstr, err.output.decode('utf-8')))
        finally:
            os.chdir(startdir)

        output = cgiesc.escape(output)

        show = True
        if 'show_cmd' in self.options:
            show = self.options['show_cmd'].lower().strip() == 'true'

        if show:
            input_node = nodes.literal_block(cmdstr, cmdstr)
            input_node['language'] = 'none'

        output_node = cmd_node(text=output)

        if show:
            return [input_node, output_node]
        else:
            return [output_node]