:confval:source_suffix allows a mapping fileext to file types

This commit is contained in:
Takeshi KOMIYA 2018-01-22 12:33:55 +09:00
parent bece0484e5
commit 69f69628ed
6 changed files with 50 additions and 10 deletions

View File

@ -22,6 +22,7 @@ Features added
* Add :event:`config-inited` event * Add :event:`config-inited` event
* Add ``sphinx.config.Any`` to represent the config value accepts any type of * Add ``sphinx.config.Any`` to represent the config value accepts any type of
value value
* :confval:`source_suffix` allows a mapping fileext to file types
Bugs fixed Bugs fixed
---------- ----------

View File

@ -90,12 +90,32 @@ General configuration
.. confval:: source_suffix .. confval:: source_suffix
The file name extension, or list of extensions, of source files. Only files The file extensions of source files. Sphinx considers the files with this
with this suffix will be read as sources. Default is ``'.rst'``. suffix as sources. This value can be a dictionary mapping file extensions
to file types. For example::
source_suffix = {
'.rst': 'restructuredtext',
'.txt': 'restructuredtext',
'.md': 'markdown',
}
By default, Sphinx only supports ``'restrcturedtext'`` file type. You can
add a new file type using source parser extensions. Please read a document
of the extension to know what file type the extension supports.
This also allows a list of file extensions. In that case, Sphinx conciders
that all they are ``'restructuredtext'``. Default is
``{'.rst': 'restructuredtext'}``.
.. note:: file extensions have to start with dot (like ``.rst``).
.. versionchanged:: 1.3 .. versionchanged:: 1.3
Can now be a list of extensions. Can now be a list of extensions.
.. vesionchanged:: 1.8
Support file type mapping
.. confval:: source_encoding .. confval:: source_encoding
The encoding of all reST source files. The recommended encoding, and the The encoding of all reST source files. The recommended encoding, and the

View File

@ -290,7 +290,7 @@ class Sphinx(object):
# type: () -> None # type: () -> None
for suffix, parser in iteritems(self.registry.get_source_parsers()): for suffix, parser in iteritems(self.registry.get_source_parsers()):
if suffix not in self.config.source_suffix and suffix != '*': if suffix not in self.config.source_suffix and suffix != '*':
self.config.source_suffix.append(suffix) self.config.source_suffix[suffix] = suffix
def _init_env(self, freshenv): def _init_env(self, freshenv):
# type: (bool) -> None # type: (bool) -> None

View File

@ -12,6 +12,7 @@
import re import re
import traceback import traceback
from os import path, getenv from os import path, getenv
from collections import OrderedDict
from six import PY2, PY3, iteritems, string_types, binary_type, text_type, integer_types from six import PY2, PY3, iteritems, string_types, binary_type, text_type, integer_types
from typing import Any, NamedTuple, Union from typing import Any, NamedTuple, Union
@ -114,7 +115,7 @@ class Config(object):
figure_language_filename = (u'{root}.{language}{ext}', 'env', [str]), figure_language_filename = (u'{root}.{language}{ext}', 'env', [str]),
master_doc = ('contents', 'env'), master_doc = ('contents', 'env'),
source_suffix = (['.rst'], 'env', Any), source_suffix = ({'.rst': 'restructuredtext'}, 'env', Any),
source_encoding = ('utf-8-sig', 'env'), source_encoding = ('utf-8-sig', 'env'),
source_parsers = ({}, 'env'), source_parsers = ({}, 'env'),
exclude_patterns = ([], 'env'), exclude_patterns = ([], 'env'),
@ -260,7 +261,9 @@ class Config(object):
return value return value
else: else:
defvalue = self.values[name][0] defvalue = self.values[name][0]
if isinstance(defvalue, dict): if self.values[name][-1] == Any:
return value
elif isinstance(defvalue, dict):
raise ValueError(__('cannot override dictionary config setting %r, ' raise ValueError(__('cannot override dictionary config setting %r, '
'ignoring (use %r to set individual elements)') % 'ignoring (use %r to set individual elements)') %
(name, name + '.key=value')) (name, name + '.key=value'))
@ -361,9 +364,25 @@ class Config(object):
def convert_source_suffix(app, config): def convert_source_suffix(app, config):
# type: (Sphinx, Config) -> None # type: (Sphinx, Config) -> None
"""This converts source_suffix to string-list.""" """This converts old styled source_suffix to new styled one.
if isinstance(config.source_suffix, string_types):
config.source_suffix = [config.source_suffix] # type: ignore * old style: str or list
* new style: a dict which maps from fileext to filetype
"""
source_suffix = config.source_suffix
if isinstance(source_suffix, string_types):
# if str, considers as reST
config.source_suffix = OrderedDict({source_suffix: 'restructuredtext'}) # type: ignore
elif isinstance(source_suffix, (list, tuple)):
# if list, considers as all of them are reST
config.source_suffix = OrderedDict([(s, 'restructuredtext') for s in source_suffix]) # type: ignore # NOQA
elif isinstance(source_suffix, dict):
# if dict, convert it to OrderedDict
config.source_suffix = OrderedDict(config.source_suffix) # type: ignore
else:
logger.warning(__("The config value `source_suffix' expected to "
"a string, list of strings or dictionary. "
"But `%r' is given." % source_suffix))
def setup(app): def setup(app):

View File

@ -372,7 +372,7 @@ class BuildEnvironment(object):
break break
else: else:
# document does not exist # document does not exist
suffix = self.config.source_suffix[0] suffix = self.config.source_suffix.keys()[0]
if base is True: if base is True:
return path.join(self.srcdir, docname) + suffix return path.join(self.srcdir, docname) + suffix
elif base is None: elif base is None:

View File

@ -603,7 +603,7 @@ def process_generate_options(app):
from sphinx.ext.autosummary.generate import generate_autosummary_docs from sphinx.ext.autosummary.generate import generate_autosummary_docs
ext = app.config.source_suffix ext = app.config.source_suffix.keys()
genfiles = [genfile + (not genfile.endswith(tuple(ext)) and ext[0] or '') genfiles = [genfile + (not genfile.endswith(tuple(ext)) and ext[0] or '')
for genfile in genfiles] for genfile in genfiles]