Пример #1
0
def test_quickstart_all_answers(tempdir):
    answers = {
        'Root path': tempdir,
        'Separate source and build': 'y',
        'Name prefix for templates': '.',
        'Project name': u'STASI™'.encode('utf-8'),
        'Author name': u'Wolfgang Schäuble & G\'Beckstein'.encode('utf-8'),
        'Project version': '2.0',
        'Project release': '2.0.1',
        'Source file suffix': '.txt',
        'Name of your master document': 'contents',
        'autodoc': 'y',
        'doctest': 'yes',
        'intersphinx': 'no',
        'todo': 'n',
        'coverage': 'no',
        'pngmath': 'N',
        'mathjax': 'no',
        'ifconfig': 'no',
        'viewcode': 'no',
        'Create Makefile': 'no',
        'Create Windows command file': 'no',
        'Do you want to use the epub builder': 'yes',
    }
    qs.term_input = mock_raw_input(answers, needanswer=True)
    qs.TERM_ENCODING = 'utf-8'
    d = {}
    qs.ask_user(d)
    qs.generate(d)

    conffile = tempdir / 'source' / 'conf.py'
    assert conffile.isfile()
    ns = {}
    execfile_(conffile, ns)
    assert ns['extensions'] == ['sphinx.ext.autodoc', 'sphinx.ext.doctest']
    assert ns['templates_path'] == ['.templates']
    assert ns['source_suffix'] == '.txt'
    assert ns['master_doc'] == 'contents'
    assert ns['project'] == u'STASI™'
    assert ns['copyright'] == u'%s, Wolfgang Schäuble & G\'Beckstein' % \
           time.strftime('%Y')
    assert ns['version'] == '2.0'
    assert ns['release'] == '2.0.1'
    assert ns['html_static_path'] == ['.static']
    assert ns['latex_documents'] == [
        ('contents', 'STASI.tex', u'STASI™ Documentation',
         u'Wolfgang Schäuble \\& G\'Beckstein', 'manual')]
    assert ns['epub_author'] == u'Wolfgang Schäuble & G\'Beckstein'
    assert ns['man_pages'] == [
        ('contents', 'stasi', u'STASI™ Documentation',
         [u'Wolfgang Schäuble & G\'Beckstein'], 1)]
    assert ns['texinfo_documents'] == [
        ('contents', 'STASI', u'STASI™ Documentation',
         u'Wolfgang Schäuble & G\'Beckstein', 'STASI',
         'One line description of project.', 'Miscellaneous'),]

    assert (tempdir / 'build').isdir()
    assert (tempdir / 'source' / '.static').isdir()
    assert (tempdir / 'source' / '.templates').isdir()
    assert (tempdir / 'source' / 'contents.txt').isfile()
Пример #2
0
 def __init__(self, dirname, filename, overrides, tags):
     self.overrides = overrides
     self.values = Config.config_values.copy()
     config = {}
     if dirname is not None:
         config_file = path.join(dirname, filename)
         config['__file__'] = config_file
         config['tags'] = tags
         with cd(dirname):
             # we promise to have the config dir as current dir while the
             # config file is executed
             try:
                 execfile_(filename, config)
             except SyntaxError as err:
                 raise ConfigError(CONFIG_SYNTAX_ERROR % err)
             except SystemExit:
                 raise ConfigError(CONFIG_EXIT_ERROR)
     # override extensions after loading the configuration (otherwise it's pointless...)
     if 'extensions' in overrides:
         if isinstance(overrides['extensions'], string_types):
             config['extensions'] = overrides.pop('extensions').split(',')
         else:
             config['extensions'] = overrides.pop('extensions')
     self._raw_config = config
     # these two must be preinitialized because extensions can add their
     # own config values
     self.setup = config.get('setup', None)
     self.extensions = config.get('extensions', [])
Пример #3
0
    def test_hieroglyph_quickstart(self):
        tempdir = tempfile.mkdtemp()

        answers = {
            'Root path': tempdir,
            'Author name(s)': 'Marcia Brady',
            'Presentation title': 'Hieroglyph Test',
        }
        sphinx_quickstart.term_input = mock_input(answers)
        quickstart.quickstart(path=tempdir)

        conffile = os.path.join(tempdir, 'conf.py')
        assert os.path.exists(conffile)
        ns = {}
        execfile_(conffile, ns)

        self.assertIn('hieroglyph', ns['extensions'])
        self.assertEqual(ns['templates_path'], ['_templates'])
        self.assertEqual(ns['source_suffix'], '.rst')
        self.assertEqual(ns['master_doc'], 'index')
        self.assertEqual(ns['project'], 'Hieroglyph Test')
        self.assertEqual(ns['html_static_path'], ['_static'])

        self.assertTrue(os.path.isdir(os.path.join(tempdir, '_static')))
        self.assertTrue(os.path.isdir(os.path.join(tempdir, '_templates')))
        self.assertTrue(os.path.exists(os.path.join(tempdir, 'index.rst')))
        self.assertTrue(os.path.exists(os.path.join(tempdir, 'Makefile')))
        self.assertTrue(os.path.exists(os.path.join(tempdir, 'make.bat')))

        shutil.rmtree(tempdir)
Пример #4
0
def loadConfig(namespace):
# ------------------------------------------------------------------------------

    u"""Load an additional configuration file into *namespace*.

    The name of the configuration file is taken from the environment
    ``SPHINX_CONF``. The external configuration file extends (or overwrites) the
    configuration values from the origin ``conf.py``.  With this you are able to
    maintain *build themes*.  """

    from sphinx.util.pycompat import execfile_

    config_file = os.environ.get("SPHINX_CONF", None)
    if (config_file is not None
        and os.path.normpath(namespace["__file__"]) != os.path.normpath(config_file) ):
        config_file = abspath(config_file)

        if os.path.isfile(config_file):
            sys.stdout.write("load additional sphinx-config: %s\n" % config_file)
            config = namespace.copy()
            config['__file__']  = config_file
            config['main_name'] = splitext(basename(config_file))[0]
            execfile_(config_file, config)
            del config['__file__']
            namespace.update(config)
        else:
            sys.stderr.write("WARNING: additional sphinx-config not found: %s\n" % config_file)
    else:
        sys.stdout.write("no additional sphinx-config\n")
Пример #5
0
def test_quickstart_defaults(tempdir):
    answers = {
        'Root path': tempdir,
        'Project name': 'Sphinx Test',
        'Author name': 'Georg Brandl',
        'Project version': '0.1',
    }
    qs.term_input = mock_input(answers)
    d = {}
    qs.ask_user(d)
    qs.generate(d)

    conffile = tempdir / 'conf.py'
    assert conffile.isfile()
    ns = {}
    execfile_(conffile, ns)
    assert ns['extensions'] == []
    assert ns['templates_path'] == ['_templates']
    assert ns['source_suffix'] == '.rst'
    assert ns['master_doc'] == 'index'
    assert ns['project'] == 'Sphinx Test'
    assert ns['copyright'] == '%s, Georg Brandl' % time.strftime('%Y')
    assert ns['version'] == '0.1'
    assert ns['release'] == '0.1'
    assert ns['todo_include_todos'] is False
    assert ns['html_static_path'] == ['_static']
    assert ns['latex_documents'] == [
        ('index', 'SphinxTest.tex', 'Sphinx Test Documentation',
         'Georg Brandl', 'manual')]

    assert (tempdir / '_static').isdir()
    assert (tempdir / '_templates').isdir()
    assert (tempdir / 'index.rst').isfile()
    assert (tempdir / 'Makefile').isfile()
    assert (tempdir / 'make.bat').isfile()
Пример #6
0
def eval_config_file(filename: str, tags: Tags) -> Dict[str, Any]:
    """Evaluate a config file."""
    namespace = {}  # type: Dict[str, Any]
    namespace['__file__'] = filename
    namespace['tags'] = tags

    with cd(path.dirname(filename)):
        # during executing config file, current dir is changed to ``confdir``.
        try:
            execfile_(filename, namespace)
        except SyntaxError as err:
            msg = __(
                "There is a syntax error in your configuration file: %s\n")
            raise ConfigError(msg % err)
        except SystemExit:
            msg = __(
                "The configuration file (or one of the modules it imports) "
                "called sys.exit()")
            raise ConfigError(msg)
        except ConfigError:
            # pass through ConfigError from conf.py as is.  It will be shown in console.
            raise
        except Exception:
            msg = __(
                "There is a programmable error in your configuration file:\n\n%s"
            )
            raise ConfigError(msg % traceback.format_exc())

    return namespace
Пример #7
0
    def __init__(self, dirname, filename, overrides, tags):
        self.overrides = overrides
        self.values = Config.config_values.copy()
        config = {}
        if dirname is not None:
            config_file = path.join(dirname, filename)
            config['__file__'] = config_file
            config['tags'] = tags
            olddir = os.getcwd()
            try:
                # we promise to have the config dir as current dir while the
                # config file is executed
                os.chdir(dirname)
                try:
                    execfile_(filename, config)
                except SyntaxError, err:
                    raise ConfigError(CONFIG_SYNTAX_ERROR % err)
            finally:
                os.chdir(olddir)

        self._raw_config = config
        # these two must be preinitialized because extensions can add their
        # own config values
        self.setup = config.get('setup', None)
        self.extensions = config.get('extensions', [])
Пример #8
0
def eval_config_file(filename, tags):
    # type: (unicode, Tags) -> Dict[unicode, Any]
    """Evaluate a config file."""
    namespace = {}  # type: Dict[unicode, Any]
    namespace['__file__'] = filename
    namespace['tags'] = tags

    with cd(path.dirname(filename)):
        # during executing config file, current dir is changed to ``confdir``.
        try:
            execfile_(filename, namespace)
        except SyntaxError as err:
            msg = __("There is a syntax error in your configuration file: %s")
            if PY3:
                msg += __("\nDid you change the syntax from 2.x to 3.x?")
            raise ConfigError(msg % err)
        except SystemExit:
            msg = __(
                "The configuration file (or one of the modules it imports) "
                "called sys.exit()")
            raise ConfigError(msg)
        except Exception:
            msg = __(
                "There is a programmable error in your configuration file:\n\n%s"
            )
            raise ConfigError(msg % traceback.format_exc())

    return namespace
Пример #9
0
    def __init__(self, dirname, filename, overrides, tags):
        self.overrides = overrides
        self.values = Config.config_values.copy()
        config = {}
        if 'extensions' in overrides:  # XXX do we need this?
            if isinstance(overrides['extensions'], string_types):
                config['extensions'] = overrides.pop('extensions').split(',')
            else:
                config['extensions'] = overrides.pop('extensions')
        if dirname is not None:
            config_file = path.join(dirname, filename)
            config['__file__'] = config_file
            config['tags'] = tags
            with cd(dirname):
                # we promise to have the config dir as current dir while the
                # config file is executed
                try:
                    execfile_(filename, config)
                except SyntaxError as err:
                    raise ConfigError(CONFIG_SYNTAX_ERROR % err)
                except SystemExit:
                    raise ConfigError(CONFIG_EXIT_ERROR)

        self._raw_config = config
        # these two must be preinitialized because extensions can add their
        # own config values
        self.setup = config.get('setup', None)
        self.extensions = config.get('extensions', [])
Пример #10
0
    def __init__(self, dirname, filename, overrides, tags):
        self.overrides = overrides
        self.values = Config.config_values.copy()
        config = {}
        if "extensions" in overrides:  # XXX do we need this?
            if isinstance(overrides["extensions"], string_types):
                config["extensions"] = overrides.pop("extensions").split(",")
            else:
                config["extensions"] = overrides.pop("extensions")
        if dirname is not None:
            config_file = path.join(dirname, filename)
            config["__file__"] = config_file
            config["tags"] = tags
            with cd(dirname):
                # we promise to have the config dir as current dir while the
                # config file is executed
                try:
                    execfile_(filename, config)
                except SyntaxError as err:
                    raise ConfigError(CONFIG_SYNTAX_ERROR % err)
                except SystemExit:
                    raise ConfigError(CONFIG_EXIT_ERROR)

        self._raw_config = config
        # these two must be preinitialized because extensions can add their
        # own config values
        self.setup = config.get("setup", None)
        self.extensions = config.get("extensions", [])
Пример #11
0
def test_execfile(capsys, tempdir):
    conf_py = tempdir / 'conf.py'
    conf_py.write_bytes(b'print("hello")\n')
    execfile_(conf_py, {})

    captured = capsys.readouterr()
    assert captured.out == 'hello\n'
Пример #12
0
    def __init__(self, dirname, filename, overrides, tags):
        self.overrides = overrides
        self.values = Config.config_values.copy()
        config = {}
        if "extensions" in overrides:
            config["extensions"] = overrides["extensions"]
        if dirname is not None:
            config_file = path.join(dirname, filename)
            config['__file__'] = config_file
            config['tags'] = tags
            olddir = os.getcwd()
            try:
                # we promise to have the config dir as current dir while the
                # config file is executed
                os.chdir(dirname)
                try:
                    execfile_(filename, config)
                except SyntaxError, err:
                    raise ConfigError(CONFIG_SYNTAX_ERROR % err)
            finally:
                os.chdir(olddir)

        self._raw_config = config
        # these two must be preinitialized because extensions can add their
        # own config values
        self.setup = config.get('setup', None)
        self.extensions = config.get('extensions', [])
Пример #13
0
def eval_config_file(filename, tags):
    # type: (unicode, Tags) -> Dict[unicode, Any]
    """Evaluate a config file."""
    namespace = {}  # type: Dict[unicode, Any]
    namespace['__file__'] = filename
    namespace['tags'] = tags

    with cd(path.dirname(filename)):
        # during executing config file, current dir is changed to ``confdir``.
        try:
            execfile_(filename, namespace)
        except SyntaxError as err:
            msg = __("There is a syntax error in your configuration file: %s")
            if PY3:
                msg += __("\nDid you change the syntax from 2.x to 3.x?")
            raise ConfigError(msg % err)
        except SystemExit:
            msg = __("The configuration file (or one of the modules it imports) "
                     "called sys.exit()")
            raise ConfigError(msg)
        except Exception:
            msg = __("There is a programmable error in your configuration file:\n\n%s")
            raise ConfigError(msg % traceback.format_exc())

    return namespace
Пример #14
0
def test_quickstart_defaults(tempdir):
    answers = {
        'Root path': tempdir,
        'Project name': 'Sphinx Test',
        'Author name': 'Georg Brandl',
        'Project version': '0.1',
    }
    qs.term_input = mock_input(answers)
    d = {}
    qs.ask_user(d)
    qs.generate(d)

    conffile = tempdir / 'conf.py'
    assert conffile.isfile()
    ns = {}
    execfile_(conffile, ns)
    assert ns['extensions'] == []
    assert ns['templates_path'] == ['_templates']
    assert ns['source_suffix'] == '.rst'
    assert ns['master_doc'] == 'index'
    assert ns['project'] == 'Sphinx Test'
    assert ns['copyright'] == '%s, Georg Brandl' % time.strftime('%Y')
    assert ns['version'] == '0.1'
    assert ns['release'] == '0.1'
    assert ns['html_static_path'] == ['_static']
    assert ns['latex_documents'] == [
        ('index', 'SphinxTest.tex', 'Sphinx Test Documentation',
         'Georg Brandl', 'manual')]

    assert (tempdir / '_static').isdir()
    assert (tempdir / '_templates').isdir()
    assert (tempdir / 'index.rst').isfile()
    assert (tempdir / 'Makefile').isfile()
    assert (tempdir / 'make.bat').isfile()
Пример #15
0
def loadConfig(namespace):
    # ------------------------------------------------------------------------------
    u"""Load an additional configuration file into *namespace*.

    The name of the configuration file is taken from the environment
    ``SPHINX_CONF``. The external configuration file extends (or overwrites) the
    configuration values from the origin ``conf.py``.  With this you are able to
    maintain *build themes*.  """

    config_file = os.environ.get("SPHINX_CONF", None)
    if (config_file is not None and os.path.normpath(namespace["__file__"]) !=
            os.path.normpath(config_file)):
        config_file = os.path.abspath(config_file)

        if os.path.isfile(config_file):
            sys.stdout.write("load additional sphinx-config: %s\n" %
                             config_file)
            config = namespace.copy()
            config['__file__'] = config_file
            execfile_(config_file, config)
            del config['__file__']
            namespace.update(config)
        else:
            sys.stderr.write(
                "WARNING: additional sphinx-config not found: %s\n" %
                config_file)
Пример #16
0
def test_execfile(capsys):
    ns = {}
    with tempfile.NamedTemporaryFile() as tmp:
        tmp.write(b'print("hello")\n')
        tmp.flush()
        execfile_(tmp.name, ns)
    captured = capsys.readouterr()
    assert captured.out == 'hello\n'
Пример #17
0
def test_execfile(capsys):
    ns = {}
    with tempfile.NamedTemporaryFile() as tmp:
        tmp.write(b'print("hello")\n')
        tmp.flush()
        execfile_(tmp.name, ns)
    captured = capsys.readouterr()
    assert captured.out == 'hello\n'
Пример #18
0
def test_quickstart_all_answers(tempdir):
    answers = {
        'Root path': tempdir,
        'Separate source and build': 'y',
        'Name prefix for templates': '.',
        'Project name': u'STASI™'.encode('utf-8'),
        'Author name': u'Wolfgang Schäuble & G\'Beckstein'.encode('utf-8'),
        'Project version': '2.0',
        'Project release': '2.0.1',
        'Project language': 'de',
        'Source file suffix': '.txt',
        'Name of your master document': 'contents',
        'autodoc': 'y',
        'doctest': 'yes',
        'intersphinx': 'no',
        'todo': 'y',
        'coverage': 'no',
        'imgmath': 'N',
        'mathjax': 'no',
        'ifconfig': 'no',
        'viewcode': 'no',
        'githubpages': 'no',
        'Create Makefile': 'no',
        'Create Windows command file': 'no',
        'Do you want to use the epub builder': 'yes',
    }
    qs.term_input = mock_input(answers, needanswer=True)
    qs.TERM_ENCODING = 'utf-8'
    d = {}
    qs.ask_user(d)
    qs.generate(d)

    conffile = tempdir / 'source' / 'conf.py'
    assert conffile.isfile()
    ns = {}
    execfile_(conffile, ns)
    assert ns['extensions'] == [
        'sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.todo'
    ]
    assert ns['templates_path'] == ['.templates']
    assert ns['source_suffix'] == '.txt'
    assert ns['master_doc'] == 'contents'
    assert ns['project'] == u'STASI™'
    assert ns['copyright'] == u'%s, Wolfgang Schäuble & G\'Beckstein' % \
        time.strftime('%Y')
    assert ns['version'] == '2.0'
    assert ns['release'] == '2.0.1'
    assert ns['todo_include_todos'] is True
    assert ns['html_static_path'] == ['.static']
    assert ns['latex_documents'] == [
        ('contents', 'STASI.tex', u'STASI™ Documentation',
         u'Wolfgang Schäuble \\& G\'Beckstein', 'manual')
    ]

    assert (tempdir / 'build').isdir()
    assert (tempdir / 'source' / '.static').isdir()
    assert (tempdir / 'source' / '.templates').isdir()
    assert (tempdir / 'source' / 'contents.txt').isfile()
Пример #19
0
def test_extensions(tempdir):
    qs.main(['-q', '-p', 'project_name', '-a', 'author',
             '--extensions', 'foo,bar,baz', tempdir])

    conffile = tempdir / 'conf.py'
    assert conffile.isfile()
    ns = {}
    execfile_(conffile, ns)
    assert ns['extensions'] == ['foo', 'bar', 'baz']
Пример #20
0
def test_extensions(tempdir):
    qs.main(['-q', '-p', 'project_name', '-a', 'author',
             '--extensions', 'foo,bar,baz', tempdir])

    conffile = tempdir / 'conf.py'
    assert conffile.isfile()
    ns = {}
    execfile_(conffile, ns)
    assert ns['extensions'] == ['foo', 'bar', 'baz']
Пример #21
0
def test_execfile_python2(capsys, app, status, warning, tempdir):
    logging.setup(app, status, warning)

    conf_py = tempdir / 'conf.py'
    conf_py.write_bytes(b'print "hello"\n')
    execfile_(conf_py, {})

    msg = ('Support for evaluating Python 2 syntax is deprecated '
           'and will be removed in Sphinx 4.0. '
           'Convert %s to Python 3 syntax.\n' % conf_py)
    assert msg in strip_escseq(warning.getvalue())
    captured = capsys.readouterr()
    assert captured.out == 'hello\n'
Пример #22
0
def test_execfile_python2(capsys, app, status, warning):
    logging.setup(app, status, warning)

    ns = {}
    with tempfile.NamedTemporaryFile() as tmp:
        tmp.write(b'print "hello"\n')
        tmp.flush()
        execfile_(tmp.name, ns)
    msg = ('Support for evaluating Python 2 syntax is deprecated '
           'and will be removed in Sphinx 4.0. '
           'Convert %s to Python 3 syntax.\n' % tmp.name)
    assert msg in strip_escseq(warning.getvalue())
    captured = capsys.readouterr()
    assert captured.out == 'hello\n'
def loadConfig(namespace):
    # ------------------------------------------------------------------------------
    u"""Load an additional configuration file into *namespace*.

    The name of the configuration file is taken from the environment
    ``SPHINX_CONF``. The external configuration file extends (or overwrites) the
    configuration values from the origin ``conf.py``.  With this you are able to
    maintain *build themes*.  """

    config_file = os.environ.get("SPHINX_CONF", None)
    if (config_file is not None and os.path.normpath(namespace["__file__"]) !=
            os.path.normpath(config_file)):
        config_file = os.path.abspath(config_file)

        # Let's avoid one conf.py file just due to latex_documents
        start = config_file.find('Documentation/')
        if start >= 0:
            start = config_file.find('/', start + 1)

        end = config_file.rfind('/')
        if start >= 0 and end > 0:
            dir = config_file[start + 1:end]

            print("source directory: %s" % dir)
            new_latex_docs = []
            latex_documents = namespace['latex_documents']

            for l in latex_documents:
                if l[0].find(dir + '/') == 0:
                    has = True
                    fn = l[0][len(dir) + 1:]
                    new_latex_docs.append((fn, l[1], l[2], l[3], l[4]))
                    break

            namespace['latex_documents'] = new_latex_docs

        # If there is an extra conf.py file, load it
        if os.path.isfile(config_file):
            sys.stdout.write("load additional sphinx-config: %s\n" %
                             config_file)
            config = namespace.copy()
            config['__file__'] = config_file
            execfile_(config_file, config)
            del config['__file__']
            namespace.update(config)
        else:
            config = namespace.copy()
            config['tags'].add("subproject")
            namespace.update(config)
Пример #24
0
def get_master_doc(conf_file):
    '''returns the master_doc' variable stored in the given config file'''
    if not os.path.isfile(conf_file):
        raise ValueError("Not conf.py file: '%s'" % conf_file)

    # execute conf file to get the master document
    # Copied from sphinx.util.pycompat.py
    _globals = {"__file__": conf_file}  # the namespace where toe xec stuff with six
    with cd(os.path.dirname(conf_file)):
        execfile_("conf.py", _globals)

    if 'master_doc' not in _globals:
        raise ValueError("'master_doc' undefined in '%s'" % conf_file)

    return _globals['master_doc']
Пример #25
0
def test_execfile_python2(capsys, app, status, warning):
    logging.setup(app, status, warning)

    ns = {}
    with tempfile.NamedTemporaryFile() as tmp:
        tmp.write(b'print "hello"\n')
        tmp.flush()
        execfile_(tmp.name, ns)
    msg = (
        'Support for evaluating Python 2 syntax is deprecated '
        'and will be removed in Sphinx 4.0. '
        'Convert %s to Python 3 syntax.\n' % tmp.name)
    assert msg in strip_escseq(warning.getvalue())
    captured = capsys.readouterr()
    assert captured.out == 'hello\n'
Пример #26
0
def test_default_filename(tempdir):
    answers = {
        'Root path': tempdir,
        'Project name': '\u30c9\u30a4\u30c4',  # Fullwidth characters only
        'Author name': 'Georg Brandl',
        'Project version': '0.1',
    }
    qs.term_input = mock_input(answers)
    d = {}
    qs.ask_user(d)
    qs.generate(d)

    conffile = tempdir / 'conf.py'
    assert conffile.isfile()
    ns = {}
    execfile_(conffile, ns)
Пример #27
0
def test_default_filename(tempdir):
    answers = {
        'Root path': tempdir,
        'Project name': u'\u30c9\u30a4\u30c4',  # Fullwidth characters only
        'Author name': 'Georg Brandl',
        'Project version': '0.1',
    }
    qs.term_input = mock_input(answers)
    d = {}
    qs.ask_user(d)
    qs.generate(d)

    conffile = tempdir / 'conf.py'
    assert conffile.isfile()
    ns = {}
    execfile_(conffile, ns)
    assert ns['latex_documents'][0][1] == 'sphinx.tex'
Пример #28
0
def get_master_doc(conf_file):
    '''returns the master_doc' variable stored in the given config file'''
    if not os.path.isfile(conf_file):
        raise ValueError("Not conf.py file: '%s'" % conf_file)

    # execute conf file to get the master document
    # Copied from sphinx.util.pycompat.py
    _globals = {
        "__file__": conf_file
    }  # the namespace where toe xec stuff with six
    with cd(os.path.dirname(conf_file)):
        execfile_("conf.py", _globals)

    if 'master_doc' not in _globals:
        raise ValueError("'master_doc' undefined in '%s'" % conf_file)

    return _globals['master_doc']
Пример #29
0
def test_default_filename(tempdir):
    answers = {
        'Root path': tempdir,
        'Project name': u'\u30c9\u30a4\u30c4',  # Fullwidth characters only
        'Author name': 'Georg Brandl',
        'Project version': '0.1',
    }
    qs.term_input = mock_input(answers)
    d = {}
    qs.ask_user(d)
    qs.generate(d)

    conffile = tempdir / 'conf.py'
    assert conffile.isfile()
    ns = {}
    execfile_(conffile, ns)
    assert ns['latex_documents'][0][1] == 'sphinx.tex'
    assert ns['man_pages'][0][1] == 'sphinx'
    assert ns['texinfo_documents'][0][1] == 'sphinx'
Пример #30
0
    def __init__(self, dirname, filename, overrides, tags):
        # type: (unicode, unicode, Dict, Tags) -> None
        self.overrides = overrides
        self.values = Config.config_values.copy()
        config = {}  # type: Dict[unicode, Any]
        if dirname is not None:
            config_file = path.join(dirname, filename)
            config['__file__'] = config_file
            config['tags'] = tags
            with cd(dirname):
                # we promise to have the config dir as current dir while the
                # config file is executed
                try:
                    execfile_(filename, config)
                except SyntaxError as err:
                    raise ConfigError(CONFIG_SYNTAX_ERROR % err)
                except SystemExit:
                    raise ConfigError(CONFIG_EXIT_ERROR)
                except Exception:
                    raise ConfigError(CONFIG_ERROR % traceback.format_exc())

        self._raw_config = config
        # these two must be preinitialized because extensions can add their
        # own config values
        self.setup = config.get('setup', None)  # type: Callable

        if 'extensions' in overrides:
            if isinstance(overrides['extensions'], string_types):
                config['extensions'] = overrides.pop('extensions').split(',')
            else:
                config['extensions'] = overrides.pop('extensions')
        self.extensions = config.get('extensions', [])  # type: List[unicode]

        # correct values of copyright year that are not coherent with
        # the SOURCE_DATE_EPOCH environment variable (if set)
        # See https://reproducible-builds.org/specs/source-date-epoch/
        if getenv('SOURCE_DATE_EPOCH') is not None:
            for k in ('copyright', 'epub_copyright'):
                if k in config:
                    config[k] = copyright_year_re.sub(r'\g<1>%s' % format_date('%Y'),
                                                      config[k])
Пример #31
0
    def __init__(self, dirname, filename, overrides, tags):
        # type: (unicode, unicode, Dict, Tags) -> None
        self.overrides = overrides
        self.values = Config.config_values.copy()
        config = {}  # type: Dict[unicode, Any]
        if dirname is not None:
            config_file = path.join(dirname, filename)
            config['__file__'] = config_file
            config['tags'] = tags
            with cd(dirname):
                # we promise to have the config dir as current dir while the
                # config file is executed
                try:
                    execfile_(filename, config)
                except SyntaxError as err:
                    raise ConfigError(CONFIG_SYNTAX_ERROR % err)
                except SystemExit:
                    raise ConfigError(CONFIG_EXIT_ERROR)
                except Exception:
                    raise ConfigError(CONFIG_ERROR % traceback.format_exc())

        self._raw_config = config
        # these two must be preinitialized because extensions can add their
        # own config values
        self.setup = config.get('setup', None)  # type: Callable

        if 'extensions' in overrides:
            if isinstance(overrides['extensions'], string_types):
                config['extensions'] = overrides.pop('extensions').split(',')
            else:
                config['extensions'] = overrides.pop('extensions')
        self.extensions = config.get('extensions', [])  # type: List[unicode]

        # correct values of copyright year that are not coherent with
        # the SOURCE_DATE_EPOCH environment variable (if set)
        # See https://reproducible-builds.org/specs/source-date-epoch/
        if getenv('SOURCE_DATE_EPOCH') is not None:
            for k in ('copyright', 'epub_copyright'):
                if k in config:
                    config[k] = copyright_year_re.sub(r'\g<1>%s' % format_date('%Y'),
                                                      config[k])
Пример #32
0
def load_sphinx_config(namespace):
    # ------------------------------------------------------------------------------
    u"""Load an additional configuration file into *namespace*.

    The name of the configuration file is taken from the environment
    ``SPHINX_CONF``. The external configuration file extends (or overwrites) the
    configuration values from the origin ``conf.py``.  With this you are able to
    maintain *build themes*.  To your docs/conf.py add::

        from sphinx_build_tools import load_sphinx_config
        ...

        # Since loadConfig overwrites settings from the global namespace, it has to be
        # the last statement in the conf.py file

        load_sphinx_config(globals())

    """

    config_file = os.environ.get("SPHINX_CONF", None)
    if (config_file is not None and os.path.normpath(namespace["__file__"]) !=
            os.path.normpath(config_file)):
        config_file = os.path.abspath(config_file)

        if os.path.isfile(config_file):
            sys.stdout.write("load additional sphinx-config: %s\n" %
                             config_file)
            config = namespace.copy()
            config['__file__'] = config_file
            execfile_(config_file, config)
            del config['__file__']
            namespace.update(config)
        else:
            sys.stderr.write(
                "WARNING: additional sphinx-config not found: %s\n" %
                config_file)
Пример #33
0
    def __init__(self, dirname, filename, overrides, tags):
        self.overrides = overrides
        self.values = Config.config_values.copy()
        config = {}
        if "extensions" in overrides:  # XXX do we need this?
            if isinstance(overrides["extensions"], string_types):
                config["extensions"] = overrides.pop("extensions").split(",")
            else:
                config["extensions"] = overrides.pop("extensions")
        if dirname is not None:
            config_file = path.join(dirname, filename)
            config["__file__"] = config_file
            config["tags"] = tags
            with cd(dirname):
                # we promise to have the config dir as current dir while the
                # config file is executed
                try:
                    execfile_(filename, config)
                except SyntaxError as err:
                    raise ConfigError(CONFIG_SYNTAX_ERROR % err)
                except SystemExit:
                    raise ConfigError(CONFIG_EXIT_ERROR)

        self._raw_config = config
        # these two must be preinitialized because extensions can add their
        # own config values
        self.setup = config.get("setup", None)
        self.extensions = config.get("extensions", [])

        # correct values of copyright year that are not coherent with
        # the SOURCE_DATE_EPOCH environment variable (if set)
        # See https://reproducible-builds.org/specs/source-date-epoch/
        if getenv("SOURCE_DATE_EPOCH") is not None:
            for k in ("copyright", "epub_copyright"):
                if k in config:
                    config[k] = copyright_year_re.sub("\g<1>%s" % format_date("%Y"), config[k])
Пример #34
0
    def test_hieroglyph_quickstart(self):
        tempdir = tempfile.mkdtemp()

        answers = {
            'Root path': tempdir,
            'Author name(s)': 'Marcia Brady',
            'Presentation title': 'Hieroglyph Test',
        }
        sphinx_quickstart.term_input = mock_input(answers)
        quickstart.quickstart(path=tempdir)

        conffile = os.path.join(tempdir, 'conf.py')
        assert os.path.exists(conffile)
        ns = {}
        execfile_(conffile, ns)

        # XXX why is there a list in the list?!
        # Apparently introduced between Sphinx 1.6.7 and 1.7.0b1
        if type(ns['extensions']) is list:
            # let's make sure there is nothing we don't expect
            self.assertEqual(len(ns['extensions']), 1)
            ns['extensions'] = ns['extensions'][0]

        self.assertIn('hieroglyph', ns['extensions'])
        self.assertEqual(ns['templates_path'], ['_templates'])
        self.assertEqual(ns['project'], 'Hieroglyph Test')
        self.assertEqual(ns['author'], 'Marcia Brady')
        self.assertEqual(ns['html_static_path'], ['_static'])

        self.assertTrue(os.path.isdir(os.path.join(tempdir, '_static')))
        self.assertTrue(os.path.isdir(os.path.join(tempdir, '_templates')))
        self.assertTrue(os.path.exists(os.path.join(tempdir, 'index.rst')))
        self.assertTrue(os.path.exists(os.path.join(tempdir, 'Makefile')))
        self.assertTrue(os.path.exists(os.path.join(tempdir, 'make.bat')))

        shutil.rmtree(tempdir)
Пример #35
0
# BASEDIR is set by <lang>/conf.py
"""
Use "-D language=<LANG>" option to build a localized CoFEA document.
For example::

    sphinx-build -D language=ja -b html . _build/html

This conf.py do:

- Specify `locale_dirs` and `gettext_compact`.
- Overrides source directory as 'CoFEA/docs/`.

"""
import os

from sphinx.util.pycompat import execfile_

os.system("git submodule update --init --force --recursive cadquery")

BASEDIR = os.path.dirname(os.path.abspath(__file__))

execfile_(os.path.join(BASEDIR, "cadquery/doc/conf.py"), globals())

locale_dirs = [os.path.join(BASEDIR, "locale/")]


def setup(app):
    app.srcdir = os.path.join(BASEDIR, "cadquery/doc/")
    app.confdir = app.srcdir
Пример #36
0
    sphinx-build -D language=ja -b html . _build/html

This conf.py do:

- Specify `locale_dirs` and `gettext_compact`.
- Overrides source directory as 'mayavi/docs/source/tvtk`.

"""
import os
from sphinx.util.pycompat import execfile_

basedir = os.path.join(
    os.path.dirname(os.path.abspath(__file__)), "mayavi/docs/source/tvtk"
)

execfile_(os.path.join(basedir, "conf.py"), globals())

locale_dirs = [os.path.join(basedir, "../../../../locale/")]


def setup(app):
    from sphinx.util.docfields import GroupedField

    app.srcdir = basedir
    app.confdir = app.srcdir
    app.add_object_type(
        "confval",
        "confval",
        objname="configuration value",
        indextemplate="pair: %s; configuration value",
    )
Пример #37
0
# BASEDIR is set by <lang>/conf.py
"""
Use "-D language=<LANG>" option to build a localized sphinx document.
For example::
    sphinx-build -D language=ja -b html . _build/html
This conf.py do:
- Specify `locale_dirs` and `gettext_compact`.
- Overrides source directory as 'handbook/`.
"""
import os
from pathlib import Path

from sphinx.util.pycompat import execfile_

BASEDIR = Path(os.path.abspath(__file__)).parent.absolute()

execfile_(str(BASEDIR / 'handbook' / 'conf.py'), globals())

locale_dirs = [str(BASEDIR / 'locale/')]
gettext_compact = False


def setup(app):
    app.srcdir = str(BASEDIR / 'handbook/')
    app.confdir = app.srcdir
Пример #38
0
For example::

    sphinx-build -D language=ja -b html . _build/html

This conf.py do:

- Specify `locale_dirs` and `gettext_compact`.
- Overrides source directory as 'CoFEA/docs/`.

"""
import os
import shutil
import sys

from sphinx.util.pycompat import execfile_

shutil.rmtree("benchmarks", ignore_errors=True)
shutil.copytree("CoFEA/docs/benchmarks", "benchmarks")
BASEDIR = os.path.dirname(os.path.abspath(__file__))

execfile_(os.path.join(BASEDIR, "CoFEA/docs/conf.py"), globals())

locale_dirs = [os.path.join(BASEDIR, "locale/")]

sys.path.insert(0, os.path.abspath("CoFEA/meshpresso"))


def setup(app):
    app.srcdir = os.path.join(BASEDIR, "CoFEA/docs/")
    app.confdir = app.srcdir
# -*- coding: utf-8 -*-
# Copyright 2019-2021 releng-tool

from sphinx.util.pycompat import execfile_
import os
import sys

if 'RELENG_TARGET_DIR' not in os.environ:
    raise SyntaxError('target directory not provided')

releng_tool_dir = os.path.abspath(os.environ['RELENG_TARGET_DIR'])
releng_tool_doc_dir = os.path.join(releng_tool_dir, 'Documentation')

# inject releng-tool into system path to allow autodocs content to render
sys.path.insert(0, releng_tool_dir)

# load releng-tool's sphinx configuration
execfile_(os.path.join(releng_tool_doc_dir, 'conf.py'), globals())

# localization options
if 'RELENG_LOCALE_DIR' not in os.environ:
    raise SyntaxError('locale directory not provided')

locale_dirs = [os.environ['RELENG_LOCALE_DIR']]
gettext_compact = False

def setup(app):
    # point application documentation to releng-tool's set
    app.confdir = releng_tool_doc_dir
    app.srcdir = releng_tool_doc_dir
Пример #40
0
"""
Use "-D language=<LANG>" option to build a localized sphinx document.
For example::

    sphinx-build -D language=ja -b html . _build/html

This conf.py do:

- Specify `locale_dirs` and `gettext_compact`.
- Overrides source directory as 'sphinx/doc/`.

"""
import os
from sphinx.util.pycompat import execfile_

BASEDIR = os.path.dirname(os.path.abspath(__file__))

execfile_(os.path.join(BASEDIR, 'sphinx/doc/conf.py'), globals())

locale_dirs = [os.path.join(BASEDIR, 'locale/')]
gettext_compact = False

setup_original = setup  # from 'sphinx/doc/conf.py'


def setup(app):
    app.srcdir = os.path.join(BASEDIR, 'sphinx/doc/')
    app.confdir = app.srcdir

    setup_original(app)
Пример #41
0
# BASEDIR is set by <lang>/conf.py
"""
Use "-D language=<LANG>" option to build a localized sphinx document.
For example::
    sphinx-build -D language=ja -b html . _build/html
This conf.py does:
- Specify `locale_dirs` and `gettext_compact`.
- Overrides source directory as 'sphinx/doc/`.
"""
import os
from sphinx.util.pycompat import execfile_

BASEDIR = os.path.dirname(os.path.abspath(__file__))

execfile_(os.path.join(BASEDIR, 'frc-docs/source/conf.py'), globals())

locale_dirs = [os.path.join(BASEDIR, 'locale/')]
gettext_compact = False

setup_original = setup 

def setup(app):
    app.srcdir = os.path.join(BASEDIR, 'frc-docs/source/')
    app.confdir = app.srcdir

    setup_original(app)