diff --git a/docs/conf.py b/docs/conf.py index 838f4e5131..796d2e5e27 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -13,7 +13,13 @@ from __future__ import unicode_literals # All configuration values have a default; values that are commented out # serve to show the default. -import sys, os +import os +import inspect +import sys + +from docutils.parsers.rst import directives +import docutils.parsers.rst.directives.misc +from sphinx.directives.other import Include as SphinxInclude sys.path.insert(0, os.path.abspath('..')) @@ -258,26 +264,55 @@ extlinks = { def _load_env_file(filename='../config.env'): - print('Loading env file: {}'.format(filename)) result = [] with open(filename) as file_object: for line in file_object: if not line.startswith('#'): - print('Found entry: {}'.format(line)) key, value = line.strip().split('=') result.append(('|{}|'.format(key), value)) return result -def GlobalSubstitution(app, docname, source): - for old, new in global_subtitutions: +def global_substitution_function(app, docname, source): + for old, new in global_subtitutions_list: source[0] = source[0].replace(old, new) +def monkey_path_include(): + """ + Monkey path docutil's Include directive to support global substitutions. + The Include class doesn't have a hook to modify the content before + inserting it back, so we add a call to our own transformation + method. We patch the base Include class, recreate Sphinx's Include class, + and register it as the new main include directive. + All this avoids copy and paste of the original code here. + """ + source_code = ''.join(inspect.getsourcelines( + docutils.parsers.rst.directives.misc.Include)[0] + ) + source_code = source_code.replace( + 'self.state_machine.insert_input(include_lines, path)', + 'include_lines=self.global_substitution(lines=include_lines)\n self.state_machine.insert_input(include_lines, path)', + ) + exec(source_code, docutils.parsers.rst.directives.misc.__dict__) + + class Include(docutils.parsers.rst.directives.misc.Include, SphinxInclude): + def global_substitution(self, lines): + result = [] + for line in lines: + for old, new in global_subtitutions_list: + line = line.replace(old, new) + result.append(line) + return result + + return Include + + def setup(app): app.add_stylesheet('css/custom.css') - app.connect('source-read', GlobalSubstitution) + app.connect('source-read', global_substitution_function) + directives.register_directive('include', monkey_path_include()) -global_subtitutions = _load_env_file() +global_subtitutions_list = _load_env_file()