def test_body(): with open(os.path.join(_srcdir, 'conf.py'), 'w') as f: f.write(''' extensions = [ 'sphinxcontrib.spelling' ] ''') with open(os.path.join(_srcdir, 'contents.rst'), 'w') as f: f.write(''' Welcome to Spelling Checker documentation! ========================================== There are several mispelled words in this txt. ''') stdout = StringIO() stderr = StringIO() app = Sphinx(_srcdir, _srcdir, _outdir, _outdir, 'spelling', status=stdout, warning=stderr, freshenv=True, ) app.build() print 'reading from %s' % app.builder.output_filename with codecs.open(app.builder.output_filename, 'r') as f: output_text = f.read() def check_one(word): assert word in output_text for word in [ '(mispelled)', '(txt)' ]: yield check_one, word return
def make_sphinx(docbase, buildername='html'): docbase = os.path.abspath(docbase) if not os.path.isdir(docbase): cprint(bcolors.WARNING, "[%s] is not a valid directory" % docbase) cprint(bcolors.OKBLUE, "Building %s..." % docbase[:67]) verbose_output = StringIO() sphinx = Sphinx( srcdir=os.path.join(docbase, 'source'), confdir=os.path.join(docbase, 'source'), outdir=os.path.join(docbase, '_build', 'html'), doctreedir=os.path.join(docbase, '_build', 'doctrees'), buildername='html', #confoverrides=None, status=verbose_output, #warning=sys.stderr, #freshenv=False, #warningiserror=False, #tags=None, #verbosity=0, #parallel=0 ) sphinx.build( #force_all=False, #filenames=None ) vprint(verbose_output.getvalue()) verbose_output.close()
def get_long_description(cleanup=True): from sphinx.application import Sphinx from sphinx.util.osutil import abspath import tempfile import shutil from doc.conf import extensions from sphinxcontrib.writers.rst import RstTranslator from sphinx.ext.graphviz import text_visit_graphviz RstTranslator.visit_dsp = text_visit_graphviz outdir = tempfile.mkdtemp(prefix='setup-', dir='.') exclude_patterns = os.listdir(mydir or '.') exclude_patterns.remove('pypi.rst') app = Sphinx(abspath(mydir), osp.join(mydir, 'doc/'), outdir, outdir + '/.doctree', 'rst', confoverrides={ 'exclude_patterns': exclude_patterns, 'master_doc': 'pypi', 'dispatchers_out_dir': abspath(outdir + '/_dispatchers'), 'extensions': extensions + ['sphinxcontrib.restbuilder'] }, status=None, warning=None) app.build(filenames=[osp.join(app.srcdir, 'pypi.rst')]) with open(outdir + '/pypi.rst') as file: res = file.read() if cleanup: shutil.rmtree(outdir) return res
def sphinx_app(tmpdir_factory): if LooseVersion(sphinx.__version__) < LooseVersion('1.8'): # Previous versions throw an error trying to pickle the scraper pytest.skip('Sphinx 1.8+ required') temp_dir = (tmpdir_factory.getbasetemp() / 'root').strpath src_dir = op.join(op.dirname(__file__), 'tinybuild') def ignore(src, names): return ('_build', 'gen_modules', 'auto_examples') shutil.copytree(src_dir, temp_dir, ignore=ignore) # For testing iteration, you can get similar behavior just doing `make` # inside the tinybuild directory src_dir = temp_dir conf_dir = temp_dir out_dir = op.join(temp_dir, '_build', 'html') toctrees_dir = op.join(temp_dir, '_build', 'toctrees') # Avoid warnings about re-registration, see: # https://github.com/sphinx-doc/sphinx/issues/5038 with docutils_namespace(): app = Sphinx(src_dir, conf_dir, out_dir, toctrees_dir, buildername='html', status=MixedEncodingStringIO()) # need to build within the context manager # for automodule and backrefs to work app.build(False, []) return app
def __init__(self, srcdir=None, buildername='html', confoverrides={}): self.cleanup_dirs = [] self.readonly = False # source settings if srcdir is None: srcdir = tempfile.mkdtemp() self.cleanup_dirs.append(srcdir) open(os.path.join(srcdir, 'conf.py'), 'w').close() else: self.readonly = True if not srcdir.startswith('/'): srcdir = os.path.join(testdir, srcdir) confdir = srcdir # _build/ directory setings self.builddir = tempfile.mkdtemp() outdir = os.path.join(self.builddir, str(buildername)) doctreedir = os.path.join(self.builddir, 'doctrees') os.mkdir(outdir) self.cleanup_dirs.append(self.builddir) # misc settings status = sys.stdout warning = sys.stdout Sphinx.__init__(self, srcdir, confdir, outdir, doctreedir, buildername, confoverrides, status, warning)
def test_html_documentation(self): output_dir = os.path.join(self.top, 'build', 'html') app = Sphinx(self.source_dir, self.source_dir, output_dir, self.doctree_dir, buildername='html', warningiserror=True) app.build(force_all=True)
def get_sphinx(): sphinx = getattr(local_data, 'sphinx', None) if sphinx is None: sphinx = Sphinx(tempdir, tempdir, tempdir, tempdir, 'json', status=None, warning=None) sphinx.builder.translator_class = CustomHTMLTranslator sphinx.env.patch_lookup_functions() sphinx.env.temp_data['docname'] = 'text' sphinx.env.temp_data['default_domain'] = 'py' pub = Publisher(reader=None, parser=None, writer=HTMLWriter(sphinx.builder), source_class=io.StringInput, destination_class=io.NullOutput) pub.set_components('standalone', 'restructuredtext', None) pub.process_programmatic_settings(None, sphinx.env.settings, None) pub.set_destination(None, None) sphinx.publisher = pub local_data.sphinx = sphinx return sphinx, sphinx.publisher
def sphinx_build(self): workdir = self._workdir if not os.path.isdir(workdir): os.makedirs(workdir) conf = os.path.join(workdir, 'conf.py') with codecs.open(conf, encoding='utf-8', mode='w') as out: out.write(SPHINX_CONF) out.write(SPHINX_CONF_APPEND) start = time.time() status = MezeStream(sys.stdout) warning = MezeStream(sys.stderr) app = Sphinx(srcdir=workdir, confdir=workdir, outdir=workdir, doctreedir=workdir, buildername='meze', confoverrides={}, status=status, warning=warning, freshenv=False, warningiserror=False, tags=[]) rst = os.path.join(workdir, 'index' + app.config.source_suffix[0]) with codecs.open(rst, encoding='utf-8', mode='w') as out: out.write(self._source) app.build(False, [rst]) self._messages.append((messages.INFO, 'Source was converted ' 'into HTML using Sphinx in {:.2f}'. format(time.time() - start))) for msg in warning.messages: items = msg.split('WARNING: ') if len(items) == 2: msg = items[1] self._messages.append((messages.WARNING, msg)) self._content, MezeBuilder.context = MezeBuilder.context['body'], None
def pytest_funcarg__app(request): """ A Sphinx application for testing. The app uses the source directory from the ``srcdir`` funcarg, and writes to the directories given by the ``outdir`` and ``doctreedir`` funcargs. Additional configuration values can be inserted into this application through the ``confoverrides`` funcarg. If the marker ``mock_lookup`` is attached to the current test, the lookup callback returned by the ``mock_lookup`` funcarg is automatically connected to the ``issuetracker-lookup-issue`` event in the the created application. If the marker ``build_app`` is attached to the current test, the app is build before returning it. Otherwise you need to build explicitly in order to get the output. """ srcdir = request.getfuncargvalue('srcdir') outdir = request.getfuncargvalue('outdir') doctreedir = request.getfuncargvalue('doctreedir') confoverrides = request.getfuncargvalue('confoverrides') app = Sphinx(str(srcdir), str(srcdir), str(outdir), str(doctreedir), 'html', confoverrides=confoverrides, status=None, warning=None, freshenv=True) request.addfinalizer(reset_global_state) if 'mock_lookup' in request.keywords: lookup_mock_issue = request.getfuncargvalue('mock_lookup') app.connect(str('issuetracker-lookup-issue'), lookup_mock_issue) if 'build_app' in request.keywords: app.build() return app
def run(self): if not color_terminal(): # Windows' poor cmd box doesn't understand ANSI sequences nocolor() if not self.verbose: status_stream = StringIO() else: status_stream = sys.stdout confoverrides = {} if self.project: confoverrides['project'] = self.project if self.version: confoverrides['version'] = self.version if self.release: confoverrides['release'] = self.release if self.today: confoverrides['today'] = self.today app = Sphinx(self.source_dir, self.config_dir, self.builder_target_dir, self.doctree_dir, self.builder, confoverrides, status_stream, freshenv=self.fresh_env) try: app.build(force_all=self.all_files) except Exception, err: from docutils.utils import SystemMessage if isinstance(err, SystemMessage): print >>sys.stderr, darkred('reST markup error:') print >>sys.stderr, err.args[0].encode('ascii', 'backslashreplace') else: raise
def build(self): """Build the documentation. Places the data into the `outdir` directory. Use it like this:: support = WebSupport(srcdir, builddir, search='xapian') support.build() This will read reStructured text files from `srcdir`. Then it will build the pickles and search index, placing them into `builddir`. It will also save node data to the database. """ if not self.srcdir: raise RuntimeError("No srcdir associated with WebSupport object") app = Sphinx( self.srcdir, self.srcdir, self.outdir, self.doctreedir, "websupport", status=self.status, warning=self.warning, ) app.builder.set_webinfo(self.staticdir, self.staticroot, self.search, self.storage) self.storage.pre_build() app.build() self.storage.post_build()
def test_title(): with open(os.path.join(_srcdir, 'conf.py'), 'w') as f: f.write(''' extensions = [ 'sphinxcontrib.spelling' ] ''') with open(os.path.join(_srcdir, 'contents.rst'), 'w') as f: f.write(''' Welcome to Speeling Checker documentation! ========================================== ''') stdout = StringIO() stderr = StringIO() app = Sphinx(_srcdir, _srcdir, _outdir, _outdir, 'spelling', status=stdout, warning=stderr, freshenv=True, ) app.build() with codecs.open(app.builder.output_filename, 'r') as f: output_text = f.read() def check_one(word): print output_text assert word in output_text for word in [ '(Speeling)', ]: yield check_one, word return
def test_spelling(self): status = StringIO() with TemporaryDirectory() as OUT_DIR: with tmp_list_append(sys.argv, 'spelling'): try: app = Sphinx( srcdir=DOCS_DIR, confdir=DOCS_DIR, outdir=OUT_DIR, doctreedir=OUT_DIR, buildername="spelling", warningiserror=True, status=status, confoverrides={ 'extensions': [ 'djangocms', 'sphinx.ext.intersphinx', 'sphinxcontrib.spelling' ] } ) app.build() self.assertEqual(app.statuscode, 0, status.getvalue()) except SphinxWarning: # while normally harmless, causes a test failure pass except: print(status.getvalue()) raise
def run(self): from sphinx.application import Sphinx sph = Sphinx('./doc/source', # source directory './doc/source', # directory containing conf.py self.output_dir, # output directory './doc/build/doctrees', # doctree directory self.target) # finally, specify the doctest builder' sph.build()
def runsphinx(text, builder, confoverrides): f = open(os.path.join(_srcdir, "index.rst"), "w") try: f.write(text.encode("utf-8")) finally: f.close() app = Sphinx(_srcdir, _fixturedir, _outdir, _outdir, builder, confoverrides) app.build()
def test_html(self): nullout = StringIO() with TemporaryDirectory() as OUT_DIR: app = Sphinx(DOCS_DIR, DOCS_DIR, OUT_DIR, OUT_DIR, "html", warningiserror=True, status=nullout) try: app.build() except: print nullout.getvalue() raise
def runsphinx(text, builder, confoverrides): f = open(os.path.join(_srcdir, 'index.rst'), 'w') try: f.write(text) finally: f.close() app = Sphinx(_srcdir, _fixturedir, _outdir, _outdir, builder, confoverrides) app.build()
def test_html_documentation(self): app = Sphinx( self.source_dir, self.config_dir, self.output_dir, self.doctree_dir, buildername='html', warningiserror=True, ) app.build(force_all=self.all_files)
def sphinx_worker(base_path, work_queue, output_queue): "A background worker thread performing Sphinx compilations" # Set up the Sphinx instance srcdir = base_path confdir = srcdir outdir = os.path.join(srcdir, '_build', 'json') freshenv = False warningiserror = False buildername = 'json' # verbosity = 0 # parallel = 0 status = SphinxStatusHandler(output_queue) warning = SphinxWarningHandler(output_queue) # error = sys.stderr # warnfile = None confoverrides = {} tags = [] doctreedir = os.path.join(outdir, '.doctrees') output_queue.put(InitializationStart()) sphinx = Sphinx(srcdir, confdir, outdir, doctreedir, buildername, confoverrides, status, warning, freshenv, warningiserror, tags) output_queue.put(InitializationEnd(extension=sphinx.config.source_suffix)) quit = False while not quit: # Get the next command off the work queue cmd = work_queue.get(block=True) if isinstance(cmd, Quit): quit = True elif isinstance(cmd, ReloadConfig): output_queue.put(InitializationStart()) freshenv = True sphinx = Sphinx(srcdir, confdir, outdir, doctreedir, buildername, confoverrides, status, warning, freshenv, warningiserror, tags) output_queue.put(InitializationEnd(extension=sphinx.config.source_suffix)) elif isinstance(cmd, BuildAll): output_queue.put(BuildStart(filenames=None)) sphinx.builder.build_all() output_queue.put(BuildEnd(filenames=None)) elif isinstance(cmd, BuildSpecific): output_queue.put(BuildStart(filenames=cmd.filenames)) sphinx.builder.build_specific(cmd.filenames) output_queue.put(BuildEnd(filenames=cmd.filenames)) # Reset the warning count so that they don't accumulate between builds. sphinx._warncount = 0
def test_text_documentation(self): # The same, but with different buildername app = Sphinx( self.source_dir, self.config_dir, self.output_dir, self.doctree_dir, buildername='text', warningiserror=False, ) app.build(force_all=self.all_files)
def __init__(self): if not exists(self.on_the_fly_doc_dir): os.mkdir(self.on_the_fly_doc_dir) Sphinx.__init__(self, srcdir = self.on_the_fly_doc_dir, confdir = openalea.misc.__path__[0], outdir = self.on_the_fly_doc_dir, doctreedir = self.on_the_fly_doc_dir, buildername = None, freshenv = True)
def test_01_html(self): with TemporaryDirectory() as OUT_DIR: app = Sphinx( DOCS_DIR, DOCS_DIR, OUT_DIR, OUT_DIR, "html", warningiserror=True, ) app.build()
def build(test_dir, confoverrides=None): os.chdir("tests/python/{0}".format(test_dir)) app = Sphinx( srcdir=".", confdir=".", outdir="_build/text", doctreedir="_build/.doctrees", buildername="text", confoverrides=confoverrides, ) app.build(force_all=True)
def __convertReSTSphinx(self, text): """ Private method to convert ReST text into HTML using 'sphinx'. @param text text to be processed (string) @return processed HTML (string) """ try: from sphinx.application import Sphinx # __IGNORE_EXCEPTION__ except ImportError: return self.tr( """<p>ReStructuredText preview requires the""" """ <b>sphinx</b> package.<br/>Install it with""" """ your package manager,'pip install Sphinx' or see""" """ <a href="http://pypi.python.org/pypi/Sphinx">""" """this page.</a></p>""" """<p>Alternatively you may disable Sphinx usage""" """ on the Editor, Filehandling configuration page.</p>""") tempDir = tempfile.mkdtemp(prefix='eric-rest-') try: filename = 'sphinx_preview' basePath = os.path.join(tempDir, filename) fh = open(basePath + '.rst', 'w', encoding='utf-8') fh.write(text) fh.close() overrides = {'html_add_permalinks': False, 'html_copy_source': False, 'html_title': 'Sphinx preview', 'html_use_index': False, 'html_use_modindex': False, 'html_use_smartypants': True, 'master_doc': filename} app = Sphinx(srcdir=tempDir, confdir=None, outdir=tempDir, doctreedir=tempDir, buildername='html', confoverrides=overrides, status=None, warning=io.StringIO()) app.build(force_all=True, filenames=None) fh = open(basePath + '.html', 'r', encoding='utf-8') html = fh.read() fh.close() finally: shutil.rmtree(tempDir) # Replace the "_static/..." references inserted by Sphinx with absolute # links to the specified DefaultStaticPath replacement. def replace(m): return '{0}="file://{1}{2}"'.format( m.group(1), self.DefaultStaticPath, m.group(2)) html = re.sub(self.StaticRegexp, replace, html) return html
def setup(app: Sphinx): def cut_module_meta(app, what, name, obj, options, lines): """Remove metadata from autodoc output.""" if what != 'module': return lines[:] = [ line for line in lines if not line.startswith((':copyright:', ':license:')) ] app.connect('autodoc-process-docstring', cut_module_meta)
def test_autodoc(tmpdir): root = str(tmpdir) tmpdir.join('conf.py').write("extensions = ['sphinx.ext.autodoc']\n") tmpdir.join('contents.rst').write( ".. automodule:: reg.tests.fixtures.module\n" " :members:\n") # status=None makes Sphinx completely quiet, in case you run # py.test with the -s switch. For debugging you might want to # remove it. app = Sphinx(root, root, root, root, 'text', status=None) app.build() assert tmpdir.join('contents.txt').read() == """\
def test_docs_build(self): from sphinx.application import Sphinx with TemporaryDirectory() as OUT_DIR: with open(os.path.join(OUT_DIR, "log"), "w+") as fobj: app = Sphinx(DOCS_DIR, DOCS_DIR, OUT_DIR, OUT_DIR, "html", warningiserror=True, status=fobj) try: app.build() except Exception: e = sys.exc_info()[1] fobj.seek(0) self.fail("%s\n%s" % (e, fobj.read()))
def test(self): from sphinx.application import Sphinx app = Sphinx(srcdir=str(root/'docs'), confdir=str(root/'docs'), outdir=str(self.tmpdir/'html'), doctreedir=str(self.tmpdir/'doctree'), buildername='html', freshenv=True, warningiserror=True, confoverrides=dict(nitpicky=True)) app.build() if app.statuscode: self.fail('sphinx build failed with code {}'.format(app.statuscode))
def pytest_funcarg__app(request): """ *Built* Sphinx application for the current test. """ srcdir = request.getfuncargvalue('srcdir') outdir = request.getfuncargvalue('outdir') doctreedir = request.getfuncargvalue('doctreedir') confoverrides = request.getfuncargvalue('confoverrides') app = Sphinx(str(srcdir), str(srcdir), str(outdir), str(doctreedir), 'html', status=None, warning=None, freshenv=None, confoverrides=confoverrides) app.build() return app
def setup(app: Sphinx) -> Dict[str, Any]: app.setup_extension('sphinx.builders.html') app.add_builder(HTMLHelpBuilder) app.add_message_catalog(__name__, path.join(package_dir, 'locales')) app.add_config_value('htmlhelp_basename', default_htmlhelp_basename, None) app.add_config_value('htmlhelp_file_suffix', None, 'html', [str]) app.add_config_value('htmlhelp_link_suffix', None, 'html', [str]) return { 'version': __version__, 'parallel_read_safe': True, 'parallel_write_safe': True, }
def setup(app: Sphinx) -> Dict[str, Any]: app.add_builder(MessageCatalogBuilder) app.add_config_value('gettext_compact', True, 'gettext', Any) app.add_config_value('gettext_location', True, 'gettext') app.add_config_value('gettext_uuid', False, 'gettext') app.add_config_value('gettext_auto_build', True, 'env') app.add_config_value('gettext_additional_targets', [], 'env') app.add_config_value('gettext_last_translator', 'FULL NAME <EMAIL@ADDRESS>', 'gettext') app.add_config_value('gettext_language_team', 'LANGUAGE <*****@*****.**>', 'gettext') return { 'version': 'builtin', 'parallel_read_safe': True, 'parallel_write_safe': True, }
def load_eval_sphinx(app: Sphinx) -> None: """Load the eval domain.""" app.add_role("eval", EvalRoleAny(), override=True) app.add_directive("eval", EvalDirectiveAny, override=True) app.add_domain(NbEvalDomain)
def setup(app: Sphinx): app.add_directive("autosummary", AutosummaryWidths, override=True) app.add_directive("autosummary-widths", WidthsDirective) app.connect("build-finished", latex.replace_unknown_unicode) app.connect("config-inited", configure)
def setup(app: Sphinx) -> Dict[str, Any]: app.setup_extension('sphinx.ext.graphviz') app.add_node(inheritance_diagram, latex=(latex_visit_inheritance_diagram, None), html=(html_visit_inheritance_diagram, None), text=(skip, None), man=(skip, None), texinfo=(texinfo_visit_inheritance_diagram, None)) app.add_directive('inheritance-diagram', InheritanceDiagram) app.add_config_value('inheritance_graph_attrs', {}, False) app.add_config_value('inheritance_node_attrs', {}, False) app.add_config_value('inheritance_edge_attrs', {}, False) app.add_config_value('inheritance_alias', {}, False) return {'version': sphinx.__display_version__, 'parallel_read_safe': True}
def setup(app: Sphinx) -> None: """Connects the extension to the Sphinx process.""" # Register callback at the builder-inited Sphinx event # See https://www.sphinx-doc.org/en/master/extdev/appapi.html app.connect("builder-inited", build_options_page)
def setup(app: Sphinx) -> Dict[str, Any]: app.add_transform(FootnoteDocnameUpdater) app.add_post_transform(SubstitutionDefinitionsRemover) app.add_post_transform(BibliographyTransform) app.add_post_transform(CitationReferenceTransform) app.add_post_transform(DocumentTargetTransform) app.add_post_transform(IndexInSectionTitleTransform) app.add_post_transform(LaTeXFootnoteTransform) app.add_post_transform(LiteralBlockTransform) app.add_post_transform(MathReferenceTransform) app.add_post_transform(ShowUrlsTransform) return { 'version': 'builtin', 'parallel_read_safe': True, 'parallel_write_safe': True, }
def make_app(**kwargs): """ Create a dummy Sphinx app, filling in various hardcoded assumptions. For example, Sphinx assumes the existence of various source/dest directories, even if you're only calling internals that never generate (or sometimes, even read!) on-disk files. This function creates safe temp directories for these instances. It also neuters Sphinx's internal logging, which otherwise causes verbosity in one's own test output and/or debug logs. Finally, it does load the given srcdir's ``conf.py``, but only to read specific bits like ``extensions`` (if requested); most of it is ignored. All args are stored in a single ``**kwargs``. Aside from the params listed below (all of which are optional), all kwargs given are turned into 'releases_xxx' config settings; e.g. ``make_app(foo='bar')`` is like setting ``releases_foo = 'bar'`` in ``conf.py``. :param str docname: Override the document name used (mostly for internal testing). :param str srcdir: Sphinx source directory path. :param str dstdir: Sphinx dest directory path. :param str doctreedir: Sphinx doctree directory path. :param bool load_extensions: Whether to load the real ``conf.py`` and setup any extensions it configures. Default: ``False``. :returns: A Sphinx ``Application`` instance. .. versionchanged:: 1.6 Added the ``load_extensions`` kwarg. """ srcdir = kwargs.pop("srcdir", mkdtemp()) dstdir = kwargs.pop("dstdir", mkdtemp()) doctreedir = kwargs.pop("doctreedir", mkdtemp()) load_extensions = kwargs.pop("load_extensions", False) real_conf = None try: # Sphinx <1.6ish Sphinx._log = lambda self, message, wfile, nonl=False: None # Sphinx >=1.6ish. Technically still lets Very Bad Things through, # unlike the total muting above, but probably OK. # NOTE: used to just do 'sphinx' but that stopped working, even on # sphinx 1.6.x. Weird. Unsure why hierarchy not functioning. for name in ("sphinx", "sphinx.sphinx.application"): logging.getLogger(name).setLevel(logging.ERROR) # App API seems to work on all versions so far. app = Sphinx( srcdir=srcdir, confdir=None, outdir=dstdir, doctreedir=doctreedir, buildername="html", ) # Might as well load the conf file here too. if load_extensions: real_conf = load_conf(srcdir) finally: for d in (srcdir, dstdir, doctreedir): # Only remove empty dirs; non-empty dirs are implicitly something # that existed before we ran, and should not be touched. try: os.rmdir(d) except OSError: pass setup(app) # Mock out the config within. More assumptions by Sphinx :( # TODO: just use real config and overlay what truly needs changing? is that # feasible given the rest of the weird ordering we have to do? If it is, # maybe just literally slap this over the return value of load_conf()... config = { "releases_release_uri": "foo_%s", "releases_issue_uri": "bar_%s", "releases_debug": False, "master_doc": "index", } # Allow tinkering with document filename if "docname" in kwargs: app.env.temp_data["docname"] = kwargs.pop("docname") # Allow config overrides via kwargs for name in kwargs: config["releases_{}".format(name)] = kwargs[name] # Stitch together as the sphinx app init() usually does w/ real conf files app.config._raw_config = config # init_values() requires a 'warn' runner on Sphinx 1.3-1.6, so if we seem # to be hitting arity errors, give it a dummy such callable. Hopefully # calling twice doesn't introduce any wacko state issues :( try: app.config.init_values() except TypeError: # boy I wish Python had an ArityError or w/e app.config.init_values(lambda x: x) # Initialize extensions (the internal call to this happens at init time, # which of course had no valid config yet here...) if load_extensions: for extension in real_conf.get("extensions", []): # But don't set up ourselves again, that causes errors if extension == "releases": continue app.setup_extension(extension) return app
def setup(app: Sphinx) -> Dict[str, Any]: app.setup_extension('sphinx.builders.latex.transforms') app.add_builder(LaTeXBuilder) app.connect('config-inited', validate_config_values) app.add_config_value( 'latex_engine', default_latex_engine, None, ENUM('pdflatex', 'xelatex', 'lualatex', 'platex', 'uplatex')) app.add_config_value('latex_documents', default_latex_documents, None) app.add_config_value('latex_logo', None, None, [str]) app.add_config_value('latex_appendices', [], None) app.add_config_value('latex_use_latex_multicolumn', False, None) app.add_config_value('latex_use_xindy', default_latex_use_xindy, None, [bool]) app.add_config_value('latex_toplevel_sectioning', None, None, ENUM(None, 'part', 'chapter', 'section')) app.add_config_value('latex_domain_indices', True, None, [list]) app.add_config_value('latex_show_urls', 'no', None) app.add_config_value('latex_show_pagerefs', False, None) app.add_config_value('latex_elements', {}, None) app.add_config_value('latex_additional_files', [], None) app.add_config_value('latex_docclass', default_latex_docclass, None) return { 'version': 'builtin', 'parallel_read_safe': True, 'parallel_write_safe': True, }
def setup(app: Sphinx) -> None: app.add_config_value("revision", "", True) app.add_css_file("rtd_theme_overrides.css")
def setup(app: Sphinx) -> Dict[str, Any]: app.add_builder(CoverageBuilder) app.add_config_value('coverage_ignore_modules', [], False) app.add_config_value('coverage_ignore_functions', [], False) app.add_config_value('coverage_ignore_classes', [], False) app.add_config_value('coverage_ignore_pyobjects', [], False) app.add_config_value('coverage_c_path', [], False) app.add_config_value('coverage_c_regexes', {}, False) app.add_config_value('coverage_ignore_c_items', {}, False) app.add_config_value('coverage_write_headline', True, False) app.add_config_value('coverage_skip_undoc_in_source', False, False) return {'version': sphinx.__display_version__, 'parallel_read_safe': True}
def sphinxify(docstring, context, buildername='html'): """ Runs Sphinx on a docstring and outputs the processed documentation. Parameters ---------- docstring : str a ReST-formatted docstring context : dict Variables to be passed to the layout template to control how its rendered (through the Sphinx variable *html_context*). buildername: str It can be either `html` or `text`. Returns ------- An Sphinx-processed string, in either HTML or plain text format, depending on the value of `buildername` """ srcdir = mkdtemp() srcdir = encoding.to_unicode_from_fs(srcdir) base_name = osp.join(srcdir, 'docstring') rst_name = base_name + '.rst' if buildername == 'html': suffix = '.html' else: suffix = '.txt' output_name = base_name + suffix # This is needed so users can type \\ on latex eqnarray envs inside raw # docstrings if context['right_sphinx_version'] and context['math_on']: docstring = docstring.replace('\\\\', '\\\\\\\\') # Add a class to several characters on the argspec. This way we can # highlight them using css, in a similar way to what IPython does. # NOTE: Before doing this, we escape common html chars so that they # don't interfere with the rest of html present in the page argspec = escape(context['argspec']) for char in ['=', ',', '(', ')', '*', '**']: argspec = argspec.replace( char, '<span class="argspec-highlight">' + char + '</span>') context['argspec'] = argspec doc_file = codecs.open(rst_name, 'w', encoding='utf-8') doc_file.write(docstring) doc_file.close() temp_confdir = False if temp_confdir: # TODO: This may be inefficient. Find a faster way to do it. confdir = mkdtemp() confdir = encoding.to_unicode_from_fs(confdir) generate_configuration(confdir) else: confdir = osp.join(get_module_source_path('spyder.utils.help')) confoverrides = {'html_context': context} doctreedir = osp.join(srcdir, 'doctrees') sphinx_app = Sphinx(srcdir, confdir, srcdir, doctreedir, buildername, confoverrides, status=None, warning=None, freshenv=True, warningiserror=False, tags=None) try: sphinx_app.build(None, [rst_name]) except SystemMessage: output = _("It was not possible to generate rich text help for this " "object.</br>" "Please see it in plain text.") return warning(output) # TODO: Investigate if this is necessary/important for us if osp.exists(output_name): output = codecs.open(output_name, 'r', encoding='utf-8').read() output = output.replace('<pre>', '<pre class="literal-block">') else: output = _("It was not possible to generate rich text help for this " "object.</br>" "Please see it in plain text.") return warning(output) if temp_confdir: shutil.rmtree(confdir, ignore_errors=True) shutil.rmtree(srcdir, ignore_errors=True) return output
def setup(app: Sphinx) -> Dict[str, Any]: app.add_node(graphviz, html=(html_visit_graphviz, None), latex=(latex_visit_graphviz, None), texinfo=(texinfo_visit_graphviz, None), text=(text_visit_graphviz, None), man=(man_visit_graphviz, None)) app.add_directive('graphviz', Graphviz) app.add_directive('graph', GraphvizSimple) app.add_directive('digraph', GraphvizSimple) app.add_config_value('graphviz_dot', 'dot', 'html') app.add_config_value('graphviz_dot_args', [], 'html') app.add_config_value('graphviz_output_format', 'png', 'html') app.add_css_file('graphviz.css') app.connect('build-finished', on_build_finished) return {'version': sphinx.__display_version__, 'parallel_read_safe': True}
def sphinxify(docstring, format='html'): r""" Runs Sphinx on a ``docstring``, and outputs the processed documentation. INPUT: - ``docstring`` -- string -- a ReST-formatted docstring - ``format`` -- string (optional, default 'html') -- either 'html' or 'text' OUTPUT: - string -- Sphinx-processed documentation, in either HTML or plain text format, depending on the value of ``format`` EXAMPLES:: sage: from sage.misc.sphinxify import sphinxify sage: sphinxify('A test') '<div class="docstring">\n \n <p>A test</p>\n\n\n</div>' sage: sphinxify('**Testing**\n`monospace`') '<div class="docstring"...<strong>Testing</strong>\n<span class="math...</p>\n\n\n</div>' sage: sphinxify('`x=y`') '<div class="docstring">\n \n <p><span class="math notranslate nohighlight">x=y</span></p>\n\n\n</div>' sage: sphinxify('`x=y`', format='text') 'x=y\n' sage: sphinxify(':math:`x=y`', format='text') 'x=y\n' TESTS:: sage: n = len(sys.path) sage: _ = sphinxify('A test') sage: assert n == len(sys.path) """ srcdir = mkdtemp() outdir = mkdtemp() src_base_name = os.path.join(srcdir, 'docstring') out_base_name = os.path.join(outdir, 'docstring') rst_name = src_base_name + '.rst' if format == 'html': suffix = '.html' else: suffix = '.txt' output_name = out_base_name + suffix with open(rst_name, 'w') as filed: filed.write(docstring) confdir = os.path.join(SAGE_DOC_SRC, 'en', 'introspect') open(os.path.join(srcdir, 'docutils.conf'), 'w').write(r""" [parsers] smart_quotes = no """) doctreedir = os.path.join(srcdir, 'doctrees') confoverrides = {'html_context': {}, 'master_doc': 'docstring'} import sys old_sys_path = list(sys.path) # Sphinx modifies sys.path # Sphinx constructor: Sphinx(srcdir, confdir, outdir, doctreedir, # buildername, confoverrides, status, warning, freshenv). sphinx_app = Sphinx(srcdir, confdir, outdir, doctreedir, format, confoverrides, None, None, True) sphinx_app.build(None, [rst_name]) sys.path = old_sys_path # We need to remove "_" from __builtin__ that the gettext module installs from six.moves import builtins builtins.__dict__.pop('_', None) if os.path.exists(output_name): output = open(output_name, 'r').read() output = output.replace('<pre>', '<pre class="literal-block">') # Translate URLs for media from something like # "../../media/...path.../blah.png" # or # "/media/...path.../blah.png" # to # "/doc/static/reference/media/...path.../blah.png" output = re.sub(r"""src=['"](/?\.\.)*/?media/([^"']*)['"]""", 'src="/doc/static/reference/media/\\2"', output) # Remove spurious \(, \), \[, \]. output = output.replace('\\(', '').replace('\\)', '').replace('\\[', '').replace('\\]', '') else: from warnings import warn warn("Sphinx did not produce any output", Warning) if format == 'html': output = '<pre class="introspection">%s</pre>' % docstring else: output = docstring shutil.rmtree(srcdir, ignore_errors=True) shutil.rmtree(outdir, ignore_errors=True) return output
def setup(app: Sphinx) -> Dict[str, Any]: app.connect('autodoc-before-process-signature', update_annotations_using_type_comments) return {'version': sphinx.__display_version__, 'parallel_read_safe': True}
def setup(app: Sphinx) -> SphinxExtMetadata: """ Setup :mod:`sphinx_toolbox.code`. .. versionadded:: 1.0.0 :param app: The Sphinx application. """ # Code block with customisable indent size. app.add_directive("code-block", CodeBlock, override=True) app.add_directive("sourcecode", CodeBlock, override=True) app.add_directive("code-cell", CodeCell) app.add_directive("output-cell", OutputCell) # Hack to get the docutils tab size, as there doesn't appear to be any other way app.setup_extension("sphinx_toolbox.tweaks.tabsize") app.add_node(Prompt, html=(visit_prompt_html, lambda *args, **kwargs: None), latex=(visit_prompt_latex, lambda *args, **kwargs: None)) app.connect("config-inited", configure) app.add_css_file("sphinx-toolbox-code.css") app.connect("build-finished", copy_asset_files) return {"parallel_read_safe": True}
def setup(app: Sphinx) -> Dict[str, Any]: app.add_event('todo-defined') app.add_config_value('todo_include_todos', False, 'html') app.add_config_value('todo_link_only', False, 'html') app.add_config_value('todo_emit_warnings', False, 'html') app.add_node(todolist) app.add_node(todo_node, html=(visit_todo_node, depart_todo_node), latex=(latex_visit_todo_node, latex_depart_todo_node), text=(visit_todo_node, depart_todo_node), man=(visit_todo_node, depart_todo_node), texinfo=(visit_todo_node, depart_todo_node)) app.add_directive('todo', Todo) app.add_directive('todolist', TodoList) app.add_domain(TodoDomain) app.connect('doctree-resolved', TodoListProcessor) return { 'version': sphinx.__display_version__, 'env_version': 2, 'parallel_read_safe': True }
def setup(app: Sphinx) -> None: _check_version(app) app.connect('builder-inited', _setup_translators) return {'parallel_read_safe': True}
def setup(app: Sphinx): app.add_config_value('api_dir', Path(), 'env') app.connect('autodoc-process-docstring', insert_function_images)
def setup(app: Sphinx) -> Dict[str, Any]: app.add_builder(TexinfoBuilder) app.add_config_value('texinfo_documents', default_texinfo_documents, None) app.add_config_value('texinfo_appendices', [], None) app.add_config_value('texinfo_elements', {}, None) app.add_config_value('texinfo_domain_indices', True, None, [list]) app.add_config_value('texinfo_show_urls', 'footnote', None) app.add_config_value('texinfo_no_detailmenu', False, None) return { 'version': 'builtin', 'parallel_read_safe': True, 'parallel_write_safe': True, }
def setup(app: Sphinx) -> Dict[str, Any]: app.add_config_value('viewcode_import', None, False) app.add_config_value('viewcode_enable_epub', False, False) app.add_config_value('viewcode_follow_imported_members', True, False) app.connect('config-inited', migrate_viewcode_import) app.connect('doctree-read', doctree_read) app.connect('env-merge-info', env_merge_info) app.connect('html-collect-pages', collect_pages) app.connect('missing-reference', missing_reference) # app.add_config_value('viewcode_include_modules', [], 'env') # app.add_config_value('viewcode_exclude_modules', [], 'env') app.add_event('viewcode-find-source') app.add_event('viewcode-follow-imported') return { 'version': sphinx.__display_version__, 'env_version': 1, 'parallel_read_safe': True }
def setup(app: Sphinx) -> Dict[str, Any]: app.add_builder(CheckExternalLinksBuilder) app.add_config_value('linkcheck_ignore', [], None) app.add_config_value('linkcheck_auth', [], None) app.add_config_value('linkcheck_request_headers', {}, None) app.add_config_value('linkcheck_retries', 1, None) app.add_config_value('linkcheck_timeout', None, None, [int]) app.add_config_value('linkcheck_workers', 5, None) app.add_config_value('linkcheck_anchors', True, None) # Anchors starting with ! are ignored since they are # commonly used for dynamic pages app.add_config_value('linkcheck_anchors_ignore', ["^!"], None) app.add_config_value('linkcheck_rate_limit_timeout', 300.0, None) return { 'version': 'builtin', 'parallel_read_safe': True, 'parallel_write_safe': True, }
def setup(app: Sphinx): # Don’t allow broken links. DO NOT CHANGE THIS LINE, fix problems instead. app.warningiserror = True
def setup(app: Sphinx) -> Dict[str, Any]: app.add_html_math_renderer('mathjax', (html_visit_math, None), (html_visit_displaymath, None)) # more information for mathjax secure url is here: # https://docs.mathjax.org/en/latest/start.html#secure-access-to-the-cdn app.add_config_value( 'mathjax_path', 'https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.7/latest.js?' 'config=TeX-AMS-MML_HTMLorMML', 'html') app.add_config_value('mathjax_options', {}, 'html') app.add_config_value('mathjax_inline', [r'\(', r'\)'], 'html') app.add_config_value('mathjax_display', [r'\[', r'\]'], 'html') app.add_config_value('mathjax_config', None, 'html') app.connect('env-updated', install_mathjax) return {'version': sphinx.__display_version__, 'parallel_read_safe': True}
def sphinxify(docstring, format='html'): r""" Runs Sphinx on a ``docstring``, and outputs the processed documentation. INPUT: - ``docstring`` -- string -- a ReST-formatted docstring - ``format`` -- string (optional, default 'html') -- either 'html' or 'text' OUTPUT: - string -- Sphinx-processed documentation, in either HTML or plain text format, depending on the value of ``format`` EXAMPLES:: sage: from sagenb.misc.sphinxify import sphinxify sage: sphinxify('A test') '\n<div class="docstring">\n \n <p>A test</p>\n\n\n</div>' sage: sphinxify('**Testing**\n`monospace`') '\n<div class="docstring"...<strong>Testing</strong>\n<span class="math"...</p>\n\n\n</div>' sage: sphinxify('`x=y`') '\n<div class="docstring">\n \n <p><span class="math">x=y</span></p>\n\n\n</div>' sage: sphinxify('`x=y`', format='text') 'x=y\n' sage: sphinxify(':math:`x=y`', format='text') 'x=y\n' """ global Sphinx if not Sphinx: from sphinx.application import Sphinx srcdir = mkdtemp() base_name = os.path.join(srcdir, 'docstring') rst_name = base_name + '.rst' if format == 'html': suffix = '.html' else: suffix = '.txt' output_name = base_name + suffix # This is needed for jsMath to work. docstring = docstring.replace('\\\\', '\\') filed = open(rst_name, 'w') filed.write(docstring) filed.close() # Sphinx constructor: Sphinx(srcdir, confdir, outdir, doctreedir, # buildername, confoverrides, status, warning, freshenv). temp_confdir = False confdir = os.path.join(SAGE_DOC, 'en', 'introspect') if not SAGE_DOC and not os.path.exists(confdir): # This may be inefficient. TODO: Find a faster way to do this. temp_confdir = True confdir = mkdtemp() generate_configuration(confdir) doctreedir = os.path.join(srcdir, 'doctrees') confoverrides = {'html_context': {}, 'master_doc': 'docstring'} sphinx_app = Sphinx(srcdir, confdir, srcdir, doctreedir, format, confoverrides, None, None, True) sphinx_app.build(None, [rst_name]) #We need to remove "_" from __builtin__ that the gettext module installs import __builtin__ __builtin__.__dict__.pop('_', None) if os.path.exists(output_name): output = open(output_name, 'r').read() output = output.replace('<pre>', '<pre class="literal-block">') # Translate URLs for media from something like # "../../media/...path.../blah.png" # or # "/media/...path.../blah.png" # to # "/doc/static/reference/media/...path.../blah.png" output = re.sub("""src=['"](/?\.\.)*/?media/([^"']*)['"]""", 'src="/doc/static/reference/media/\\2"', output) else: print "BUG -- Sphinx error" if format == 'html': output = '<pre class="introspection">%s</pre>' % docstring else: output = docstring if temp_confdir: shutil.rmtree(confdir, ignore_errors=True) shutil.rmtree(srcdir, ignore_errors=True) return output
def doctree_read(app: Sphinx, doctree: Node) -> None: env = app.builder.env if not hasattr(env, '_viewcode_modules'): env._viewcode_modules = {} # type: ignore if app.builder.name == "singlehtml": return if app.builder.name.startswith("epub") and not env.config.viewcode_enable_epub: return def has_tag(modname, fullname, docname, refname): entry = env._viewcode_modules.get(modname, None) # type: ignore if entry is False: return code_tags = app.emit_firstresult('viewcode-find-source', modname) if code_tags is None: try: analyzer = ModuleAnalyzer.for_module(modname) analyzer.find_tags() except Exception: env._viewcode_modules[modname] = False # type: ignore return code = analyzer.code tags = analyzer.tags else: code, tags = code_tags if entry is None or entry[0] != code: entry = code, tags, {}, refname env._viewcode_modules[modname] = entry # type: ignore _, tags, used, _ = entry if fullname in tags: used[fullname] = docname return True for objnode in doctree.traverse(addnodes.desc): if objnode.get('domain') != 'py': continue names = set() # type: Set[str] for signode in objnode: if not isinstance(signode, addnodes.desc_signature): continue modname = signode.get('module') fullname = signode.get('fullname') refname = modname if env.config.viewcode_follow_imported_members: new_modname = app.emit_firstresult( 'viewcode-follow-imported', modname, fullname, ) if not new_modname: new_modname = _get_full_modname(app, modname, fullname) modname = new_modname if not modname: continue fullname = signode.get('fullname') if not has_tag(modname, fullname, env.docname, refname): continue if fullname in names: # only one link per name, please continue names.add(fullname) pagename = '_modules/' + modname.replace('.', '/') inline = nodes.inline('', _('[source]'), classes=['viewcode-link']) onlynode = addnodes.only(expr='html') onlynode += addnodes.pending_xref('', inline, reftype='viewcode', refdomain='std', refexplicit=False, reftarget=pagename, refid=fullname, refdoc=env.docname) signode += onlynode
def setup(app: Sphinx) -> None: app.add_directive("pip-command-usage", PipCommandUsage) app.add_directive("pip-command-description", PipCommandDescription) app.add_directive("pip-command-options", PipCommandOptions) app.add_directive("pip-general-options", PipGeneralOptions) app.add_directive("pip-index-options", PipIndexOptions) app.add_directive("pip-requirements-file-options-ref-list", PipReqFileOptionsReference) app.add_directive("pip-cli", PipCLIDirective)
def setup(app: Sphinx) -> Dict[str, Any]: app.add_html_math_renderer('mathjax', (html_visit_math, None), (html_visit_displaymath, None)) # more information for mathjax secure url is here: # https://docs.mathjax.org/en/latest/start.html#secure-access-to-the-cdn app.add_config_value( 'mathjax_path', 'https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js', 'html') app.add_config_value('mathjax_options', {}, 'html') app.add_config_value('mathjax_inline', [r'\(', r'\)'], 'html') app.add_config_value('mathjax_display', [r'\[', r'\]'], 'html') app.add_config_value('mathjax_config', None, 'html') app.connect('env-updated', install_mathjax) return {'version': sphinx.__display_version__, 'parallel_read_safe': True}
def __init__(self, srcdir=None, confdir=None, outdir=None, doctreedir=None, buildername='html', confoverrides=None, status=None, warning=None, freshenv=False, warningiserror=False, tags=None, copy_srcdir_to_tmpdir=False, create_new_srcdir=False, cleanup_on_errors=True, verbosity=0, parallel=0): self.cleanup_trees = [] self.cleanup_on_errors = cleanup_on_errors if create_new_srcdir: assert srcdir is None, 'conflicted: create_new_srcdir, srcdir' tmpdir = mkdtemp() self.cleanup_trees.append(tmpdir) tmproot = tmpdir / 'root' tmproot.makedirs() (tmproot / 'conf.py').write_text('') srcdir = tmproot assert srcdir is not None, 'srcdir not found' srcdir = path(srcdir).abspath() if copy_srcdir_to_tmpdir: tmpdir = mkdtemp() self.cleanup_trees.append(tmpdir) tmproot = tmpdir / srcdir.basename() srcdir.copytree(tmproot) srcdir = tmproot self.builddir = srcdir.joinpath('_build') else: self.builddir = mkdtemp() self.cleanup_trees.append(self.builddir) if confdir is None: confdir = srcdir if outdir is None: outdir = self.builddir.joinpath(buildername) if not outdir.isdir(): outdir.makedirs() if doctreedir is None: doctreedir = self.builddir.joinpath('doctrees') if not doctreedir.isdir(): doctreedir.makedirs() if confoverrides is None: confoverrides = {} if status is None: status = StringIO() if warning is None: warning = StringIO() if sphinx_version < '1.3': Sphinx.__init__(self, srcdir, confdir, outdir, doctreedir, buildername, confoverrides, status, warning, freshenv, warningiserror, tags) else: Sphinx.__init__(self, srcdir, confdir, outdir, doctreedir, buildername, confoverrides, status, warning, freshenv, warningiserror, tags, verbosity, parallel)
def setup(app: Sphinx) -> Dict[str, Any]: # I need autodoc app.setup_extension('sphinx.ext.autodoc') app.add_node(autosummary_toc, html=(autosummary_toc_visit_html, autosummary_noop), latex=(autosummary_noop, autosummary_noop), text=(autosummary_noop, autosummary_noop), man=(autosummary_noop, autosummary_noop), texinfo=(autosummary_noop, autosummary_noop)) app.add_node(autosummary_table, html=(autosummary_table_visit_html, autosummary_noop), latex=(autosummary_noop, autosummary_noop), text=(autosummary_noop, autosummary_noop), man=(autosummary_noop, autosummary_noop), texinfo=(autosummary_noop, autosummary_noop)) app.add_directive('autosummary', Autosummary) app.add_role('autolink', AutoLink()) app.connect('builder-inited', process_generate_options) app.add_config_value('autosummary_context', {}, True) app.add_config_value('autosummary_filename_map', {}, 'html') app.add_config_value('autosummary_generate', [], True, [bool]) app.add_config_value('autosummary_generate_overwrite', True, False) app.add_config_value('autosummary_mock_imports', lambda config: config.autodoc_mock_imports, 'env') app.add_config_value('autosummary_imported_members', [], False, [bool]) return {'version': sphinx.__display_version__, 'parallel_read_safe': True}
def build_main(argv: List[str] = sys.argv[1:]) -> int: """Sphinx build "main" command-line entry.""" parser = get_parser() args = parser.parse_args(argv) if args.noconfig: args.confdir = None elif not args.confdir: args.confdir = args.sourcedir if not args.doctreedir: args.doctreedir = os.path.join(args.outputdir, '.doctrees') # handle remaining filename arguments filenames = args.filenames missing_files = [] for filename in filenames: if not os.path.isfile(filename): missing_files.append(filename) if missing_files: parser.error(__('cannot find files %r') % missing_files) if args.force_all and filenames: parser.error(__('cannot combine -a option and filenames')) if args.color == 'no' or (args.color == 'auto' and not color_terminal()): nocolor() status = sys.stdout warning = sys.stderr error = sys.stderr if args.quiet: status = None if args.really_quiet: status = warning = None if warning and args.warnfile: try: warnfp = open(args.warnfile, 'w') except Exception as exc: parser.error( __('cannot open warning file %r: %s') % (args.warnfile, exc)) warning = Tee(warning, warnfp) # type: ignore error = warning confoverrides = {} for val in args.define: try: key, val = val.split('=', 1) except ValueError: parser.error( __('-D option argument must be in the form name=value')) confoverrides[key] = val for val in args.htmldefine: try: key, val = val.split('=') except ValueError: parser.error( __('-A option argument must be in the form name=value')) try: val = int(val) except ValueError: pass confoverrides['html_context.%s' % key] = val if args.nitpicky: confoverrides['nitpicky'] = True app = None try: confdir = args.confdir or args.sourcedir with patch_docutils(confdir), docutils_namespace(): app = Sphinx(args.sourcedir, args.confdir, args.outputdir, args.doctreedir, args.builder, confoverrides, status, warning, args.freshenv, args.warningiserror, args.tags, args.verbosity, args.jobs, args.keep_going) app.build(args.force_all, filenames) return app.statuscode except (Exception, KeyboardInterrupt) as exc: handle_exception(app, args, exc, error) return 2