def __init__(self, space_name):
     SphinxError.__init__(self,
         """---\n"""
         """The configured Confluence space does not appear to be """
         """valid: %s\n""" % space_name +
         """---\n"""
     )
 def __init__(self):
     SphinxError.__init__(self,
         """---\n"""
         """Your Confluence server is too old. Need at least Confluence """
         """v4.0 or higher.\n"""
         """---\n"""
     )
Example #3
0
 def __init__(self, msg, stderr=None, stdout=None):
     # type: (unicode, unicode, unicode) -> None
     if stderr:
         msg += '\n[stderr]\n' + stderr.decode(sys_encoding, 'replace')
     if stdout:
         msg += '\n[stdout]\n' + stdout.decode(sys_encoding, 'replace')
     SphinxError.__init__(self, msg)
 def __init__(self, details):
     SphinxError.__init__(self,
         """---\n"""
         """An unsupported Confluence API call has been made.\n"""
         """\n"""
         """%s""" % details +
         """\n---\n"""
     )
 def __init__(self, details):
     SphinxError.__init__(self,
         """---\n"""
         """Do not have permission for this action on the Confluence """
         """server.\n\n"""
         """%s\n""" % details +
         """---\n"""
     )
 def __init__(self):
     SphinxError.__init__(self,
         """---\n"""
         """Unable to authenticate with the proxy server.\n"""
         """\n"""
         """Ensure your proxy's username and password are correct.\n"""
         """---\n"""
     )
 def __init__(self, ex):
     SphinxError.__init__(self,
         """---\n"""
         """An SSL issue has been detected when trying to load the """
         """the certificates provided.\n"""
         """details: %s\n""" % ex +
         """---\n"""
     )
 def __init__(self):
     SphinxError.__init__(self,
         """---\n"""
         """Unable to authenticate with the Confluence server.\n"""
         """\n"""
         """Ensure your username and password are correct. If your """
         """username and password is correct, you may need to unlock """
         """your Confluence account be re-logging in with your browser """
         """or asking your Confluence administrator for help.\n"""
         """---\n"""
     )
 def __init__(self, server_url):
     SphinxError.__init__(self,
         """---\n"""
         """A request to communicate with the Confluence server has """
         """timed out.\n"""
         """\n"""
         """Ensure the server is running or your Confluence server URL """
         """is valid:\n\n"""
         """    %s\n""" % server_url +
         """---\n"""
     )
 def __init__(self):
     SphinxError.__init__(self,
         """---\n"""
         """Unable to authenticate with the Confluence server.\n"""
         """\n"""
         """While this could be your username or password being """
         """incorrect, this plugin as detected that the Atlassian """
         """Seraph instance has logged you out. This could be a """
         """result of a server-related issue. If this persisted, """
         """try contacting your Confluence administrator for help.\n"""
         """---\n"""
     )
 def __init__(self, server_url, ex):
     SphinxError.__init__(self,
         """---\n"""
         """An issue has been detected when trying to communicate with """
         """Confluence server.\n"""
         """\n"""
         """Ensure the server is running or your Confluence server URL """
         """is valid:\n\n"""
         """    %s\n""" % server_url +
         """\n(details: %s""" % ex +
         """)\n"""
         """---\n"""
     )
 def __init__(self, server_url):
     SphinxError.__init__(self,
         """---\n"""
         """Confluence Remote API appears to be disabled.\n"""
         """\n"""
         """First, ensure the server is running or your Confluence """
         """server URL is valid:\n\n"""
         """    %s\n""" % server_url +
         """\n"""
         """If you are sure your server URL is correct, you will need """
         """to ask your Confluence administrator to enable """
         """'Remote API (XML-RPC & SOAP)'.\n"""
         """---\n"""
     )
Example #13
0
    def init(self):
        # type: () -> None
        super(AppleHelpBuilder, self).init()
        # the output files for HTML help must be .html only
        self.out_suffix = '.html'
        self.link_suffix = '.html'

        if self.config.applehelp_bundle_id is None:
            raise SphinxError('You must set applehelp_bundle_id before '
                              'building Apple Help output')

        self.bundle_path = path.join(self.outdir,
                                     self.config.applehelp_bundle_name +
                                     '.help')
        self.outdir = path.join(self.bundle_path,
                                'Contents',
                                'Resources',
                                self.config.applehelp_locale + '.lproj')
Example #14
0
def html_visit_bokeh_palette_group(self, node):
    self.body.append(CSS)
    self.body.append('<div class="container-fluid"><div class="row">"')
    group = getattr(bp, node['group'], None)
    if not isinstance(group, dict):
        raise SphinxError("invalid palette group name %r" % node['group'])
    names = sorted(group)
    for name in names:
        palettes = group[name]
        # arbitrary cuttoff here, idea is to not show large (e.g 256 length) palettes
        numbers = [x for x in sorted(palettes) if x < 30]
        html = PALETTE_GROUP_DETAIL.render(name=name,
                                           numbers=numbers,
                                           palettes=palettes)
        self.body.append(html)
    self.body.append('</div></div>')
    self.body.append(JS)
    raise nodes.SkipNode
Example #15
0
 def copy_image_files(self) -> None:
     if self.images:
         stringify_func = ImageAdapter(self.app.env).get_original_image_uri
         for src in status_iterator(self.images, __('copying images... '), "brown",
                                    len(self.images), self.app.verbosity,
                                    stringify_func=stringify_func):
             dest = self.images[src]
             try:
                 copy_asset_file(path.join(self.srcdir, src),
                                 path.join(self.outdir, dest))
             except Exception as err:
                 logger.warning(__('cannot copy image file %r: %s'),
                                path.join(self.srcdir, src), err)
     if self.config.latex_logo:
         if not path.isfile(path.join(self.confdir, self.config.latex_logo)):
             raise SphinxError(__('logo file %r does not exist') % self.config.latex_logo)
         else:
             copy_asset_file(path.join(self.confdir, self.config.latex_logo), self.outdir)
Example #16
0
def get_image_filename_for_language(filename, env):
    # type: (unicode, BuildEnvironment) -> unicode
    if not env.config.language:
        return filename

    filename_format = env.config.figure_language_filename
    d = dict()
    d['root'], d['ext'] = path.splitext(filename)
    dirname = path.dirname(d['root'])
    if dirname and not dirname.endswith(path.sep):
        dirname += path.sep
    d['path'] = dirname
    d['basename'] = path.basename(d['root'])
    d['language'] = env.config.language
    try:
        return filename_format.format(**d)
    except KeyError as exc:
        raise SphinxError('Invalid figure_language_filename: %r' % exc)
Example #17
0
    def set_versioning_method(self, method, compare):
        # type: (unicode, bool) -> None
        """This sets the doctree versioning method for this environment.

        Versioning methods are a builder property; only builders with the same
        versioning method can share the same doctree directory.  Therefore, we
        raise an exception if the user tries to use an environment with an
        incompatible versioning method.
        """
        if method not in versioning_conditions:
            raise ValueError('invalid versioning method: %r' % method)
        condition = versioning_conditions[method]
        if self.versioning_condition not in (None, condition):
            raise SphinxError('This environment is incompatible with the '
                              'selected builder, please choose another '
                              'doctree directory.')
        self.versioning_condition = condition
        self.versioning_compare = compare
Example #18
0
    def run(self):
        env = self.state.document.settings.env

        docdir = dirname(env.doc2path(env.docname))

        gallery_file = join(docdir, self.arguments[0])

        gallery_dir = join(dirname(dirname(gallery_file)), "gallery")
        if not exists(gallery_dir) and isdir(gallery_dir):
            raise SphinxError("gallery dir %r missing for gallery file %r" %
                              (gallery_dir, gallery_file))

        spec = json.load(open(gallery_file))
        names = [detail['name'] for detail in spec['details']]

        rst_text = GALLERY_PAGE.render(names=names)

        return self._parse(rst_text, "<bokeh-gallery>")
Example #19
0
    def copy_support_files(self) -> None:
        """copy TeX support files from texinputs."""
        # configure usage of xindy (impacts Makefile and latexmkrc)
        # FIXME: convert this rather to a confval with suitable default
        #        according to language ? but would require extra documentation
        if self.config.language:
            xindy_lang_option = \
                XINDY_LANG_OPTIONS.get(self.config.language[:2],
                                       '-L general -C utf8 ')
            xindy_cyrillic = self.config.language[:2] in XINDY_CYRILLIC_SCRIPTS
        else:
            xindy_lang_option = '-L english -C utf8 '
            xindy_cyrillic = False
        context = {
            'latex_engine': self.config.latex_engine,
            'xindy_use': self.config.latex_use_xindy,
            'xindy_lang_option': xindy_lang_option,
            'xindy_cyrillic': xindy_cyrillic,
        }
        logger.info(bold(__('copying TeX support files...')))
        staticdirname = path.join(package_dir, 'texinputs')
        for filename in os.listdir(staticdirname):
            if not filename.startswith('.'):
                copy_asset_file(path.join(staticdirname, filename),
                                self.outdir,
                                context=context)

        # use pre-1.6.x Makefile for make latexpdf on Windows
        if os.name == 'nt':
            staticdirname = path.join(package_dir, 'texinputs_win')
            copy_asset_file(path.join(staticdirname, 'Makefile_t'),
                            self.outdir,
                            context=context)

        # the logo is handled differently
        if self.config.latex_logo:
            if not path.isfile(path.join(self.confdir,
                                         self.config.latex_logo)):
                raise SphinxError(
                    __('logo file %r does not exist') % self.config.latex_logo)
            else:
                copy_asset_file(
                    path.join(self.confdir, self.config.latex_logo),
                    self.outdir)
Example #20
0
def build_finished(app, exception):
    files = set()

    for (script, js, js_path, source) in app.env.bokeh_plot_files.values():
        files.add(js_path)

    files_iter = app.status_iterator(sorted(files),
                                     'copying bokeh-plot files... ',
                                     console.brown, len(files),
                                     lambda x: basename(x))

    for file in files_iter:
        target = join(app.builder.outdir, "scripts", basename(file))
        ensuredir(dirname(target))
        try:
            copyfile(file, target)
        except OSError as e:
            raise SphinxError('cannot copy local file %r, reason: %s' %
                              (file, e))
    def get_js_source(self):
        env = self.state.document.settings.env
        js_file = self.options.get("js_file", False)
        # js_file *or* js code content, but not both
        if js_file and self.content:
            raise SphinxError("bokehjs-content:: directive can't have both js_file and content")

        if js_file:
            log.debug("[bokehjs-content] handling external example in %r: %s", env.docname, js_file)
            path = js_file
            if not js_file.startswith("/"):
                path = join(env.app.srcdir, path)
            js_source = decode_utf8(open(path).read())
        else:
            log.debug("[bokehjs-content] handling inline example in %r", env.docname)
            path = env.bokeh_plot_auxdir  # code runner just needs any real path
            js_source = '\n'.join(self.content)

        return js_source
def build_finished(app, exception):
    ''' Generate a ``sitemap.txt`` from the collected HTML page links.

    '''
    filename = join(app.outdir, "sitemap.xml")

    links_iter = status_iterator(sorted(app.sitemap_links),
                                 'adding links to sitemap... ', 'brown',
                                 len(app.sitemap_links), app.verbosity)

    try:
        with open(filename, 'w') as f:
            f.write(_header)
            for link in links_iter:
                f.write(_item %
                        escape(link.strip().replace("https://", "http://")))
            f.write(_footer)
    except OSError as e:
        raise SphinxError('cannot write sitemap.txt, reason: %s' % e)
Example #23
0
def join_keys(lang1, key1, lang2, key2):
    if key1 == key2 or key2 == '':
        return key1
    SEP = ('_', '-')
    k = ""
    l2 = len(key2)
    for i, c in enumerate(key1):
        if i < l2 and c == key2[i]:
            if not c in SEP or k == "" or k[-1] != c:
                k += c
    if not k or k in SEP:
        raise SphinxError(
            "Corresponding RST file names must match in multilingual courses:\n"
            + key1 + "\n" + key2)
    if k[-1] in SEP:
        k = k[:-1]
    if k[0] in SEP:
        k = k[1:]
    return k
Example #24
0
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]
    def add_feedback(self, node, data, paragraph):
        if not paragraph:
            return

        # Add feedback node for rendering without writing to file.
        data['feedback'] = ('#!children', 'feedback')
        feedbacks = aplus_nodes.html('p', {'class':'feedback-holder'}, no_write=True)

        for i,line in slicer(paragraph):
            if not '§' in line[0]:
                raise SphinxError('Feedback separator § exptected: {}'.format(line[0]))
            value,content = line[0].split('§', 1)
            value = value.strip()
            line[0] = content.strip()
            isnot = False
            compare_regexp = False
            if value.startswith('!'):
                isnot = True
                value = value[1:]
            if value.startswith('regexp:'):
                compare_regexp = True
                value = value[7:]

            # Create document elements.
            hint = aplus_nodes.html('div')
            text = aplus_nodes.html('p', {})
            text.store_html('hint')
            nested_parse_with_titles(self.state, line, text)
            hint.append(text)
            feedbacks.append(hint)

            # Add configuration data.
            fbdata = {
                'value': value,
                'label': ('#!html', 'hint'),
            }
            if isnot:
                fbdata['not'] = True
            if compare_regexp:
                fbdata['compare_regexp'] = True
            hint.set_yaml(fbdata, 'feedback')

        node.append(feedbacks)
Example #26
0
def _process_script(source, filename, env, js_name, use_relative_paths=False):
    # This is lame, but seems to be required for python 2
    source = CODING.sub("", source)

    # Explicitly make sure old extensions are not included until a better
    # automatic mechanism is available
    Model._clear_extensions()

    # quick and dirty way to inject Google API key
    if "GOOGLE_API_KEY" in source:
        GOOGLE_API_KEY = getenv('GOOGLE_API_KEY')
        if GOOGLE_API_KEY is None:
            if env.config.bokeh_missing_google_api_key_ok:
                GOOGLE_API_KEY = "MISSING_API_KEY"
            else:
                raise SphinxError(
                    "The GOOGLE_API_KEY environment variable is not set. Set GOOGLE_API_KEY to a valid API key, "
                    "or set bokeh_missing_google_api_key_ok=True in conf.py to build anyway (with broken GMaps)"
                )
        run_source = source.replace("GOOGLE_API_KEY", GOOGLE_API_KEY)
    else:
        run_source = source

    c = ExampleHandler(source=run_source, filename=filename)
    d = Document()
    c.modify_document(d)
    if c.error:
        raise PlotScriptError(c.error_detail)

    script_path = None
    if (use_relative_paths):
        script_path = join("$REL_PATH$", js_name)
    else:
        script_path = join("/scripts", js_name)

    js_path = join(env.bokeh_plot_auxdir, js_name)
    js, script = autoload_static(d.roots[0], resources, script_path)

    with open(js_path, "w") as f:
        f.write(js)

    return (script, js, js_path, source)
Example #27
0
def _process_script(source, filename, env, js_name, use_relative_paths=False):
    # Explicitly make sure old extensions are not included until a better
    # automatic mechanism is available
    Model._clear_extensions()

    # quick and dirty way to inject Google API key
    if "GOOGLE_API_KEY" in source:
        GOOGLE_API_KEY = getenv("GOOGLE_API_KEY")
        if GOOGLE_API_KEY is None:
            if env.config.bokeh_missing_google_api_key_ok:
                GOOGLE_API_KEY = "MISSING_API_KEY"
            else:
                raise SphinxError(
                    "The GOOGLE_API_KEY environment variable is not set. Set GOOGLE_API_KEY to a valid API key, "
                    "or set bokeh_missing_google_api_key_ok=True in conf.py to build anyway (with broken GMaps)"
                )
        run_source = source.replace("GOOGLE_API_KEY", GOOGLE_API_KEY)
    else:
        run_source = source

    c = ExampleHandler(source=run_source, filename=filename)
    d = Document()

    # We may need to instantiate deprecated objects as part of documenting
    # them in the reference guide. Suppress any warnings here to keep the
    # docs build clean just for this case
    with warnings.catch_warnings():
        if "reference" in env.docname:
            warnings.filterwarnings("ignore", category=BokehDeprecationWarning)
        c.modify_document(d)

    if c.error:
        raise RuntimeError(c.error_detail)

    resources = get_sphinx_resources()
    js_path = join(env.bokeh_plot_auxdir, js_name)
    js, script = autoload_static(d.roots[0], resources, js_name)

    with open(js_path, "w") as f:
        f.write(js)

    return (script, js, js_path, source)
Example #28
0
    def __init__(self, versions, context):
        """Initialize a versions list.

        :param list versions: List with mixture of of strings or dictionaries with keys ``id`` and ``name``.
        :param dict context: Jinja2 HTML context.
        """
        self._versions = []
        for v in versions:
            try:
                v.items()
                _v = Version(**v)
            except TypeError as exc:
                raise SphinxError(
                    "Version dictionary is malformed (must have keys `id` and `name`: %s\n%s\n"
                    % (str(v), str(exc)))
            except AttributeError:
                # it's a string
                _v = Version(v, v)
            self._versions.append(_v)
        self._context = context
Example #29
0
def get_image_filename_for_language(filename: str,
                                    env: "BuildEnvironment") -> str:
    filename_format = env.config.figure_language_filename
    d = dict()
    d['root'], d['ext'] = path.splitext(filename)
    dirname = path.dirname(d['root'])
    if dirname and not dirname.endswith(path.sep):
        dirname += path.sep
    docpath = path.dirname(env.docname)
    if docpath and not docpath.endswith(path.sep):
        docpath += path.sep
    d['path'] = dirname
    d['basename'] = path.basename(d['root'])
    d['docpath'] = docpath
    d['language'] = env.config.language
    try:
        return filename_format.format(**d)
    except KeyError as exc:
        raise SphinxError('Invalid figure_language_filename: %r' %
                          exc) from exc
Example #30
0
def build_finished(app, exception):
    files = set()

    for (script, js, js_path, source, docpath) in app.env.bokeh_plot_files.values():
        files.add((js_path, docpath))

    files_iter = status_iterator(sorted(files),
                                 'copying bokeh-plot files... ',
                                 'brown',
                                 len(files),
                                 app.verbosity,
                                 stringify_func=lambda x: basename(x[0]))

    for (file, docpath) in files_iter:
        target = join(app.builder.outdir, docpath, basename(file))
        ensuredir(dirname(target))
        try:
            copyfile(file, target)
        except OSError as e:
            raise SphinxError('cannot copy local file %r, reason: %s' % (file, e))
Example #31
0
def typedoc_output(abs_source_paths, sphinx_conf_dir, config_path):
    """Return the loaded JSON output of the TypeDoc command run over the given
    paths."""
    command = Command('typedoc')
    if config_path:
        command.add('--tsconfig', normpath(join(sphinx_conf_dir, config_path)))

    with 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 load(getreader('utf-8')(temp))
Example #32
0
    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 #33
0
def analyze_typescript(abs_source_paths, app):
    command = doclets.Command('typedoc')
    if app.config.jsdoc_config_path:
        command.add('--tsconfig', app.config.jsdoc_config_path)

    json_path = '../docs/mico-admin/ts/typedoc.json'

    source = abs_source_paths[0]
    command.add('--exclude', '**/node_modules/**/*.*', '--json', json_path, '--ignoreCompilerErrors', *abs_source_paths)
    if not on_rtd:
        # only build typedoc json locally as readthedocs build container does not
        # support it natively (and typedoc process takes a while to finish)
        try:
            subprocess.call(command.make(), cwd=source)
            with open(json_path) as typedoc_json:
                typedoc = load(typedoc_json)

            def clean_paths(typedoc):
                """Make all paths relative to not leak path info to github."""
                if not isinstance(typedoc, dict):
                    return
                for key in typedoc:
                    if isinstance(typedoc[key], dict):
                        clean_paths(typedoc[key])
                    if isinstance(typedoc[key], list):
                        for entry in typedoc[key]:
                            clean_paths(entry)
                    if key == 'originalName':
                        filepath = typedoc[key]
                        typedoc[key] = relpath(filepath)
            clean_paths(typedoc)
            with open(json_path, mode='w') as typedoc_json:
                dump(typedoc, typedoc_json)
        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:
    with open('mico-admin/ts/typedoc.json') as temp:
        return doclets.parse_typedoc(temp)
Example #34
0
    def __call__(self, name: str, rawtext: str, text: str, lineno: int,
                 inliner: Inliner, options: Dict = {}, content: List[str] = []
                 ) -> Tuple[List[Node], List[system_message]]:
        self.rawtext = rawtext
        self.text = unescape(text)
        self.lineno = lineno
        self.inliner = inliner
        self.options = options
        self.content = content

        # guess role type
        if name:
            self.name = name.lower()
        else:
            self.name = self.env.temp_data.get('default_role')
            if not self.name:
                self.name = self.env.config.default_role
            if not self.name:
                raise SphinxError('cannot determine default role!')

        return self.run()
Example #35
0
def analyze(app):
    """Run JSDoc or another analysis tool across a whole codebase, and squirrel
    away its results in a language-specific Analyzer."""
    # Normalize config values:
    source_paths = [app.config.js_source_path] if isinstance(app.config.js_source_path, str) else app.config.js_source_path
    abs_source_paths = [normpath(join(app.confdir, path)) for path in source_paths]
    root_for_relative_paths = root_or_fallback(
        normpath(join(app.confdir, app.config.root_for_relative_js_paths)) if app.config.root_for_relative_js_paths else None,
        abs_source_paths)

    # Pick analyzer:
    try:
        analyzer = {'javascript': JsAnalyzer,
                    'typescript': TsAnalyzer}[app.config.js_language]
    except KeyError:
        raise SphinxError('Unsupported value of js_language in config: %s' % app.config.js_language)

    # Analyze source code:
    app._sphinxjs_analyzer = analyzer.from_disk(abs_source_paths,
                                                app,
                                                root_for_relative_paths)
Example #36
0
def prepare_env(app, env, docname):
    """
    Prepares the sphinx environment to store sphinx-needs internal data.
    """
    if not hasattr(env, 'needs_all_needs'):
        # Used to store all needed information about all needs in document
        env.needs_all_needs = {}

    if not hasattr(env, 'needs_functions'):
        # Used to store all registered functions for supporting dynamic need values.
        env.needs_functions = {}

        # needs_functions = getattr(app.config, 'needs_functions', [])
        needs_functions = app.needs_functions
        if needs_functions is None:
            needs_functions = []
        if not isinstance(needs_functions, list):
            raise SphinxError(
                'Config parameter needs_functions must be a list!')

        # Register built-in functions
        for need_common_func in needs_common_functions:
            register_func(env, need_common_func)

        # Register functions configured by user
        for needs_func in needs_functions:
            register_func(env, needs_func)

    app.config.needs_hide_options += ['hidden']
    app.config.needs_extra_options['hidden'] = directives.unchanged

    if not hasattr(env, 'needs_workflow'):
        # Used to store workflow status information for already executed tasks.
        # Some tasks like backlink_creation need be be performed only once.
        # But most sphinx-events get called several times (for each single document file), which would also
        # execute our code several times...
        env.needs_workflow = {
            'backlink_creation': False,
            'dynamic_values_resolved': False
        }
Example #37
0
    def finish(self):
        # type: () -> None
        self.copy_image_files()

        # copy TeX support files from texinputs
        context = {'latex_engine': self.config.latex_engine}
        logger.info(bold(__('copying TeX support files...')))
        staticdirname = path.join(package_dir, 'texinputs')
        for filename in os.listdir(staticdirname):
            if not filename.startswith('.'):
                copy_asset_file(path.join(staticdirname, filename),
                                self.outdir,
                                context=context)

        # use pre-1.6.x Makefile for make latexpdf on Windows
        if os.name == 'nt':
            staticdirname = path.join(package_dir, 'texinputs_win')
            copy_asset_file(path.join(staticdirname, 'Makefile_t'),
                            self.outdir,
                            context=context)

        # copy additional files
        if self.config.latex_additional_files:
            logger.info(bold(__('copying additional files...')), nonl=1)
            for filename in self.config.latex_additional_files:
                logger.info(' ' + filename, nonl=1)
                copy_asset_file(path.join(self.confdir, filename), self.outdir)
            logger.info('')

        # the logo is handled differently
        if self.config.latex_logo:
            if not path.isfile(path.join(self.confdir,
                                         self.config.latex_logo)):
                raise SphinxError(
                    __('logo file %r does not exist') % self.config.latex_logo)
            else:
                copy_asset_file(
                    path.join(self.confdir, self.config.latex_logo),
                    self.outdir)
        logger.info(__('done'))
Example #38
0
    def finish(self):
        # type: () -> None
        # copy image files
        if self.images:
            self.info(bold('copying images...'), nonl=1)
            for src, dest in iteritems(self.images):
                self.info(' ' + src, nonl=1)
                copy_asset_file(path.join(self.srcdir, src),
                                path.join(self.outdir, dest))
            self.info()

        # copy TeX support files from texinputs
        context = {'latex_engine': self.config.latex_engine}
        self.info(bold('copying TeX support files...'))
        staticdirname = path.join(package_dir, 'texinputs')
        for filename in os.listdir(staticdirname):
            if not filename.startswith('.'):
                copy_asset_file(path.join(staticdirname, filename),
                                self.outdir,
                                context=context)

        # copy additional files
        if self.config.latex_additional_files:
            self.info(bold('copying additional files...'), nonl=1)
            for filename in self.config.latex_additional_files:
                self.info(' ' + filename, nonl=1)
                copy_asset_file(path.join(self.confdir, filename), self.outdir)
            self.info()

        # the logo is handled differently
        if self.config.latex_logo:
            if not path.isfile(path.join(self.confdir,
                                         self.config.latex_logo)):
                raise SphinxError('logo file %r does not exist' %
                                  self.config.latex_logo)
            else:
                copy_asset_file(
                    path.join(self.confdir, self.config.latex_logo),
                    self.outdir)
        self.info('done')
Example #39
0
    def run(self) -> List[Node]:
        ncolumns = self.options.get('columns', 2)
        node = addnodes.compact_paragraph()
        node.document = self.state.document
        self.state.nested_parse(self.content, self.content_offset, node)
        if len(node.children) != 1 or not isinstance(node.children[0],
                                                     nodes.bullet_list):
            reporter = self.state.document.reporter
            raise SphinxError('table_from_list content is not a list')
        fulllist = node.children[0]

        # fill list with empty items to have a number of entries
        # that is divisible by ncolumns
        if (len(fulllist) % ncolumns) != 0:
            missing = int(ncolumns - (len(fulllist) % ncolumns))
            for i in range(0, missing):
                fulllist += list_item()

        table = nodes.table()
        tgroup = nodes.tgroup(cols=ncolumns)
        table += tgroup

        for i in range(ncolumns):
            tgroup += nodes.colspec(colwidth=1)

        tbody = nodes.tbody()
        tgroup += tbody
        current_row = nodes.row()

        for idx, cell in enumerate(fulllist.children):
            if len(current_row.children) == ncolumns:
                tbody += current_row
                current_row = nodes.row()
            entry = nodes.entry()
            current_row += entry
            if len(cell.children) > 0:
                entry += cell.children[0]

        tbody += current_row
        return [table]
Example #40
0
def build_finished(app, exception):
    import renderdoc as rd
    import qrenderdoc as qrd

    from sphinx.domains.python import PythonDomain
    from sphinx.errors import SphinxError

    if exception is not None:
        return

    print(rd)
    print(qrd)

    # Get list of documented/indexed python objects
    pydomain = app.env.get_domain('py')
    if not hasattr(pydomain, 'objects'):
        print("WARNING: Sphinx version is too old to check objects validity. Upgrade to at least Sphinx 2.1.0")
        return
    objs = pydomain.objects

    # Enumerate the namespaced objects in both modules
    items = []
    for module_name in ['renderdoc', 'qrenderdoc']:
        module = sys.modules[module_name]
        entries = dir(module)
        for item in dir(module):
            if 'INTERNAL:' not in str(module.__dict__[item].__doc__):
                items.append('{}.{}'.format(module_name, item))

    items = set(filter(lambda i: re.search('__|SWIG|ResourceId_Null|rdcfixedarray_of|rdcarray_of|Structured.*List', i) is None, items))

    # Remove any documented/indexed python objects
    items -= set(objs.keys())

    # Print an error if any remain
    if len(items) > 0:
        items = sorted(list(items))
        raise SphinxError("These {} global classes/functions are not included in the documentation index:\n* {}".format(len(items), '\n* '.join(items)))

    print("All python objects are linked in the documentation.")
Example #41
0
def register_func(env, 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 = {}

    func_name = need_function.__name__

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

    env.needs_functions[func_name] = {
        'name': func_name,
        'function': need_function
    }
Example #42
0
    def finish(self):
        # copy image files
        if self.images:
            self.info(bold('copying images...'), nonl=1)
            for src, dest in iteritems(self.images):
                self.info(' ' + src, nonl=1)
                copyfile(path.join(self.srcdir, src),
                         path.join(self.outdir, dest))
            self.info()

        # copy TeX support files from texinputs
        self.info(bold('copying TeX support files...'))
        staticdirname = path.join(package_dir, 'texinputs')
        for filename in os.listdir(staticdirname):
            if not filename.startswith('.'):
                copyfile(path.join(staticdirname, filename),
                         path.join(self.outdir, filename))

        # copy additional files
        if self.config.latex_additional_files:
            self.info(bold('copying additional files...'), nonl=1)
            for filename in self.config.latex_additional_files:
                self.info(' ' + filename, nonl=1)
                copyfile(path.join(self.confdir, filename),
                         path.join(self.outdir, path.basename(filename)))
            self.info()

        # the logo is handled differently
        if self.config.latex_logo:
            logobase = path.basename(self.config.latex_logo)
            logotarget = path.join(self.outdir, logobase)
            if not path.isfile(path.join(self.confdir,
                                         self.config.latex_logo)):
                raise SphinxError('logo file %r does not exist' %
                                  self.config.latex_logo)
            elif not path.isfile(logotarget):
                copyfile(path.join(self.confdir, self.config.latex_logo),
                         logotarget)
        self.info('done')
Example #43
0
 def __init__(self, msg, stderr=None, stdout=None):
     if stderr:
         msg += "\n[stderr]\n" + stderr.decode(sys_encoding, "replace")
     if stdout:
         msg += "\n[stdout]\n" + stdout.decode(sys_encoding, "replace")
     SphinxError.__init__(self, msg)
Example #44
0
 def __init__(self, msg, stderr=None, stdout=None):
     if stderr:
         msg += '\n[stderr]\n' + stderr
     if stdout:
         msg += '\n[stdout]\n' + stdout
     SphinxError.__init__(self, msg)