diff --git a/lib/matplotlib/sphinxext/plot_directive.py b/lib/matplotlib/sphinxext/plot_directive.py index d40e0c58b4a5..c28b2e6a2528 100644 --- a/lib/matplotlib/sphinxext/plot_directive.py +++ b/lib/matplotlib/sphinxext/plot_directive.py @@ -866,10 +866,11 @@ def run(arguments, content, options, state_machine, state, lineno): shutil.copyfile(fn, destimg) # copy script (if necessary) - Path(dest_dir, output_base + source_ext).write_text( - doctest.script_from_examples(code) - if source_file_name == rst_file and is_doctest - else code, - encoding='utf-8') + if config.plot_html_show_source_link: + Path(dest_dir, output_base + source_ext).write_text( + doctest.script_from_examples(code) + if source_file_name == rst_file and is_doctest + else code, + encoding='utf-8') return errors diff --git a/lib/matplotlib/tests/test_sphinxext.py b/lib/matplotlib/tests/test_sphinxext.py index 668563ee5045..02d56aeedc55 100644 --- a/lib/matplotlib/tests/test_sphinxext.py +++ b/lib/matplotlib/tests/test_sphinxext.py @@ -97,10 +97,35 @@ def plot_directive_file(num): assert filecmp.cmp(range_6, plot_file(5)) -def build_sphinx_html(source_dir, doctree_dir, html_dir): +def test_plot_html_show_source_link(tmpdir): + source_dir = Path(tmpdir) / 'src' + source_dir.mkdir() + parent = Path(__file__).parent + shutil.copyfile(parent / 'tinypages/conf.py', source_dir / 'conf.py') + shutil.copytree(parent / 'tinypages/_static', source_dir / '_static') + doctree_dir = source_dir / 'doctrees' + (source_dir / 'index.rst').write_text(""" +.. plot:: + + plt.plot(range(2)) +""") + # Make sure source scripts are created by default + html_dir1 = source_dir / '_build' / 'html1' + build_sphinx_html(source_dir, doctree_dir, html_dir1) + assert "index-1.py" in [p.name for p in html_dir1.iterdir()] + # Make sure source scripts are NOT created when + # plot_html_show_source_link` is False + html_dir2 = source_dir / '_build' / 'html2' + build_sphinx_html(source_dir, doctree_dir, html_dir2, + extra_args=['-D', 'plot_html_show_source_link=0']) + assert "index-1.py" not in [p.name for p in html_dir2.iterdir()] + + +def build_sphinx_html(source_dir, doctree_dir, html_dir, extra_args=None): # Build the pages with warnings turned into errors + extra_args = [] if extra_args is None else extra_args cmd = [sys.executable, '-msphinx', '-W', '-b', 'html', - '-d', str(doctree_dir), str(source_dir), str(html_dir)] + '-d', str(doctree_dir), str(source_dir), str(html_dir), *extra_args] proc = Popen(cmd, stdout=PIPE, stderr=PIPE, universal_newlines=True, env={**os.environ, "MPLBACKEND": ""}) out, err = proc.communicate()