pax_global_header00006660000000000000000000000064145075030000014504gustar00rootroot0000000000000052 comment=6c15c425edda0de3e18d8ecbfd4168a6710a72f7 nb2plots-0.7.2/000077500000000000000000000000001450750300000132555ustar00rootroot00000000000000nb2plots-0.7.2/.coveragerc000066400000000000000000000001351450750300000153750ustar00rootroot00000000000000[run] branch = True source = nb2plots include = */nb2plots/* omit = nb2plots/_version.py nb2plots-0.7.2/.gitattributes000066400000000000000000000000421450750300000161440ustar00rootroot00000000000000nb2plots/_version.py export-subst nb2plots-0.7.2/.github/000077500000000000000000000000001450750300000146155ustar00rootroot00000000000000nb2plots-0.7.2/.github/workflows/000077500000000000000000000000001450750300000166525ustar00rootroot00000000000000nb2plots-0.7.2/.github/workflows/main.yml000066400000000000000000000016261450750300000203260ustar00rootroot00000000000000on: push: branches: - main pull_request: branches: - main name: Run tox tests jobs: tox_test: name: Run tox tests steps: - name: Checkout source code uses: actions/checkout@v2 - name: Run tox tests id: test uses: fedora-python/tox-github-action@main with: tox_env: ${{ matrix.tox_env }} dnf_install: /usr/bin/pandoc - name: Upload HTML coverage report uses: actions/upload-artifact@v2 with: name: html-report path: htmlcov if-no-files-found: ignore strategy: matrix: tox_env: [ # This list has to be maintained manually :( # You can get it from `tox -l | sed "s/$/,/"` # Update in tox.ini py38-min, py38, py39, py310, py311, ] # Use GitHub's Linux Docker host runs-on: ubuntu-latest nb2plots-0.7.2/.gitignore000066400000000000000000000001741450750300000152470ustar00rootroot00000000000000*.pyc *~ __pycache__/ build/ .coverage dist/ *.egg-info/ MANIFEST .ipynb_checkpoints/ htmlcov/ .cache/ .pytest_cache/ .tox/ nb2plots-0.7.2/.mailmap000066400000000000000000000000541450750300000146750ustar00rootroot00000000000000Lumír 'Frenzy' Balhar nb2plots-0.7.2/Changelog000066400000000000000000000077621450750300000151030ustar00rootroot00000000000000################## nb2plots Changelog ################## MB below is short for Matthew Brett. ***** 0.7.2 ***** Bugfix release. * Fixed broken import from change in nbconvert (thanks to Jarrod Millman for the report - issue 32). ***** 0.7.1 ***** Bugfix release. * Fixed broken import in nb2plots, with test (thanks to Jerry James for the report - issue 31). ***** 0.7.0 ***** Maintenance release. * Updates for Tox actions for CI testing (Lumír Balhar). * Drop Python 2.7 and 3.7 * Update to work with Sphinx 7 ***** 0.6.1 ***** Bugfix release. * Fix for newer Docutils change in node attributes (MB). * Test fixes for newer Sphinx, Notebook, nbconvert (Lumir Balhar, MB). * Fix escapes in not-raw strings (Jerry James). * Fix import of Sequence for newer Python (Jerry James). * Update versioneer (MB). * Tox / Github actions for testing (Lumir Balhar) ***** 0.6.0 ***** New feature release. * Add hide from / show to options to nbplot directive. This gives a more flexible way of concealing individual plots from specific builders, such as the HTML or doctest builders. See the documentation of nbplot for more detail. * Fix bug writing Notebooks, Python files for ReST sources not at root of project tree. * Add options to set Jupyter kernel timeout when building full notebooks (thanks to Juan Nunez-Iglesias for the suggestion); * Make compatible with newest Numpy, nbconvert. * Refactor tests to use Pytest instead of Nose. * Refactor Sphinx testers and script running testers in own packages. ***** 0.5.2 ***** Bugfix release. * Fix compatibility with Sphinx 1.6 series; * Fix bug causing crash in LaTeX builder with code-links directives in subdirectories of main project (thanks to Jarrod Millman for the report). ***** 0.5.1 ***** New feature and bugfix release. Minor API breakage. * add explicit Markdown, Python, Notebook builders. You can build the whole site to Markdown with commands like ``sphinx-build -b markdown -d dt_dir src_dir md_dir``. * add ability of Markdown etc builders to resolve internal references relative to an HTTP build, using new ``markdown_http_base`` configuration option; * API break - change of template specification for epilogue to ``nbplot`` output; no longer include the source code in the template, but evaluate source code as ReST separately. This will cause anyone using custom templates pain, as their code will crash. To fix, simply remove the reference to source code in the template; * slightly extend range of doctree nodes that Markdown converter can deal with. *** 0.5 *** New feature release. * add ability to convert ReST to Markdown, Python .py files, clear and full Jupyter notebooks; * add ``mpl-interactive`` directive to signal presence of ``%matplotlib`` commands in notebook and ReST; * add ``code-links`` directive to add links to versions of ReST file as Python ``.py`` file, clear and full notebooks; * add ability to configure alternative versions of nbplot directives according to build-time configuration; * add directive to allow page-specific configuration for the directive alternative machinery; * add more general Sphinx testing machinery; * commit to setuptools; * improve conversion of matplotlib objects from output cells to doctest output in ReST page; * start basic documentation; * minor API breakage - do not split nbplot code blocks at ``plt.show()``. I discovered this horrible hack left over from the matplotlib plot directive when refactoring, and removed it to make refactoring easier; * minor API breakage - do not write individual nbplot directives as ``.py`` files; they don't make much sense for nbplot use, and the code was not linking to these files in any case; *** 0.4 *** New feature release. * ``nb2plots`` script now always outputs converted notebooks as UTF-8, rather than doing a ``print()`` to stdout; * add ``raises`` option to ``nbplot`` directive, to test that nbplot blocks to raise errors while building the HTML; * fix CI testing to actually run on Python 3.3-3.5. .. vim: ft=rst nb2plots-0.7.2/LICENSE000066400000000000000000000155551450750300000142750ustar00rootroot00000000000000.. _license: ********************** Copyright and Licenses ********************** nb2plots ======== The nb2plots package, including all examples, code snippets and attached documentation is covered by the 2-clause BSD license. Copyright (c) 2015-2023, Matthew Brett All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 3rd party code and data ======================= Some code distributed within the nb2plots sources was developed by other projects. This code is distributed under their respective licenses that are listed below. Matplotlib plot extension ------------------------- The ``nbplots`` module is an edited version of ``matplotlib/lib/matplotlib/sphinxext/plot_directive.py``. Among the major changes are the following: * rename of 'plot' directive to 'nbplot'; * rename of 'plot_*' configuration options to 'nbplot_*' equivalent; * nbplot removes the option to point to Python script file rather than using the code in the directive; * nbplot keeps the namespace across directives in the same page, by default; * include-source is True by default; * nbplot can include multiple "parts" that can be selected via the "render-parts" and "run-parts" options; * do not use cached output when rebuilding page to avoid errors from stale output; * fix bug including empty parens when ``nofigs`` not specified (also fixed upstream); * empty ``setup_module`` to avoid breakage of nose doctests; * fix of plot doctest. The following license covers the plot directive code: LICENSE AGREEMENT FOR MATPLOTLIB 1.2.0 -------------------------------------- 1. This LICENSE AGREEMENT is between John D. Hunter ("JDH"), and the Individual or Organization ("Licensee") accessing and otherwise using matplotlib software in source or binary form and its associated documentation. 2. Subject to the terms and conditions of this License Agreement, JDH hereby grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce, analyze, test, perform and/or display publicly, prepare derivative works, distribute, and otherwise use matplotlib 1.2.0 alone or in any derivative version, provided, however, that JDH's License Agreement and JDH's notice of copyright, i.e., "Copyright (c) 2002-2011 John D. Hunter; All Rights Reserved" are retained in matplotlib 1.2.0 alone or in any derivative version prepared by Licensee. 3. In the event Licensee prepares a derivative work that is based on or incorporates matplotlib 1.2.0 or any part thereof, and wants to make the derivative work available to others as provided herein, then Licensee hereby agrees to include in any such work a brief summary of the changes made to matplotlib 1.2.0. 4. JDH is making matplotlib 1.2.0 available to Licensee on an "AS IS" basis. JDH MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, JDH MAKES NO AND DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF MATPLOTLIB 1.2.0 WILL NOT INFRINGE ANY THIRD PARTY RIGHTS. 5. JDH SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF MATPLOTLIB 1.2.0 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING MATPLOTLIB 1.2.0, OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. 6. This License Agreement will automatically terminate upon a material breach of its terms and conditions. 7. Nothing in this License Agreement shall be deemed to create any relationship of agency, partnership, or joint venture between JDH and Licensee. This License Agreement does not grant permission to use JDH trademarks or trade name in a trademark sense to endorse or promote products or services of Licensee, or any third party. 8. By copying, installing or otherwise using matplotlib 1.2.0, Licensee agrees to be bound by the terms and conditions of this License Agreement. rst2md ------ The files nb2plots/doctree2md.py and scripts/rst2md derive from the "markdown.py" and "rst2md.py" files from "rst2md" project by Chris Wrench: https://github.com/cgwrench/rst2md ``rst2md`` has the following license: Copyright (c) 2012, C. G. Wrench All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. nb2plots-0.7.2/MANIFEST.in000066400000000000000000000004371450750300000150170ustar00rootroot00000000000000include versioneer.py include nb2plots/_version.py include README.rst include LICENSE include *requirements.txt recursive-include nb2plots/tests/proj1 * recursive-include nb2plots/tests/data * recursive-include nb2plots/tests/rst_md_files * recursive-include nb2plots/tests/otherpages * nb2plots-0.7.2/README.rst000066400000000000000000000136241450750300000147520ustar00rootroot00000000000000################################################## nb2plots - converting between notebooks and sphinx ################################################## See the nb2plots documentation_ for more information. .. shared-text-body ************ What it does ************ ``nb2plots`` converts Jupyter_ notebooks to ReST_ files for Sphinx_, and back again. Nb2plots assumes that the ReST document will become the source for your Sphinx web pages, but also for future versions of the notebook. The notebook may serve as a draft for the polished ReST page, and an output format from the Sphinx build. Why? Read on. **************************************** Why convert Jupyter notebooks to Sphinx? **************************************** Jupyter notebooks are just what the doctor ordered when hacking up a quick tutorial, or preparing a software demo. The problems start when you want to do not-trivial edits to the notebooks, or you need features that notebooks don't have, such as flexible cross-referencing, extensible markup, and so on. Notebooks are also painful to use with version control. These times make you wish your notebook was in a standard extensible text format, such as ReST_. You could convert your notebook to ReST using the standard `nbconvert`_ command, but this gives rather ugly ReST, and you lose all the nice code execution and figure generation that the notebook is good at. Enter Nb2plots. The ``nb2plots`` command converts notebooks to specially formatted ReST pages. Use with:: nb2plots notebook.ipynb > with_plots.rst Nb2plots converts your notebook to not-very-ugly ReST, where the code cells become ``nbplot`` directives in your ReST file. Specifically, a notebook code cell like this:: a = 1 becomes (in the ReST document):: .. nbplot:: >>> a = 1 The ``nbplot`` directives run the contained code when Sphinx builds your ReST files, and embed the results of any plots that your code makes. Actually, ``nbplot`` is an extended and edited version of the `matplotlib plot directive`_. Building your pages runs all the code and regenerates the figures, and you get much of the reproducible goodness of the notebook experience. You can also run the standard Sphinx ``doctest`` extension over your pages to check the doctest output of the code cells. The ReST version of your notebook has many advantages - it is easier to edit in your favorite text editor, and you can extend and configure the execution and display of the code in several different ways. For example, you can hide some code cells (Nbplot directives) if the code is not interesting to your point, but you still want the generated figure. You can configure your Nbplot directives to run different code for different configurations. For these options, see |nbplot-documentation|. But - what do you lose, when going from a notebook to a Nb2plots ReST document? ********************************** I want notebooks and .py files too ********************************** You may also want a version of your document that your users can execute. Perhaps the page build is generating some tricky errors or warnings, and you want to experiment with the code in the page interactively. Perhaps your users are used to notebooks, and prefer the code in that format. Nb2plots also contains Sphinx extensions that cause the Sphinx build to generate Python code files and Jupyter notebooks from the ReST source. When you add the Nb2plots ReST directive ``code-links`` to your ReST page, it will cause the Sphinx build to create a Python code file and notebook versions of your page, and adds download links to these versions:: .. code-links:: See |code-links-documentation| for details. ************************** Show me what it looks like ************************** For a very simple example, see |worked-example|. For a moderate-sized teaching site that makes extensive use of Nb2plots, see https://matthew-brett.github.io/teaching. ************ Installation ************ :: pip install nb2plots You will need Pandoc_ installed and available as the ``pandoc`` command. To install Pandoc on OSX, we recommend homebrew_:: brew install pandoc ************* Configuration ************* Add the following to your Sphinx ``conf.py`` file:: extensions = ["nb2plots"] See |nbplot-documentation| for the various ``conf.py`` configuration settings. **** Code **** See https://github.com/matthew-brett/nb2plots Released under the BSD two-clause license - see the file ``LICENSE`` in the source distribution. Github Actions kindly tests the code automatically under Python versions 3.8 through 3.11. The latest released version is at https://pypi.python.org/pypi/nb2plots ***** Tests ***** * Install ``nb2plots`` * Install the pytest_ testing framework, the ``mock`` package, and the ``scripttester`` package:: pip install pytest mock scripttester * Run the tests with:: py.test --pyargs nb2plots ******* Support ******* Please put up issues on the `nb2plots issue tracker`_. .. standalone-references .. |nbplot-documentation| replace:: `nbplots documentation`_ .. |worked-example| replace:: `worked example`_ .. |code-links-documentation| replace:: `code-links documentation`_ .. _nbplots documentation: https://matthew-brett.github.io/nb2plots/nbplots.html .. _code-links documentation: https://matthew-brett.github.io/nb2plots/code_links.html .. _worked example: https://matthew-brett.github.io/nb2plots/worked_example.html .. _documentation: https://matthew-brett.github.io/nb2plots .. _pandoc: http://pandoc.org .. _jupyter: jupyter.org .. _homebrew: brew.sh .. _sphinx: http://sphinx-doc.org .. _rest: http://docutils.sourceforge.net/rst.html .. _nb2plots issue tracker: https://github.com/matthew-brett/nb2plots/issues .. _matplotlib plot directive: http://matplotlib.org/sampledoc/extensions.html .. _nbconvert: http://nbconvert.readthedocs.org/en/latest/ .. _pytest: https://pytest.readthedocs.io .. _mock: https://github.com/testing-cabal/mock nb2plots-0.7.2/doc-requirements.txt000066400000000000000000000001111450750300000172750ustar00rootroot00000000000000# Requirements for building docs -r requirements.txt ghp-import numpydoc nb2plots-0.7.2/doc/000077500000000000000000000000001450750300000140225ustar00rootroot00000000000000nb2plots-0.7.2/doc/.gitignore000066400000000000000000000000731450750300000160120ustar00rootroot00000000000000converted_example.rst converted_plus_notebooks.rst _build/ nb2plots-0.7.2/doc/Makefile000066400000000000000000000176731450750300000155000ustar00rootroot00000000000000# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS ?= SPHINXBUILD = sphinx-build PAPER = BUILDDIR = _build # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . # the i18n builder cannot share the environment and doctrees with the others I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . .PHONY: help help: @echo "Please use \`make ' where is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " singlehtml to make a single large HTML file" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " applehelp to make an Apple Help Book" @echo " devhelp to make HTML files and a Devhelp project" @echo " epub to make an epub" @echo " epub3 to make an epub3" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " latexpdf to make LaTeX files and run them through pdflatex" @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" @echo " text to make text files" @echo " man to make manual pages" @echo " texinfo to make Texinfo files" @echo " info to make Texinfo files and run them through makeinfo" @echo " gettext to make PO message catalogs" @echo " changes to make an overview of all changed/added/deprecated items" @echo " xml to make Docutils-native XML files" @echo " pseudoxml to make pseudoxml-XML files for display purposes" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" @echo " coverage to run coverage check of the documentation (if enabled)" @echo " dummy to check syntax errors of document sources" .PHONY: clean clean: rm -rf $(BUILDDIR)/* .PHONY: html html: example html-only .PHONY: html-only html-only: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." .PHONY: dirhtml dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." .PHONY: singlehtml singlehtml: $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml @echo @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." .PHONY: pickle pickle: $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." .PHONY: json json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." .PHONY: htmlhelp htmlhelp: $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in $(BUILDDIR)/htmlhelp." .PHONY: qthelp qthelp: $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp @echo @echo "Build finished; now you can run "qcollectiongenerator" with the" \ ".qhcp project file in $(BUILDDIR)/qthelp, like this:" @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/nb2plots.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/nb2plots.qhc" .PHONY: applehelp applehelp: $(SPHINXBUILD) -b applehelp $(ALLSPHINXOPTS) $(BUILDDIR)/applehelp @echo @echo "Build finished. The help book is in $(BUILDDIR)/applehelp." @echo "N.B. You won't be able to view it unless you put it in" \ "~/Library/Documentation/Help or install it in your application" \ "bundle." .PHONY: devhelp devhelp: $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp @echo @echo "Build finished." @echo "To view the help file:" @echo "# mkdir -p $$HOME/.local/share/devhelp/nb2plots" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/nb2plots" @echo "# devhelp" .PHONY: epub epub: $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub @echo @echo "Build finished. The epub file is in $(BUILDDIR)/epub." .PHONY: epub3 epub3: $(SPHINXBUILD) -b epub3 $(ALLSPHINXOPTS) $(BUILDDIR)/epub3 @echo @echo "Build finished. The epub3 file is in $(BUILDDIR)/epub3." .PHONY: latex latex: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." @echo "Run \`make' in that directory to run these through (pdf)latex" \ "(use \`make latexpdf' here to do that automatically)." .PHONY: latexpdf latexpdf: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through pdflatex..." $(MAKE) -C $(BUILDDIR)/latex all-pdf @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." .PHONY: latexpdfja latexpdfja: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through platex and dvipdfmx..." $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." .PHONY: text text: $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text @echo @echo "Build finished. The text files are in $(BUILDDIR)/text." .PHONY: man man: $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man @echo @echo "Build finished. The manual pages are in $(BUILDDIR)/man." .PHONY: texinfo texinfo: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." @echo "Run \`make' in that directory to run these through makeinfo" \ "(use \`make info' here to do that automatically)." .PHONY: info info: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo "Running Texinfo files through makeinfo..." make -C $(BUILDDIR)/texinfo info @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." .PHONY: gettext gettext: $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale @echo @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." .PHONY: changes changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." .PHONY: linkcheck linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." .PHONY: doctest doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt." .PHONY: coverage coverage: $(SPHINXBUILD) -b coverage $(ALLSPHINXOPTS) $(BUILDDIR)/coverage @echo "Testing of coverage in the sources finished, look at the " \ "results in $(BUILDDIR)/coverage/python.txt." .PHONY: xml xml: $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml @echo @echo "Build finished. The XML files are in $(BUILDDIR)/xml." .PHONY: pseudoxml pseudoxml: $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml @echo @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." .PHONY: dummy dummy: $(SPHINXBUILD) -b dummy $(ALLSPHINXOPTS) $(BUILDDIR)/dummy @echo @echo "Build finished. Dummy builder generates no files." example: example_notebook.ipynb mkdir -p $(BUILDDIR)/html jupyter nbconvert --to html example_notebook.ipynb --stdout > \ $(BUILDDIR)/html/example_notebook.html nb2plots example_notebook.ipynb > converted_example.rst cp converted_example.rst converted_plus_notebooks.rst echo '.. code-links::' >> converted_plus_notebooks.rst github: html ghp-import -n $(BUILDDIR)/html/ git push origin gh-pages:gh-pages --force @echo @echo "Published to Github" nb2plots-0.7.2/doc/README.rst000066400000000000000000000005461450750300000155160ustar00rootroot00000000000000###################### nb2plots documentation ###################### To build the documentation, change to the ``doc`` directory (containing this file) and run:: pip install -r ../doc-requirements.txt make html To upload to github pages:: make github You will need repository write permissions to upload pages to the main github repository. nb2plots-0.7.2/doc/_static/000077500000000000000000000000001450750300000154505ustar00rootroot00000000000000nb2plots-0.7.2/doc/_static/.gitignore000066400000000000000000000000001450750300000174260ustar00rootroot00000000000000nb2plots-0.7.2/doc/code_links.rst000066400000000000000000000012731450750300000166710ustar00rootroot00000000000000.. _code-links-documentation: ############################## Using the code-links directive ############################## The ``code-links`` directive is a short cut for adding links to your ReST page pointing to Python code files and Jupyter notebooks. When Sphinx sees this directive, it converts the ReST page to a Python code file and notebooks, and add links to these files in the built HTML. Use like this: .. code-block:: rest .. code-links:: Here is an example, generating very boring code and notebooks: .. code-links:: .. _code-links-directive: ******************** code-links directive ******************** .. automodule:: nb2plots.codelinks .. include:: links_names.inc nb2plots-0.7.2/doc/conf.py000066400000000000000000000240041450750300000153210ustar00rootroot00000000000000#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # nb2plots documentation build configuration file, created by # sphinx-quickstart on Fri Dec 16 08:41:58 2016. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # # import os # import sys # sys.path.insert(0, os.path.abspath('.')) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. # # needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.mathjax', 'sphinx.ext.githubpages', 'texext.math_dollar', 'numpydoc', 'nb2plots', ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # # source_suffix = ['.rst', '.md'] source_suffix = '.rst' # The encoding of source files. # # source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = 'nb2plots' copyright = '2016-2023, Matthew Brett' author = 'Matthew Brett' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The full version, including alpha/beta/rc tags. import nb2plots release = nb2plots.__version__ # The short X.Y version. version = '.'.join(release.split('.')[:2]) # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. language = 'en' # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: # # today = '' # # Else, today_fmt is used as the format for a strftime call. # # today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This patterns also effect to html_static_path and html_extra_path exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store', 'README.rst'] # The reST default role (used for this markup: `text`) to use for all # documents. # # default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. # # add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). # # add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. # # show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. # modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. # keep_warnings = False # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = False # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # html_theme = 'alabaster' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. # # html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. # html_theme_path = [] # The name for this set of Sphinx documents. # " v documentation" by default. # # html_title = 'nb2plots v0.4' # A shorter title for the navigation bar. Default is the same as html_title. # # html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. # # html_logo = None # The name of an image file (relative to this directory) to use as a favicon of # the docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. # # html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. # # html_extra_path = [] # If not None, a 'Last updated on:' timestamp is inserted at every page # bottom, using the given strftime format. # The empty string is equivalent to '%b %d, %Y'. # # html_last_updated_fmt = None # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. # # html_use_smartypants = True # Custom sidebar templates, maps document names to template names. # # html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. # # html_additional_pages = {} # If false, no module index is generated. # # html_domain_indices = True # If false, no index is generated. # # html_use_index = True # If true, the index is split into individual pages for each letter. # # html_split_index = False # If true, links to the reST sources are added to the pages. # # html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. # # html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. # # html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. # # html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). # html_file_suffix = None # Language to be used for generating the HTML full-text search index. # Sphinx supports the following languages: # 'da', 'de', 'en', 'es', 'fi', 'fr', 'h', 'it', 'ja' # 'nl', 'no', 'pt', 'ro', 'r', 'sv', 'tr', 'zh' # # html_search_language = 'en' # A dictionary with options for the search language support, empty by default. # 'ja' uses this config value. # 'zh' user can custom change `jieba` dictionary path. # # html_search_options = {'type': 'default'} # The name of a javascript file (relative to the configuration directory) that # implements a search results scorer. If empty, the default will be used. # # html_search_scorer = 'scorer.js' # Output file base name for HTML help builder. htmlhelp_basename = 'nb2plotsdoc' # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). # # 'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). # # 'pointsize': '10pt', # Additional stuff for the LaTeX preamble. # # 'preamble': '', # Latex figure (float) alignment # # 'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ (master_doc, 'nb2plots.tex', 'nb2plots Documentation', 'Matthew Brett', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. # # latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. # # latex_use_parts = False # If true, show page references after internal links. # # latex_show_pagerefs = False # If true, show URL addresses after external links. # # latex_show_urls = False # Documents to append as an appendix to all manuals. # # latex_appendices = [] # It false, will not define \strong, \code, itleref, \crossref ... but only # \sphinxstrong, ..., \sphinxtitleref, ... To help avoid clash with user added # packages. # # latex_keep_old_macro_names = True # If false, no module index is generated. # # latex_domain_indices = True # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ (master_doc, 'nb2plots', 'nb2plots Documentation', [author], 1) ] # If true, show URL addresses after external links. # # man_show_urls = False # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ (master_doc, 'nb2plots', 'nb2plots Documentation', author, 'nb2plots', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. # # texinfo_appendices = [] # If false, no module index is generated. # # texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. # # texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. # # texinfo_no_detailmenu = False markdown_http_base = 'https://matthew-brett.github.io/nb2plots' # Doctest configuration. Use older numpy array representation. doctest_global_setup = 'from nb2plots.testing import setup_test; setup_test()' nb2plots-0.7.2/doc/devel/000077500000000000000000000000001450750300000151215ustar00rootroot00000000000000nb2plots-0.7.2/doc/devel/design.rst000066400000000000000000000045071450750300000171320ustar00rootroot00000000000000########################### Design of a notebook writer ########################### Pages that will be converted to notebooks have, somewhere in them, one of two intepreted text roles, like this:: :clearnotebook:`Download as notebook without outputs` :fullnotebook:`Download as notebook with outputs` These generate page content equivalent to ``:download:`Download as notebook .ipynb```, where ``.rst`` is the name of the ReST page containing the notebook role. ``:clearnotebook:`` creates a notebook without outputs, and ``:fullnotebook:`` creates the notebook and executes it, writing the notebook with generated outputs. The text within the backticks is the link text that will appear in the build html, unless the text is ``.`` (a period). This special case causes the link text to be ``Download as IPython notebook``. It appears that docutils insists that there must be some text between the backticks. For both directives, you can specify the written filename of the notebook with the ``text `` form of the role:: :clearnotebook:`to get this page as an ipynb file ` If you want to specify the filename, you must specify link text as well. For example ``:clearnotebook:```` will result in the default filename, and a link text of ````. You can have multiple notebook roles pointing to the same file (default or otherwise), as long as they are all of the same type (clear or full). For example, you can have multiple ``:clearnotebook:`.``` roles in one ReST page, (all pointing to ``.ipynb``, but you cannot have a ``:fullnotebook:`.``` role in that page, because that would mean that the clear and full notebook roles were trying to point to the same file. ********* Mechanics ********* On page parse (``doctree-resolved`` event), register that the page containing the notebook role should generate notebook, and whether this should be "full" or "clear". Store in ``app.env``, with link to Either collect the doctrees in the ``doctree-resolved`` event, or collect the docnames there, and then generate the notebooks in ``html-collect-pages`` event. Add notebook vistor functions via ``app.add_node(clearnotebook, html=(visit_notebook_node, depart_notebook_node)`` in ``setup`` function. Maybe make a new ``Writer`` class to write the notebook from the doctree. nb2plots-0.7.2/doc/devel/improving_markdown.rst000066400000000000000000000115141450750300000215710ustar00rootroot00000000000000######################################### Improving the ReST to Markdown conversion ######################################### Nb2plots includes a converter from ReST to Markdown. As you will see in the ``LICENSE`` file, the basis for this converter comes from the `rst2md project`_ by Chris Wrench, with thanks. At the time of writing (December 2016) the Nb2plots converter could deal with a considerably larger range of Markdown than the original rst2md project. However, the converter still does not deal specifically with a fairly large number of Sphinx / ReST constructs, so we would be very grateful for your help in improving the converter. These are some hints how to go about that. ******** Workflow ******** * Set yourself up with a git fork and clone of the `nb2plots code`_. Install the development code with something like: .. code-block:: bash pip install -e . from the root ``nb2plots`` directory (the directory containing the ``setup.py`` file. * Make sure the current tests pass with: .. code-block:: bash py.test nb2plots * Identify a ReST construct you would like to handle, or handle better. Let's say you you've decided to make the converter do something sensible with the ``:PEP:`` text role in ReST; * Make a new ReST file that uses the construct, and put it in the ``nb2plots/tests/rst_md_files`` directory. For example your file could be ``nb2plots/tests/rst_md_files/pep.rst`` with contents: .. code-block:: rest Test converting the :pep:`8` text role to Markdown The file have any name, as long as it has a ``.rst`` extension. * You might want to check what doctree the ReST file generates. The doctree is the form that the Markdown converter will use. See the pseudo XML version of the doctree with: .. code-block:: bash sphinx2pxml nb2plots/tests/rst_md_files/pep.rst This will show you the doctree node types and their attributes. * If your construct is valid in vanilla `docutils`_ ReST, then run the ``rst2md`` converter over the file and see what it looks like. In the case of the ``pep`` text role, you might see a message that the ``pep`` role is not yet supported, and the output will omit the ``pep`` role contents: .. code-block:: bash rst2md nb2plots/tests/rst_md_files/pep.rst * If your construct is only valid for Sphinx_ ReST, then run the ``sphinx2md`` converter on it, and see what happens: .. code-block:: bash sphinx2md nb2plots/tests/rst_md_files/pep.rst * Now have a look at the code in the ``nb2plots.doctree2md`` module. Add new ``visit_`` / ``depart_`` methods or modify the existing methods to handle your construct better. Try the ``rst2md`` and ``sphinx2md`` commands on the ReST file to see what the output looks like; * If your Markdown is valid docutils ReST, write the current output of ``rst2md`` to the ``rst_md_files`` directory with a ``.md`` extension: .. code-block:: bash rst2md nb2plots/tests/rst_md_files/pep.rst > nb2plots/tests/rst_md_files/pep.md If your Markdown is not valid docutils ReST, you can skip the ``rst2md`` test by writing an output file containing the work "skip": .. code-block:: bash echo "skip" > nb2plots/tests/rst_md_files/pep.md If the ``sphinx2md`` script should give a different output from the ``rst2md`` docutils converter, write that output with a ``.smd`` extension: .. code-block:: bash sphinx2md nb2plots/tests/rst_md_files/pep.rst > nb2plots/tests/rst_md_files/pep.smd These tests also test the output of the original ReST page (here ``pep.rst`` to Jupyter notebooks, and Python ``.py`` files. Check these conversions with the matching scripts: .. code-block:: bash sphinx2py nb2plots/tests/rst_md_files/pep.rst .. code-block:: bash sphinx2nb nb2plots/tests/rst_md_files/pep.rst When you are satisfied, build the test files to check against: .. code-block:: bash sphinx2py nb2plots/tests/rst_md_files/pep.rst > nb2plots/tests/rst_md_files/pep.py .. code-block:: bash sphinx2nb nb2plots/tests/rst_md_files/pep.rst > nb2plots/tests/rst_md_files/pep.ipynb * Run the relevant tests: .. code-block:: bash py.test nb2plots/tests/test_doctree2md.py py.test nb2plots/tests/test_sphinx2md.py py.test nb2plots/tests/test_doctree2py.py py.test nb2plots/tests/test_doctree2nb.py These will test your new ReST file, and the various other example ReST files, against their expected Markdown, code and notebook outputs. * Once the relevant tests are fixed, run all the tests to check that the rest of the code (such as notebook conversion) is still working as expected. If the tests fail, but you think your output is better than the previous output that the tests are using, feel free to edit. .. code-block:: bash py.test nb2plots * Make a pull request to `nb2plots github`_. .. include:: ../links_names.inc nb2plots-0.7.2/doc/devel/make_release.rst000066400000000000000000000033241450750300000202720ustar00rootroot00000000000000################## Releasing nb2plots ################## * Review the open list of `nb2plots issues`_. Check whether there are outstanding issues that can be closed, and whether there are any issues that should delay the release. Label them. * Review and update the release notes. Review and update the :file:`Changelog` file. Get a partial list of contributors with something like:: git log 0.7.. | grep '^Author' | cut -d' ' -f 2- | sort | uniq where ``0.7`` was the last release tag name. Then manually go over ``git shortlog 0.7..`` to make sure the release notes are as complete as possible and that every contributor was recognized. * Use the opportunity to update the ``.mailmap`` file if there are any duplicate authors listed from ``git shortlog -ns``. * Check the copyright years in ``doc/conf.py`` and ``LICENSE``; * Check the output of:: rst2html.py README.rst > ~/tmp/readme.html because this will be the output used by PyPi_ * Check `nb2plots travis-ci`_. * Once everything looks good, you are ready to upload the source release to PyPi. See `setuptools intro`_. Make sure you have a file ``\$HOME/.pypirc``, of form:: [pypi] username = __token__ This will in due course ask you for your PyPI token, for upload. * Tag the release. This will also set the version (we are using versioneer_ to manage versions via git tags):: git tag -s 0.7 * Clean:: # Check no files outside version control that you want to keep git status # Nuke git clean -fxd * When ready:: python -m build . --sdist twine upload dist/nb2plots*.tar.gz * Upload the release commit and tag to github:: git push git push --tags .. include:: ../links_names.inc nb2plots-0.7.2/doc/devel/sphinx_example_project.rst000066400000000000000000000020571450750300000224310ustar00rootroot00000000000000######################################## Test Sphinx builds on an example project ######################################## If you've developed Sphinx extensions before, you'll know that they can be hard to test. Have a look at the machinery in `sphinxtesters `_ for a somewhat general way of writing tests for Sphinx builds, and ``nb2plots/tests/test_nbplots.py`` for many examples using that machinery. Sometimes, what you really want to do, is try an actual Sphinx build from the command line. At least, that is what I often want to do, so I made an example Sphinx project to play with at ``nb2plots/tests/futz``. To get started: .. code-block:: bash cd nb2plots/tests/futz make init Now you can edit the files in the example Sphinx project in the ``proj1`` directory. For example, you might want to try out some ReST by editing the example page ``proj1/a_page.rst``. Try the HTML build with: .. code-block:: bash make html Have a look at the simple ``Makefile`` for some other ``make`` targets. nb2plots-0.7.2/doc/example_notebook.ipynb000066400000000000000000000335311450750300000204250ustar00rootroot00000000000000{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "## An interesting example\n", "\n", "This is an interesting example." ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "array([ 0. , 0.00628947, 0.01257895, 0.01886842, 0.0251579 ,\n", " 0.03144737, 0.03773685, 0.04402632, 0.0503158 , 0.05660527])" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import numpy as np\n", "x = np.linspace(0, 2 * np.pi, 1000)\n", "x[:10]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Even more interesting than that:" ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "collapsed": true }, "outputs": [], "source": [ "%matplotlib inline" ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "[]" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" }, { "data": { "image/png": "iVBORw0KGgoAAAANSUhEUgAAAXwAAAEACAYAAACwB81wAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAIABJREFUeJzt3Xm81nPex/HXJylMJi1UU6ZVyDIoo0IdssQYNbaIsYxB\nYlqM7N1yMzcxabclZ9TdaFEpiYROstxpUzhF0oqWMYnK0vK9//ieZs7k1DnXuZbv73dd7+fj0eMs\n/VzXW50+1+f6/r6LOecQEZHsVyF0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qO2ce9/MqgDzgA5x+fMH\nMLMDnHNbzWwf4G2gm3MuNsXHzHoCzYGfO+fOD50nEWb2GdDcOReD41h+ysz+Bsx0zuWbWUXgAOfc\nN4FjJayojq4BTnLOrS7pmqh0+LFenOWcewuI5Q87gHNurXPu/aLPNwOL8esnYsM5t7Xo08r4yQjh\nO5kyMrNxid2tAAACKklEQVR6wLnA06GzlJMRnVqSEDM7EDjVOZcP4JzbHsdiX+QMYNmeij1E5y+p\npMVZsSo42cLMGgDHAbPDJklM0ZDIAmAtMN05Nyd0pgT0B3oRoxep3ThgmpnNMbPrQodJUCPgH2aW\nXzQs8pSZ7R86VDl1Ap7b2wVRKfhanBUBRcM5zwPdizr92HDO7XTOHQ/UA04ys2ahM5WFmf0GWFf0\nDsvY+zYlUdXaOdcC/y7lpqIhzrioCJwADHXOnQBsBe4IGylxZrYvcD4wbm/XRaXgrwF+Wezrevix\nfMmQorHL54GRzrlJofOUV9Hb8QKgfeAoZXUycH7ROPhzwGlmNiJwpoQ459YWfdwATCReW6esAVY7\n5+YWff08/gUgbs4B5hX9HexRVAr+vxZnmVkl/OKsuM1WiGt3tsszQKFzbmDoIIkys5pmVrXo8/3x\nY5mxuOHsnLvLOfdL51wj/M/9G865K0PnKiszO6DonSFm9jPgLODDsKnKzjm3DlhtZk2LvtUOKAwY\nqbwuo5ThHIjIiVfOuR1mtmtxVgVgeJwWZ5nZ34E8oIaZrQLu3XUTKA7M7GTgcuCDonFwB9zlnHsl\nbLIyqwM8WzRLoQIwxjk3NXCmXFELmFi0LUpFYJRz7tXAmRLVDRhVNCzyGXBN4DwJKdbkXF/qtVGY\nlikiIukXlSEdERFJMxV8EZEcoYIvIpIjVPBFRHKECr6ISI5QwRcRyREq+CIiOUIFX0QkR/w/qrXc\nuLlO7OYAAAAASUVORK5CYII=\n", "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "import matplotlib.pyplot as plt\n", "\n", "plt.plot(x, np.sin(x))" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.5.2" } }, "nbformat": 4, "nbformat_minor": 2 } nb2plots-0.7.2/doc/index.rst000066400000000000000000000015211450750300000156620ustar00rootroot00000000000000.. nb2plots documentation master file, created by sphinx-quickstart on Fri Dec 16 08:41:58 2016. You can adapt this file completely to your liking, but it should at least contain the root `toctree` directive. nb2plots - the documentation that is not missing ================================================ Introduction: .. toctree:: :maxdepth: 2 introduction worked_example scripts In more depth: .. toctree:: :maxdepth: 2 nbplots mpl_interactive code_links markdown_base Developer docs: .. toctree:: :maxdepth: 2 devel/improving_markdown devel/sphinx_example_project devel/make_release .. toctree:: :hidden: converted_example converted_plus_notebooks devel/design Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search` nb2plots-0.7.2/doc/introduction.rst000066400000000000000000000002311450750300000172710ustar00rootroot00000000000000###### Basics ###### .. include:: ../README.rst :start-after: shared-text-body :end-before: standalone-references .. include:: links_names.inc nb2plots-0.7.2/doc/links_names.inc000066400000000000000000000043461450750300000170270ustar00rootroot00000000000000.. links, substitutions to include across pages. .. vim: ft=rst .. This project .. _nb2plots code: .. _nb2plots github: http://github.com/matthew-brett/nb2plots .. _nb2plots pypi: http://pypi.python.org/pypi/nb2plots .. _nb2plots issue tracker: .. _nb2plots issues: http://github.com/matthew-brett/nb2plots/issues .. _nb2plots travis-ci: https://travis-ci.org/matthew-brett/nb2plots .. _documentation: https://matthew-brett.github.io/nb2plots .. Code support .. _versioneer: https://github.com/warner/python-versioneer .. _setuptools intro: http://packages.python.org/an_example_pypi_project/setuptools.html .. Relevant projects .. _pandoc: http://pandoc.org .. _jupyter: jupyter.org .. _homebrew: brew.sh .. _sphinx: http://sphinx-doc.org .. _rest: http://docutils.sourceforge.net/rst.html .. _`Sphinx reST`: http://sphinx.pocoo.org/rest.html .. _reST: http://docutils.sourceforge.net/rst.html .. _matplotlib plot directive: http://matplotlib.org/sampledoc/extensions.html .. _nbconvert: http://nbconvert.readthedocs.org/en/latest/ .. _ipython: http://ipython.org/ .. _docutils: http://docutils.sourceforge.net .. _rst2md project: https://github.com/cgwrench/rst2md .. Python and common libraries .. _python: https://www.python.org .. _python standard library: http://docs.python.org/3/library .. _python.org releases: http://www.python.org/download/releases .. _setuptools: http://pypi.python.org/pypi/setuptools .. _matplotlib: http://matplotlib.org/ .. _pytest: https://pytest.readthedocs.io .. _nose: http://readthedocs.org/docs/nose/en/latest .. _mock: https://github.com/testing-cabal/mock .. _pip: http://pypi.python.org/pypi/pip .. _PEP8: https://www.python.org/dev/peps/pep-0008/ .. _Python glossary: https://docs.python.org/3/glossary.html .. _pypi: http://pypi.python.org/pypi .. Licenses .. _GPL: http://www.gnu.org/licenses/gpl.html .. _BSD: http://www.opensource.org/licenses/bsd-license.php .. Substitutions .. |emdash| unicode:: U+02014 .. |--| unicode:: U+2013 .. en dash .. |---| unicode:: U+2014 .. em dash, trimming surrounding whitespace :trim: .. |nbplot-documentation| replace:: :ref:`nbplots-documentation` .. |code-links-documentation| replace:: :ref:`code-links-documentation` .. |worked-example| replace:: :ref:`worked-example` nb2plots-0.7.2/doc/make.bat000066400000000000000000000174111450750300000154330ustar00rootroot00000000000000@ECHO OFF REM Command file for Sphinx documentation if "%SPHINXBUILD%" == "" ( set SPHINXBUILD=sphinx-build ) set BUILDDIR=_build set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . set I18NSPHINXOPTS=%SPHINXOPTS% . if NOT "%PAPER%" == "" ( set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% ) if "%1" == "" goto help if "%1" == "help" ( :help echo.Please use `make ^` where ^ is one of echo. html to make standalone HTML files echo. dirhtml to make HTML files named index.html in directories echo. singlehtml to make a single large HTML file echo. pickle to make pickle files echo. json to make JSON files echo. htmlhelp to make HTML files and a HTML help project echo. qthelp to make HTML files and a qthelp project echo. devhelp to make HTML files and a Devhelp project echo. epub to make an epub echo. epub3 to make an epub3 echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter echo. text to make text files echo. man to make manual pages echo. texinfo to make Texinfo files echo. gettext to make PO message catalogs echo. changes to make an overview over all changed/added/deprecated items echo. xml to make Docutils-native XML files echo. pseudoxml to make pseudoxml-XML files for display purposes echo. linkcheck to check all external links for integrity echo. doctest to run all doctests embedded in the documentation if enabled echo. coverage to run coverage check of the documentation if enabled echo. dummy to check syntax errors of document sources goto end ) if "%1" == "clean" ( for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i del /q /s %BUILDDIR%\* goto end ) REM Check if sphinx-build is available and fallback to Python version if any %SPHINXBUILD% 1>NUL 2>NUL if errorlevel 9009 goto sphinx_python goto sphinx_ok :sphinx_python set SPHINXBUILD=python -m sphinx.__init__ %SPHINXBUILD% 2> nul if errorlevel 9009 ( echo. echo.The 'sphinx-build' command was not found. Make sure you have Sphinx echo.installed, then set the SPHINXBUILD environment variable to point echo.to the full path of the 'sphinx-build' executable. Alternatively you echo.may add the Sphinx directory to PATH. echo. echo.If you don't have Sphinx installed, grab it from echo.http://sphinx-doc.org/ exit /b 1 ) :sphinx_ok if "%1" == "html" ( %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/html. goto end ) if "%1" == "dirhtml" ( %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. goto end ) if "%1" == "singlehtml" ( %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. goto end ) if "%1" == "pickle" ( %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can process the pickle files. goto end ) if "%1" == "json" ( %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can process the JSON files. goto end ) if "%1" == "htmlhelp" ( %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can run HTML Help Workshop with the ^ .hhp project file in %BUILDDIR%/htmlhelp. goto end ) if "%1" == "qthelp" ( %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can run "qcollectiongenerator" with the ^ .qhcp project file in %BUILDDIR%/qthelp, like this: echo.^> qcollectiongenerator %BUILDDIR%\qthelp\nb2plots.qhcp echo.To view the help file: echo.^> assistant -collectionFile %BUILDDIR%\qthelp\nb2plots.ghc goto end ) if "%1" == "devhelp" ( %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp if errorlevel 1 exit /b 1 echo. echo.Build finished. goto end ) if "%1" == "epub" ( %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub if errorlevel 1 exit /b 1 echo. echo.Build finished. The epub file is in %BUILDDIR%/epub. goto end ) if "%1" == "epub3" ( %SPHINXBUILD% -b epub3 %ALLSPHINXOPTS% %BUILDDIR%/epub3 if errorlevel 1 exit /b 1 echo. echo.Build finished. The epub3 file is in %BUILDDIR%/epub3. goto end ) if "%1" == "latex" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex if errorlevel 1 exit /b 1 echo. echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. goto end ) if "%1" == "latexpdf" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex cd %BUILDDIR%/latex make all-pdf cd %~dp0 echo. echo.Build finished; the PDF files are in %BUILDDIR%/latex. goto end ) if "%1" == "latexpdfja" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex cd %BUILDDIR%/latex make all-pdf-ja cd %~dp0 echo. echo.Build finished; the PDF files are in %BUILDDIR%/latex. goto end ) if "%1" == "text" ( %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text if errorlevel 1 exit /b 1 echo. echo.Build finished. The text files are in %BUILDDIR%/text. goto end ) if "%1" == "man" ( %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man if errorlevel 1 exit /b 1 echo. echo.Build finished. The manual pages are in %BUILDDIR%/man. goto end ) if "%1" == "texinfo" ( %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo if errorlevel 1 exit /b 1 echo. echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. goto end ) if "%1" == "gettext" ( %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale if errorlevel 1 exit /b 1 echo. echo.Build finished. The message catalogs are in %BUILDDIR%/locale. goto end ) if "%1" == "changes" ( %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes if errorlevel 1 exit /b 1 echo. echo.The overview file is in %BUILDDIR%/changes. goto end ) if "%1" == "linkcheck" ( %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck if errorlevel 1 exit /b 1 echo. echo.Link check complete; look for any errors in the above output ^ or in %BUILDDIR%/linkcheck/output.txt. goto end ) if "%1" == "doctest" ( %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest if errorlevel 1 exit /b 1 echo. echo.Testing of doctests in the sources finished, look at the ^ results in %BUILDDIR%/doctest/output.txt. goto end ) if "%1" == "coverage" ( %SPHINXBUILD% -b coverage %ALLSPHINXOPTS% %BUILDDIR%/coverage if errorlevel 1 exit /b 1 echo. echo.Testing of coverage in the sources finished, look at the ^ results in %BUILDDIR%/coverage/python.txt. goto end ) if "%1" == "xml" ( %SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml if errorlevel 1 exit /b 1 echo. echo.Build finished. The XML files are in %BUILDDIR%/xml. goto end ) if "%1" == "pseudoxml" ( %SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml if errorlevel 1 exit /b 1 echo. echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml. goto end ) if "%1" == "dummy" ( %SPHINXBUILD% -b dummy %ALLSPHINXOPTS% %BUILDDIR%/dummy if errorlevel 1 exit /b 1 echo. echo.Build finished. Dummy builder generates no files. goto end ) if "%1" == "github" ( %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html ghp-import -n -p -b gh-pages -f %BUILDDIR%/html/ if errorlevel 1 exit /b 1 echo. echo Published to Github goto end ) :end nb2plots-0.7.2/doc/markdown_base.rst000066400000000000000000000025721450750300000173760ustar00rootroot00000000000000.. _links-in-markdown: ################# Links in Markdown ################# By default, if your ReST documents has internal links, then generated Markdown output like the Notebook files or the Python code files drop these links, replacing them with some suitable text. Internal links can be :ref:`internal to the document `, via the ``:ref:`` role, or to :doc:`other ReST pages `, using the ``:doc:`` role. Links can also be to files to download, such as :download:`conf.py`. It's often the case that you have built HTTP pages on the web somewhere, so it would make sense for the built Markdown to point to the HTTP versions of these links, rather than dropping them. You can tell ``nb2plots`` where your built HTTP docs are, by setting the ``markdown_http_base`` value in your ``conf.py`` file, like this:: markdown_http_base = 'https://example.com' If you set this value to any string other than the empty string, the Markdown builders will use this base URL to resolve internal links. In fact, I've set that option in the ``conf.py`` for this project, like this:: markdown_http_base = 'https://matthew-brett.github.io/nb2plots' Have a look at the generated Python code and Notebook code for this page, via the links below. You should see that the Markdown links resolve to the HTTP pages at https://matthew-brett.github.io/nb2plots. .. code-links:: nb2plots-0.7.2/doc/mpl_interactive.rst000066400000000000000000000024241450750300000177430ustar00rootroot00000000000000################################### Using the mpl-interactive directive ################################### Many notebooks have code cells generating matplotlib_ plots. Nearly all of these have a code cell near the top with the IPython magic command ``%matplotlib inline`` or ``%matplotlib nbagg``. This commands tell the notebook to embed the plots inside the notebook rather than generate them in separate windows. When ``nb2plots`` converts a notebook to ReST, it detects these commands, and adds a new directive ``.. mpl-interactive::`` at the matching place in the ReST page. When Sphinx builds the ReST page to HTML, the directive put boilerplate text into the page reminding the user that they may want to use the ``%matplotlib`` magic command in the IPython_ console, or ``%matplotlib inline`` when they are running the commands in the Jupyter notebook. The ``mpl-interactive`` directive also serves as marker when converting the ReST page to a notebook again; the directive generates a notebook code cell with the ``%matplotlib inline`` magic at the matching location, like this: .. mpl-interactive:: .. _mpl-interactive-directive: ************************* mpl-interactive directive ************************* .. automodule:: nb2plots.mpl_interactive .. include:: links_names.inc nb2plots-0.7.2/doc/nbplots.rst000066400000000000000000000032021450750300000162320ustar00rootroot00000000000000.. _nbplots-documentation: ########################## Using the nbplot directive ########################## The ``nbplot`` directive is very similar to the `matplotlib plot directive`_, and started life as a fork of that code. It differs mainly in that its default is to keep the name-space from one ``nbplot`` directive to the next in a given page. It also has output defaults adapted to directive contents with source code rather than pointing to a standalone script. For example, here is the source for an Nbplot directive: .. code-block:: rest .. nbplot:: >>> a = 1 >>> a 1 This renders as: .. nbplot:: >>> a = 1 >>> a 1 All Nbplot directives in a page share a namespace with the first (by default). Here is another Nbplot directive: .. nbplot:: >>> b = a >>> b 1 Nbplot directives can also make |--| plots: .. nbplot:: >>> import matplotlib.pyplot as plt >>> plt.plot(range(10)) [...] Notice that the HTML version of the page contains links to high and low resolution PNG versions of the plot, and a PDF version. The code in Nbplot directives gets executed during the page build, so your build will detect any errors. With doctest code blocks, like the above, you can also test the doctest output, using the Sphinx ``doctest`` builder, which you might be able to run with: .. code-block:: bash make doctest See the ``run-parts`` and ``render-parts`` options to run and render different code according to your local configuration. .. _nbplot-directive: **************** nbplot directive **************** .. automodule:: nb2plots.nbplots .. include:: links_names.inc nb2plots-0.7.2/doc/scripts.rst000066400000000000000000000022551450750300000162470ustar00rootroot00000000000000################### Scripts in nb2plots ################### Nbplots installs the following command-line scripts: * ``nb2plots`` |--| converts Jupyter notebooks to a ReST page with :doc:`nbplot directives ` for the code cells; * ``sphinx2py`` |--| converts a ReST page that may have nbplot directives or doctest blocks into a Python ``.py`` code file, where everything other than the nbplot directives and doctest blocks become comments in Markdown text format; * ``sphinx2nb`` |--| converts a ReST page that may have nbplot directives or doctest blocks into a Jupyter notebook, where the nbplot directives and doctest blocks become code cells; * ``sphinx2md`` |--| converts a ReST page into a Markdown page, where the conversion assumes the Sphinx versions of directives and roles; * ``sphinx2pxml`` |--| converts a ReST page into a Sphinx pseudo XML page, where the conversion assumes the Sphinx versions of directives and roles; * ``rst2md`` |--| converts a ReST page into a Markdown page, where the conversion assumes the `docutils`_ versions of directives and roles; All these scripts write their output to standard output (stdout). .. include:: links_names.inc nb2plots-0.7.2/doc/worked_example.rst000066400000000000000000000044561450750300000175730ustar00rootroot00000000000000.. _worked-example: ############## Worked example ############## Let's say I have a notebook `example notebook `_. You can download the notebook from :download:`example_notebook.ipynb`. I want to make this notebook into a ReST page to include in my Sphinx project. First I convert the notebook with the ``nb2plots`` script:: nb2plots example_notebook.ipynb > converted_notebook.rst This results in the ReST page `converted_example.rst <_sources/converted_example.rst.txt>`_, which builds as HTML to :doc:`converted_example`. If you look at the `source of the converted notebook <_sources/converted_example.rst.txt>`_ you will see two custom Nb2plots directives: * :ref:`nbplot ` |--| housing the content from the code cells in the original notebook; * :ref:`mpl-interactive ` |--| noting that the user may want to use the ``%matplotlib`` magic for interactive plots. Notice that each Nbplot directive on a single page uses the same namespace, by default, so the Nbplot directives on your page can build up variables in the same way that a notebook does. The notebook code cells convert to doctest blocks, so I can check the correctness of the code on my page with the Sphinx doctest extension: .. code-block:: bash make doctest This example page converts well, but, in practice, you may well want to edit the ReST document to clean up some differences between the notebook code cells and doctest blocks in Nbplot directives. Now let's say that I would like to make this page available to my users as Jupyter notebooks and / or a Python code file. To do this, I add the following directive to the end of my page (or wherever I like): .. code-block:: rest .. code-links:: See the :ref:`code-links-directive` for more detail. When I do this, I get a built HTML page :doc:`like this `. Note the three links to the Python code file and notebooks at the end of the page. The first link is to the Python code file. The second is to a notebook that has not been executed, and has no outputs. The third is to a version of the same notebook that has been executed, and has the code output cells. See the :ref:`code-links-directive` documentation for options to select which of these links to add. .. include:: links_names.inc nb2plots-0.7.2/min-requirements.txt000066400000000000000000000003011450750300000173140ustar00rootroot00000000000000# Minimum requirements # When updating here, update version in requirements. ipython[notebook]==7.16.3 sphinx==4 numpy==1.20 matplotlib==3.2 sphinxtesters==0.2.2 texext==0.6.6 nbconvert==6.0.7 nb2plots-0.7.2/nb2plots/000077500000000000000000000000001450750300000150205ustar00rootroot00000000000000nb2plots-0.7.2/nb2plots/__init__.py000066400000000000000000000005561450750300000171370ustar00rootroot00000000000000# nb2plots package from . import _version __version__ = _version.get_versions()['version'] from . import nbplots from . import runroles from . import mpl_interactive from . import codelinks from . import sphinx2foos def setup(app): nbplots.setup(app) runroles.setup(app) mpl_interactive.setup(app) codelinks.setup(app) sphinx2foos.setup(app) nb2plots-0.7.2/nb2plots/_version.py000066400000000000000000000563241450750300000172300ustar00rootroot00000000000000 # This file helps to compute a version number in source trees obtained from # git-archive tarball (such as those provided by githubs download-from-tag # feature). Distribution tarballs (built by setup.py sdist) and build # directories (produced by setup.py build) will contain a much shorter file # that just contains the computed version number. # This file is released into the public domain. Generated by # versioneer-0.22 (https://github.com/python-versioneer/python-versioneer) """Git implementation of _version.py.""" import errno import os import re import subprocess import sys from typing import Callable, Dict import functools def get_keywords(): """Get the keywords needed to look up the version information.""" # these strings will be replaced by git during git-archive. # setup.py/versioneer.py will grep for the variable names, so they must # each be defined on a line of their own. _version.py will just call # get_keywords(). git_refnames = " (HEAD -> main, tag: 0.7.2)" git_full = "6c15c425edda0de3e18d8ecbfd4168a6710a72f7" git_date = "2023-10-05 10:46:40 +0100" keywords = {"refnames": git_refnames, "full": git_full, "date": git_date} return keywords class VersioneerConfig: """Container for Versioneer configuration parameters.""" def get_config(): """Create, populate and return the VersioneerConfig() object.""" # these strings are filled in when 'setup.py versioneer' creates # _version.py cfg = VersioneerConfig() cfg.VCS = "git" cfg.style = "pep440" cfg.tag_prefix = "" cfg.parentdir_prefix = "nb2plots-" cfg.versionfile_source = "nb2plots/_version.py" cfg.verbose = False return cfg class NotThisMethod(Exception): """Exception raised if a method is not valid for the current scenario.""" LONG_VERSION_PY: Dict[str, str] = {} HANDLERS: Dict[str, Dict[str, Callable]] = {} def register_vcs_handler(vcs, method): # decorator """Create decorator to mark a method as the handler of a VCS.""" def decorate(f): """Store f in HANDLERS[vcs][method].""" if vcs not in HANDLERS: HANDLERS[vcs] = {} HANDLERS[vcs][method] = f return f return decorate def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, env=None): """Call the given command(s).""" assert isinstance(commands, list) process = None popen_kwargs = {} if sys.platform == "win32": # This hides the console window if pythonw.exe is used startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW popen_kwargs["startupinfo"] = startupinfo for command in commands: try: dispcmd = str([command] + args) # remember shell=False, so use git.cmd on windows, not just git process = subprocess.Popen([command] + args, cwd=cwd, env=env, stdout=subprocess.PIPE, stderr=(subprocess.PIPE if hide_stderr else None), **popen_kwargs) break except OSError: e = sys.exc_info()[1] if e.errno == errno.ENOENT: continue if verbose: print("unable to run %s" % dispcmd) print(e) return None, None else: if verbose: print("unable to find command, tried %s" % (commands,)) return None, None stdout = process.communicate()[0].strip().decode() if process.returncode != 0: if verbose: print("unable to run %s (error)" % dispcmd) print("stdout was %s" % stdout) return None, process.returncode return stdout, process.returncode def versions_from_parentdir(parentdir_prefix, root, verbose): """Try to determine the version from the parent directory name. Source tarballs conventionally unpack into a directory that includes both the project name and a version string. We will also support searching up two directory levels for an appropriately named parent directory """ rootdirs = [] for _ in range(3): dirname = os.path.basename(root) if dirname.startswith(parentdir_prefix): return {"version": dirname[len(parentdir_prefix):], "full-revisionid": None, "dirty": False, "error": None, "date": None} rootdirs.append(root) root = os.path.dirname(root) # up a level if verbose: print("Tried directories %s but none started with prefix %s" % (str(rootdirs), parentdir_prefix)) raise NotThisMethod("rootdir doesn't start with parentdir_prefix") @register_vcs_handler("git", "get_keywords") def git_get_keywords(versionfile_abs): """Extract version information from the given file.""" # the code embedded in _version.py can just fetch the value of these # keywords. When used from setup.py, we don't want to import _version.py, # so we do it with a regexp instead. This function is not used from # _version.py. keywords = {} try: with open(versionfile_abs, "r") as fobj: for line in fobj: if line.strip().startswith("git_refnames ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["refnames"] = mo.group(1) if line.strip().startswith("git_full ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["full"] = mo.group(1) if line.strip().startswith("git_date ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["date"] = mo.group(1) except OSError: pass return keywords @register_vcs_handler("git", "keywords") def git_versions_from_keywords(keywords, tag_prefix, verbose): """Get version information from git keywords.""" if "refnames" not in keywords: raise NotThisMethod("Short version file found") date = keywords.get("date") if date is not None: # Use only the last line. Previous lines may contain GPG signature # information. date = date.splitlines()[-1] # git-2.2.0 added "%cI", which expands to an ISO-8601 -compliant # datestamp. However we prefer "%ci" (which expands to an "ISO-8601 # -like" string, which we must then edit to make compliant), because # it's been around since git-1.5.3, and it's too difficult to # discover which version we're using, or to work around using an # older one. date = date.strip().replace(" ", "T", 1).replace(" ", "", 1) refnames = keywords["refnames"].strip() if refnames.startswith("$Format"): if verbose: print("keywords are unexpanded, not using") raise NotThisMethod("unexpanded keywords, not a git-archive tarball") refs = {r.strip() for r in refnames.strip("()").split(",")} # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of # just "foo-1.0". If we see a "tag: " prefix, prefer those. TAG = "tag: " tags = {r[len(TAG):] for r in refs if r.startswith(TAG)} if not tags: # Either we're using git < 1.8.3, or there really are no tags. We use # a heuristic: assume all version tags have a digit. The old git %d # expansion behaves like git log --decorate=short and strips out the # refs/heads/ and refs/tags/ prefixes that would let us distinguish # between branches and tags. By ignoring refnames without digits, we # filter out many common branch names like "release" and # "stabilization", as well as "HEAD" and "master". tags = {r for r in refs if re.search(r'\d', r)} if verbose: print("discarding '%s', no digits" % ",".join(refs - tags)) if verbose: print("likely tags: %s" % ",".join(sorted(tags))) for ref in sorted(tags): # sorting will prefer e.g. "2.0" over "2.0rc1" if ref.startswith(tag_prefix): r = ref[len(tag_prefix):] # Filter out refs that exactly match prefix or that don't start # with a number once the prefix is stripped (mostly a concern # when prefix is '') if not re.match(r'\d', r): continue if verbose: print("picking %s" % r) return {"version": r, "full-revisionid": keywords["full"].strip(), "dirty": False, "error": None, "date": date} # no suitable tags, so version is "0+unknown", but full hex is still there if verbose: print("no suitable tags, using unknown + full revision id") return {"version": "0+unknown", "full-revisionid": keywords["full"].strip(), "dirty": False, "error": "no suitable tags", "date": None} @register_vcs_handler("git", "pieces_from_vcs") def git_pieces_from_vcs(tag_prefix, root, verbose, runner=run_command): """Get version from 'git describe' in the root of the source tree. This only gets called if the git-archive 'subst' keywords were *not* expanded, and _version.py hasn't already been rewritten with a short version string, meaning we're inside a checked out source tree. """ GITS = ["git"] if sys.platform == "win32": GITS = ["git.cmd", "git.exe"] # GIT_DIR can interfere with correct operation of Versioneer. # It may be intended to be passed to the Versioneer-versioned project, # but that should not change where we get our version from. env = os.environ.copy() env.pop("GIT_DIR", None) runner = functools.partial(runner, env=env) _, rc = runner(GITS, ["rev-parse", "--git-dir"], cwd=root, hide_stderr=True) if rc != 0: if verbose: print("Directory %s not under git control" % root) raise NotThisMethod("'git rev-parse --git-dir' returned error") MATCH_ARGS = ["--match", "%s*" % tag_prefix] if tag_prefix else [] # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] # if there isn't one, this yields HEX[-dirty] (no NUM) describe_out, rc = runner(GITS, ["describe", "--tags", "--dirty", "--always", "--long", *MATCH_ARGS], cwd=root) # --long was added in git-1.5.5 if describe_out is None: raise NotThisMethod("'git describe' failed") describe_out = describe_out.strip() full_out, rc = runner(GITS, ["rev-parse", "HEAD"], cwd=root) if full_out is None: raise NotThisMethod("'git rev-parse' failed") full_out = full_out.strip() pieces = {} pieces["long"] = full_out pieces["short"] = full_out[:7] # maybe improved later pieces["error"] = None branch_name, rc = runner(GITS, ["rev-parse", "--abbrev-ref", "HEAD"], cwd=root) # --abbrev-ref was added in git-1.6.3 if rc != 0 or branch_name is None: raise NotThisMethod("'git rev-parse --abbrev-ref' returned error") branch_name = branch_name.strip() if branch_name == "HEAD": # If we aren't exactly on a branch, pick a branch which represents # the current commit. If all else fails, we are on a branchless # commit. branches, rc = runner(GITS, ["branch", "--contains"], cwd=root) # --contains was added in git-1.5.4 if rc != 0 or branches is None: raise NotThisMethod("'git branch --contains' returned error") branches = branches.split("\n") # Remove the first line if we're running detached if "(" in branches[0]: branches.pop(0) # Strip off the leading "* " from the list of branches. branches = [branch[2:] for branch in branches] if "master" in branches: branch_name = "master" elif not branches: branch_name = None else: # Pick the first branch that is returned. Good or bad. branch_name = branches[0] pieces["branch"] = branch_name # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] # TAG might have hyphens. git_describe = describe_out # look for -dirty suffix dirty = git_describe.endswith("-dirty") pieces["dirty"] = dirty if dirty: git_describe = git_describe[:git_describe.rindex("-dirty")] # now we have TAG-NUM-gHEX or HEX if "-" in git_describe: # TAG-NUM-gHEX mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) if not mo: # unparsable. Maybe git-describe is misbehaving? pieces["error"] = ("unable to parse git-describe output: '%s'" % describe_out) return pieces # tag full_tag = mo.group(1) if not full_tag.startswith(tag_prefix): if verbose: fmt = "tag '%s' doesn't start with prefix '%s'" print(fmt % (full_tag, tag_prefix)) pieces["error"] = ("tag '%s' doesn't start with prefix '%s'" % (full_tag, tag_prefix)) return pieces pieces["closest-tag"] = full_tag[len(tag_prefix):] # distance: number of commits since tag pieces["distance"] = int(mo.group(2)) # commit: short hex revision ID pieces["short"] = mo.group(3) else: # HEX: no tags pieces["closest-tag"] = None count_out, rc = runner(GITS, ["rev-list", "HEAD", "--count"], cwd=root) pieces["distance"] = int(count_out) # total number of commits # commit date: see ISO-8601 comment in git_versions_from_keywords() date = runner(GITS, ["show", "-s", "--format=%ci", "HEAD"], cwd=root)[0].strip() # Use only the last line. Previous lines may contain GPG signature # information. date = date.splitlines()[-1] pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1) return pieces def plus_or_dot(pieces): """Return a + if we don't already have one, else return a .""" if "+" in pieces.get("closest-tag", ""): return "." return "+" def render_pep440(pieces): """Build up version string, with post-release "local version identifier". Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty Exceptions: 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += plus_or_dot(pieces) rendered += "%d.g%s" % (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" else: # exception #1 rendered = "0+untagged.%d.g%s" % (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" return rendered def render_pep440_branch(pieces): """TAG[[.dev0]+DISTANCE.gHEX[.dirty]] . The ".dev0" means not master branch. Note that .dev0 sorts backwards (a feature branch will appear "older" than the master branch). Exceptions: 1: no tags. 0[.dev0]+untagged.DISTANCE.gHEX[.dirty] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: if pieces["branch"] != "master": rendered += ".dev0" rendered += plus_or_dot(pieces) rendered += "%d.g%s" % (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" else: # exception #1 rendered = "0" if pieces["branch"] != "master": rendered += ".dev0" rendered += "+untagged.%d.g%s" % (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" return rendered def pep440_split_post(ver): """Split pep440 version string at the post-release segment. Returns the release segments before the post-release and the post-release version number (or -1 if no post-release segment is present). """ vc = str.split(ver, ".post") return vc[0], int(vc[1] or 0) if len(vc) == 2 else None def render_pep440_pre(pieces): """TAG[.postN.devDISTANCE] -- No -dirty. Exceptions: 1: no tags. 0.post0.devDISTANCE """ if pieces["closest-tag"]: if pieces["distance"]: # update the post release segment tag_version, post_version = pep440_split_post(pieces["closest-tag"]) rendered = tag_version if post_version is not None: rendered += ".post%d.dev%d" % (post_version+1, pieces["distance"]) else: rendered += ".post0.dev%d" % (pieces["distance"]) else: # no commits, use the tag as the version rendered = pieces["closest-tag"] else: # exception #1 rendered = "0.post0.dev%d" % pieces["distance"] return rendered def render_pep440_post(pieces): """TAG[.postDISTANCE[.dev0]+gHEX] . The ".dev0" means dirty. Note that .dev0 sorts backwards (a dirty tree will appear "older" than the corresponding clean one), but you shouldn't be releasing software with -dirty anyways. Exceptions: 1: no tags. 0.postDISTANCE[.dev0] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += ".post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" rendered += plus_or_dot(pieces) rendered += "g%s" % pieces["short"] else: # exception #1 rendered = "0.post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" rendered += "+g%s" % pieces["short"] return rendered def render_pep440_post_branch(pieces): """TAG[.postDISTANCE[.dev0]+gHEX[.dirty]] . The ".dev0" means not master branch. Exceptions: 1: no tags. 0.postDISTANCE[.dev0]+gHEX[.dirty] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += ".post%d" % pieces["distance"] if pieces["branch"] != "master": rendered += ".dev0" rendered += plus_or_dot(pieces) rendered += "g%s" % pieces["short"] if pieces["dirty"]: rendered += ".dirty" else: # exception #1 rendered = "0.post%d" % pieces["distance"] if pieces["branch"] != "master": rendered += ".dev0" rendered += "+g%s" % pieces["short"] if pieces["dirty"]: rendered += ".dirty" return rendered def render_pep440_old(pieces): """TAG[.postDISTANCE[.dev0]] . The ".dev0" means dirty. Exceptions: 1: no tags. 0.postDISTANCE[.dev0] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += ".post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" else: # exception #1 rendered = "0.post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" return rendered def render_git_describe(pieces): """TAG[-DISTANCE-gHEX][-dirty]. Like 'git describe --tags --dirty --always'. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix) """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"]: rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) else: # exception #1 rendered = pieces["short"] if pieces["dirty"]: rendered += "-dirty" return rendered def render_git_describe_long(pieces): """TAG-DISTANCE-gHEX[-dirty]. Like 'git describe --tags --dirty --always -long'. The distance/hash is unconditional. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix) """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) else: # exception #1 rendered = pieces["short"] if pieces["dirty"]: rendered += "-dirty" return rendered def render(pieces, style): """Render the given version pieces into the requested style.""" if pieces["error"]: return {"version": "unknown", "full-revisionid": pieces.get("long"), "dirty": None, "error": pieces["error"], "date": None} if not style or style == "default": style = "pep440" # the default if style == "pep440": rendered = render_pep440(pieces) elif style == "pep440-branch": rendered = render_pep440_branch(pieces) elif style == "pep440-pre": rendered = render_pep440_pre(pieces) elif style == "pep440-post": rendered = render_pep440_post(pieces) elif style == "pep440-post-branch": rendered = render_pep440_post_branch(pieces) elif style == "pep440-old": rendered = render_pep440_old(pieces) elif style == "git-describe": rendered = render_git_describe(pieces) elif style == "git-describe-long": rendered = render_git_describe_long(pieces) else: raise ValueError("unknown style '%s'" % style) return {"version": rendered, "full-revisionid": pieces["long"], "dirty": pieces["dirty"], "error": None, "date": pieces.get("date")} def get_versions(): """Get version information or return default if unable to do so.""" # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have # __file__, we can work backwards from there to the root. Some # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which # case we can only use expanded keywords. cfg = get_config() verbose = cfg.verbose try: return git_versions_from_keywords(get_keywords(), cfg.tag_prefix, verbose) except NotThisMethod: pass try: root = os.path.realpath(__file__) # versionfile_source is the relative path from the top of the source # tree (where the .git directory might live) to this file. Invert # this to find the root from __file__. for _ in cfg.versionfile_source.split('/'): root = os.path.dirname(root) except NameError: return {"version": "0+unknown", "full-revisionid": None, "dirty": None, "error": "unable to find root of source tree", "date": None} try: pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose) return render(pieces, cfg.style) except NotThisMethod: pass try: if cfg.parentdir_prefix: return versions_from_parentdir(cfg.parentdir_prefix, root, verbose) except NotThisMethod: pass return {"version": "0+unknown", "full-revisionid": None, "dirty": None, "error": "unable to compute version", "date": None} nb2plots-0.7.2/nb2plots/codelinks.py000066400000000000000000000102511450750300000173440ustar00rootroot00000000000000""" Directive to insert links to current document as runnable code. As a bare directive, with no options, inserts links to the current document as a Python code file; a clear notebook (no outputs) and a full notebook (outputs inserted by executing the built notebook):: .. code-links: You can select one or more of these links with a list as an argument to the directive, where "python", "clear" and "full" refer to a Python code file, clear notebook file and a full notebook file, respectively. For example:: .. code-links: python .. code-links: python full .. code-links: clear full ``python clear full`` is the default. Kernel timeout -------------- When you build the full notebook, Jupyter will execute the code in each cell. By default, Jupyter will time out for any cell that takes longer than 30 seconds to execute. You can change this default for the whole project with the ``fill_notebook_timeout`` setting in the ``conf.py`` file (see below). If you just want to change the setting for a single page, you can add the ``timeout`` option to the ``code-links`` directive. For example:: .. code-links: :timeout: 120 Set the ``timeout`` value to -1 or ``none`` to disable timeout entirely for this directive / page. Configuration options --------------------- The code-links directive has the following configuration options, that can be set in the ``conf.py`` file. fill_notebook_timeout Default value for Jupyter kernel timeout when executing notebooks during page build. If not set, default is 30 seconds. Set to -1 or None to disable timeout. """ from docutils.statemachine import StringList from docutils import nodes from docutils.parsers.rst import Directive from .runroles import NAME2ROLE, convert_timeout, runrole_reference class code_links(nodes.container): """ Node to contain code links """ class CodeLinks(Directive): """ Add links to built runnable code from contained page. """ has_content = False required_arguments = 0 optional_arguments = 3 option_spec = {'timeout': convert_timeout} _type2params = dict(python=dict(role_name='pyfile', suffix=''), clear=dict(role_name='clearnotebook', suffix=''), full=dict(role_name='fullnotebook', suffix='_full')) code_links_node = code_links def _role_lines(self): """ Text lines for notebook roles of types requested in options. """ code_types = (self.arguments if len(self.arguments) else ['python', 'clear', 'full']) env = self.state.document.settings.env lines = [] for code_type in code_types: params = self._type2params[code_type] suffix = params['suffix'] role_name = params['role_name'] role = NAME2ROLE[role_name] lines.append( '* :{role_name}:`{descr} `'.format( role_name=role_name, descr=role.default_text, docname=env.docname, suffix=suffix, ext=role.default_extension)) return lines def run(self): lines = [] body_lines = self._role_lines() for i, line in enumerate(body_lines): suffix = '.' if i == len(body_lines) - 1 else ';' lines.append('{}{}'.format(line, suffix)) node = self.code_links_node('\n'.join(lines)) self.state.nested_parse(StringList(lines), self.content_offset, node) if 'timeout' in self.options: for node in node.traverse(runrole_reference): if node['reftype'] == 'fullnotebook': node['timeout'] = self.options['timeout'] return [node] def setup(app): app.add_directive('code-links', CodeLinks) # Pass through containers used as markers for code links null = lambda self, node : None app.add_node(CodeLinks.code_links_node, **{builder: (null, null) for builder in ('html', 'latex', 'text', 'texinfo')}) app.add_config_value('fill_notebook_timeout', 30, True) nb2plots-0.7.2/nb2plots/commands.py000066400000000000000000000017171450750300000172010ustar00rootroot00000000000000""" Support for command-line scripts """ import sys from argparse import ArgumentParser from .converters import NbConverter def get_parser(description): """ Get parser for sphinx2something utilities """ parser = ArgumentParser(description=description) parser.add_argument('rst_file', help = 'ReST file to convert') parser.add_argument('-W', '--warn-is-error', action='store_true', help = 'turn warnings into errors') return parser def do_main(description, buildername): """ Get main clause for sphinx2something utilities """ parser = get_parser(description) args = parser.parse_args() with open(args.rst_file, 'rt') as fobj: contents = fobj.read() converter = NbConverter(buildername, status=sys.stderr, warningiserror=args.warn_is_error) output = converter.from_rst(contents) sys.stdout.buffer.write(output.encode('utf-8')) nb2plots-0.7.2/nb2plots/converters.py000066400000000000000000000114021450750300000175620ustar00rootroot00000000000000""" Convert ReST and doctrees to various formats using nb2plots defaults """ import sys from os.path import join as pjoin from importlib import import_module from docutils.io import Output from sphinxtesters import TempApp class UnicodeOutput(Output): """ Don't do anything to the string; just return it. """ default_destination_path = '' def write(self, data): """ Store `data` in `self.destination`, and return it.""" self.destination = data return data class Converter(object): """ Class to convert from ReST or doctree to output format """ default_conf = '' def __init__(self, buildername='text', conf_txt=None, status=sys.stdout, warningiserror=True): """ Build ReST text in string `rst_text` into doctree. Parameters ---------- buildername : str, optional Builder name. conf_txt : None or str Text for ``conf.py`` file controlling Sphinx build. status : file-like object or None, optional File-like object to which to write build status messages, or None for no build status messages. warningiserror : {True, False}, optional if True, raise an error for warning during the Sphinx build. """ self.buildername = buildername self.conf_txt = conf_txt if not conf_txt is None else self.default_conf self.status = status self.warningiserror = warningiserror def _make_app(self, rst_text): """ Make, return Sphinx application instance for input ReST text. """ return TempApp(rst_text, self.conf_txt, status=self.status, warningiserror=self.warningiserror, buildername=self.buildername) def _build_rst(self, rst_text, resolve=True): """ Build ReST text in string `rst_text` into doctree. Parameters ---------- rst_text : str string containing ReST to build. resolve : {True, False}, optional Whether to resolve references before returning doctree. Returns ------- doctree : node document node. app : object Sphinx application object. This will need to be cleaned up (``app.cleanup()``) after use. """ app = self._make_app(rst_text) master_doc = app.config.master_doc out_fname = pjoin(app.tmp_dir, master_doc + '.rst') with open(out_fname, 'wt') as fobj: fobj.write(rst_text) # Force build of everything app.build(True, []) if resolve: dt = app.env.get_and_resolve_doctree(master_doc, app.builder) else: dt = app.env.get_doctree(master_doc) return dt, app def from_doctree(self, doctree, builder): """ Convert doctree `doctree` to output format Parameters ---------- doctree : node Document node. builder : object Sphinx builder object. Returns ------ output : str Representation in output format """ builder.prepare_writing([builder.config.master_doc]) return builder.writer.write(doctree, UnicodeOutput()) def from_rst(self, rst_text, resolve=True): """ Build Sphinx formatted ReST text `rst_text` into output format Parameters ---------- rst_text : str string containing ReST to build. resolve : {True, False}, optional Whether to resolve references before returning doctree. Returns ------- output : str Text in output format """ doctree, app = self._build_rst(rst_text, resolve) res = self.from_doctree(doctree, app.builder) app.cleanup() return res def can_import(module_str): try: import_module(module_str) except ImportError: return False return True DEFAULT_EXTENSIONS = [ext_name for ext_name in ["nb2plots", 'sphinx.ext.autodoc', # to silence math_dollar warning 'sphinx.ext.mathjax', # to enable math output 'texext.math_dollar'] # to enable inline dollar syntax if can_import(ext_name)] DEFAULT_CONF = """\ master_doc = 'contents' # For compatibility with Sphinx 2 extensions = [{}] """.format(',\n'.join('"{}"'.format(ext_name) for ext_name in DEFAULT_EXTENSIONS)) class NbConverter(Converter): default_conf = DEFAULT_CONF # Some standard converters to_pxml = NbConverter('pseudoxml') to_markdown = NbConverter('markdown') to_py = NbConverter('python') to_notebook = NbConverter('jupyter') nb2plots-0.7.2/nb2plots/doctree2md.py000066400000000000000000000435771450750300000174420ustar00rootroot00000000000000# -*- coding: utf-8 -*- """Simple Markdown writer for reStructuredText. See: * https://daringfireball.net/projects/markdown/syntax * https://guides.github.com/pdfs/markdown-cheatsheet-online.pdf """ import re from textwrap import dedent import posixpath __docformat__ = 'reStructuredText' from docutils import frontend, nodes, writers, languages from collections import OrderedDict from .nbplots import checked_visit class IndentLevel(object): """ Class to hold text being written for a certain indentation level For example, all text in list_elements need to be indented. A list_element creates one of these indentation levels, and all text contained in the list_element gets written to this IndentLevel. When we leave the list_element, we ``write`` the text with suitable prefixes to the next level down, which might be the base of the document (document body) or another indentation level, if this is - for example - a nested list. In most respects, IndentLevel behaves like a list. """ def __init__(self, base, prefix, first_prefix=None): self.base = base # The list to which we eventually write self.prefix = prefix # Text prepended to lines # Text prepended to first list self.first_prefix = prefix if first_prefix is None else first_prefix # Our own list to which we append before doing a ``write`` self.content = [] def append(self, new): self.content.append(new) def __getitem__(self, index): return self.content[index] def __len__(self): return len(self.content) def __bool__(self): return len(self) != 0 def write(self): """ Add ``self.contents`` with current ``prefix`` and ``first_prefix`` Add processed ``self.contents`` to ``self.base``. The first line has ``first_prefix`` prepended, further lines have ``prefix`` prepended. Empty (all whitespace) lines get written as bare carriage returns, to avoid ugly extra whitespace. """ string = ''.join(self.content) lines = string.splitlines(True) if len(lines) == 0: return texts = [self.first_prefix + lines[0]] for line in lines[1:]: if line.strip() == '': # avoid prefix for empty lines texts.append('\n') else: texts.append(self.prefix + line) self.base.append(''.join(texts)) def _make_method(to_add): """ Make a method that adds `to_add` We need this function so that `to_add` is a fresh and unique variable at the time the method is defined. """ def method(self, node): self.add(to_add) return method def add_pref_suff(pref_suff_map): """ Decorator adds visit, depart methods for prefix/suffix pairs """ def dec(cls): # Need _make_method to ensure new variable picked up for each iteration # of the loop. The defined method picks up this new variable in its # scope. for key, (prefix, suffix) in pref_suff_map.items(): setattr(cls, 'visit_' + key, _make_method(prefix)) setattr(cls, 'depart_' + key, _make_method(suffix)) return cls return dec def add_pass_thru(pass_thrus): """ Decorator adds explicit pass-through visit and depart methods """ def meth(self, node): pass def dec(cls): for element_name in pass_thrus: for meth_prefix in ('visit_', 'depart_'): meth_name = meth_prefix + element_name if hasattr(cls, meth_name): raise ValueError('method name {} already defined' .format(meth_name)) setattr(cls, meth_name, meth) return cls return dec # Characters that should be escaped in Markdown ESCAPE_RE = re.compile(r'([\\*`])') # Doctree elements for which Markdown element is PREF_SUFF_ELEMENTS = { 'emphasis': ('*', '*'), # Could also use ('_', '_') 'strong' : ('**', '**'), # Could also use ('__', '__') 'literal' : ('`', '`'), 'subscript' : ('', ''), 'superscript' : ('', ''), } # Doctree elements explicitly passed through without extra markup PASS_THRU_ELEMENTS = ('document', 'container', 'target', 'inline', 'definition_list', 'definition_list_item', 'term', 'field_list', 'field_list_item', 'field', 'field_name', 'mpl_hint', 'pending_xref', 'compound', ) @add_pass_thru(PASS_THRU_ELEMENTS) @add_pref_suff(PREF_SUFF_ELEMENTS) class Translator(nodes.NodeVisitor): std_indent = ' ' def __init__(self, document, builder=None): nodes.NodeVisitor.__init__(self, document) self.builder = builder self.settings = settings = document.settings lcode = settings.language_code self.language = languages.get_language(lcode, document.reporter) # Not-None here indicates Markdown should use HTTP for internal and # download links. self.markdown_http_base = (builder.markdown_http_base if builder else None) # Warn only once per writer about unsupported elements self._warned = set() # Lookup table to get section list from name self._lists = OrderedDict((('head', []), ('body', []), ('foot', []))) # Reset attributes modified by reading self.reset() # Attribute shortcuts self.head, self.body, self.foot = self._lists.values() def reset(self): """ Initialize object for fresh read """ for part in self._lists.values(): part[:] = [] # Current section heading level during writing self.section_level = 0 # FIFO list of list prefixes, while writing nested lists. Each element # corresponds to one level of nesting. Thus ['1. ', '1. ', '* '] would # occur when writing items of an unordered list, that is nested within # an ordered list, that in turn is nested in another ordered list. self.list_prefixes = [] # FIFO list of indentation levels. When we are writing a block of text # that should be indented, we create a new indentation level. We only # write the text when we leave the indentation level, so we can insert # the correct prefix for every line. self.indent_levels = [] # Flag indicating we are processing docinfo items self._in_docinfo = False # Flag for whether to escape characters self._escape_text = True def astext(self): """Return the final formatted document as a string.""" parts = [''.join(lines).strip() for lines in self._lists.values()] parts = [part + '\n\n' for part in parts if part] return ''.join(parts).strip() + '\n' def ensure_eol(self): """Ensure the last line in current base is terminated by new line.""" out = self.get_current_output() if out and out[-1] and out[-1][-1] != '\n': out.append('\n') def get_current_output(self, section='body'): """ Get list or IndentLevel to which we are currently writing """ return (self.indent_levels[-1] if self.indent_levels else self._lists[section]) def add(self, string, section='body'): """ Add `string` to `section` or current output Parameters ---------- string : str String to add to output document section : {'body', 'head', 'foot'}, optional Section of document that generated text should be appended to, if not already appending to an indent level. If already appending to an indent level, method will ignore `section`. Use :meth:`add_section` to append to a section unconditionally. """ self.get_current_output(section).append(string) def add_section(self, string, section='body'): """ Add `string` to `section` regardless of current output Can be useful when forcing write to header or footer. Parameters ---------- string : str String to add to output document section : {'body', 'head', 'foot'}, optional Section of document that generated text should be appended to. """ self._lists[section].append(string) def start_level(self, prefix, first_prefix=None, section='body'): """ Create a new IndentLevel with `prefix` and `first_prefix` """ base = (self.indent_levels[-1].content if self.indent_levels else self._lists[section]) level = IndentLevel(base, prefix, first_prefix) self.indent_levels.append(level) def finish_level(self): """ Remove most recent IndentLevel and write contents """ level = self.indent_levels.pop() level.write() def escape_chars(self, txt): # Escape (some) characters with special meaning for Markdown return ESCAPE_RE.sub(r'\\\1', txt) def visit_Text(self, node): text = node.astext() if self._escape_text: text = self.escape_chars(text) self.add(text) def depart_Text(self, node): pass def visit_comment(self, node): txt = node.astext() if txt.strip(): self.add('\n') raise nodes.SkipNode def visit_docinfo(self, node): self._in_docinfo = True def depart_docinfo(self, node): self._in_docinfo = False def process_docinfo_item(self, node): """ Called explicitly from methods in this class """ self.add_section('% {}\n'.format(node.astext()), section='head') raise nodes.SkipNode def visit_definition(self, node): self.add('\n\n') self.start_level(' ', ': ') def depart_definition(self, node): self.finish_level() visit_field_body = visit_definition depart_field_body = depart_definition def visit_paragraph(self, node): pass def depart_paragraph(self, node): self.ensure_eol() self.add('\n') def visit_math_block(self, node): # docutils math block self._escape_text = False self.add('$$\n') def depart_math_block(self, node): self._escape_text = True self.ensure_eol() self.add('$$\n\n') def visit_displaymath(self, node): # sphinx math blocks become displaymath self.add('$$\n{}\n$$\n\n'.format(node['latex'])) raise nodes.SkipNode def visit_math(self, node): # sphinx math node has 'latex' attribute, docutils does not if 'latex' in node: # sphinx math node self.add('${}$'.format(node['latex'])) raise nodes.SkipNode # docutils math node self._escape_text = False self.add('$') def depart_math(self, node): # sphinx node skipped in visit, only docutils gets here self._escape_text = True self.add('$') def visit_literal_block(self, node): self._escape_text = False if 'code' in node['classes']: # Sphinx < 2 code_type = node['classes'][1] else: # Sphinx >= 2 language = node.get('language', '') code_type = '' if language == 'default' else language self.add('```' + code_type + '\n') def depart_literal_block(self, node): self._escape_text = True self.ensure_eol() self.add('```\n\n') def visit_doctest_block(self, node): self._escape_text = False self.add('```python\n') depart_doctest_block = depart_literal_block def visit_block_quote(self, node): self.start_level('> ') def depart_block_quote(self, node): self.finish_level() def visit_section(self, node): self.section_level += 1 def depart_section(self, node): self.section_level -= 1 def visit_enumerated_list(self, node): self.list_prefixes.append('1. ') def depart_enumerated_list(self, node): self.list_prefixes.pop() def visit_bullet_list(self, node): self.list_prefixes.append('* ') depart_bullet_list = depart_enumerated_list def visit_list_item(self, node): first_prefix = self.list_prefixes[-1] prefix = ' ' * len(first_prefix) self.start_level(prefix, first_prefix) def depart_list_item(self, node): self.finish_level() def visit_problematic(self, node): self.add('\n\n```\n{}\n```\n\n'.format(node.astext())) raise nodes.SkipNode def visit_system_message(self, node): if node['level'] < self.document.reporter.report_level: # Level is too low to display raise nodes.SkipNode line = ', line %s' % node['line'] if node.hasattr('line') else '' self.add("```\nSystem Message: {}:{}\n\n{}\n```\n\n".format( node['source'], line, node.astext())) raise nodes.SkipNode def visit_title(self, node): self.add((self.section_level + 1) * '#' + ' ') def depart_title(self, node): self.ensure_eol() self.add('\n') def visit_subtitle(self, node): self.add((self.section_level + 2) * '#' + ' ') depart_subtitle = depart_title def visit_transition(self, node): # Simply replace a transition by a horizontal rule. # Could use three or more '*', '_' or '-'. self.add('\n---\n\n') raise nodes.SkipNode def _refuri2http(self, node): # Replace 'refuri' in reference with HTTP address, if possible # None for no possible address url = node.get('refuri') if not node.get('internal'): return url # If HTTP page build URL known, make link relative to that. if not self.markdown_http_base: return None this_doc = self.builder.current_docname if url in (None, ''): # Reference to this doc url = self.builder.get_target_uri(this_doc) else: # URL is relative to the current docname. this_dir = posixpath.dirname(this_doc) if this_dir: url = posixpath.normpath('{}/{}'.format(this_dir, url)) url = '{}/{}'.format(self.markdown_http_base, url) if 'refid' in node: url += '#' + node['refid'] return url def visit_reference(self, node): # If no target possible, pass through. url = self._refuri2http(node) if url is None: return self.add('[{0}]({1})'.format(node.astext(), url)) raise nodes.SkipNode def depart_reference(self, node): pass def visit_nbplot_epilogue(self, node): raise nodes.SkipNode def visit_nbplot_not_rendered(self, node): raise nodes.SkipNode def visit_code_links(self, node): raise nodes.SkipNode def visit_index(self, node): # Drop index entries raise nodes.SkipNode def visit_substitution_definition(self, node): # Drop substitution definitions - the doctree already contains the text # with substitutions applied. raise nodes.SkipNode def visit_only(self, node): if node['expr'] == 'markdown': self.add(dedent(node.astext()) + '\n') raise nodes.SkipNode def visit_runrole_reference(self, node): raise nodes.SkipNode def visit_download_reference(self, node): # If not resolving internal links, or there is no filename specified, # pass through. filename = node.get('filename') if None in (self.markdown_http_base, filename): return target_url = '{}/_downloads/{}'.format(self.markdown_http_base, filename) self.add('[{}]({})'.format(node.astext(), target_url)) raise nodes.SkipNode def depart_download_reference(self, node): pass visit_compact_paragraph = visit_paragraph depart_compact_paragraph = depart_paragraph def visit_nbplot_container(self, node): checked_visit(self, node) def depart_nbplot_container(self, node): pass def unknown_visit(self, node): """ Warn once per instance for unsupported nodes Intercept docinfo items if in docinfo block. """ if self._in_docinfo: self.process_docinfo_item(node) return # We really don't know this node type, warn once per node type node_type = node.__class__.__name__ if node_type not in self._warned: self.document.reporter.warning('The ' + node_type + ' element not yet supported in Markdown.') self._warned.add(node_type) raise nodes.SkipNode class Writer(writers.Writer): supported = ('markdown',) """Formats this writer supports.""" output = None """Final translated form of `document`.""" # Add configuration settings for additional Markdown flavours here. settings_spec = ( 'Markdown-Specific Options', None, (('Extended Markdown syntax.', ['--extended-markdown'], {'default': 0, 'action': 'store_true', 'validator': frontend.validate_boolean}), ('Strict Markdown syntax. Default: true', ['--strict-markdown'], {'default': 1, 'action': 'store_true', 'validator': frontend.validate_boolean}),)) translator_class = Translator def __init__(self, builder=None): writers.Writer.__init__(self) self.builder = builder def translate(self): visitor = self.translator_class(self.document, self.builder) self.document.walkabout(visitor) self.output = visitor.astext() nb2plots-0.7.2/nb2plots/doctree2nb.py000066400000000000000000000015401450750300000174210ustar00rootroot00000000000000""" Convert doctree to Jupyter notebook """ from docutils import nodes from nbformat import v4 as nbf from . import doctree2py as d2py class Translator(d2py.Translator): def _init_output(self): self._notebook = nbf.new_notebook() def _add_text_block(self, txt): self._notebook['cells'].append(nbf.new_markdown_cell(txt)) def astext(self): """ Return the document as a string """ self.flush_text() return nbf.writes(self._notebook) def add_code_block(self, txt): self.flush_text() self._notebook['cells'].append(nbf.new_code_cell(txt)) def visit_mpl_hint(self, node): self.add_code_block('%matplotlib inline') raise nodes.SkipNode class Writer(d2py.Writer): supported = ('jupyter',) """Formats this writer supports.""" translator_class = Translator nb2plots-0.7.2/nb2plots/doctree2py.py000066400000000000000000000065711450750300000174630ustar00rootroot00000000000000""" Writer to convert doctree to Python .py file """ import re from textwrap import dedent from docutils import nodes from . import doctree2md as d2m # The following regular expression comes from Python source file "doctest.py". # License for that file recorded as: # # Released to the public domain 16-Jan-2001, by Tim Peters (tim@python.org). # # This regular expression is used to find doctest examples in a # string. It defines three groups: `source` is the source code # (including leading indentation and prompts); `indent` is the # indentation of the first (PS1) line of the source code; and # `want` is the expected output (including leading indentation). _EXAMPLE_RE = re.compile(r''' # Source consists of a PS1 line followed by zero or more PS2 lines. (?P (?:^(?P [ ]*) >>> .*) # PS1 line (?:\n [ ]* \.\.\. .*)*) # PS2 lines \n? # Want consists of any non-blank lines that do not start with PS1. (?P (?:(?![ ]*$) # Not a blank line (?![ ]*>>>) # Not a line starting with PS1 .+$\n? # But any other line )*) ''', re.MULTILINE | re.VERBOSE) def parse_doctest(doctest_txt): txt = dedent(doctest_txt.expandtabs()) parts = [] for m in _EXAMPLE_RE.finditer(txt): indent = len(m.group('indent')) source_lines = m.group('source').splitlines() source = '\n'.join([L[indent + 4:] for L in source_lines]) parts.append(source) return '\n'.join(parts) class Translator(d2m.Translator): def __init__(self, document, builder=None): d2m.Translator.__init__(self, document, builder) self._in_nbplot = False self._init_output() def _init_output(self): self._out_lines = [] def reset(self): d2m.Translator.reset(self) self._in_nbplot = False def flush_text(self): txt = d2m.Translator.astext(self).strip() if txt: self._add_text_block(txt) self.reset() def _add_text_block(self, txt): self._out_lines += ['# ' + line if line.strip() else '#' for line in txt.splitlines()] self._out_lines.append('') def add_code_block(self, txt): self.flush_text() self._out_lines += txt.splitlines() + [''] def astext(self): """ Return the document as a string """ self.flush_text() return '\n'.join(self._out_lines) def visit_doctest_block(self, node): doctest_txt = node.astext().strip() if doctest_txt: self.add_code_block(parse_doctest(doctest_txt)) raise nodes.SkipNode def visit_nbplot_container(self, node): d2m.Translator.visit_nbplot_container(self, node) self._in_nbplot = True def depart_nbplot_container(self, node): self._in_nbplot = False def visit_runrole_reference(self, node): raise nodes.SkipNode def visit_literal_block(self, node): """ A literal block may be in an nbplot container """ if not self._in_nbplot: return d2m.Translator.visit_literal_block(self, node) self.add_code_block(node.astext()) raise nodes.SkipNode class Writer(d2m.Writer): supported = ('pyfile',) """Formats this writer supports.""" output = None """Final translated form of `document`.""" translator_class = Translator nb2plots-0.7.2/nb2plots/from_notebook.py000066400000000000000000000101021450750300000202270ustar00rootroot00000000000000#!python """ Convert from notebook to rst page with plot directives """ import re from jinja2 import DictLoader import traitlets import traitlets.config as config import nbformat import nbconvert MPL_INLINE = re.compile(r"^\s*%\s*matplotlib\s+(inline|nbagg)\s*$", re.MULTILINE) # Template to label code and output and plot blocks dl = DictLoader({'rst_plots.tpl': """\ {%- extends '__RST_DEFAULT_TEMPLATE__' -%} {% block input %} {%- if cell.source.strip() | has_mpl_inline -%} .. mpl-interactive:: {% endif -%} {%- if cell.source.strip() | strip_ipy -%} ##CODE_START## {{ cell.source | strip_ipy | to_doctests | indent}} ##CODE_END## {% endif -%} {% endblock input %} {%- block execute_result -%} {%- block data_priority scoped -%} {{ super() }} {%- endblock -%} {%- endblock execute_result -%} {%- block data_svg -%} {%- endblock data_svg -%} {%- block data_png -%} {%- endblock data_png -%} {%- block stream -%} ##STDOUT_START## {{ output.text | ellipse_mpl | indent }} ##STDOUT_END## {%- endblock stream -%} {%- block data_text scoped -%} ##END_OUT_START## {{ output.data['text/plain'] | ellipse_mpl | indent }} ##END_OUT_END## {%- endblock data_text -%} """.replace('__RST_DEFAULT_TEMPLATE__', nbconvert.RSTExporter().template_file)}) def has_mpl_inline(code): return MPL_INLINE.search(code) def strip_ipy(code): """ Strip any ipython magic lines """ return '\n'.join([line for line in code.split('\n') if not line.strip().startswith('%')]) def to_doctests(code, first='>>> ', cont='... '): """Add docstring prompts to code snippets""" new_code = [] code_list = code.split('\n') prefix = first last_line_no = len(code_list) - 1 for i, line in enumerate(code_list): if line.strip() != '': prefix = cont if line.startswith(' ') else first new_code.append(prefix + line) continue # For blank lines, we always strip the whitespace, but we will need a # prefix for anything but the last line if i == last_line_no: prefix = '' elif code_list[i + 1].startswith(' '): # Use continuation for line following prefix = cont.rstrip() else: # Use prefix for previous line prefix = prefix.rstrip() new_code.append(prefix) return '\n'.join(new_code) MPL_LIST_OUT = re.compile(r'\[\]') MPL_OBJ_OUT = re.compile(r'') def ellipse_mpl(text): """ Replace outputs of matplotlib objects with ellipses """ text = MPL_LIST_OUT.sub('[...]', text) return MPL_OBJ_OUT.sub('<...>', text) class PlotsExporter(nbconvert.RSTExporter): template_file = 'rst_plots.tpl' filters = traitlets.Dict(dict( has_mpl_inline=has_mpl_inline, to_doctests=to_doctests, strip_ipy=strip_ipy, ellipse_mpl=ellipse_mpl, ), config=True) # Code, with option stdout and optional end-of-block output CODE_WITH_OUTPUT = re.compile( '^##CODE_START##\n' '(?P.*?)' '^##CODE_END##(\n|$)' '([\\s\\n]*?' '^##STDOUT_START##\n' '(?P.*?)' '^##STDOUT_END##(\n|$))?' '([\\s\\n]*?' '^##END_OUT_START##\n' '(?P.*?)' '^##END_OUT_END##(\n|$))?', re.S | re.M) PLOT_DIRECTIVE_PREFIX = """\ .. nbplot:: """ def repl_code_plot(match): groups = match.groupdict(default='') out = ''.join((PLOT_DIRECTIVE_PREFIX, groups['code'], groups['end_out'])) if groups['stdout']: out += '\n' + groups['stdout'] return out def convert_nb_fname(nb_fname): with open(nb_fname, 'rt') as nb_fobj: notebook = nbformat.read(nb_fobj, as_version=4) return convert_nb(notebook) def convert_nb(notebook): # Turn off output preprocessor (we don't want the figures) c = config.Config({ 'ExtractOutputPreprocessor':{'enabled': False} }) plots_exporter = PlotsExporter(extra_loaders=[dl], config=c) output, resources = plots_exporter.from_notebook_node(notebook) return CODE_WITH_OUTPUT.sub(repl_code_plot, output) nb2plots-0.7.2/nb2plots/mpl_interactive.py000066400000000000000000000033301450750300000205560ustar00rootroot00000000000000""" Directive to handle ``%matplotlib [inline]`` in Sphinx, Notebooks The directive is a marker to tell the Notebook converter to put a ``%matplotlib inline`` code cell at this position in the text. Use thusly:: .. mpl-interactive:: With no content (as above), the directive inserts a Hint into the ReST text suggesting ``%matplotlib`` in the IPython console, or ``%matplotlib inline`` in the Notebook. You can specify some other message with:: .. mpl-interactive:: Your text here. The text can be any valid ReStructured text. """ from docutils.parsers.rst.directives.admonitions import Hint from docutils import nodes from docutils.statemachine import StringList class mpl_hint(nodes.hint): """ Node signals presence of MPL interactive block """ class MPLInteractive(Hint): """ Output information on IPython / MPL interactive mode in Sphinx """ node_class = mpl_hint default_text = """\ If running in the IPython console, consider running ``%matplotlib`` to enable interactive plots. If running in the Jupyter Notebook, use ``%matplotlib inline``. """ def run(self): if len(self.content) == 0: self.content = StringList(self.default_text.splitlines()) return super(MPLInteractive, self).run() def visit_mpl_inter(self, node): self.visit_hint(node) def depart_mpl_inter(self, node): self.depart_hint(node) def setup(app): setup.app = app setup.config = app.config setup.confdir = app.confdir # mpl_hint treated same as hint app.add_node(mpl_hint, **{builder: (visit_mpl_inter, depart_mpl_inter) for builder in ('html', 'latex', 'text')}) app.add_directive('mpl-interactive', MPLInteractive) nb2plots-0.7.2/nb2plots/nbplots.py000066400000000000000000001147751450750300000170720ustar00rootroot00000000000000""" A directive for including a matplotlib plot in a Sphinx document. This directive is based on the ``plot`` directive of matplotlib, with thanks. By default, in HTML output, `nbplot` will include a .png file with a link to a high-res .png and .pdf. In LaTeX output, it will include a .pdf. The source code for the plot is **inline content** to the directive:. It can be with or without *doctest* syntax. Here's an example without doctest syntax:: .. nbplot:: import matplotlib.pyplot as plt import matplotlib.image as mpimg import numpy as np img = mpimg.imread('_static/stinkbug.png') imgplot = plt.imshow(img) Here's an example with doctest syntax:: .. nbplot:: A plotting example: >>> import matplotlib.pyplot as plt >>> plt.plot([1,2,3], [4,5,6]) #doctest: +ELLIPSIS [...] Options ------- The ``nbplot`` directive supports the following options: format : {'python', 'doctest'} Specify the format of the input. If not specified, nbplot guesses the format from the content. include-source : bool Whether to display the source code. The default can be changed using the `nbplot_include_source` variable in ``conf.py``. Any doctests in the source code will still be run by the doctest builder. `include-source` has the same effect as ``:hide-from: all`` then ``:show-to: doctest`` (in fact, that is how it is implemented). See below for interactions of ``:include-source:`` and these options. hide-from : str Space-separated list of builders that should not render any source from this directive. Can also be the special value "all", hiding the source from all builders. Any builder names in `show-to` override builders specified with this option. If you apply ``:hide-from:`` options as well as ``:include-source: false`` (see above), these will have no effect, because ``:include-source: false`` implies ``:hide-from: all``. show-to : str Space-separated list of builders that *should* render any source from this directive. Builder names here override any builders specified in `hide-from`. If you apply ``:show-to:`` options as well as ``:include-source: false`` (see above) these can enable additional builders on top of the implied ``doctest`` builder. encoding : str If this source file is in a non-UTF8 or non-ASCII encoding, the encoding must be specified using the `:encoding:` option. The encoding will not be inferred using the ``-*- coding -*-`` metacomment. keepfigs : bool If specified, do not close figures from previous plot command. This allows you to build up a plot in stages, with the current nbplot command building on the figure generated by previous nbplot commands. nofigs : bool If specified, the code block will be run, but no figures will be inserted. This is sometimes necessary when your code generates a plot, but you do not want to include it. If the code does not generate a plot, this option is not necessary. raises : str String giving error class. The code runner will assert this error was raised by the enclosed code, and suppress stderr. render-parts : str The contents of the directive may be divided into "parts" at lines containing ``.. part`` with a blank line before and after. This option gives a Python expression returning an integer or tuple giving the indices of the *parts* that should be used for the built output of the code block. These to-be-built parts can be different from the parts used to generate the figures associated with the block, defined in the ``run-parts`` option below. The typical use is for building when running the ``render-parts`` would be too slow, or the building system does not have the requirements to run the code in ``render-parts``. The contents of this option is a Python expression returning an integer or a tuple, where an integer is the index of the part to render, and a tuple is a tuple of such integers. The expression operates in a namespace defined by the contents of the ``nbplot_flags`` config variable (a dict) and any extra namespace defined above this directive with :class:`NBPlotFlags` directives. Any selected parts get labeled such that the doctest builder does not see them, and therefore they do not get picked up by the sphinx doctest extension. The nbplots extension tells the other builders to build the skipped doctest as if it were a standard doctest. Examples:: :render-parts: 0 if have_matlab else 1 Default value is 0. run-parts : str See ``render-parts`` above. Python expression that returns integer or tuple giving indices for parts that should be executed when generating the figures. Any doctests in these parts also get wrapped in standard doctest blocks, and so will be picked up by the sphinx doctest builder. Examples:: :run-parts: 0 if slow else 1 Default value is 0. The namespace of the nbplot command is reset to empty for each document. The code in each nbplot directive instance in a given document uses the namespace generated by previous nbplot directive instances in the same document. Additionally, this directive supports all of the options of the `image` directive, except for `target` (since plot will add its own target). These include `alt`, `height`, `width`, `scale`, `align` and `class`. Configuration options --------------------- The nbplot directive has the following configuration options: nbplot_include_source Default value for the include-source option nbplot_pre_code Code that should be executed before each plot. nbplot_formats File formats to generate. List of tuples or strings:: [(suffix, dpi), suffix, ...] that determine the file format and the DPI. For entries whose DPI was omitted, sensible defaults are chosen. When passing from the command line through sphinx_build the list should be passed as suffix:dpi,suffix:dpi, .... nbplot_html_show_formats Whether to show links to the files in HTML. nbplot_rcparams A dictionary containing any non-standard rcParams that should be applied at the beginning of each document. nbplot_working_directory By default, the working directory will be changed to the directory of the example, so the code can get at its data files, if any. Also its path will be added to `sys.path` so it can import any helper modules sitting beside it. This configuration option can be used to specify a central directory (also added to `sys.path`) where data files and helper modules for all code are located. If the directory is relative, directory taken to be relative to root directory of the project (rather than source directory). nbplot_template Provide a customized template for preparing restructured text. """ try: from collections.abc import Sequence except ImportError: from collections import Sequence from collections import defaultdict import sys, os, shutil, io, re, textwrap from os.path import (relpath, abspath, join as pjoin, dirname, exists, basename, splitext, isdir) import traceback from pprint import pformat from docutils.statemachine import StringList from docutils import nodes from docutils.parsers.rst import directives from docutils.parsers.rst.directives.images import Image align = Image.align from docutils.parsers.rst import Directive import jinja2 def format_template(template, **kw): return jinja2.Template(template).render(**kw) import matplotlib import matplotlib.cbook as cbook matplotlib.use('Agg') import matplotlib.pyplot as plt from matplotlib._pylab_helpers import Gcf __version__ = 2 def _get_rawsource(node): # Docutils < 0.18 has rawsource attribute, otherwise, build it. if hasattr(node, 'rawsource'): return node.rawsource return nodes.unescape(node, restore_backslashes=True) class NBPlotFlags(Directive): """ Set flag namespace for nbplot """ has_content = True required_arguments = 0 optional_arguments = 0 def run(self): document = self.state.document env = document.settings.env docname = env.docname local_ns = env.nbplot_flag_namespaces[docname] exec('\n'.join(self.content), None, local_ns) return [] class NBPlotShowFlags(Directive): """ Show flag namespace for nbplot This directive shows the result of :class:`NBPlotFlags` directives, for debugging and testing. """ has_content = True required_arguments = 0 optional_arguments = 0 def run(self): document = self.state.document env = document.settings.env docname = env.docname local_ns = env.nbplot_flag_namespaces[docname] content = pformat(local_ns) return [nodes.literal_block(content, content)] # Options for NBPlotDirective def _option_boolean(arg): if not arg or not arg.strip(): # no argument given, assume used as a flag return True elif arg.strip().lower() in ('no', '0', 'false'): return False elif arg.strip().lower() in ('yes', '1', 'true'): return True else: raise PlotValueError('"%s" unknown boolean' % arg) def _option_format(arg): return directives.choice(arg, ('python', 'doctest')) def _option_align(arg): return directives.choice( arg, ("top", "middle", "bottom", "left", "center", "right")) class nbplot_container(nodes.container, nodes.Targetable): """ Container for rendered nbplot contents Also serves as a reference target. """ def likes_builder(self, builder_name): """ Return True if attributes specify this is an acceptable build Parameters ---------- builder_name : str Name of builder by which the node is being visited. Returns ------- liked : bool True if node attributes are compatible with `builder_name`, False otherwise. """ hide_from = self.get('hide-from', []) show_to = self.get('show-to', []) if builder_name in show_to: return True if 'all' in hide_from: return False return builder_name not in hide_from class nbplot_epilogue(nodes.container, nodes.Targetable): """ Container for figures etc following nbplot """ class dont_doctest_block(nodes.General, nodes.FixedTextElement): """ Container to hide doctest block from doctest builder """ def doctest_filter(node): """ True if node is a ``doctest_block`` node """ return isinstance(node, nodes.doctest_block) class NBPlotDirective(Directive): """ Implements nbplot directive """ + __doc__ has_content = True required_arguments = 0 optional_arguments = 0 final_argument_whitespace = False option_spec = {'alt': directives.unchanged, 'height': directives.length_or_unitless, 'width': directives.length_or_percentage_or_unitless, 'scale': directives.nonnegative_int, 'align': _option_align, 'class': directives.class_option, 'hide-from': directives.unchanged, 'show-to': directives.unchanged, 'include-source': _option_boolean, 'format': _option_format, 'keepfigs': directives.flag, 'nofigs': directives.flag, 'encoding': directives.encoding, 'raises': directives.unchanged, 'render-parts': directives.unchanged, 'run-parts': directives.unchanged, } # Node classes for rendered, not rendered nbplot contents nbplot_node = nbplot_container nbplot_epilogue = nbplot_epilogue dont_doctest_block = dont_doctest_block def _dont_doctest_doctests(self, tree): """ Replace ``doctest_block`` nodes with ``dont_doctest_block`` nodes """ for node in tree.traverse(doctest_filter): raw_source = _get_rawsource(node) new_node = self.dont_doctest_block(raw_source, raw_source) node.replace_self(new_node) def rst2nodes(self, lines, node_class, node_attrs=None): """ Build docutils nodes from list of ReST strings `lines` Parameters ---------- lines : list list of strings containing ReST. node_class : :class:`nodes.Node` class Container class for output node_attrs : None or dict, optional Attributes to apply to instance of `node_class`. These simply get applied to the containing node, except where they signal that the contents should be hidden from the doctest builder, in which case the doctest_block nodes get swapped for similar nodes that don't get picked up by the doctest builder. Returns ------- nodes : list A length 1 list of nodes, where contained node is of type `node_class` and node contents are nodes generated from ReST in `lines`. """ node_attrs = {} if node_attrs is None else node_attrs text = '\n'.join(lines) node = node_class(text) for key, value in node_attrs.items(): if value: node[key] = value self.add_name(node) if len(lines) != 0: self.state.nested_parse(StringList(lines), self.content_offset, node) # Implement hiding of doctests from doctest builder if not likes_builder(node, 'doctest'): self._dont_doctest_doctests(node) return [node] def _get_parts(self, option_name): if option_name not in self.options: return (0,) env = self.state.document.settings.env name_space = env.nbplot_flag_namespaces[env.docname].copy() indices = eval(self.options[option_name], name_space) return indices if isinstance(indices, Sequence) else (indices,) def _select_parts(self): parts = parse_parts(self.content) to_render = [parts[i]['contents'] for i in self._get_parts('render-parts')] to_run = [parts[i]['contents'] for i in self._get_parts('run-parts')] return ('\n'.join(sum(to_render, [])), '\n'.join(sum(to_run, []))) def _contains_doctest(self, multi_str): """ Check ``format`` option for doctest specifier, else guess """ if 'format' in self.options: return False if self.options['format'] == 'python' else True return contains_doctest(multi_str) def _build_epilogue(self, images, source_rel_dir, build_dir): """ Build the epilogue housing the image links """ document = self.state.document config = document.settings.env.config nofigs = 'nofigs' in self.options # how to link to files from the RST file rst_file = document.attributes['source'] rst_dir = dirname(rst_file) dest_dir_link = pjoin(relpath(setup.confdir, rst_dir), source_rel_dir).replace(os.path.sep, '/') build_dir_link = relpath(build_dir, rst_dir).replace(os.path.sep, '/') images_to_show = [] if nofigs else images[:] n_to_show = len(images_to_show) opts = [':%s: %s' % (key, val) for key, val in self.options.items() if key in ('alt', 'height', 'width', 'scale', 'align', 'class')] # These are the headers for blocks in the template that link to the # various build plot images - where the logic is different for each # builder. only_html = ".. only:: html" only_latex = ".. only:: latex" only_texinfo = ".. only:: texinfo" # Build source text for image link epilogue epilogue_source = format_template( config.nbplot_template or EPILOGUE_TEMPLATE, dest_dir=dest_dir_link, build_dir=build_dir_link, multi_image=n_to_show > 1, only_html=only_html, only_latex=only_latex, only_texinfo=only_texinfo, options=opts, images=images_to_show, html_show_formats=config.nbplot_html_show_formats and n_to_show) return self.rst2nodes(epilogue_source.splitlines(), self.nbplot_epilogue) def _copy_image_files(self, images, dest_dir): # copy image files to builder's output directory, if necessary if not exists(dest_dir): cbook.mkdirs(dest_dir) for img in images: for fn in img.filenames(): destimg = pjoin(dest_dir, basename(fn)) if fn != destimg: shutil.copyfile(fn, destimg) def _proc_builder_opts(self, config): """ Process options related to later per-node selection of builders hide-from ad show-to options apply on top of include-source option and config setting. """ options = self.options options.setdefault('include-source', config.nbplot_include_source) if options['include-source']: node_attrs = {'hide-from': [], 'show-to': []} else: # include-source is False node_attrs = {'hide-from': ['all'], 'show-to': ['doctest']} for opt_name in node_attrs: if opt_name not in options: continue values = options[opt_name].split() node_attrs[opt_name] += [b_name.strip() for b_name in values] return node_attrs def run(self): document = self.state.document config = document.settings.env.config env = document.settings.env docname = env.docname # Check and fill options for skipping nodes per builder node_attrs = self._proc_builder_opts(config) # If this is the first directive in the document, clear context if env.nbplot_reset_markers.get(docname, False): context_reset = False else: env.nbplot_reset_markers[docname] = True context_reset = True close_figs = False if 'keepfigs' in self.options else True counter = document.attributes.get('_plot_counter', 0) + 1 document.attributes['_plot_counter'] = counter source_file_name = document.attributes['source'] base, ext = splitext(basename(source_file_name)) output_base = '%s-%d' % (base, counter) # ensure that LaTeX includegraphics doesn't choke in foo.bar.pdf # filenames output_base = output_base.replace('.', '-') # should the code raise an exception? raises = (eval(self.options['raises']) if 'raises' in self.options else None) # determine output directory name fragment source_rel_name = relpath(source_file_name, setup.confdir) source_rel_dir = dirname(source_rel_name) while source_rel_dir.startswith(os.path.sep): source_rel_dir = source_rel_dir[1:] # build_dir: where to place output files (temporarily) build_dir = pjoin(dirname(setup.app.doctreedir), 'nbplot_directive', source_rel_dir) # get rid of .. in paths, also changes pathsep # see note in Python docs for warning about symbolic links on Windows. # need to compare source and dest paths at end build_dir = os.path.normpath(build_dir) if not exists(build_dir): os.makedirs(build_dir) # output_dir: final location in the builder's directory dest_dir = abspath(pjoin(setup.app.builder.outdir, source_rel_dir)) if not exists(dest_dir): # no problem here for me, but just use built-ins os.makedirs(dest_dir) # We are now going to chose which parts of the text go to which # builders. We might have specified which builders we want all the # text to go to, using the hide-from, and show-to options, or # (equivalently) using the include-source option. Or, we might have # split the code into parts, to send some of the code to the renderers, # such as HTML, and other parts of the code to the doctest builder # only. For most builders, we do that by adding 'hide-from' and # 'show-to' attributes to the containing doctest node, and notifying # the builders visiting the node to discard the node, if those # attributes say they should. However, the doctest builder does not # visit, so we have have to run some doctree post-processing on the # nbplot nodes, to check hide-from, show-to for the 'doctest' builder, # and, if the node should be hidden from the doctest builder, we # replace the doctest_block nodes with something that behaves in the # same way as a doctest_block node for all the visiting builders, but, # because it is not a doctest_block node, does not get picked up by the # doctest builder. # Break contents into parts, and select to_render, to_run = self._select_parts() # make figures try: images = render_figures(to_run, source_file_name, build_dir, output_base, config=config, context = True, # keep plot context function_name = None, context_reset=context_reset, close_figs=close_figs, raises=raises) errors = [] except PlotError as err: reporter = self.state.memo.reporter sm = reporter.system_message( 2, 'Exception plotting {output_base}\n' 'from: {source_file_name}\n' 'with code:\n\n{to_run}\n\n' 'Exception:\n{err}'.format(**locals()), line=self.lineno) images = [] errors = [sm] # generate output restructuredtext lines = [''] + [row.rstrip() for row in to_render.split('\n')] # If the code is not in doctest format, make it into code blocks. if not self._contains_doctest(to_render): lines = (['.. code-block:: python'] + [' ' + line for line in lines]) # If we're going to run different code from the source we're rendering # then change node_attrs in place to hide the rendered code from the # doctest builder. if to_render != to_run: _hide_from_builder(node_attrs, 'doctest') # Build the rendered node rendered_nodes = self.rst2nodes(lines, self.nbplot_node, node_attrs) # Epilogue node contains the built figures and supporting stuff. epilogue = self._build_epilogue(images, source_rel_dir, build_dir) ret = rendered_nodes + epilogue + errors self._copy_image_files(images, dest_dir) # Now, we need to put in nodes for the code that ran, so the doctest # builder can find it. But, we hide these nodes from all the other # builders (using hide-from all). if to_render != to_run and self._contains_doctest(to_run): lines = [''] + [row.rstrip() for row in to_run.split('\n')] ret += self.rst2nodes( lines, self.nbplot_node, {'hide-from': ['all'], 'show-to': ['doctest']}) return ret def _hide_from_builder(attrs, builder_name): """ Change ``show-to, hide-from`` values to hide from `builder_name` Modify `attrs` in-place. Parameters ---------- attrs : dict Dict containing keys ``hide-from`` and ``show-to``. builder_name : str Name of builder that we want `attrs` to signal hiding from. """ if builder_name in attrs['show-to']: attrs['show-to'].remove(builder_name) if builder_name not in attrs['hide-from']: attrs['hide-from'].append(builder_name) #------------------------------------------------------------------------------ # Doctest handling #------------------------------------------------------------------------------ def contains_doctest(text): try: # check if it's valid Python as-is compile(text, '', 'exec') return False except SyntaxError: pass r = re.compile(r'^\s*>>>', re.M) m = r.search(text) return bool(m) def unescape_doctest(text): """ Extract code from a piece of text, which contains either Python code or doctests. """ if not contains_doctest(text): return text code = "" for line in text.split("\n"): m = re.match(r'^\s*(>>>|\.\.\.) (.*)$', line) if m: code += m.group(2) + "\n" elif line.strip(): code += "# " + line.strip() + "\n" else: code += "\n" return code #------------------------------------------------------------------------------ # Template #------------------------------------------------------------------------------ EPILOGUE_TEMPLATE = """ {{ only_html }} {% if html_show_formats and not multi_image %} ( {%- for img in images -%} {%- for fmt in img.formats -%} {%- if not loop.first -%}, {% endif -%} `{{ fmt }} <{{ dest_dir }}/{{ img.basename }}.{{ fmt }}>`__ {%- endfor -%} {%- endfor -%} ) {% endif %} {% for img in images %} .. figure:: {{ build_dir }}/{{ img.basename }}.png {% for option in options -%} {{ option }} {% endfor %} {% if html_show_formats and multi_image -%} ( {%- for fmt in img.formats -%} {%- if not loop.first -%}, {% endif -%} `{{ fmt }} <{{ dest_dir }}/{{ img.basename }}.{{ fmt }}>`__ {%- endfor -%} ) {%- endif -%} {% endfor %} {{ only_latex }} {% for img in images %} {% if 'pdf' in img.formats -%} .. image:: {{ build_dir }}/{{ img.basename }}.pdf {% endif -%} {% endfor %} {{ only_texinfo }} {% for img in images %} .. image:: {{ build_dir }}/{{ img.basename }}.png {% for option in options -%} {{ option }} {% endfor %} {% endfor %} """ # the context of the plot for all directives plot_context = dict() class ImageFile(object): def __init__(self, basename, path): self.basename = basename self.dirname = path self.formats = [] def filename(self, format): return pjoin(self.dirname, "%s.%s" % (self.basename, format)) def filenames(self): return [self.filename(fmt) for fmt in self.formats] class PlotError(RuntimeError): pass class PlotValueError(ValueError): pass PARTER = re.compile(r"""(?:\n\n|^)\.\.\ part\n # part separator ((?:\ *\w+\ *=\ *.+\n)*) # attributes \n """, re.VERBOSE) ATTRIBUTER = re.compile(r'^(\w+) *= *(.+?) *$') def _proc_part_def(part_def): """ Return part dictionary from `part_def` string """ if part_def == '': return {} if not part_def.startswith(' '): raise PlotValueError('Part attributes should be indented') justified = textwrap.dedent(part_def).splitlines() if any(s.startswith(' ') for s in justified): raise PlotValueError('Part attributes should have same indentation') return dict(ATTRIBUTER.match(line).groups() for line in justified) def _part_strs2dicts(part_strs): """ Return part def, contents pairs as part dictionaries """ dicts = [] while len(part_strs): part_dict = _proc_part_def(part_strs.pop(0)) part_dict['contents'] = part_strs.pop(0).splitlines() dicts.append(part_dict) return dicts def parse_parts(lines): """ Parse string list `content` into `parts` Parameters ---------- lines : sequence of str Contents from directive. Each element is a line. Returns ------- parts : list List of dicts. Each dict is a "part". Part dicts each have key ``contents``, with value being a list of strings, one string per line. The other key, value pairs are attributes of this part. """ text = '\n'.join(lines).strip() part_strs = PARTER.split(text) if len(part_strs) == 1: return [{'contents': part_strs[0].splitlines()}] if part_strs[0] == '': # begins with part attributes part_strs.pop(0) else: # does not begin with part attributes, insert empty attributes part_strs.insert(0, '') return _part_strs2dicts(part_strs) def _check_wd(path): try: abs_path = abspath(path) except TypeError as err: raise TypeError(str(err) + '\n`nbplot_working_directory` option in ' 'Sphinx configuration file must be a string or ' 'None') if not isdir(abs_path): raise OSError('`nbplot_working_directory` option (="{}") in ' 'Sphinx configuration file must be a valid ' 'directory path'.format(path)) return abs_path def run_code(code, code_path=None, ns=None, function_name=None, workdir=None, pre_code=None, raises=None): """ Run `code` from file at `code_path` in namespace `ns` Parameters ---------- code : str code to run. code_path : str Filename containing the code. ns : None or dict, optional Python namespace in which to execute code. If None, make fresh namespace. function_name : None or str, optional If non-empty string, name of function to execute after executing `code`. workdir : None or str, optional Working directory in which to run code. Defaults to current working directory. pre_code : None or str, optional Any code to run before `code`. raises : None or Exception class An exception that the run code should raise. Returns ------- ns : dict Namespace, filled from execution of `code`. """ # Change the working directory to the directory of the example, so # it can get at its data files, if any. Add its path to sys.path # so it can import any helper modules sitting beside it. pwd = os.getcwd() old_sys_path = list(sys.path) workdir = os.getcwd() if workdir is None else workdir os.chdir(workdir) sys.path.insert(0, workdir) # Reset sys.argv old_sys_argv = sys.argv sys.argv = [code_path] # Redirect stdout stdout = sys.stdout sys.stdout = io.StringIO() # Assign a do-nothing print function to the namespace. There # doesn't seem to be any other way to provide a way to (not) print # that works correctly across Python 2 and 3. def _dummy_print(*arg, **kwarg): pass ns = {} if ns is None else ns try: try: code = unescape_doctest(code) if pre_code and not ns: exec(str(pre_code), ns) ns['print'] = _dummy_print if "__main__" in code: exec("__name__ = '__main__'", ns) if raises is None: exec(code, ns) else: # Code should raise exception try: exec(code, ns) except raises: pass if function_name: exec(function_name + "()", ns) except (Exception, SystemExit): raise PlotError(traceback.format_exc()) finally: os.chdir(pwd) sys.argv = old_sys_argv sys.path[:] = old_sys_path sys.stdout = stdout return ns def render_figures(code, code_path, output_dir, output_base, config, context=True, function_name=None, context_reset=False, close_figs=False, raises=None): """ Run plot code and save the hi/low res PNGs, PDF in `output_dir` Save the images under `output_dir` with file names derived from `output_base`. Parameters ---------- code : str String containing code to run. code_path : str Path of file containing code. Usually path to ``.rst`` file. output_dir : str Path to which to write output images from plots. output_base : str Prefix for filename(s) for output image(s). config : instance Sphinx configuration instance. context : {True, False}, optional If True, use persistent context (workspace) for executing code. Otherwise create new empty context for executing code. function_name : None or str, optional If not-empty str, name of function to execute after executing `code`. context_reset : {False, True}, optional If True, clear persistent context (workspace) for code. close_figs : {False, True}, optional If True, close all figures generated before our `code` runs. False can be useful when building up a plot with several `code` blocks. raises : None or Exception, optional Exception class that code should raise, or None, for no exception. """ # -- Parse format list default_dpi = {'png': 80, 'hires.png': 200, 'pdf': 200} formats = [] plot_formats = config.nbplot_formats if isinstance(plot_formats, str): # String Sphinx < 1.3, Split on , to mimic # Sphinx 1.3 and later. Sphinx 1.3 always # returns a list. plot_formats = plot_formats.split(',') for fmt in plot_formats: if isinstance(fmt, str): if ':' in fmt: suffix,dpi = fmt.split(':') formats.append((str(suffix), int(dpi))) else: formats.append((fmt, default_dpi.get(fmt, 80))) elif type(fmt) in (tuple, list) and len(fmt)==2: formats.append((str(fmt[0]), int(fmt[1]))) else: raise PlotError('invalid image format "%r" in nbplot_formats' % fmt) # Build the output ns = plot_context if context else {} if context_reset: plt.close('all') matplotlib.rc_file_defaults() matplotlib.rcParams.update(config.nbplot_rcparams) plot_context.clear() close_figs = not context or close_figs # Get working directory for code execution if setup.config.nbplot_working_directory is not None: workdir = _check_wd(setup.config.nbplot_working_directory) elif code_path is not None: workdir = abspath(dirname(code_path)) else: workdir = None if close_figs: plt.close('all') run_code(code, code_path, ns, function_name, workdir=workdir, pre_code=setup.config.nbplot_pre_code, raises=raises) images = [] fig_managers = Gcf.get_all_fig_managers() for j, figman in enumerate(fig_managers): if len(fig_managers) == 1: img = ImageFile(output_base, output_dir) else: img = ImageFile("%s_%02d" % (output_base, j), output_dir) images.append(img) for format, dpi in formats: try: figman.canvas.figure.savefig(img.filename(format), dpi=dpi) except Exception: raise PlotError(traceback.format_exc()) img.formats.append(format) return images # Sphinx event handlers def _false(): # Must be function rather than lambda to allow pickling of environment return False def do_builder_init(app): env = app.env env.nbplot_reset_markers = defaultdict(_false) env.nbplot_flag_namespaces = defaultdict(dict) def do_purge_doc(app, env, docname): """ Clear markers for whether `docname` has seen a plot context reset """ env.nbplot_reset_markers[docname] = False env.nbplot_flag_namespaces[docname] = env.config.nbplot_flags.copy() def likes_builder(node, builder_name): return (not hasattr(node, 'likes_builder') or node.likes_builder(builder_name)) def checked_visit(self, node): if not likes_builder(node, self.builder.name): raise nodes.SkipNode def checked_depart(self, node): pass def dont_doctest_visit(self, node): # Make node behave like doctest node, for builders that visit. This allows # us to make another not-doctest_block node to replace the actual # ductest_block node, so that, for builders that visit, such as html, we # get the same output, but thd doctest builder passes over it, because it # is not a doctest_block node. self.visit_doctest_block(node) def dont_doctest_depart(self, node): self.depart_doctest_block(node) def setup(app): setup.app = app setup.config = app.config setup.confdir = app.confdir # Builders which run visit methods on nodes. Basically everything but # doctest. visiting_builders = ('html', 'latex', 'text', 'texinfo') # Containers used as markers for nbplot contents for node_class in (nbplot_container, nbplot_epilogue): app.add_node(node_class, **{builder: (checked_visit, checked_depart) for builder in visiting_builders}) # Allow nodes hidden from doctest builder to render on other builders app.add_node(dont_doctest_block, **{builder: (dont_doctest_visit, dont_doctest_depart) for builder in visiting_builders}) app.add_directive('nbplot', NBPlotDirective) app.add_directive('nbplot-flags', NBPlotFlags) app.add_directive('nbplot-show-flags', NBPlotShowFlags) pre_default = "import numpy as np\nfrom matplotlib import pyplot as plt\n" app.add_config_value('nbplot_pre_code', pre_default, True) app.add_config_value('nbplot_include_source', True, True) app.add_config_value('nbplot_formats', ['png', 'hires.png', 'pdf'], True) app.add_config_value('nbplot_html_show_formats', True, True) app.add_config_value('nbplot_rcparams', {}, True) app.add_config_value('nbplot_working_directory', None, True) app.add_config_value('nbplot_template', None, True) app.add_config_value('nbplot_flags', {}, True) # Create dictionaries in builder environment app.connect(str('builder-inited'), do_builder_init) # Clear marker indicating that we have already started parsing a page app.connect(str('env-purge-doc'), do_purge_doc) nb2plots-0.7.2/nb2plots/runroles.py000066400000000000000000000305271450750300000172520ustar00rootroot00000000000000""" Sphinx extension to convert RST pages to notebooks """ from os import makedirs from os.path import join as pjoin, dirname, isdir from copy import deepcopy from collections import defaultdict from docutils import nodes, utils from docutils.parsers.rst.roles import set_classes import sphinx from sphinx.util.nodes import split_explicit_title, set_role_source_info from sphinx.errors import ExtensionError # Use notebook format version 4 from nbformat import v4 as nbf import nbconvert as nbc from . import doctree2nb, doctree2py from .sphinx2foos import PythonBuilder, NotebookBuilder from .converters import UnicodeOutput SPHINX_GE_6 = sphinx.version_info[0] >= 6 class RunRoleError(ExtensionError): """ Error for runnable role Sphinx extensions """ class runrole_reference(nodes.reference): """Node for references to built runnable, similar to pending_xref.""" class PyRunRole(object): """ Role builder for Python code file """ default_text = 'Download this page as a Python code file' default_extension = '.py' code_type = 'pyfile' builder_class = PythonBuilder encoding = 'utf-8' _cache = {} def __call__(self, name, rawtext, text, lineno, inliner, options={}, content=[]): """ Register this document for later building as runnable code file. Parameters ---------- name : str The role name used in the document. rawtext : str The entire markup snippet, including the role markup. text : str The text marked with the role. lineno : int The line number where `rawtext` appears in the input. inliner : object The inliner instance that called us. options : dict, optional Directive options for customization. content : content, optional The directive content for customization. Returns ------- nodes : list list of nodes to insert into the document. Can be empty. messages : list list of system messages. Can be empty. """ # Get objects from context env = inliner.document.settings.env # process class options. # http://docutils.sourceforge.net/docs/howto/rst-roles.html # Remaining options will be added as attributes of the node (see # below). set_classes(options) # Get title and link text = utils.unescape(text) text = self.default_text if text.strip() == '.' else text has_fname, title, fname = split_explicit_title(text) if not has_fname: fname = '/' + env.docname + self.default_extension refnode = runrole_reference(rawtext, title, reftype=self.code_type, refdoc=env.docname, reftarget=fname, **options) # We may need the line number for warnings set_role_source_info(inliner, lineno, refnode) return [refnode], [] def write_queue(self, queue, app): """ Write queue of runnable nodes Parameters ---------- queue : iterable Iterable of Docutils nodes, where the nodes specify runnable builds, including (for each node) the filename of original ReST document. app : Sphinx Application Application responsible for build. """ for node in queue: self.write(node, app) def write(self, node, app): """ Build + cache runnable, or return build from cache. Parameters ---------- node : docutils node Docutils node specifying runnable build, including filename of original ReST document. app : Sphinx Application Application responsible for build. """ out_fname = _relfn2outpath(node['filename'], app) built = self.get_built(node, app) path = dirname(out_fname) if not isdir(path): makedirs(path) with open(out_fname, 'wb') as fobj: fobj.write(built.encode(self.encoding)) def get_built(self, node, app): """ Build, cache, return output object, or return from cache. Parameters ---------- node : object Runrole node. app : object Sphinx application in charge of build Returns ------- output : built output. """ code_type = self.code_type own_params = app.env.runrole_cache[node['refdoc']] if own_params.get(code_type) is None: own_params[code_type] = self._build(node, app) return own_params[code_type] def _build(self, node, app): """ Return string containing built / resolved version of `doctree` """ args = (app, app.env) if SPHINX_GE_6 else (app,) builder = self.builder_class(*args) docname = node['refdoc'] doctree = app.env.get_and_resolve_doctree(docname, builder) builder.prepare_writing([docname]) # Set current docname for writer to work out link targets builder.current_docname = docname return builder.writer.write(doctree, UnicodeOutput()) class ClearNotebookRunRole(PyRunRole): """ Role builder for not-evaluated notebook """ default_text = 'Download this page as a Jupyter notebook (no outputs)' default_extension = '.ipynb' code_type = 'clearnotebook' builder_class = NotebookBuilder def convert_timeout(argument): """ Allow -1, 0, positive integers and None These are the valid options for the nbconvert timeout option. """ if argument.lower() == 'none': return None value = int(argument) if value < -1: raise ValueError('Value less than -1 not allowed') return value class FullNotebookRunRole(ClearNotebookRunRole): """ Role builder for evaluated notebook """ default_text = 'Download this page as a Jupyter notebook (with outputs)' code_type = 'fullnotebook' options = dict(timeout=convert_timeout) def __init__(self, clear_role): self.clear_role = clear_role def write_queue(self, queue, app): """ Write queue of runnable nodes Choose longest timeout for duplicate builds. Parameters ---------- queue : iterable Iterable of Docutils nodes, where the nodes specify runnable builds, including (for each node) the filename of original ReST document. app : Sphinx Application Application responsible for build. """ # Set longest timeout to duplicates for docname in set(n['refdoc'] for n in queue): duplicates = [n for n in queue if n['refdoc'] == docname] timeouts = set(n['timeout'] for n in duplicates if 'timeout' in n) if len(timeouts) < 2: continue max_timeout = (-1 if {None, -1}.intersection(timeouts) else max(timeouts)) for n in duplicates: n['timeout'] = max_timeout for node in queue: self.write(node, app) def _build(self, node, env): """ Return byte string containing built version of `doctree` """ empty_json = self.clear_role.get_built(node, env) timeout = node.get('timeout', env.config.fill_notebook_timeout) full_nb = fill_notebook(nbf.reads(empty_json), timeout=timeout) return nbf.writes(full_nb) # Collect instances of the known role types _clearnotebook = ClearNotebookRunRole() NAME2ROLE = dict(pyfile=PyRunRole(), codefile=PyRunRole(), # compatibility with older name clearnotebook=_clearnotebook, fullnotebook=FullNotebookRunRole(_clearnotebook)) def do_builder_init(app): """ Initialize builder with empty runrole caches and queues. """ env = app.env env.runrole_queue = defaultdict(list) env.runrole_cache = defaultdict(dict) def do_purge_doc(app, env, docname): """ Clear caches and queues of runrole builds from this `docname`. """ env.runrole_cache.pop(docname, None) queues = env.runrole_queue for code_type in queues: queues[code_type] = [node for node in queues[code_type] if node['refdoc'] != docname] def collect_runfiles(app, doctree, fromdocname): r""" Collate requested runnable files, store in env Traverse doctree, find runrole nodes, and collect the nodes that need to be built. Store references to the nodes in the ``env.runroles_queue`` dictionary, The dictionary has keys giving runrole type (string, one of 'pyfile', 'clearnotebook', 'fullnotebook') and values that are lists of nodes to be built into runnable outputs. Set filename of file to be built into node. Called at ``doctree-resolved`` event. """ env = app.env queues = env.runrole_queue files = {} for ref in doctree.traverse(runrole_reference): # Calculate filename of file to be built, relative to project root rel_fn, _ = env.relfn2path(ref['reftarget'], ref['refdoc']) ref['filename'] = rel_fn # Check for duplicates. It's OK to reference a file that is already # registered for building, but it must be of the same code type. code_type = ref['reftype'] if rel_fn not in files: files[rel_fn] = code_type elif files[rel_fn] != code_type: raise RunRoleError( 'Trying to register filename {0} as type {1}, ' 'but it is already registered as type {2}'.format( rel_fn, code_type, files[rel_fn])) # The queue can have duplicate combinations of (docname, code_type, # rel_fn). queues[code_type].append(ref) def _relfn2outpath(rel_path, app): return pjoin(app.outdir, rel_path) def write_runfiles(app, exception): """ Write notebooks / code files when build has finished :func:`collect_runfiles` has already collected the files that need to be built, and stored then in the ``env.runroles`` dictionary. See the docstring for that function for details. We cycle through these collected relative filenames, and build the necessary files using the ``write`` method of the stored role instances. Called at ``build-finished`` event. """ if exception is not None: return for code_type, queue in app.env.runrole_queue.items(): NAME2ROLE[code_type].write_queue(queue, app) def visit_runrole(self, node): self.body.append( ''.format( node['filename'])) self.context.append('') def depart_runrole(self, node): self.body.append(self.context.pop()) def fill_notebook(nb, timeout=30): """ Execute notebook `nb` and return notebook with built outputs """ preprocessor = nbc.preprocessors.execute.ExecutePreprocessor( timeout=timeout) preprocessor.enabled = True RD = nbc.exporters.exporter.ResourcesDict res = RD() res['metadata'] = RD() output_nb, _ = preprocessor(deepcopy(nb), res) return output_nb def drop_visit(self, node): raise nodes.SkipNode def setup(app): # Add runrole roles for name, role in NAME2ROLE.items(): app.add_role(name, role) # Create dictionaries in builder environment app.connect(str('builder-inited'), do_builder_init) # Delete caches when document re-initialized app.connect('env-purge-doc', do_purge_doc) # Collect and check all runrole nodes when doctree done app.connect('doctree-resolved', collect_runfiles) # Write output files at end of build app.connect('build-finished', write_runfiles) app.add_node(runrole_reference, html=(visit_runrole, depart_runrole), text=(drop_visit, None), latex=(drop_visit, None)) # Register translators to allow other extensions to extend ipynb and python # code visit, depart methods with app.add_node as we have just done for the # html translator in the lines above. See: # http://www.sphinx-doc.org/en/1.4.8/extdev/tutorial.html#the-setup-function app.set_translator('markdown', doctree2py.Translator) app.set_translator('pyfile', doctree2py.Translator) app.set_translator('ipynb', doctree2nb.Translator) nb2plots-0.7.2/nb2plots/sphinx2foos.py000066400000000000000000000032211450750300000176520ustar00rootroot00000000000000""" Sphinx builders for output formats """ import sphinx from sphinx.builders.text import TextBuilder from . import doctree2md, doctree2py, doctree2nb SPHINX_GE_6 = sphinx.version_info[0] >= 6 class MarkdownBuilder(TextBuilder): name = 'markdown' format = 'markdown' out_suffix = '.md' writer_class = doctree2md.Writer def __init__(self, app, env=None): """ Initialize Markdown (and friends) builder """ args = (app, env) if SPHINX_GE_6 else (app,) super(MarkdownBuilder, self).__init__(*args) # If None or empty string, do not resolve internal links. Otherwise, # use as base for HTML-style links. Applies to internal references and # download references. self.markdown_http_base = (self.config.markdown_http_base if self.config.markdown_http_base else None) def prepare_writing(self, docnames): self.writer = self.writer_class(self) def get_target_uri(self, docname, typ=None): if self.markdown_http_base: return docname + '.html' return super(MarkdownBuilder, self).get_target_uri(docname, typ) class PythonBuilder(MarkdownBuilder): name = 'python' out_suffix = '.py' writer_class = doctree2py.Writer class NotebookBuilder(PythonBuilder): name = 'jupyter' out_suffix = '.ipynb' writer_class = doctree2nb.Writer def setup(app): app.add_builder(MarkdownBuilder) app.add_builder(PythonBuilder) app.add_builder(NotebookBuilder) # Base URL for Markdown link conversion app.add_config_value('markdown_http_base', None, True) nb2plots-0.7.2/nb2plots/strdiff.py000066400000000000000000000022171450750300000170350ustar00rootroot00000000000000""" Utility to show differences between strings Used for debugging test output """ def get_diff(str1, str2, fmt_indent=None): """ Return line-by-line difference between multiline strings """ output = [] str_lists = [str1.splitlines(), str2.splitlines()] lens = [len(L) for L in str_lists] min_len = min(lens) fmt_str = 'L{:d}, {:2s}: {}' if fmt_indent is None: fmt_indent = len(fmt_str.format(0, '', '')) * ' ' for i in range(min(lens)): L1 = str_lists[0][i] L2 = str_lists[1][i] if L1 == L2: output.append(fmt_str.format(i, 'OK', L1)) else: output.append(fmt_str.format(i, 'S1', L1)) output.append(fmt_str.format(i, 'S2', L2)) diff = lens[1] - lens[0] if diff != 0: longer = diff > 0 abs_diff = diff if diff > 0 else -diff output.append('Remaining line{} in {} string {}:'.format( 's' if abs_diff > 1 else '', 'second' if longer else 'first', 'are' if abs_diff > 1 else 'is', )) output += [fmt_indent + L for L in str_lists[longer][min_len:]] return '\n'.join(output) nb2plots-0.7.2/nb2plots/testing/000077500000000000000000000000001450750300000164755ustar00rootroot00000000000000nb2plots-0.7.2/nb2plots/testing/__init__.py000066400000000000000000000016001450750300000206030ustar00rootroot00000000000000""" Package providing utilities for testing """ from os.path import abspath, dirname, join as pjoin import numpy as np from sphinxtesters import SourcesBuilder DATA_PATH = abspath(pjoin( dirname(__file__), '..', 'tests', 'rst_md_files')) # Regular expression snippets shared across testers. # Optional translation parameter in document tag. OPT_TRANS = r'( translation_progress=".*")?' def setup_test(): np.set_printoptions(legacy="1.13") class PlotsBuilder(SourcesBuilder): """ Class to build pages with nbplots default extensions Used by several test functions. """ conf_source = """\ master_doc = "contents" # Compatibility with Sphinx 2 extensions = ["nb2plots", "sphinx.ext.doctest"] """ def stripeq(actual, expected): """ True if LR stripped `actual` equal to LR stripped `expected` """ return actual.strip() == expected.strip() nb2plots-0.7.2/nb2plots/testing/convutils.py000066400000000000000000000045121450750300000210770ustar00rootroot00000000000000""" Utilities for testing conversion between formats """ import difflib from docutils.core import publish_string from docutils.writers.pseudoxml import Writer as PXMLWriter from docutils.io import StringOutput # Translate inserted smartquote characters back to their original form _UNSMART_IN = u'\u2019\u201c\u201d\u2026' _UNSMART_OUT = (u"'", u'"', u'"', u"...") UNSMART_TABLE = {ord(x): y for x, y in zip(_UNSMART_IN, _UNSMART_OUT)} _UNSMART_OUT_NB = (u"'", u'\\"', u'\\"', u"...") UNSMART_TABLE_NB = {ord(x): y for x, y in zip(_UNSMART_IN, _UNSMART_OUT_NB)} def fcontents(fname, mode='b'): with open(fname, 'r' + mode) as fobj: contents = fobj.read() return contents def unsmart(in_str): # Remove effect of smart quotes # See: https://github.com/sphinx-doc/sphinx/issues/3967 return in_str.translate(UNSMART_TABLE) def unsmart_nb(in_str): # Remove effect of smart quotes in notebook cells return in_str.translate(UNSMART_TABLE_NB) def unsmart_converter(converter, table=None): # Decorate function to remove effect of smart quotes. def unsmarted(rst_str): return unsmart(converter(rst_str)) return unsmarted def _diff_strs(first, second): # Replicate some of the standard string comparison error message. # This is from unittest.TestCase.assertMultiLineEqual firstlines = first.splitlines(True) secondlines = second.splitlines(True) if len(firstlines) == 1 and first.strip('\r\n') == first: firstlines = [first + '\n'] secondlines = [second + '\n'] return ''.join(difflib.ndiff(firstlines, secondlines)) def convert_assert(rst_str, converter, expected, encoding='utf8'): actual = converter(rst_str) if (actual == expected): assert actual == expected return # Make some useful debugging output if encoding is not None: actual = actual.decode(encoding) expected = expected.decode(encoding) msg = ('actual, expected not equal:\n' + _diff_strs(actual, expected)) pxml = publish_string(rst_str, writer=PXMLWriter()) msg += '\nwith doctree\n' + pxml.decode( 'utf8' if encoding is None else encoding) assert actual == expected, msg def doctree_assert(doctree, writer, expected): destination = StringOutput(encoding='utf8') assert writer.write(doctree, destination) == expected nb2plots-0.7.2/nb2plots/testing/mockapp.py000066400000000000000000000005011450750300000204750ustar00rootroot00000000000000""" Mocking Sphinx apps for testing """ try: # Python >=3.3 from unittest import mock except ImportError: import mock from sphinx.application import Sphinx from sphinx.config import Config def get_app(): app = mock.Mock(Sphinx) app.confdir = None app.config = mock.Mock(Config) return app nb2plots-0.7.2/nb2plots/testing/nbtesters.py000066400000000000000000000020041450750300000210540ustar00rootroot00000000000000""" Utils for testing notebooks """ from copy import deepcopy from nbformat import v4 as nbf def rm_ids(nb): nb2 = deepcopy(nb) for cell in nb2['cells']: if 'id' in cell: del cell['id'] return nb2 def assert_nb_equiv(ipynb, expected): actual_nb = nbf.reads(ipynb) expected_nb = nbf.reads(expected) # Ignore different minor versions of Notebook format # It does not appear to be possible to request specific minor versions of # the Notebook format. expected_nb['nbformat_minor'] = actual_nb['nbformat_minor'] # 'language_info' key seems to have arrived in metadata as a result of # nbconvert 5.3.1 -> 5.4.0 (5.4.0 released September 7 2018). Previously # it was empty. actual_nb['metadata'].pop('language_info', None) # 'execution' in cell metadata from nbconvert 6.0 for cell in actual_nb['cells']: if 'execution' in cell['metadata']: cell['metadata'].pop('execution') assert rm_ids(actual_nb) == rm_ids(expected_nb) nb2plots-0.7.2/nb2plots/tests/000077500000000000000000000000001450750300000161625ustar00rootroot00000000000000nb2plots-0.7.2/nb2plots/tests/__init__.py000066400000000000000000000000311450750300000202650ustar00rootroot00000000000000# nb2plots.tests package nb2plots-0.7.2/nb2plots/tests/conftest.py000066400000000000000000000003071450750300000203610ustar00rootroot00000000000000""" Skip the origin Gohlke transforms for doctests. That file needs some specific doctest setup. """ from os.path import join as pjoin collect_ignore = [pjoin('proj1', "conf.py"), 'rst_md_files'] nb2plots-0.7.2/nb2plots/tests/data/000077500000000000000000000000001450750300000170735ustar00rootroot00000000000000nb2plots-0.7.2/nb2plots/tests/data/converted_example.rst000066400000000000000000000007601450750300000233340ustar00rootroot00000000000000 An interesting example ---------------------- This is an interesting example. .. nbplot:: >>> import numpy as np >>> x = np.linspace(0, 2 * np.pi, 1000) >>> x[:10] array([ 0. , 0.00628947, 0.01257895, 0.01886842, 0.0251579 , 0.03144737, 0.03773685, 0.04402632, 0.0503158 , 0.05660527]) Even more interesting than that: .. mpl-interactive:: .. nbplot:: >>> import matplotlib.pyplot as plt >>> >>> plt.plot(x, np.sin(x)) [...] nb2plots-0.7.2/nb2plots/tests/data/converted_plus_notebooks.ipynb000066400000000000000000000015731450750300000252630ustar00rootroot00000000000000{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "## An interesting example\n", "\n", "This is an interesting example." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", "x = np.linspace(0, 2 * np.pi, 1000)\n", "x[:10]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Even more interesting than that:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "%matplotlib inline" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import matplotlib.pyplot as plt\n", "\n", "plt.plot(x, np.sin(x))" ] } ], "metadata": {}, "nbformat": 4, "nbformat_minor": 2 }nb2plots-0.7.2/nb2plots/tests/data/converted_plus_notebooks.py000066400000000000000000000006021450750300000245620ustar00rootroot00000000000000# ## An interesting example # # This is an interesting example. import numpy as np x = np.linspace(0, 2 * np.pi, 1000) x[:10] # Even more interesting than that: # # If running in the IPython console, consider running `%matplotlib` to enable # interactive plots. If running in the Jupyter Notebook, use `%matplotlib # inline`. import matplotlib.pyplot as plt plt.plot(x, np.sin(x)) nb2plots-0.7.2/nb2plots/tests/data/example_notebook.ipynb000066400000000000000000000335311450750300000234760ustar00rootroot00000000000000{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "## An interesting example\n", "\n", "This is an interesting example." ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "array([ 0. , 0.00628947, 0.01257895, 0.01886842, 0.0251579 ,\n", " 0.03144737, 0.03773685, 0.04402632, 0.0503158 , 0.05660527])" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import numpy as np\n", "x = np.linspace(0, 2 * np.pi, 1000)\n", "x[:10]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Even more interesting than that:" ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "collapsed": true }, "outputs": [], "source": [ "%matplotlib inline" ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "[]" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" }, { "data": { "image/png": "iVBORw0KGgoAAAANSUhEUgAAAXwAAAEACAYAAACwB81wAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAIABJREFUeJzt3Xm81nPex/HXJylMJi1UU6ZVyDIoo0IdssQYNbaIsYxB\nYlqM7N1yMzcxabclZ9TdaFEpiYROstxpUzhF0oqWMYnK0vK9//ieZs7k1DnXuZbv73dd7+fj0eMs\n/VzXW50+1+f6/r6LOecQEZHsVyF0ABERyQwVfBGRHKGCLyKSI1TwRURyhAq+iEiOUMEXEckRKSn4\nZjbczNaZ2aK9XDPIzJaa2ftmdlwqnldERMouVR1+PnD2nn7TzM4BGjvnDgNuAJ5I0fOKiEgZpaTg\nO+feAjbu5ZIOwIiia2cDVc2sViqeW0REyiZTY/h1gdXFvv686HsiIpIhmSr4VsL3tKeDiEgGVczQ\n86wBDi32dT3gi90vMjO9CIiIlINzrqTG+j+kssM3Su7kASYDVwKYWUvga+fcupIudM7F9te9996b\n1H+/aZPjoYccdes6TjvNkZ/v2LgxscfYutUxcaKjY0dHtWqO225zrFuXmfyhfym/8udidufK3ien\nalrm34F3gKZmtsrMrjGzG8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cM5zwPdizr92HDO7XTOHQ/UA04ys2ahM5WFmf0GWFf0\nDsvY+zYlUdXaOdcC/y7lpqIhzrioCJwADHXOnQBsBe4IGylxZrYvcD4wbm/XRaXgrwF+Wezrevix\nfMmQorHL54GRzrlJofOUV9Hb8QKgfeAoZXUycH7ROPhzwGlmNiJwpoQ459YWfdwATCReW6esAVY7\n5+YWff08/gUgbs4B5hX9HexRVAr+vxZnmVkl/OKsuM1WiGt3tsszQKFzbmDoIIkys5pmVrXo8/3x\nY5mxuOHsnLvLOfdL51wj/M/9G865K0PnKiszO6DonSFm9jPgLODDsKnKzjm3DlhtZk2LvtUOKAwY\nqbwuo5ThHIjIiVfOuR1mtmtxVgVgeJwWZ5nZ34E8oIaZrQLu3XUTKA7M7GTgcuCDonFwB9zlnHsl\nbLIyqwM8WzRLoQIwxjk3NXCmXFELmFi0LUpFYJRz7tXAmRLVDRhVNCzyGXBN4DwJKdbkXF/qtVGY\nlikiIukXlSEdERFJMxV8EZEcoYIvIpIjVPBFRHKECr6ISI5QwRcRyREq+CIiOUIFX0QkR/w/qrXc\nuLlO7OYAAAAASUVORK5CYII=\n", "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "import matplotlib.pyplot as plt\n", "\n", "plt.plot(x, np.sin(x))" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.5.2" } }, "nbformat": 4, "nbformat_minor": 2 } nb2plots-0.7.2/nb2plots/tests/data/small.ipynb000066400000000000000000001406441450750300000212570ustar00rootroot00000000000000{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Some text" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Some more test with mathematics $a = b$ and more:\n", "\n", "$$\n", "b = c\n", "c = \\vec{v}\n", "$$\n", "\n", "Yet more text" ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import numpy as np\n", "import matplotlib.pyplot as plt" ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "collapsed": false }, "outputs": [], "source": [ "%matplotlib inline" ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "4" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a = 2\n", "b = a\n", "b * a\n", "for i in range(3):\n", " c = a * i\n", "c" ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "[]" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" }, { "data": { "image/png": [ "iVBORw0KGgoAAAANSUhEUgAAAWoAAAEACAYAAACatzzfAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\n", "AAALEgAACxIB0t1+/AAAEk1JREFUeJzt3W2spGV9x/Hv77DyrKiV+IRgoCE+NBapQSNoj4FUxIox\n", "aaLY1IQam/AgxBgj8UVZXrTgC8uatElDBFpbtMa1tmKoAqFHQ1oeFFawC2olFpBCNK1UYkNx+ffF\n", "3MhwOGfnnnNm5r5n5vtJTs6Z3XvO/nN299rvuXZmrlQVkqT+Wul6AEnS/rlQS1LPuVBLUs+5UEtS\n", "z7lQS1LPuVBLUs+1WqiTXJjk7ubtgmkPJUl62siFOslrgQ8CbwBOAN6V5LhpDyZJGmhT1K8Gbqmq\n", "x6tqH/AN4D3THUuS9JQ2C/V3gbcmeUGSQ4EzgFdMdyxJ0lN2jLqgqu5N8kngRuDnwB7gl9MeTJI0\n", "kHFf6yPJnwAPVNVfrvtxXzREksZUVWlz0cg34Mjm/dHAXuCIDa6pNp9rlm/Azq5ncKbFmamvcznT\n", "fMwEtQJ1HtRPoD4KdUDbdXPk1kfjS0leCDwBnFtVj7a8nyQtvYRjgSuBg4BTqvhe8+OttFqoq+qt\n", "W5xPkpZWwgp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", "wV+o85Kc0vE8O4ATgb+oqhOBXwAXdTvS05I8BzgT+GIPZnk+g+/0j2GwDXJ4kvd3OVNV3Qt8ErgR\n", "uI7BtvEvN7t+uwv1g8DRQ7ePovtvKXqr+bZrN/A3VfWPXc8zrPm2eQ04veNRTgbOTHIfgxp7W5LP\n", "djwTVfVw8/4nwJcZbPt16UHggar6VnN7N4OFuy/eAXy7+Xp17TTgvqr6r2ab4e+BN3c8E1V1dVX9\n", "VlWtMtiq/cFm1253ob4d+PUkxzT/i/o+oBf/S0+/auwpVwF7q+rTXQ8CkORFSY5oPj6EwR/oe7uc\n", "qao+UVVHV9WxDP483VRVH+hypiSHNt8JkeQw4HcYfOvamap6BHggyfHND50K7O1wpPXOogfbHo37\n", "gTclOThJGHytOn8uSJIjm/dHM9if3vTrta0TXqqnT4ZJ8jkGr5T1a0nuBy5+6j9dOpzpZOD3gbub\n", "PeECPlFVX+twrJcCf928lO0K8IWquq7DefrqxcCXm5dJ2AFcU1XXdzwTwAXANc02w33A2R3PAzzj\n", "H/0/6noWgKq6Lclu4E7gieb9Fd1OBcCXkryQwUznVtWjm13oE14kqed683AjSdLGXKglqedcqCWp\n", "51yoJannXKglqedcqCWp51yoJannXKglqef+H3gApgS1T0rTAAAAAElFTkSuQmCC\n" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "plt.plot(range(10))" ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "[]" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" }, { "data": { "image/png": [ "iVBORw0KGgoAAAANSUhEUgAAAWoAAAEACAYAAACatzzfAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\n", "AAALEgAACxIB0t1+/AAAEk1JREFUeJzt3W2spGV9x/Hv77DyrKiV+IRgoCE+NBapQSNoj4FUxIox\n", "aaLY1IQam/AgxBgj8UVZXrTgC8uatElDBFpbtMa1tmKoAqFHQ1oeFFawC2olF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", "51yoJannXKglqedcqCWp51yoJannXKglqef+H3gApgS1T0rTAAAAAElFTkSuQmCC\n" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "plt.plot(range(10))" ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" }, { "data": { "image/png": [ "iVBORw0KGgoAAAANSUhEUgAAAVwAAAEACAYAAAD/Ws6gAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\n", "AAALEgAACxIB0t1+/AAAIABJREFUeJztvX/MdctV3/dd773YbUVtICR2a+NrN4HSpFgmpraDi+yW\n", "oNop5UZRWqCJatNKQfwQkZBSIjeS7QqlOM0fxHFaZGoiQCIGWRW+kNCYQi4UDMY117Fb+xrT2tgX\n", "516q2JaLiRpz39U/zp49a9astWb2Ofs5z7zb85XOe/bMrFmzZp+zP3vt2fs8LzEzpqampqZuXndu\n", "O4CpqampzxdN4E5NTU1dSRO4U1NTU1fSBO7U1NTUlTSBOzU1NXUlTeBOTU1NXUkXAZeIvpiI3kFE\n", "HyKif0xET3fsniSi3ySiR4jopy8Zc2pqaupeFV3yHC4RvQHAP2fmv0VE3wfgi5n5rxt2n2Hmp10Q\n", "59TU1NQ9r0uB+yiAlzHzE0T0TAAPM/NXGnb/LzP/6xfEOTU1NXXP69I13D/GzE8AADM/DuCPOnZP\n", "JaLfIKJ3EtGDF445NTU1dU/q/pYBEf08gGfIKgAM4G9sGOc5zPw4ET0PwC8S0fuY+SPbQp2ampq6\n", "t9UELjN/g9dGRE8Q0TPEksLvOT4eX94/QkQPA/hqABVwiWj+YYepqanhxcx0Tr8mcBt6CMCrAbwB\n", "wKsAvF0bENEXAfgDZv6XRPSlAL52sXf02gtDugn9EoD/EKfk/o5697ajuj3a/gGAv3xhHHvX/W2A\n", "/tpplxFlM1q+m2ZZbScbXNp/KX/mbwJf9JrSn/Yt7XV/s032d2KI+j/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8A+M3ls7y1fdUT0y3t\n", "q69aYnnvcqz/N8b3/KrHX2dMm4+9+cOHqampqSvptpcUpqampj5vNIE7NTU1dSVN4E5NTU1dSRO4\n", "U1NTU1fSBO7U1NTUlTSBOzU1NXUlTeBOTU1NXUkTuFNTU1NX0v8PO5GQprdkcNkAAAAASUVORK5C\n", "YII=\n" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "plt.imshow(np.arange(12).reshape((3, 4)))" ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "one\n", "two\n" ] }, { "data": { "text/plain": [ "3" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Code that prints stuff with end result\n", "print('one')\n", "print('two')\n", "3" ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "hello, again\n" ] } ], "source": [ "# Code that prints stuff without end result\n", "print('hello, again')" ] }, { "cell_type": "code", "execution_count": 9, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def xyz_trans_vol(vol, x_y_z_trans):\n", " \"\"\" Make a new copy of `vol` translated by `x_y_z_trans` voxels\n", "\n", " x_y_z_trans is a sequence or array length 3, containing the (x, y, z) translations in voxels.\n", " \n", " Values in `x_y_z_trans` can be positive or negative, and can be floats.\n", " \"\"\"\n", " x_y_z_trans = np.array(x_y_z_trans)" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.5.2" } }, "nbformat": 4, "nbformat_minor": 0 } nb2plots-0.7.2/nb2plots/tests/data/small.rst000066400000000000000000000022561450750300000207420ustar00rootroot00000000000000 Some text ========= Some more test with mathematics :math:`a = b` and more: .. math:: b = c c = \vec{v} Yet more text .. nbplot:: >>> import numpy as np >>> import matplotlib.pyplot as plt .. mpl-interactive:: .. nbplot:: >>> a = 2 >>> b = a >>> b * a >>> for i in range(3): ... c = a * i >>> c 4 .. nbplot:: >>> plt.plot(range(10)) [...] .. nbplot:: >>> plt.plot(range(10)) [...] .. nbplot:: >>> plt.imshow(np.arange(12).reshape((3, 4))) <...> .. nbplot:: >>> # Code that prints stuff with end result >>> print('one') >>> print('two') >>> 3 3 one two .. nbplot:: >>> # Code that prints stuff without end result >>> print('hello, again') hello, again .. nbplot:: >>> def xyz_trans_vol(vol, x_y_z_trans): ... """ Make a new copy of `vol` translated by `x_y_z_trans` voxels ... ... x_y_z_trans is a sequence or array length 3, containing the (x, y, z) translations in voxels. ... ... Values in `x_y_z_trans` can be positive or negative, and can be floats. ... """ ... x_y_z_trans = np.array(x_y_z_trans) nb2plots-0.7.2/nb2plots/tests/futz/000077500000000000000000000000001450750300000171525ustar00rootroot00000000000000nb2plots-0.7.2/nb2plots/tests/futz/.gitignore000066400000000000000000000000741450750300000211430ustar00rootroot00000000000000html/ proj1/ nbplot_directive/ *.rst *.tpl *.ipynb *_files/ nb2plots-0.7.2/nb2plots/tests/futz/Makefile000066400000000000000000000006301450750300000206110ustar00rootroot00000000000000BUILDDIR = build SRCDIR = proj1 all: build-html clean: rm -rf $(BUILDDIR) init: clean rm -rf $(SRCDIR) cp -r ../$(SRCDIR) . build-% : sphinx-build -W -b $* -d $(BUILDDIR) $(SRCDIR) $(BUILDDIR) debug-% : sphinx-build -P -W -b $* -d $(BUILDDIR) $(SRCDIR) $(BUILDDIR) permissive-% : sphinx-build -b $* -d $(BUILDDIR) $(SRCDIR) $(BUILDDIR) html: build-html doctest: build-doctest text: build-text nb2plots-0.7.2/nb2plots/tests/futz/README.rst000066400000000000000000000006441450750300000206450ustar00rootroot00000000000000################# Futzing directory ################# The tests are all well and good in their temporary directory, but sometimes I need to do an actual sphinx build and check what the output is, for debugging and so on. I do that in this directory. Something like:: make init make html Then I might copy some stuff into the ``proj1`` subdirectory that ``make init`` made for me, before retrying the build. nb2plots-0.7.2/nb2plots/tests/otherpages/000077500000000000000000000000001450750300000203235ustar00rootroot00000000000000nb2plots-0.7.2/nb2plots/tests/otherpages/some_plots.rst000066400000000000000000000023421450750300000232420ustar00rootroot00000000000000########## Some plots ########## Plot 1: .. nbplot:: plt.plot(range(10)) a = 99 Plot 2: .. nbplot:: plt.plot(range(6)) Plot 3 has length 4: .. nbplot:: plt.plot(range(4)) Plot 4 shows that a new block sees context created from the previous blocks: .. nbplot:: assert a == 99 Plot 5 defines ``a`` in a context block: .. nbplot:: plt.plot(range(6)) a = 10 Plot 6 shows that a block sees the new variable. It also uses ``:nofigs:``: .. nbplot:: :nofigs: assert a == 10 b = 4 Plot 7 uses a variable previously defined in previous ``nofigs`` context. It also closes any previous figures to create a fresh figure: .. nbplot:: assert b == 4 plt.plot(range(b)) Plot 8 opens a new figure with ``keepfigs``. The directive will plot both the first and the second figure: .. nbplot:: :keepfigs: plt.figure() plt.plot(range(6)) Plot 9 shows the default behavior in action. By default we close all figures previous to this plot directive, so we get always plot the figure we create in the directive: .. nbplot:: # Very unusual comment plt.figure() plt.plot(range(4)) Plot 10 uses ``include-source``: .. nbplot:: :include-source: true # Only a comment nb2plots-0.7.2/nb2plots/tests/proj1/000077500000000000000000000000001450750300000172155ustar00rootroot00000000000000nb2plots-0.7.2/nb2plots/tests/proj1/.gitignore000066400000000000000000000000101450750300000211740ustar00rootroot00000000000000_build/ nb2plots-0.7.2/nb2plots/tests/proj1/README.md000066400000000000000000000001611450750300000204720ustar00rootroot00000000000000# Test project for sphinx extensions A tiny sphinx project from ``sphinx-quickstart`` with all default answers. nb2plots-0.7.2/nb2plots/tests/proj1/_static/000077500000000000000000000000001450750300000206435ustar00rootroot00000000000000nb2plots-0.7.2/nb2plots/tests/proj1/_static/.gitignore000066400000000000000000000000001450750300000226210ustar00rootroot00000000000000nb2plots-0.7.2/nb2plots/tests/proj1/_static/README.txt000066400000000000000000000004621450750300000223430ustar00rootroot00000000000000############################### Static directory for test pages ############################### We need this README file to make sure the ``_static`` directory gets created in the installation. The tests check for warnings in builds, and, when the ``_static`` directory is absent, this raises a warning. nb2plots-0.7.2/nb2plots/tests/proj1/a_page.rst000066400000000000000000000002431450750300000211620ustar00rootroot00000000000000######### A section ######### Some text. :clearnotebook:`notebook here` More text. :fullnotebook:`full ` Text is endless. :pyfile:`code here` nb2plots-0.7.2/nb2plots/tests/proj1/conf.py000066400000000000000000000200301450750300000205070ustar00rootroot00000000000000# -*- coding: utf-8 -*- # # documentation build configuration file, created by # sphinx-quickstart on Tue Mar 18 11:58:34 2014. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys from os.path import join as pjoin, abspath import sphinx # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = ['nb2plots'] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'project' copyright = u'2015, Matthew Brett' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '0.1' # The full version, including alpha/beta/rc tags. release = '0.1' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all # documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. #keep_warnings = False # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'classic' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. #html_extra_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'projectdoc' # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ ('index', 'project.tex', u'project Documentation', u'Matplotlib developers', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'project', u'project Documentation', [u'Matplotlib developers'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'project', u'project Documentation', u'Matplotlib developers', 'project', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. #texinfo_no_detailmenu = False nb2plots-0.7.2/nb2plots/tests/proj1/index.rst000066400000000000000000000006461450750300000210640ustar00rootroot00000000000000.. project documentation master file, created by sphinx-quickstart on Tue Mar 18 11:58:34 2014. You can adapt this file completely to your liking, but it should at least contain the root `toctree` directive. Welcome to the documentation ============================ Contents: .. toctree:: :maxdepth: 2 a_page Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search` nb2plots-0.7.2/nb2plots/tests/rst_md_files/000077500000000000000000000000001450750300000206345ustar00rootroot00000000000000nb2plots-0.7.2/nb2plots/tests/rst_md_files/blockquotes.ipynb000066400000000000000000000010511450750300000242270ustar00rootroot00000000000000{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "> Blockquotes are very handy in email to emulate reply text.\n", "> This line is part of the same quote.\n", "\n", "Quote break.\n", "\n", "> This is a very long line that will still be quoted properly when it wraps.\n", "> Oh boy let's keep writing to make sure this is long enough to actually wrap\n", "> for everyone. Oh, you can *put* **Markdown** into a blockquote." ] } ], "metadata": {}, "nbformat": 4, "nbformat_minor": 1 }nb2plots-0.7.2/nb2plots/tests/rst_md_files/blockquotes.md000066400000000000000000000005201450750300000235060ustar00rootroot00000000000000> Blockquotes are very handy in email to emulate reply text. > This line is part of the same quote. Quote break. > This is a very long line that will still be quoted properly when it wraps. > Oh boy let's keep writing to make sure this is long enough to actually wrap > for everyone. Oh, you can *put* **Markdown** into a blockquote. nb2plots-0.7.2/nb2plots/tests/rst_md_files/blockquotes.py000066400000000000000000000005361450750300000235450ustar00rootroot00000000000000# > Blockquotes are very handy in email to emulate reply text. # > This line is part of the same quote. # # Quote break. # # > This is a very long line that will still be quoted properly when it wraps. # > Oh boy let's keep writing to make sure this is long enough to actually wrap # > for everyone. Oh, you can *put* **Markdown** into a blockquote. nb2plots-0.7.2/nb2plots/tests/rst_md_files/blockquotes.rst000066400000000000000000000005321450750300000237210ustar00rootroot00000000000000 Blockquotes are very handy in email to emulate reply text. This line is part of the same quote. Quote break. This is a very long line that will still be quoted properly when it wraps. Oh boy let's keep writing to make sure this is long enough to actually wrap for everyone. Oh, you can *put* **Markdown** into a blockquote. nb2plots-0.7.2/nb2plots/tests/rst_md_files/code.ipynb000066400000000000000000000007221450750300000226120ustar00rootroot00000000000000{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "Here is some code:\n", "\n", "```python\n", "a = 1\n", "b = 2\n", "print(a + b)\n", "```\n", "\n", "Some intervening text, then more code:\n", "\n", "```c\n", "a = 1;\n", "b = 2;\n", "fprintf('%d\\n', a + b);\n", "```\n", "\n", "What do you think?" ] } ], "metadata": {}, "nbformat": 4, "nbformat_minor": 1 }nb2plots-0.7.2/nb2plots/tests/rst_md_files/code.md000066400000000000000000000002471450750300000220730ustar00rootroot00000000000000Here is some code: ```python a = 1 b = 2 print(a + b) ``` Some intervening text, then more code: ```c a = 1; b = 2; fprintf('%d\n', a + b); ``` What do you think? nb2plots-0.7.2/nb2plots/tests/rst_md_files/code.py000066400000000000000000000003051450750300000221160ustar00rootroot00000000000000# Here is some code: # # ```python # a = 1 # b = 2 # print(a + b) # ``` # # Some intervening text, then more code: # # ```c # a = 1; # b = 2; # fprintf('%d\n', a + b); # ``` # # What do you think? nb2plots-0.7.2/nb2plots/tests/rst_md_files/code.rst000066400000000000000000000003071450750300000223000ustar00rootroot00000000000000Here is some code: .. code:: python a = 1 b = 2 print(a + b) Some intervening text, then more code: .. code:: c a = 1; b = 2; fprintf('%d\n', a + b); What do you think? nb2plots-0.7.2/nb2plots/tests/rst_md_files/comment.ipynb000066400000000000000000000004251450750300000233420ustar00rootroot00000000000000{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "Some text\n", "\n", "\n", "More text." ] } ], "metadata": {}, "nbformat": 4, "nbformat_minor": 1 }nb2plots-0.7.2/nb2plots/tests/rst_md_files/comment.md000066400000000000000000000001051450750300000226140ustar00rootroot00000000000000Some text More text. nb2plots-0.7.2/nb2plots/tests/rst_md_files/comment.py000066400000000000000000000001211450750300000226420ustar00rootroot00000000000000# Some text # # # More text. nb2plots-0.7.2/nb2plots/tests/rst_md_files/comment.rst000066400000000000000000000001061450750300000230250ustar00rootroot00000000000000Some text .. A multiline comment with blank lines More text. nb2plots-0.7.2/nb2plots/tests/rst_md_files/cross_references.ipynb000066400000000000000000000011121450750300000252240ustar00rootroot00000000000000{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "## Refereed section\n", "\n", "This section refers to itself.\n", "\n", "It also refers forward to the next section.\n", "\n", "Then, and finally, it refers to itself with its own name: Refereed section.\n", "\n", "## Rerefereed\n", "\n", "This section refers to this document at Refereed section, and with an\n", "explicit title, to this document.\n", "\n", "Now `contents.rst`." ] } ], "metadata": {}, "nbformat": 4, "nbformat_minor": 2 }nb2plots-0.7.2/nb2plots/tests/rst_md_files/cross_references.md000066400000000000000000000000051450750300000245030ustar00rootroot00000000000000skip nb2plots-0.7.2/nb2plots/tests/rst_md_files/cross_references.py000066400000000000000000000005211450750300000245360ustar00rootroot00000000000000# ## Refereed section # # This section refers to itself. # # It also refers forward to the next section. # # Then, and finally, it refers to itself with its own name: Refereed section. # # ## Rerefereed # # This section refers to this document at Refereed section, and with an # explicit title, to this document. # # Now `contents.rst`. nb2plots-0.7.2/nb2plots/tests/rst_md_files/cross_references.rst000066400000000000000000000006721450750300000247250ustar00rootroot00000000000000.. _a-ref: ################ Refereed section ################ This section refers to :ref:`itself `. It also refers forward to the :ref:`next section `. Then, and finally, it refers to itself with its own name: :ref:`a-ref`. .. _b-ref: ########## Rerefereed ########## This section refers to this document at :doc:`contents`, and with an explicit title, to :doc:`this document `. Now :download:`contents.rst`. nb2plots-0.7.2/nb2plots/tests/rst_md_files/cross_references.smd000066400000000000000000000004731450750300000246770ustar00rootroot00000000000000## Refereed section This section refers to itself. It also refers forward to the next section. Then, and finally, it refers to itself with its own name: Refereed section. ## Rerefereed This section refers to this document at Refereed section, and with an explicit title, to this document. Now `contents.rst`. nb2plots-0.7.2/nb2plots/tests/rst_md_files/definitions.ipynb000066400000000000000000000007201450750300000242110ustar00rootroot00000000000000{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "Start text.\n", "\n", "first definition\n", "\n", ": Here I define the first thing.\n", "\n", "second definition\n", "\n", ": Now I define the second thing. The definition can get long enough that it\n", " goes over more than one line.\n", "\n", "More text." ] } ], "metadata": {}, "nbformat": 4, "nbformat_minor": 1 }nb2plots-0.7.2/nb2plots/tests/rst_md_files/definitions.md000066400000000000000000000003231450750300000234670ustar00rootroot00000000000000Start text. first definition : Here I define the first thing. second definition : Now I define the second thing. The definition can get long enough that it goes over more than one line. More text. nb2plots-0.7.2/nb2plots/tests/rst_md_files/definitions.py000066400000000000000000000003461450750300000235240ustar00rootroot00000000000000# Start text. # # first definition # # : Here I define the first thing. # # second definition # # : Now I define the second thing. The definition can get long enough that it # goes over more than one line. # # More text. nb2plots-0.7.2/nb2plots/tests/rst_md_files/definitions.rst000066400000000000000000000003211450750300000236750ustar00rootroot00000000000000Start text. first definition Here I define the first thing. second definition Now I define the second thing. The definition can get long enough that it goes over more than one line. More text. nb2plots-0.7.2/nb2plots/tests/rst_md_files/docinfo.ipynb000066400000000000000000000022701450750300000233210ustar00rootroot00000000000000{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "## Docinfo Example\n", "\n", "author\n", "\n", ": Our noble selves\n", "\n", "contact\n", "\n", ": [ons@organization.com](mailto:ons@organization.com)\n", "\n", "The items above become \"docinfo\" in Docutils, and \"field\"s in Sphinx.\n", "\n", "author\n", "\n", ": J Random Hacker\n", "\n", "contact\n", "\n", ": [jrh@example.com](mailto:jrh@example.com)\n", "\n", "date\n", "\n", ": 2002-08-18\n", "\n", "status\n", "\n", ": Work In Progress\n", "\n", "version\n", "\n", ": 1\n", "\n", "filename\n", "\n", ": $RCSfile$\n", "\n", "copyright\n", "\n", ": This document has been placed in the public domain. You are\n", " welcome to claim this as your own work. It can go into your\n", " thesis. You can publish it in a book. You can patent it. You\n", " can do anything you like with it.\n", "\n", "The above are \"field\"s in Docutils and Sphinx." ] } ], "metadata": {}, "nbformat": 4, "nbformat_minor": 1 }nb2plots-0.7.2/nb2plots/tests/rst_md_files/docinfo.md000066400000000000000000000011371450750300000226010ustar00rootroot00000000000000% Our noble selves % ons@organization.com # Docinfo Example The items above become "docinfo" in Docutils, and "field"s in Sphinx. author : J Random Hacker contact : [jrh@example.com](mailto:jrh@example.com) date : 2002-08-18 status : Work In Progress version : 1 filename : $RCSfile$ copyright : This document has been placed in the public domain. You are welcome to claim this as your own work. It can go into your thesis. You can publish it in a book. You can patent it. You can do anything you like with it. The above are "field"s in Docutils and Sphinx. nb2plots-0.7.2/nb2plots/tests/rst_md_files/docinfo.py000066400000000000000000000013311450750300000226250ustar00rootroot00000000000000# ## Docinfo Example # # author # # : Our noble selves # # contact # # : [ons@organization.com](mailto:ons@organization.com) # # The items above become "docinfo" in Docutils, and "field"s in Sphinx. # # author # # : J Random Hacker # # contact # # : [jrh@example.com](mailto:jrh@example.com) # # date # # : 2002-08-18 # # status # # : Work In Progress # # version # # : 1 # # filename # # : $RCSfile$ # # copyright # # : This document has been placed in the public domain. You are # welcome to claim this as your own work. It can go into your # thesis. You can publish it in a book. You can patent it. You # can do anything you like with it. # # The above are "field"s in Docutils and Sphinx. nb2plots-0.7.2/nb2plots/tests/rst_md_files/docinfo.rst000066400000000000000000000011371450750300000230110ustar00rootroot00000000000000Docinfo Example =============== :author: Our noble selves :contact: ons@organization.com The items above become "docinfo" in Docutils, and "field"s in Sphinx. :author: J Random Hacker :contact: jrh@example.com :date: 2002-08-18 :status: Work In Progress :version: 1 :filename: $RCSfile$ :copyright: This document has been placed in the public domain. You are welcome to claim this as your own work. It can go into your thesis. You can publish it in a book. You can patent it. You can do anything you like with it. The above are "field"s in Docutils and Sphinx. nb2plots-0.7.2/nb2plots/tests/rst_md_files/docinfo.smd000066400000000000000000000012251450750300000227620ustar00rootroot00000000000000## Docinfo Example author : Our noble selves contact : [ons@organization.com](mailto:ons@organization.com) The items above become "docinfo" in Docutils, and "field"s in Sphinx. author : J Random Hacker contact : [jrh@example.com](mailto:jrh@example.com) date : 2002-08-18 status : Work In Progress version : 1 filename : $RCSfile$ copyright : This document has been placed in the public domain. You are welcome to claim this as your own work. It can go into your thesis. You can publish it in a book. You can patent it. You can do anything you like with it. The above are "field"s in Docutils and Sphinx. nb2plots-0.7.2/nb2plots/tests/rst_md_files/doctests.ipynb000066400000000000000000000016521450750300000235330ustar00rootroot00000000000000{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "Here are some:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# doctest blocks\n", "a = 1\n", "a" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Interspersed with text." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# another block\n", "b = [1, 2, 3]\n", "b" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Explaining here." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Here is a comment line that goes beyond the normal 80 character line wrap to test (non) wrapping" ] } ], "metadata": {}, "nbformat": 4, "nbformat_minor": 2 }nb2plots-0.7.2/nb2plots/tests/rst_md_files/doctests.md000066400000000000000000000004531450750300000230100ustar00rootroot00000000000000Here are some: ```python >>> # doctest blocks >>> a = 1 >>> a 1 ``` Interspersed with text. ```python >>> # another block >>> b = [1, 2, 3] >>> b [1, 2, 3] ``` Explaining here. ```python >>> # Here is a comment line that goes beyond the normal 80 character line wrap to test (non) wrapping ``` nb2plots-0.7.2/nb2plots/tests/rst_md_files/doctests.py000066400000000000000000000003371450750300000230410ustar00rootroot00000000000000# Here are some: # doctest blocks a = 1 a # Interspersed with text. # another block b = [1, 2, 3] b # Explaining here. # Here is a comment line that goes beyond the normal 80 character line wrap to test (non) wrapping nb2plots-0.7.2/nb2plots/tests/rst_md_files/doctests.rst000066400000000000000000000004011450750300000232110ustar00rootroot00000000000000Here are some: >>> # doctest blocks >>> a = 1 >>> a 1 Interspersed with text. >>> # another block >>> b = [1, 2, 3] >>> b [1, 2, 3] Explaining here. >>> # Here is a comment line that goes beyond the normal 80 character line wrap to test (non) wrapping nb2plots-0.7.2/nb2plots/tests/rst_md_files/escaping.ipynb000066400000000000000000000007131450750300000234710ustar00rootroot00000000000000{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "Here is some *emphasis* and here is an actual \\* asterisk.\n", "\n", "You can have actual \\`backticks\\` too.\n", "\n", "And real \\\\backslashes.\n", "\n", "No escaping in $1 * 2$.\n", "\n", "No escaping in a math block:\n", "\n", "$$\n", "3 * 4\n", "$$" ] } ], "metadata": {}, "nbformat": 4, "nbformat_minor": 2 }nb2plots-0.7.2/nb2plots/tests/rst_md_files/escaping.md000066400000000000000000000003001450750300000227400ustar00rootroot00000000000000Here is some *emphasis* and here is an actual \* asterisk. You can have actual \`backticks\` too. And real \\backslashes. No escaping in $1 * 2$. No escaping in a math block: $$ 3 * 4 $$ nb2plots-0.7.2/nb2plots/tests/rst_md_files/escaping.py000066400000000000000000000003251450750300000227770ustar00rootroot00000000000000# Here is some *emphasis* and here is an actual \* asterisk. # # You can have actual \`backticks\` too. # # And real \\backslashes. # # No escaping in $1 * 2$. # # No escaping in a math block: # # $$ # 3 * 4 # $$ nb2plots-0.7.2/nb2plots/tests/rst_md_files/escaping.rst000066400000000000000000000003171450750300000231600ustar00rootroot00000000000000Here is some *emphasis* and here is an actual \* asterisk. You can have actual \`backticks\` too. And real \\backslashes. No escaping in :math:`1 * 2`. No escaping in a math block: .. math:: 3 * 4 nb2plots-0.7.2/nb2plots/tests/rst_md_files/index.ipynb000066400000000000000000000003501450750300000230040ustar00rootroot00000000000000{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "This is a normal reST paragraph that contains several index\n", "entries." ] } ], "metadata": {}, "nbformat": 4, "nbformat_minor": 2 }nb2plots-0.7.2/nb2plots/tests/rst_md_files/index.md000066400000000000000000000000051450750300000222600ustar00rootroot00000000000000skip nb2plots-0.7.2/nb2plots/tests/rst_md_files/index.py000066400000000000000000000001111450750300000223060ustar00rootroot00000000000000# This is a normal reST paragraph that contains several index # entries. nb2plots-0.7.2/nb2plots/tests/rst_md_files/index.rst000066400000000000000000000001541450750300000224750ustar00rootroot00000000000000This is a normal reST :index:`paragraph` that contains several :index:`index entries `. nb2plots-0.7.2/nb2plots/tests/rst_md_files/index.smd000066400000000000000000000001051450750300000224440ustar00rootroot00000000000000This is a normal reST paragraph that contains several index entries. nb2plots-0.7.2/nb2plots/tests/rst_md_files/links.ipynb000066400000000000000000000007001450750300000230140ustar00rootroot00000000000000{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "## A section\n", "\n", "A test for links. An [inline link](http://nipy.org).\n", "\n", "A [link reference](http://python.org).\n", "\n", "An internal reference.\n", "\n", "### Another section\n", "\n", "A reference to an [inline link](http://nipy.org)." ] } ], "metadata": {}, "nbformat": 4, "nbformat_minor": 1 }nb2plots-0.7.2/nb2plots/tests/rst_md_files/links.md000066400000000000000000000003121450750300000222720ustar00rootroot00000000000000# A section A test for links. An [inline link](http://nipy.org). A [link reference](http://python.org). An internal reference. ## Another section A reference to an [inline link](http://nipy.org). nb2plots-0.7.2/nb2plots/tests/rst_md_files/links.py000066400000000000000000000003351450750300000223270ustar00rootroot00000000000000# ## A section # # A test for links. An [inline link](http://nipy.org). # # A [link reference](http://python.org). # # An internal reference. # # ### Another section # # A reference to an [inline link](http://nipy.org). nb2plots-0.7.2/nb2plots/tests/rst_md_files/links.rst000066400000000000000000000004141450750300000225050ustar00rootroot00000000000000.. _internal reference: ********* A section ********* A test for links. An `inline link `_. A `link reference`_. An `internal reference`_. Another section =============== A reference to an `inline link`_. .. _link reference: http://python.org nb2plots-0.7.2/nb2plots/tests/rst_md_files/links.smd000066400000000000000000000003141450750300000224570ustar00rootroot00000000000000## A section A test for links. An [inline link](http://nipy.org). A [link reference](http://python.org). An internal reference. ### Another section A reference to an [inline link](http://nipy.org). nb2plots-0.7.2/nb2plots/tests/rst_md_files/lists.ipynb000066400000000000000000000015631450750300000230420ustar00rootroot00000000000000{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "1. First ordered list item\n", "\n", "1. Another item\n", "\n", " * Unordered sub-list.\n", "\n", " * Another sub-item.\n", "\n", "1. Actual numbers don't matter, just that it's a number\n", "\n", " 1. Ordered sub-list\n", "\n", "1. And another item.\n", "\n", " You can have properly indented paragraphs within list items. Notice the\n", " blank line above. The text can keep going on for a long time, flowing\n", " across\n", " *many* lines. There may be stuff such as $a = b$ and `literals`.\n", "\n", " You can have a line break within the list.\n", "\n", " Note that this line is separate, but within the same paragraph." ] } ], "metadata": {}, "nbformat": 4, "nbformat_minor": 1 }nb2plots-0.7.2/nb2plots/tests/rst_md_files/lists.md000066400000000000000000000010341450750300000223120ustar00rootroot000000000000001. First ordered list item 1. Another item * Unordered sub-list. * Another sub-item. 1. Actual numbers don't matter, just that it's a number 1. Ordered sub-list 1. And another item. You can have properly indented paragraphs within list items. Notice the blank line above. The text can keep going on for a long time, flowing across *many* lines. There may be stuff such as $a = b$ and `literals`. You can have a line break within the list. Note that this line is separate, but within the same paragraph. nb2plots-0.7.2/nb2plots/tests/rst_md_files/lists.py000066400000000000000000000010771450750300000223510ustar00rootroot00000000000000# 1. First ordered list item # # 1. Another item # # * Unordered sub-list. # # * Another sub-item. # # 1. Actual numbers don't matter, just that it's a number # # 1. Ordered sub-list # # 1. And another item. # # You can have properly indented paragraphs within list items. Notice the # blank line above. The text can keep going on for a long time, flowing # across # *many* lines. There may be stuff such as $a = b$ and `literals`. # # You can have a line break within the list. # # Note that this line is separate, but within the same paragraph. nb2plots-0.7.2/nb2plots/tests/rst_md_files/lists.rst000066400000000000000000000010431450750300000225220ustar00rootroot000000000000001. First ordered list item 2. Another item * Unordered sub-list. * Another sub-item. 1. Actual numbers don't matter, just that it's a number 1. Ordered sub-list 4. And another item. You can have properly indented paragraphs within list items. Notice the blank line above. The text can keep going on for a long time, flowing across *many* lines. There may be stuff such as :math:`a = b` and ``literals``. You can have a line break within the list. Note that this line is separate, but within the same paragraph. nb2plots-0.7.2/nb2plots/tests/rst_md_files/literals.ipynb000066400000000000000000000010741450750300000235200ustar00rootroot00000000000000{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "## Another title\n", "\n", "Here a `literal` followed by a:\n", "\n", "```\n", "Literal block, not :math:`parsed`.\n", "```\n", "\n", "On it goes, to another:\n", "\n", "```\n", "This block has a very long line, that goes beyond the normal 80-or-so characters, to see whether not-wrapping works correctly.\n", "```\n", "\n", "Finishes with dramatic exhortation." ] } ], "metadata": {}, "nbformat": 4, "nbformat_minor": 2 }nb2plots-0.7.2/nb2plots/tests/rst_md_files/literals.md000066400000000000000000000004431450750300000227760ustar00rootroot00000000000000# Another title Here a `literal` followed by a: ``` Literal block, not :math:`parsed`. ``` On it goes, to another: ``` This block has a very long line, that goes beyond the normal 80-or-so characters, to see whether not-wrapping works correctly. ``` Finishes with dramatic exhortation. nb2plots-0.7.2/nb2plots/tests/rst_md_files/literals.py000066400000000000000000000004751450750300000230330ustar00rootroot00000000000000# ## Another title # # Here a `literal` followed by a: # # ``` # Literal block, not :math:`parsed`. # ``` # # On it goes, to another: # # ``` # This block has a very long line, that goes beyond the normal 80-or-so characters, to see whether not-wrapping works correctly. # ``` # # Finishes with dramatic exhortation. nb2plots-0.7.2/nb2plots/tests/rst_md_files/literals.rst000066400000000000000000000004711450750300000232070ustar00rootroot00000000000000############# Another title ############# Here a ``literal`` followed by a:: Literal block, not :math:`parsed`. On it goes, to another:: This block has a very long line, that goes beyond the normal 80-or-so characters, to see whether not-wrapping works correctly. Finishes with dramatic exhortation. nb2plots-0.7.2/nb2plots/tests/rst_md_files/literals.smd000066400000000000000000000004441450750300000231620ustar00rootroot00000000000000## Another title Here a `literal` followed by a: ``` Literal block, not :math:`parsed`. ``` On it goes, to another: ``` This block has a very long line, that goes beyond the normal 80-or-so characters, to see whether not-wrapping works correctly. ``` Finishes with dramatic exhortation. nb2plots-0.7.2/nb2plots/tests/rst_md_files/math_markup.ipynb000066400000000000000000000005621450750300000242120ustar00rootroot00000000000000{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "## Title\n", "\n", "Some text with $a = 1$ where line continues.\n", "\n", "A math block:\n", "\n", "$$\n", "c = 2\n", "d = 5\n", "$$\n", "\n", "Text after the math block." ] } ], "metadata": {}, "nbformat": 4, "nbformat_minor": 1 }nb2plots-0.7.2/nb2plots/tests/rst_md_files/math_markup.md000066400000000000000000000001641450750300000234670ustar00rootroot00000000000000# Title Some text with $a = 1$ where line continues. A math block: $$ c = 2 d = 5 $$ Text after the math block. nb2plots-0.7.2/nb2plots/tests/rst_md_files/math_markup.py000066400000000000000000000002111450750300000235100ustar00rootroot00000000000000# ## Title # # Some text with $a = 1$ where line continues. # # A math block: # # $$ # c = 2 # d = 5 # $$ # # Text after the math block. nb2plots-0.7.2/nb2plots/tests/rst_md_files/math_markup.rst000066400000000000000000000002131450750300000236720ustar00rootroot00000000000000Title ##### Some text with :math:`a = 1` where line continues. A math block: .. math:: c = 2 d = 5 Text after the math block. nb2plots-0.7.2/nb2plots/tests/rst_md_files/math_markup.smd000066400000000000000000000001651450750300000236530ustar00rootroot00000000000000## Title Some text with $a = 1$ where line continues. A math block: $$ c = 2 d = 5 $$ Text after the math block. nb2plots-0.7.2/nb2plots/tests/rst_md_files/nbplot.ipynb000066400000000000000000000033121450750300000231740ustar00rootroot00000000000000{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "## Nbplot file\n", "\n", "Introducing..." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "a = 1\n", "a" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "... the `nbplot`." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "b = 1\n", "a" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "%matplotlib inline" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "A block to test line-wrapping:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Here is a comment line that goes beyond the normal 80 character line wrap to test (non) wrapping" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Markdown builder can be forced to skip:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Should not appear in Markdown" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Python builder can be forced to skip:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Should not appear in Python" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Jupyter builder can be forced to skip:" ] } ], "metadata": {}, "nbformat": 4, "nbformat_minor": 2 } nb2plots-0.7.2/nb2plots/tests/rst_md_files/nbplot.md000066400000000000000000000000051450750300000224470ustar00rootroot00000000000000skip nb2plots-0.7.2/nb2plots/tests/rst_md_files/nbplot.py000066400000000000000000000010701450750300000225020ustar00rootroot00000000000000# ## Nbplot file # # Introducing... a = 1 a # ... the `nbplot`. b = 1 a # If running in the IPython console, consider running `%matplotlib` to enable # interactive plots. If running in the Jupyter Notebook, use `%matplotlib # inline`. # # A block to test line-wrapping: # Here is a comment line that goes beyond the normal 80 character line wrap to test (non) wrapping # Markdown builder can be forced to skip: # Should not appear in Markdown # Python builder can be forced to skip: # # Jupyter builder can be forced to skip: # Should not appear in Notebook nb2plots-0.7.2/nb2plots/tests/rst_md_files/nbplot.rst000066400000000000000000000012601450750300000226630ustar00rootroot00000000000000########### Nbplot file ########### Introducing... .. nbplot:: >>> a = 1 >>> a 1 ... the ``nbplot``. .. nbplot:: >>> b = 1 >>> a 1 .. mpl-interactive:: A block to test line-wrapping: .. nbplot:: >>> # Here is a comment line that goes beyond the normal 80 character line wrap to test (non) wrapping Markdown builder can be forced to skip: .. nbplot:: :hide-from: markdown >>> # Should not appear in Markdown Python builder can be forced to skip: .. nbplot:: :hide-from: python >>> # Should not appear in Python Jupyter builder can be forced to skip: .. nbplot:: :hide-from: jupyter >>> # Should not appear in Notebook nb2plots-0.7.2/nb2plots/tests/rst_md_files/nbplot.smd000066400000000000000000000012051450750300000226350ustar00rootroot00000000000000## Nbplot file Introducing... ```python >>> a = 1 >>> a 1 ``` ... the `nbplot`. ```python >>> b = 1 >>> a 1 ``` If running in the IPython console, consider running `%matplotlib` to enable interactive plots. If running in the Jupyter Notebook, use `%matplotlib inline`. A block to test line-wrapping: ```python >>> # Here is a comment line that goes beyond the normal 80 character line wrap to test (non) wrapping ``` Markdown builder can be forced to skip: Python builder can be forced to skip: ```python >>> # Should not appear in Python ``` Jupyter builder can be forced to skip: ```python >>> # Should not appear in Notebook ``` nb2plots-0.7.2/nb2plots/tests/rst_md_files/only.ipynb000066400000000000000000000004461450750300000226640ustar00rootroot00000000000000{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "Text.\n", "\n", "After HTML-specific text.\n", "\n", "Specific to Markdown\n", "\n", "After Markdown-specific text." ] } ], "metadata": {}, "nbformat": 4, "nbformat_minor": 2 }nb2plots-0.7.2/nb2plots/tests/rst_md_files/only.md000066400000000000000000000000051450750300000221320ustar00rootroot00000000000000skip nb2plots-0.7.2/nb2plots/tests/rst_md_files/only.py000066400000000000000000000001411450750300000221630ustar00rootroot00000000000000# Text. # # After HTML-specific text. # # Specific to Markdown # # After Markdown-specific text. nb2plots-0.7.2/nb2plots/tests/rst_md_files/only.rst000066400000000000000000000002241450750300000223450ustar00rootroot00000000000000Text. .. only:: html Specific to HTML After HTML-specific text. .. only:: markdown Specific to Markdown After Markdown-specific text. nb2plots-0.7.2/nb2plots/tests/rst_md_files/only.smd000066400000000000000000000001261450750300000223210ustar00rootroot00000000000000Text. After HTML-specific text. Specific to Markdown After Markdown-specific text. nb2plots-0.7.2/nb2plots/tests/rst_md_files/sect_text.ipynb000066400000000000000000000003071450750300000237010ustar00rootroot00000000000000{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "## A section\n", "\n", "Some *text*." ] } ], "metadata": {}, "nbformat": 4, "nbformat_minor": 1 }nb2plots-0.7.2/nb2plots/tests/rst_md_files/sect_text.md000066400000000000000000000000321450750300000231530ustar00rootroot00000000000000# A section Some *text*. nb2plots-0.7.2/nb2plots/tests/rst_md_files/sect_text.py000066400000000000000000000000401450750300000232020ustar00rootroot00000000000000# ## A section # # Some *text*. nb2plots-0.7.2/nb2plots/tests/rst_md_files/sect_text.rst000066400000000000000000000000541450750300000233670ustar00rootroot00000000000000######### A section ######### Some *text*. nb2plots-0.7.2/nb2plots/tests/rst_md_files/sect_text.smd000066400000000000000000000000331450750300000233370ustar00rootroot00000000000000## A section Some *text*. nb2plots-0.7.2/nb2plots/tests/rst_md_files/sections.ipynb000066400000000000000000000013061450750300000235260ustar00rootroot00000000000000{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "## Top section\n", "\n", "First paragraph.\n", "\n", "Second paragraph.\n", "\n", "Third paragraph.\n", "\n", "### H2 section\n", "\n", "More text.\n", "\n", "### H2 section again\n", "\n", "Continued text.\n", "\n", "#### H3 section\n", "\n", "Drones on.\n", "\n", "##### H4 section\n", "\n", "Sink-hole boring.\n", "\n", "#### H3 section again\n", "\n", "Still boring.\n", "\n", "### H2 section again\n", "\n", "As if from the start." ] } ], "metadata": {}, "nbformat": 4, "nbformat_minor": 1 }nb2plots-0.7.2/nb2plots/tests/rst_md_files/sections.md000066400000000000000000000004271450750300000230100ustar00rootroot00000000000000# Top section First paragraph. Second paragraph. Third paragraph. ## H2 section More text. ## H2 section again Continued text. ### H3 section Drones on. #### H4 section Sink-hole boring. ### H3 section again Still boring. ## H2 section again As if from the start. nb2plots-0.7.2/nb2plots/tests/rst_md_files/sections.py000066400000000000000000000005151450750300000230360ustar00rootroot00000000000000# ## Top section # # First paragraph. # # Second paragraph. # # Third paragraph. # # ### H2 section # # More text. # # ### H2 section again # # Continued text. # # #### H3 section # # Drones on. # # ##### H4 section # # Sink-hole boring. # # #### H3 section again # # Still boring. # # ### H2 section again # # As if from the start. nb2plots-0.7.2/nb2plots/tests/rst_md_files/sections.rst000066400000000000000000000006301450750300000232140ustar00rootroot00000000000000########### Top section ########### First paragraph. Second paragraph. Third paragraph. ********** H2 section ********** More text. **************** H2 section again **************** Continued text. H3 section ========== Drones on. H4 section ---------- Sink-hole boring. H3 section again ================ Still boring. **************** H2 section again **************** As if from the start. nb2plots-0.7.2/nb2plots/tests/rst_md_files/sections.smd000066400000000000000000000004361450750300000231730ustar00rootroot00000000000000## Top section First paragraph. Second paragraph. Third paragraph. ### H2 section More text. ### H2 section again Continued text. #### H3 section Drones on. ##### H4 section Sink-hole boring. #### H3 section again Still boring. ### H2 section again As if from the start. nb2plots-0.7.2/nb2plots/tests/rst_md_files/substitution.ipynb000066400000000000000000000003121450750300000244470ustar00rootroot00000000000000{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "Here is a some *actual* text substituted value." ] } ], "metadata": {}, "nbformat": 4, "nbformat_minor": 2 }nb2plots-0.7.2/nb2plots/tests/rst_md_files/substitution.md000066400000000000000000000000601450750300000237260ustar00rootroot00000000000000Here is a some *actual* text substituted value. nb2plots-0.7.2/nb2plots/tests/rst_md_files/substitution.py000066400000000000000000000000621450750300000237600ustar00rootroot00000000000000# Here is a some *actual* text substituted value. nb2plots-0.7.2/nb2plots/tests/rst_md_files/substitution.rst000066400000000000000000000001261450750300000241410ustar00rootroot00000000000000Here is a |subst-var| substituted value. .. |subst-var| replace:: some *actual* text nb2plots-0.7.2/nb2plots/tests/rst_md_files/subtitle.ipynb000066400000000000000000000004441450750300000235340ustar00rootroot00000000000000{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "## A title\n", "\n", "### A subtitle\n", "\n", "Some text.\n", "\n", "### A section\n", "\n", "More text." ] } ], "metadata": {}, "nbformat": 4, "nbformat_minor": 1 }nb2plots-0.7.2/nb2plots/tests/rst_md_files/subtitle.md000066400000000000000000000000771450750300000230150ustar00rootroot00000000000000# A title ## A subtitle Some text. ## A section More text. nb2plots-0.7.2/nb2plots/tests/rst_md_files/subtitle.py000066400000000000000000000001201450750300000230320ustar00rootroot00000000000000# ## A title # # ### A subtitle # # Some text. # # ### A section # # More text. nb2plots-0.7.2/nb2plots/tests/rst_md_files/subtitle.rst000066400000000000000000000001611450750300000232170ustar00rootroot00000000000000####### A title ####### ********** A subtitle ********** Some text. ********* A section ********* More text. nb2plots-0.7.2/nb2plots/tests/rst_md_files/subtitle.smd000066400000000000000000000001021450750300000231650ustar00rootroot00000000000000## A title ### A subtitle Some text. ### A section More text. nb2plots-0.7.2/nb2plots/tests/test_builders.py000066400000000000000000000130011450750300000213770ustar00rootroot00000000000000""" Tests for Markdown and other builders """ from os.path import join as pjoin, isfile import re from nb2plots.testing import PlotsBuilder class TestMarkdownBuild(PlotsBuilder): """ Markdown builder without specified base URL """ builder = 'markdown' rst_sources = {'a_page': """\ .. _a-ref: ################ Refereed section ################ This section refers to :ref:`itself `. It also refers forward to the :ref:`next section `. Then, and finally, it refers to itself with its own name: :ref:`a-ref`. .. _b-ref: ########## Rerefereed ########## This section refers to this document at :doc:`a_page`, and with an explicit title, to :doc:`this document `. Then to :doc:`a_page`. Again to :doc:`another doc `. Now :download:`a_page.rst`. Then :download:`another page `. .. code-links:: Then `a link `_. Again, we :doc:`link to another doc `.""", 'subdir1/b_page': """\ ############ Another page ############ Here is another page. It refers to :doc:`/a_page`.""", 'subdir2/c_page': """\ ############ Further page ############ Here is further page. It refers to :doc:`../a_page`. It also refers to :doc:`/subdir1/b_page`."""} def test_output(self): assert self.get_built_file('contents.md').strip() == '' assert self.get_built_file('a_page.md') == """\ ## Refereed section This section refers to itself. It also refers forward to the next section. Then, and finally, it refers to itself with its own name: Refereed section. ## Rerefereed This section refers to this document at Refereed section, and with an explicit title, to this document. Then to Refereed section. Again to another doc. Now `a_page.rst`. Then `another page`. Then [a link](https://another-place.com/page.html). Again, we link to another doc. """ assert self.get_built_file(pjoin('subdir1', 'b_page.md')) == """\ ## Another page Here is another page. It refers to Refereed section. """ assert self.get_built_file(pjoin('subdir2', 'c_page.md')) == """\ ## Further page Here is further page. It refers to Refereed section. It also refers to Another page. """ class TestBasedMarkdownBuild(TestMarkdownBuild): """ Markdown builder with specified base URL """ conf_source = ('master_doc = "contents"\n' 'extensions = ["nb2plots"]\n' 'markdown_http_base = "https://dynevor.org"') def test_output(self): assert self.get_built_file('contents.md').strip() == '' expected_re = r"""## Refereed section This section refers to \[itself\]\(https://dynevor.org/a_page.html#a-ref\)\. It also refers forward to the \[next section\]\(https://dynevor.org/a_page.html#b-ref\)\. Then, and finally, it refers to itself with its own name: \[Refereed section\]\(https://dynevor.org/a_page\.html#a-ref\)\. ## Rerefereed This section refers to this document at \[Refereed section\]\(https://dynevor\.org/a_page\.html\), and with an explicit title, to \[this document\]\(https://dynevor\.org/a_page.html\)\. Then to \[Refereed section\]\(https://dynevor\.org/a_page.html\)\. Again to \[another doc\]\(https://dynevor\.org/a_page.html\)\. Now \[a_page\.rst\]\(https://dynevor.org/_downloads/([a-f0-9]+/)?a_page.rst\)\. Then \[another page\]\(https://dynevor\.org/_downloads/([a-f0-9]+/)?a_page.rst\)\. Then \[a link\]\(https://another-place.com/page.html\)\. Again, we \[link to another doc\]\(https://dynevor.org/subdir1/b_page\.html\)\. """ actual = self.get_built_file('a_page.md') assert re.match(expected_re, actual) assert self.get_built_file(pjoin('subdir1', 'b_page.md')) == """\ ## Another page Here is another page. It refers to [Refereed section](https://dynevor.org/a_page.html). """ assert self.get_built_file(pjoin('subdir2', 'c_page.md')) == """\ ## Further page Here is further page. It refers to [Refereed section](https://dynevor.org/a_page.html). It also refers to [Another page](https://dynevor.org/subdir1/b_page.html). """ class TestPythonBuild(PlotsBuilder): """ Python builder without specified base URL """ builder = 'python' rst_sources = {'a_page': """\ .. _a-ref: A section ========= Some text This section refers to :ref:`itself `. .. nbplot:: >>> a = 1 """} def test_output(self): assert self.get_built_file('contents.py').strip() == '' assert self.get_built_file('a_page.py') == """\ # ## A section # # Some text # # This section refers to itself. a = 1 """ class TestBasedPythonBuild(TestPythonBuild): """ Python builder with specified base URL """ conf_source = ('master_doc = "contents"\n' 'extensions = ["nb2plots"]\n' 'markdown_http_base = "https://dynevor.org"') def test_output(self): assert self.get_built_file('contents.py').strip() == '' assert self.get_built_file('a_page.py') == """\ # ## A section # # Some text # # This section refers to [itself](https://dynevor.org/a_page.html#a-ref). a = 1 """ class TestLatexBuild(PlotsBuilder): """ Test LaTeX build In particular, test that code outputs in a subdirectory work without raising an error. """ builder = 'latex' rst_sources = {'foo/a_page': """\ A section ========= .. code-links:: """} toctree_pages = list(rst_sources) def test_output(self): for suffix in ('.py', '.ipynb', '_full.ipynb'): assert isfile(pjoin(self.out_dir, 'foo', 'a_page' + suffix)) nb2plots-0.7.2/nb2plots/tests/test_codelinks.py000066400000000000000000000072571450750300000215610ustar00rootroot00000000000000""" Test code-links directive """ from os.path import isfile, join as pjoin import re from nb2plots.converters import to_pxml from nb2plots.testing import PlotsBuilder def test_codelinks(): def as_pxml(rst_text): return to_pxml.from_rst(rst_text, resolve=False) page = """\ Text here .. code-links:: More text here.""" both_re = re.compile(r""" Text here Download this page as a Python code file ; Download this page as a Jupyter notebook \(no outputs\) ; Download this page as a Jupyter notebook \(with outputs\) . More text here.""") pxml = as_pxml(page) assert both_re.match(pxml) # Default is 'both' page = """\ Text here .. code-links:: python clear full More text here.""" pxml = as_pxml(page) assert both_re.match(pxml) page = """\ Text here .. code-links:: clear More text here.""" pxml = as_pxml(page) assert re.match(r""" Text here Download this page as a Jupyter notebook \(no outputs\) . More text here.""" , pxml) page = """\ Text here .. code-links:: full More text here.""" pxml = as_pxml(page) assert re.match(r""" Text here Download this page as a Jupyter notebook \(with outputs\) . More text here.""", pxml) page = """\ Text here .. code-links:: full python More text here.""" pxml = as_pxml(page) assert re.match(r""" Text here Download this page as a Jupyter notebook \(with outputs\) ; Download this page as a Python code file . More text here.""", pxml) class TestSubdirCodeLinks(PlotsBuilder): """ Test output file locations for code-links directive. """ rst_sources = {'foo/a_page': """\ A section ######### .. code-links:: More text. """} def test_output(self): for suffix in ('.py', '.ipynb', '_full.ipynb'): assert isfile(pjoin(self.out_dir, 'foo', 'a_page' + suffix)) nb2plots-0.7.2/nb2plots/tests/test_config.py000066400000000000000000000021751450750300000210450ustar00rootroot00000000000000# -*- coding: utf-8 -*- """ Tests for nb2plots.nbplot extension """ from nb2plots import nbplots as nbp from nb2plots.testing import mockapp def test_nbplots_setup(): # Test extension setup works as expected app = mockapp.get_app() nbp.setup(app) config_names = ['nbplot_pre_code', 'nbplot_include_source', 'nbplot_formats', 'nbplot_html_show_formats', 'nbplot_rcparams', 'nbplot_working_directory', 'nbplot_template', 'nbplot_flags'] connects = [ ('builder-inited', nbp.do_builder_init), ('env-purge-doc', nbp.do_purge_doc), ] for method_name, args, kwargs in app.method_calls: if (method_name == 'add_config_value' and args[0] in config_names): config_names.remove(args[0]) if (method_name == 'connect' and args[0:2] in connects): connects.remove(args[0:2]) assert len(config_names) == 0, \ 'config set failed for {}'.format(config_names) assert len(connects) == 0, 'Connections failed' nb2plots-0.7.2/nb2plots/tests/test_converters.py000066400000000000000000000014211450750300000217630ustar00rootroot00000000000000""" Test bare Converter class """ import re from nb2plots.converters import Converter from nb2plots.testing import OPT_TRANS NEW_PAGE = u""" More fancy title ++++++++++++++++ More compelling text """ def test_converter(): # Default converter conv = Converter() text = conv.from_rst(NEW_PAGE) assert text.strip() == """\ More fancy title **************** More compelling text""" # pseudoxml converter conv = Converter('pseudoxml') pxml = conv.from_rst(NEW_PAGE) assert re.search( rf'' r"""
More fancy title <paragraph> More compelling text """, pxml) is not None �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������nb2plots-0.7.2/nb2plots/tests/test_doctree2md.py����������������������������������������������������0000664�0000000�0000000�00000005274�14507503000�0021633�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """ Test writer conversions Test running writer over example files and chosen snippets """ import sys from os.path import join as pjoin from glob import glob from functools import partial from io import TextIOWrapper, BytesIO from docutils import nodes from docutils.utils import new_document from docutils.core import publish_string from nb2plots.doctree2md import Writer, IndentLevel from nb2plots.testing import DATA_PATH from nb2plots.testing.convutils import (convert_assert, doctree_assert, fcontents) def assert_conv_equal(rst_str, md_expected, encoding='utf8'): converter = partial(publish_string, writer=Writer()) convert_assert(rst_str, converter, md_expected, encoding) def assert_dt_equal(doctree, md_expected): doctree_assert(doctree, Writer(), md_expected) def test_example_files(): # test rst2md script over all .rst files checking against .md files for rst_fname in glob(pjoin(DATA_PATH, '*.rst')): rst_contents = fcontents(rst_fname) md_fname = rst_fname[:-3] + 'md' md_contents = fcontents(md_fname) # Skip files containing text "skip". These are files for which the # source ReST is not valid in plain docutils, such as those containing # Sphinx directives and roles. if md_contents.strip() != b'skip': assert_conv_equal(rst_contents, md_contents) def test_indent_level(): # Test IndentLevel object level = IndentLevel(['foo', 'bar'], 'prefix') assert len(level) == 0 level.append('baz') assert len(level) == 1 def test_container(): # Test container node passed through doc = new_document('md-test') container = nodes.container() doc.append(container) container.append(nodes.Text('Boo!')) assert_dt_equal(doc, b'Boo!\n') def test_snippets(): assert_conv_equal("Some text", b"Some text\n") assert_conv_equal("With *emphasis*", b"With *emphasis*\n") assert_conv_equal("That's **strong**", b"That's **strong**\n") assert_conv_equal("As ``literal``", b"As `literal`\n") assert_conv_equal("To ``defrole``", b"To `defrole`\n") assert_conv_equal("Now :math:`a = 1`", b"Now $a = 1$\n") def test_system_message(): # This output could surely be improved. old_stderr = sys.stderr sys.stderr = TextIOWrapper(BytesIO()) try: assert_conv_equal('Text. :bad-role:`.`. More text.', b"""\ Text. ``` :bad-role:`.` ``` . More text. ``` System Message: <string>:, line 1 <string>:1: (ERROR/3) Unknown interpreted text role "bad-role". ``` """) finally: sys.stderr = old_stderr ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������nb2plots-0.7.2/nb2plots/tests/test_doctree2nb.py����������������������������������������������������0000664�0000000�0000000�00000010544�14507503000�0021626�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������""" Test conversion of doctree to Jupyter notebook """ from os.path import join as pjoin from glob import glob import re from nbformat import v4 as nbf from nb2plots.converters import to_notebook # Shortcuts n_nb = nbf.new_notebook n_md_c = nbf.new_markdown_cell n_c_c = nbf.new_code_cell from nb2plots.testing import DATA_PATH from nb2plots.testing.convutils import fcontents, unsmart_nb from nb2plots.testing.nbtesters import assert_nb_equiv ID_RE = re.compile(r'"id":\s+".*?",\s*\n?') def to_nb_safe(rst_str): out = to_notebook.from_rst(rst_str) return unsmart_nb(out) def cells2json(cells): nb = nbf.new_notebook() nb['cells'] += cells return nbf.writes(nb) def rm_json_id(s): return ID_RE.sub(s, '') def assert_rst_cells_equal(rst_text, cells): actual = to_notebook.from_rst(rst_text) expected = cells2json(cells) assert rm_json_id(actual) == rm_json_id(expected) def test_basic(): assert_rst_cells_equal('Some text', [n_md_c('Some text')]) def test_runrole_reference(): # Ignore notebook reference in source ReST assert_rst_cells_equal('Some text :clearnotebook:`.`', [n_md_c('Some text')]) assert_rst_cells_equal('Some text :fullnotebook:`.`', [n_md_c('Some text')]) def test_only(): for builder_name in ('html', 'latex', 'unbelievable'): assert_rst_cells_equal( """ Before .. only:: {0} Specific to builder {0} After""".format(builder_name), [n_md_c('Before\n\nAfter')]) assert_rst_cells_equal( """ Before .. only:: markdown More text After""".format(builder_name), [n_md_c('Before\n\nMore text\n\nAfter')]) def test_doctests(): assert_rst_cells_equal("""\ Text 1 >>> # A comment >>> a = 1 Text 2 """, [n_md_c('Text 1'), n_c_c('# A comment\na = 1'), n_md_c('Text 2')]) def test_nbplots(): # nbplot directive with doctest markers assert_rst_cells_equal("""\ Text 1 .. nbplot:: >>> # A comment >>> a = 1 Text 2 """, [n_md_c('Text 1'), n_c_c('# A comment\na = 1'), n_md_c('Text 2')]) # nbplot directive with no doctest markers assert_rst_cells_equal("""\ Text 1 .. nbplot:: # A comment a = 1 Text 2 """, [n_md_c('Text 1'), n_c_c('# A comment\na = 1'), n_md_c('Text 2')]) # Doctest interspersed with text assert_rst_cells_equal("""\ Text 1 .. nbplot:: >>> # A comment Some thoughts I had >>> a = 1 Text 2 """, [n_md_c('Text 1'), n_c_c('# A comment'), n_md_c('Some thoughts I had'), n_c_c('a = 1'), n_md_c('Text 2')]) def assert_conv_equal(rst_str, expected): assert_nb_equiv(to_nb_safe(rst_str), expected) def test_example_files(): # test conversion over all .rst files, checking against .ipynb files for rst_fname in glob(pjoin(DATA_PATH, '*.rst')): rst_contents = fcontents(rst_fname, 't') nb_fname = rst_fname[:-3] + 'ipynb' nb_contents = fcontents(nb_fname, 't') assert_conv_equal(rst_contents, nb_contents) def test_notebook_basic(): # Test conversion of basic ReST to ipynb JSON ipynb = to_notebook.from_rst(r""" Title ===== Some text with :math:`a = 1` math. .. math:: \textrm{math block} .. nbplot:: >>> c = 1 >>> c 1 More text. .. nbplot:: >>> d = 2 >>> d 2""") expected = r"""{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "## Title\n", "\n", "Some text with $a = 1$ math.\n", "\n", "$$\n", "\\textrm{math block}\n", "$$" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "c = 1\n", "c" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "More text." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "d = 2\n", "d" ] } ], "metadata": {}, "nbformat": 4, "nbformat_minor": 1 }""" assert_nb_equiv(ipynb, expected) def test_default_mathdollar(): # Test mathdollar extension present by default. ipynb = to_notebook.from_rst(r'Some text with $a = 1$ math.') expected = r"""{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "Some text with $a = 1$ math." ] } ], "metadata": {}, "nbformat": 4, "nbformat_minor": 1 }""" assert_nb_equiv(ipynb, expected) ������������������������������������������������������������������������������������������������������������������������������������������������������������nb2plots-0.7.2/nb2plots/tests/test_doctree2py.py����������������������������������������������������0000664�0000000�0000000�00000002520�14507503000�0021652�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������""" Test conversion of Sphinx format ReST to Python .py files Test running writer over example files and chosen snippets. """ from os.path import join as pjoin from glob import glob from nb2plots.doctree2py import parse_doctest from nb2plots.converters import to_py from nb2plots.testing import DATA_PATH from nb2plots.testing.convutils import (convert_assert, fcontents, unsmart_converter) def test_doctest_parser(): assert parse_doctest('>>> # comment') == '# comment' assert parse_doctest('>>> a = 10') == 'a = 10' assert parse_doctest(' >>> a = 10') == 'a = 10' assert (parse_doctest(' >>> a = 10\n >>> b = 20') == 'a = 10\nb = 20') assert (parse_doctest( ' >>> for i in (1, 2):\n ... print(i)') == 'for i in (1, 2):\n print(i)') to_py_safe = unsmart_converter(to_py.from_rst) def assert_conv_equal(rst_str, md_expected, unsmart=True): convert_assert(rst_str, to_py_safe, md_expected, None) def test_example_files(): # test conversion code over all .rst files checking against .py files for rst_fname in glob(pjoin(DATA_PATH, '*.rst')): rst_contents = fcontents(rst_fname, 't') py_fname = rst_fname[:-3] + 'py' contents = fcontents(py_fname, 't') assert_conv_equal(rst_contents, contents) ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������nb2plots-0.7.2/nb2plots/tests/test_from_notebook.py�������������������������������������������������0000664�0000000�0000000�00000012277�14507503000�0022447�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������""" Testing from_notebook module """ from os.path import dirname, join as pjoin import nbformat from ..from_notebook import (convert_nb, convert_nb_fname, to_doctests, has_mpl_inline, CODE_WITH_OUTPUT) from ..testing import stripeq DATA_PATH = pjoin(dirname(__file__), 'data') PLT_HDR = "\n.. nbplot::\n\n" def test_simple_cells(): v4 = nbformat.v4 nb = v4.new_notebook() # Markdown -> default conversion md_cell = v4.new_markdown_cell('# Some text') nb['cells'] = [md_cell] exp_text = "\nSome text\n=========\n" assert stripeq(convert_nb(nb), exp_text) # Code -> replaced with plot directive / doctest markers code_cell = v4.new_code_cell('a = 10') nb['cells'] = [code_cell] exp_code = PLT_HDR + " >>> a = 10\n" assert stripeq(convert_nb(nb), exp_code) # Empty code -> no output empty_code_cell = v4.new_code_cell('') nb['cells'] = [empty_code_cell] exp_empty_code = "\n" # nbconvert 5.3.0 started returning '' from an empty code cell assert convert_nb(nb) in (exp_empty_code, '') # magic lines get stripped magic_code_cell = v4.new_code_cell('%timeit a = 1') nb['cells'] = [magic_code_cell] assert stripeq(convert_nb(nb), exp_empty_code) # Magic lines stripped from within other code lines mixed_magic_code_cell = v4.new_code_cell('%timeit a = 1\nb = 2') exp_mixed_magic = PLT_HDR + " >>> b = 2\n" nb['cells'] = [mixed_magic_code_cell] assert stripeq(convert_nb(nb), exp_mixed_magic) def test_mpl_inline_works(): # Test we get a mpl-interactive directive for %matplotlib inline v4 = nbformat.v4 nb = v4.new_notebook() code_cell = v4.new_code_cell('%matplotlib inline\na = 10') nb['cells'] = [code_cell] exp_code = "\n.. mpl-interactive::\n{} >>> a = 10\n".format(PLT_HDR) assert stripeq(convert_nb(nb), exp_code) def test_mpl_inline(): assert not has_mpl_inline('') assert not has_mpl_inline('%matplotlib inline # foo') assert has_mpl_inline('%matplotlib inline') assert has_mpl_inline('% matplotlib inline') assert has_mpl_inline(' % matplotlib inline') assert not has_mpl_inline('%matplotlib nbagg # foo') assert has_mpl_inline('%matplotlib nbagg') assert has_mpl_inline('% matplotlib nbagg\nb = 2') assert has_mpl_inline('a = 1\n% matplotlib nbagg\nb = 2') def test_to_doctests(): # Test to_doctests filter assert to_doctests('') == '' assert to_doctests('a = 1') == '>>> a = 1' assert to_doctests('a = 1\nb = 2') == '>>> a = 1\n>>> b = 2' assert (to_doctests( """ a = 1 for i in (1, 2): a += i for j in (2, 3): a += j print(a) for i in (1, 2): a += i print(a) """) == """>>> >>> a = 1 >>> for i in (1, 2): ... a += i ... ... for j in (2, 3): ... a += j ... >>> print(a) >>> for i in (1, 2): ... ... a += i >>> print(a) """) assert (to_doctests( """def xyz_trans_vol(vol, x_y_z_trans): \"\"\" Make a new copy of `vol` translated by `x_y_z_trans` voxels x_y_z_trans is a sequence or array length 3, containing the (x, y, z) translations in voxels. Values in `x_y_z_trans` can be positive or negative, and can be floats. \"\"\" x_y_z_trans = np.array(x_y_z_trans) """) == """>>> def xyz_trans_vol(vol, x_y_z_trans): ... \"\"\" Make a new copy of `vol` translated by `x_y_z_trans` voxels ... ... x_y_z_trans is a sequence or array length 3, containing the (x, y, z) translations in voxels. ... ... Values in `x_y_z_trans` can be positive or negative, and can be floats. ... \"\"\" ... x_y_z_trans = np.array(x_y_z_trans) """) def test_small(): # Regression tests on small notebook nb_fname = pjoin(DATA_PATH, 'small.ipynb') rst_fname = pjoin(DATA_PATH, 'small.rst') out = convert_nb_fname(nb_fname) with open(rst_fname, 'rt') as fobj: assert stripeq(out, fobj.read()) code = \ """##CODE_START## a = 1 b = 2 ##CODE_END##""" code_value = 'a = 1\nb = 2\n' stdout = \ """##STDOUT_START## one two ##STDOUT_END##""" stdout_value = 'one\ntwo\n' end_out = \ """##END_OUT_START## three 4 ##END_OUT_END##""" end_out_value = 'three\n4\n' def test_code_regex(): # Test regular expression matching for code, output parts def get_dict(s): match = CODE_WITH_OUTPUT.search(s) if match is None: return None return match.groupdict() # Check that the code part must match assert get_dict(stdout) is None assert get_dict(end_out) is None # Check different joins still allows detection of parts for combination, output in zip( ((code,), (code, stdout), (code, end_out), (code, stdout, end_out)), (dict(code=code_value, stdout=None, end_out=None), dict(code=code_value, stdout=stdout_value, end_out=None), dict(code=code_value, stdout=None, end_out=end_out_value), dict(code=code_value, stdout=stdout_value, end_out=end_out_value) )): for joiner in ('\n', '\n \n\n'): in_str = joiner.join(combination) assert get_dict(in_str) == output # Check adding extra carriage returns etc is OK in_str += '\n\n' assert get_dict(in_str) == output ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������nb2plots-0.7.2/nb2plots/tests/test_mpl_interactive.py�����������������������������������������������0000664�0000000�0000000�00000002055�14507503000�0022762�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������""" Test mpl-interactive directive """ import re from nb2plots.converters import to_pxml def test_mpl_interactive(): page = """\ Text here .. mpl-interactive:: More text here.""" pxml = to_pxml.from_rst(page) assert re.match("""\ <document source=".*?"> <paragraph> Text here <mpl_hint> <paragraph> If running in the IPython console, consider running <literal> %matplotlib to enable interactive plots. If running in the Jupyter Notebook, use <literal> %matplotlib inline . <paragraph> More text here.""", pxml) page = """\ Text here .. mpl-interactive:: Any ReST you *like*. More text here.""" pxml = to_pxml.from_rst(page) assert re.match("""\ <document source=".*?"> <paragraph> Text here <mpl_hint> <paragraph> Any ReST you <emphasis> like . <paragraph> More text here.""", pxml) �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������nb2plots-0.7.2/nb2plots/tests/test_nbplots.py�������������������������������������������������������0000664�0000000�0000000�00000063751�14507503000�0021270�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������""" Tests for build using nbplot extension """ from os.path import (join as pjoin, dirname, isdir) import re import os from docutils.nodes import paragraph, title import sphinx SPHINX_ge_1p8 = sphinx.version_info[:2] >= (1, 8) from nb2plots.nbplots import (run_code, parse_parts, nbplot_container, nbplot_epilogue) from sphinxtesters import SourcesBuilder from nb2plots.testing import PlotsBuilder, OPT_TRANS from nb2plots.testing.nbtesters import assert_nb_equiv import pytest HERE = dirname(__file__) # Variation in doctest block. DOCTEST_BLOCK_RE = r'<doctest_block (classes="doctest" )?xml:space="preserve">' def get_otherpage(fname): with open(pjoin(HERE, 'otherpages', fname), 'rt') as fobj: return fobj.read() def file_same(file1, file2): with open(file1, 'rb') as fobj: contents1 = fobj.read() with open(file2, 'rb') as fobj: contents2 = fobj.read() return contents1 == contents2 def test_run_code(): # Test run_code function ns1 = run_code('a = 10') assert ns1['a'] == 10 assert not 'b' in ns1 # New namespace by default ns2 = run_code('b = 20') assert ns2['b'] == 20 assert not 'a' in ns2 # Adding to a namespace ns3 = run_code('c = 30', ns=ns1) assert ns3 is ns1 assert ns1['c'] == 30 # Checking raises run_code('d', raises=NameError) class TestNbplots(SourcesBuilder): conf_source = ('extensions = ["nb2plots"]\n' 'nbplot_include_source = False\n') rst_sources = dict(a_page=get_otherpage('some_plots.rst')) def test_some_plots(self): assert isdir(self.out_dir) def plot_file(num): return pjoin(self.out_dir, 'a_page-{0}.png'.format(num)) range_10, range_6, range_4 = [plot_file(i) for i in range(1, 4)] # Plot 5 is range(6) plot assert file_same(range_6, plot_file(5)) # Plot 7 is range(4) plot assert file_same(range_4, plot_file(7)) # Plot 8 uses the old range(4) figure and the new range(6) figure assert file_same(range_4, plot_file('8_00')) assert file_same(range_6, plot_file('8_01')) # Plot 9 shows the default close-figures behavior in action assert file_same(range_4, plot_file(9)) # Plot 9 does not include source html_contents = self.get_built_file('a_page.html') # Plot 10 has included source assert '# Only a comment' in html_contents class TestDefaultSource(PlotsBuilder): """ Check that default is to include source, not source links """ rst_sources = dict(a_page="""\ A title ------- .. nbplot:: # Only a comment """) def test_include_source_default(self): # Plot 1 has included source html_contents = self.get_built_file('a_page.html') assert '# Only a comment' in html_contents # Plot 1 has no source link html_contents = self.get_built_file('a_page.html') assert 'href=".//a_page-1.py">Source code</a>' not in html_contents class TestAnnoyingParens(PlotsBuilder): """ Test we've fixed the empty parens bug The matplotlib plotter puts an annoying empty open/close parens in the output when html source link is off, and there are no figures. """ conf_source = ('extensions = ["nb2plots"]\n' 'nbplot_html_show_source_link = False') rst_sources = dict(a_page="""\ A title ------- .. nbplot:: # Only a comment """) def test_annoying_parens(self): # Plot 1 has included source assert not '<p>()</p>' in self.get_built_file('a_page.html') class TestDefaultContext(PlotsBuilder): """ Test that default context is to keep across plots, reset each doc """ rst_sources = dict(a_page="""\ A title ------- .. nbplot:: # The namespace reset at the beginning of each document assert 'a' not in globals() a = 1 Some text. .. nbplot:: b = a # A plot preserved across nbplot directives plt.plot(range(10)) More text. .. nbplot:: :keepfigs: # This one should result in the same plot as the previous nbplot b = b + 3 Yet more text. .. nbplot:: # Here, no plot, without the keepfigs directive assert b == 4 """, another_page="""\ Another title ------------- .. nbplot:: # The namespace reset at the beginning of each document assert 'a' not in globals() a = 2 Some text. .. nbplot:: c = a """) def test_rebuild_context(self): # Does rebuilding still delete context? (Tested in nbplots asserts) with open(pjoin(self.page_source, 'another_page.rst'), 'a') as fobj: fobj.write('\nSomething added\n') with open(pjoin(self.page_source, 'a_page.rst'), 'a') as fobj: fobj.write('\nSomething added\n') self.__class__.build_source() class TestRcparams(PlotsBuilder): """ Test that rcparams get applied and kept across plots in documents """ conf_source = ('extensions = ["nb2plots"]\n' 'nbplot_rcparams = {"text.color": "red"}\n') rst_sources = dict(a_page="""\ The start --------- Plot 1 .. nbplot:: plt.text(0, 0, "I'm Mr Brightside", color='red') Plot 2 - shows the default is the same: .. nbplot:: plt.text(0, 0, "I'm Mr Brightside") Plot 3 - changes the default: .. nbplot:: plt.rcParams['text.color'] = 'blue' plt.text(0, 0, 'Open up my eager eyes') Plot 4 - new default is blue: .. nbplot:: plt.text(0, 0, 'Open up my eager eyes', color='blue') """, b_page=""" Another title ------------- Plot color resumes at red: .. nbplot:: plt.text(0, 0, "I'm Mr Brightside") .. nbplot:: plt.rcParams['text.color'] = 'blue' plt.text(0, 0, "Open up my eager eyes") """) def test_rcparams(self): # Test plot rcparams applied at beginning of page def gpf(name, num): # Get plot file return pjoin(self.out_dir, '{0}-{1}.png'.format(name, num)) red_bright = gpf('a_page', 2) blue_eager = gpf('a_page', 4) assert file_same(gpf('a_page', 1), red_bright) assert file_same(gpf('a_page', 3), blue_eager) assert file_same(gpf('b_page', 1), red_bright) class TestDefaultPre(PlotsBuilder): """ Check that default pre code is importing numpy as pyplot Tested in plot directive body """ rst_sources=dict(a_page="""\ A title ------- .. nbplot:: np.inf plt.plot(range(10)) """) class TestNonDefaultPre(PlotsBuilder): """ Check that pre code is run in fresh plot context Tested in plot directive body """ conf_source=('extensions = ["nb2plots"]\n' 'nbplot_pre_code = "import numpy as foo; bar = 1"\n') rst_sources=dict(a_page="""\ A title ------- .. nbplot:: foo.inf assert bar == 1 """) class TestHiddenDoctests(PlotsBuilder): """ Check that doctest code gets hidden but still run Build using text builder to get more simply testable output. """ builder = 'text' rst_sources=dict(a_page="""\ A title ------- .. nbplot:: :include-source: false >>> a = 1 >>> b = 2 Text1 .. nbplot:: >>> assert a == 1 >>> assert b == 2 Text2 .. nbplot:: :include-source: false c = 3 Text3 .. nbplot:: >>> assert 'c' in globals() """) def test_whats_in_the_page(self): txt_contents = self.get_built_file('a_page.txt') assert 'a = 1' not in txt_contents assert 'b = 2' not in txt_contents assert 'a == 1' in txt_contents assert 'b == 2' in txt_contents assert 'c = 3' not in txt_contents class TestMoreDoctests(PlotsBuilder): """ Check that doctest code gets hidden but still tested Build using doctest builder """ builder = 'doctest' rst_sources=dict(a_page="""\ A title ------- .. nbplot:: :include-source: false >>> a = 1 >>> b = 2 Text1 .. nbplot:: >>> a 1 >>> b 2 Text2 .. nbplot:: :include-source: false c = 3 Text3 .. nbplot:: >>> 'c' not in globals() True """) class TestNoRaises(PlotsBuilder): """ Confirm that exception, without raises option, generates error """ should_error = True rst_sources=dict(a_page="""\ A title ------- .. nbplot:: # Another comment raise ValueError """) class TestRaisesOption(PlotsBuilder): """ Check raises option to nbplot directive proceeds without error """ rst_sources=dict(a_page="""\ A title ------- .. nbplot:: :raises: ValueError # Another comment raise ValueError """) def test_include_source_default(self): # Check that source still included assert '# Another comment' in self.get_built_file('a_page.html') class TestReference(PlotsBuilder): """ Check that reference is correctly generated. First check that the code gets built for html as predicted """ builder = 'pseudoxml' rst_sources=dict(a_page="""\ A title ------- .. _a-ref: .. nbplot:: >>> a = 1 See :ref:`the ref <a-ref>`. """) def test_reference(self): # Check that reference correctly included built = self.get_built_file('a_page.pseudoxml') expected_regexp = re.compile( r'<document _plot_counter="1" source=".*?a_page.rst"' rf'{OPT_TRANS}' r'( xmlns:\w+=".*")*>' r""" \s+<section ids="a-title" names="a\\ title"> \s+ <title> \s+ A title \s+ <target ids="a-ref" names="a-ref"> \s+ <nbplot_container> \s+ <doctest_block.*> \s+ >>> a = 1 \s+ <nbplot_epilogue> \s+ <.*> \s+ <paragraph> \s+ See\s \s+ <reference internal="True" refid="a-ref"> \s+ <inline.*?> \s+ the ref \.""", re.DOTALL) assert expected_regexp.match(built) class TestFlags(PlotsBuilder): """ Check flags get set correctly """ builder = 'pseudoxml' literal_header = ( r'<literal_block ' + (r'force(_highlighting)?="False" language="default" linenos="False" ' if SPHINX_ge_1p8 else '') + 'xml:space="preserve">') rst_sources=dict(a_page="""\ A title ------- .. nbplot-flags:: a = 1 b = 2 .. nbplot-show-flags:: Some text .. nbplot-flags:: c = 3 .. nbplot-show-flags:: """) def test_flags(self): # Check that flags correctly set from flag directives built = self.get_built_file('a_page.pseudoxml') expected = r""" <title> A title {literal_header} {{'a': 1, 'b': 2}} <paragraph> Some text {literal_header} {{'a': 1, 'b': 2, 'c': 3}}""".format( literal_header=self.literal_header) assert re.search(expected, built) class TestFlagsConfig(TestFlags): """ Check flags set from global config """ conf_source=("""\ extensions = ["nb2plots"] nbplot_flags = {'flag1': 5, 'flag2': 6} """) def test_flags(self): # Check that global flags merged with local built = self.get_built_file('a_page.pseudoxml') expected = r""" <title> A title {literal_header} {{'a': 1, 'b': 2, 'flag1': 5, 'flag2': 6}} <paragraph> Some text {literal_header} {{'a': 1, 'b': 2, 'c': 3, 'flag1': 5, 'flag2': 6}}""".format( literal_header=self.literal_header) assert re.search(expected, built) class TestWithoutSkip(PlotsBuilder): """ Check that doctest code can be bracketed into skipped, not skipped First check that the code gets built for txt as predicted """ builder = 'text' conf_source = ('extensions = ["nb2plots", "sphinx.ext.doctest"]\n' 'nbplot_flags = {"skip": False}') rst_sources=dict(a_page="""\ A title ------- .. nbplot:: >>> # always >>> a = 'default' Some text .. nbplot:: :render-parts: 1 if skip else 0 :run-parts: 1 if skip else 0 >>> a = 'skip is False' .. part >>> a = 'skip is True' Keep text coming .. nbplot:: :render-parts: 1 if skip else 2 :run-parts: 1 if skip else 2 >>> # An empty part, never used .. part >>> b = 'skip appears to be True' >>> a == 'skip is True' True .. part >>> b = 'skip appears to be False' >>> a == 'skip is False' True Text continues .. nbplot:: :run-parts: 1 if skip else 0 >>> # doctest only run when skip flag False, always rendered >>> b == 'skip appears to be False' True .. part >>> # only when skip flag True >>> b == 'skip appears to be True' True """) def test_pages(self): # Test that the skip=False sections selected txt = self.get_built_file('a_page.txt') assert ">>> # always\n>>> a = 'default'" in txt assert ">>> a = 'skip is False'" in txt assert ">>> a = 'skip is True'" not in txt # Note ==, distinguishing from test above assert ">>> a == 'skip is True'" not in txt assert ">>> a == 'skip is False'" in txt assert ">>> b == 'skip appears to be False'" in txt assert ">>> b == 'skip appears to be True'" not in txt class TestWithoutSkipDoctest(TestWithoutSkip): builder = 'doctest' def test_pages(self): # No pages built by doctest return class TestWithoutSkipStructure(TestWithoutSkip): builder = 'pseudoxml' def test_pages(self): # Test that the skip=False sections selected p_xml = self.get_built_file('a_page.pseudoxml') regex = re.compile( r"""<document _plot_counter="\d" source=".+?"> <section ids="a-title" names="a\\ title"> <title> A title <nbplot_container> {DOCTEST_BLOCK_RE} >>> # always >>> a = 'default' <nbplot_epilogue> <comment xml:space="preserve"> <comment xml:space="preserve"> <comment xml:space="preserve"> <paragraph> Some text <nbplot_container> {DOCTEST_BLOCK_RE} >>> a = 'skip is False' <nbplot_epilogue> <comment xml:space="preserve"> <comment xml:space="preserve"> <comment xml:space="preserve"> <paragraph> Keep text coming <nbplot_container> {DOCTEST_BLOCK_RE} >>> b = 'skip appears to be False' >>> a == 'skip is False' True <nbplot_epilogue> <comment xml:space="preserve"> <comment xml:space="preserve"> <comment xml:space="preserve"> <paragraph> Text continues <nbplot_container> {DOCTEST_BLOCK_RE} >>> # doctest only run when skip flag False, always rendered >>> b == 'skip appears to be False' True""".format(**globals())) assert(regex.match(p_xml) is not None) class TestWithSkip(TestWithoutSkip): """ Check that doctest code can be skipped according to flag """ conf_source = ('extensions = ["nb2plots", "sphinx.ext.doctest"]\n' 'nbplot_flags = {"skip": True}') def test_pages(self): # Test that the skip=True sections selected txt = self.get_built_file('a_page.txt') assert ">>> # always\n>>> a = 'default'" in txt assert ">>> a = 'skip is False'" not in txt assert ">>> a = 'skip is True'" in txt # Note ==, distinguishing from test above assert ">>> a == 'skip is True'" in txt assert ">>> a == 'skip is False'" not in txt # The rendered version always has the first section, regardless of skip assert ">>> b == 'skip appears to be False'" in txt assert ">>> b == 'skip appears to be True'" not in txt class TestWithSkipStructure(TestWithSkip): builder = 'pseudoxml' def test_pages(self): # Test that the skip=True sections selected p_xml = self.get_built_file('a_page.pseudoxml') regex = re.compile( r"""<document _plot_counter="\d" source=".+?"> <section ids="a-title" names="a\\ title"> <title> A title <nbplot_container> {DOCTEST_BLOCK_RE} >>> # always >>> a = 'default' <nbplot_epilogue> <comment xml:space="preserve"> <comment xml:space="preserve"> <comment xml:space="preserve"> <paragraph> Some text <nbplot_container> {DOCTEST_BLOCK_RE} >>> a = 'skip is True' <nbplot_epilogue> <comment xml:space="preserve"> <comment xml:space="preserve"> <comment xml:space="preserve"> <paragraph> Keep text coming <nbplot_container> {DOCTEST_BLOCK_RE} >>> b = 'skip appears to be True' >>> a == 'skip is True' True <nbplot_epilogue> <comment xml:space="preserve"> <comment xml:space="preserve"> <comment xml:space="preserve"> <paragraph> Text continues <nbplot_container hide-from="doctest"> <dont_doctest_block xml:space="preserve"> >>> # doctest only run when skip flag False, always rendered >>> b == 'skip appears to be False' True <nbplot_epilogue> <comment xml:space="preserve"> <comment xml:space="preserve"> <comment xml:space="preserve"> <nbplot_container hide-from="all" show-to="doctest"> {DOCTEST_BLOCK_RE} >>> # only when skip flag True >>> b == 'skip appears to be True' True""".format(**globals())) assert(regex.match(p_xml) is not None) class TestWithSkipDoctest(TestWithSkip): builder = 'doctest' def test_pages(self): # No pages built by doctest return class TestOtherWD(PlotsBuilder): """ Check that it is possible to run code with other working directory """ rst_sources=dict(a_page="""\ A title ------- .. nbplot:: >>> # Code run during page generation, e.g. html build >>> import os >>> assert os.getcwd().endswith('my_wd') >>> # Working directory is on Python PATH >>> import funky_module """) @classmethod def modify_source(cls): super(TestOtherWD, cls).modify_source() work_dir = pjoin(cls.build_path, 'my_wd') os.mkdir(work_dir) with open(pjoin(work_dir, 'funky_module.py'), 'wt') as fobj: fobj.write('# A funky module\n') with open(pjoin(cls.page_source, 'conf.py'), 'at') as fobj: fobj.write('\nnbplot_working_directory = "{}"\n'.format(work_dir)) class TestClearNotebook(PlotsBuilder): """ Test build of clear notebook with clearnotebook role """ builder = 'text' rst_sources=dict(a_page="""\ A title ------- :clearnotebook:`.` :clearnotebook:`clear notebook <clear.ipynb>` :fullnotebook:`full notebook <full.ipynb>` Some text. .. nbplot:: >>> a = 1 >>> a 1 """) def test_pages(self): txt = self.get_built_file('a_page.txt') assert re.match( r'\n?A title\n\*{7}\n\n\nSome text.\n\n>>> a = 1\n>>> a\n1\n', txt) ipynb = self.get_built_file('a_page.ipynb') assert_nb_equiv(ipynb, r""" { "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "## A title\n", "\n", "\n", "\n", "\n", "Some text." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "a = 1\n", "a" ] } ], "metadata": {}, "nbformat": 4, "nbformat_minor": 1 }""") assert self.get_built_file('clear.ipynb') == ipynb full = self.get_built_file('full.ipynb') assert_nb_equiv(full, r""" { "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "## A title\n", "\n", "\n", "\n", "\n", "Some text." ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "1" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a = 1\n", "a" ] } ], "metadata": {}, "nbformat": 4, "nbformat_minor": 1 }""") def test_part_finding(): assert parse_parts([]) == [{'contents': []}] assert (parse_parts(['a = 1', 'b = 2']) == [{'contents': ['a = 1', 'b = 2']}]) assert (parse_parts(['a = 1', 'b = 2', '', '.. part', '', 'c = 4']) == [{'contents': ['a = 1', 'b = 2']}, {'contents': ['c = 4']}]) # Need blank lines between assert (parse_parts(['a = 1', 'b = 2', '.. part', '', 'c = 4']) == [{'contents': ['a = 1', 'b = 2', '.. part', '', 'c = 4']}]) assert (parse_parts(['a = 1', 'b = 2', '', '.. part', 'c = 4']) == [{'contents': ['a = 1', 'b = 2', '', '.. part', 'c = 4']}]) # Add some attributes assert (parse_parts(['a = 1', 'b = 2', '', '.. part', ' foo=bar', ' baz=boo', '', 'c = 4']) == [{'contents': ['a = 1', 'b = 2']}, {'contents': ['c = 4'], 'foo': 'bar', 'baz': 'boo'}]) # Can have spaces around the equals assert (parse_parts(['a = 1', 'b = 2', '', '.. part', ' foo =bar', ' baz= boo', '', 'c = 4']) == [{'contents': ['a = 1', 'b = 2']}, {'contents': ['c = 4'], 'foo': 'bar', 'baz': 'boo'}]) assert (parse_parts(['a = 1', 'b = 2', '', '.. part', ' foo = bar', ' baz= boo', '', 'c = 4']) == [{'contents': ['a = 1', 'b = 2']}, {'contents': ['c = 4'], 'foo': 'bar', 'baz': 'boo'}]) # Cannot continue on same line as part separator assert (parse_parts(['a = 1', 'b = 2', '', '.. part foo=bar', '', 'c = 4']) == [{'contents': ['a = 1', 'b = 2', '', '.. part foo=bar', '', 'c = 4']}]) # Must be indentation with pytest.raises(ValueError): parse_parts(['a = 1', 'b = 2', '', '.. part', 'foo=bar', '', 'c = 4']) # Must be same indentation with pytest.raises(ValueError): parse_parts(['a = 1', 'b = 2', '', '.. part', ' foo=bar', 'baz=boo', '', 'c = 4']) with pytest.raises(ValueError): parse_parts(['a = 1', 'b = 2', '', '.. part', ' foo=bar', ' baz=boo', '', 'c = 4']) # Add some attributes in the first part assert (parse_parts(['.. part', ' mr=brightside', ' eager=eyes', '', 'a = 1', 'b = 2', '', '.. part', ' foo=bar', ' baz=boo', '', 'c = 4']) == [{'contents': ['a = 1', 'b = 2'], 'mr': 'brightside', 'eager': 'eyes'}, {'contents': ['c = 4'], 'foo': 'bar', 'baz': 'boo'}]) # Contents with spaces, leading and trailing spaces skipped assert (parse_parts(['a = 1', 'b = 2', '', '.. part', ' foo=[1, 2, s]', ' bar= more stuff ', '', 'c = 4']) == [{'contents': ['a = 1', 'b = 2']}, {'contents': ['c = 4'], 'foo': '[1, 2, s]', 'bar': 'more stuff'}]) class TestHideShow(PlotsBuilder): """ Check that hide-from and show-to options respected """ conf_source = ('extensions = ["nb2plots", "sphinx.ext.doctest"]\n') builder = 'text' rst_sources=dict(a_page="""\ ######### A section ######### A plot that does not show its source (but does get run by doctest). .. nbplot:: :include-source: false >>> a = 1 The next incantation is nearly the same, except we also show the output in the text builder (but no other). .. nbplot:: :hide-from: all :show-to: doctest text >>> b = 2 Here we hide the output from everything, including doctests, but show it to the text builder again. .. nbplot:: :hide-from: all :show-to: text # Enigmatic sentence. Show to everything (including doctest builder). .. nbplot:: >>> assert a == 1 >>> assert b == 2 Hide from doctest builder, but no other. .. nbplot:: :hide-from: doctest >>> a = 99 Show that the doctest builder did not see the previous plot directive. .. nbplot:: >>> a == 1 True """) def test_hide_show(self): built = self.get_built_file('a_page.txt') expected = """\ A section ********* A plot that does not show its source (but does get run by doctest). The next incantation is nearly the same, except we also show the output in the text builder (but no other). >>> b = 2 Here we hide the output from everything, including doctests, but show it to the text builder again. # Enigmatic sentence. Show to everything (including doctest builder). >>> assert a == 1 >>> assert b == 2 Hide from doctest builder, but no other. >>> a = 99 Show that the doctest builder did not see the previous plot directive. >>> a == 1 True """ # Blank lines at beginning differ in Sphinx versions assert built.strip() == expected.strip() class TestHideShowTests(TestHideShow): """ Test that the doctests pass, requining the hide/show to work """ builder = 'doctest' def test_hide_show(self): # The build tests the doctests - here we test the doctree built = self.get_doctree('a_page') expected_node_types = [title] + [ paragraph, nbplot_container, nbplot_epilogue] * 4 for node, exp_type in zip(built[0].children, expected_node_types): assert type(node) == exp_type class TestHideShowHtml(TestHideShow): """ Test that the HTML does not see the hidden section """ builder = 'html' def test_hide_show(self): built = self.get_built_file('a_page.html') assert not '# Enigmatic sentence' in built �����������������������nb2plots-0.7.2/nb2plots/tests/test_proj1.py���������������������������������������������������������0000664�0000000�0000000�00000005064�14507503000�0020633�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������""" Tests for proj1 build using sphinx extensions """ from os.path import (join as pjoin, dirname, isdir, exists) from sphinxtesters import PageBuilder HERE = dirname(__file__) PAGE_HEADER = """\ A title ======= """ class Proj1Builder(PageBuilder): """ Build using 'proj1' directory as template to modify """ page_source_template = pjoin(HERE, 'proj1') class TestProj1(Proj1Builder): def test_basic_build(self): assert isdir(self.out_dir) assert isdir(self.doctree_dir) doctree = self.get_doctree('a_page') assert len(doctree.document) == 1 doctree_str = self.doctree2str(doctree) expected = ( '<title>A section\n' 'Some text.\n' '' 'notebook here\n' 'More text.\n' '' 'full\n' 'Text is endless.\n' '' 'code here') assert doctree_str == expected # Check the expected files were written for fname in ('a_page.ipynb', 'another.ipynb', 'a_page.py'): built_fname = pjoin(self.build_path, 'html', fname) assert exists(built_fname) class TestNotSameName(Proj1Builder): @classmethod def modify_source(cls): with open(pjoin(cls.page_source, 'a_page.rst'), 'wt') as fobj: fobj.write(PAGE_HEADER + """ :clearnotebook:`.` (the default name and text). :fullnotebook:`Get it here ` (not-default name). """) class TestSameNameIpy(Proj1Builder): should_error = True @classmethod def modify_source(cls): with open(pjoin(cls.page_source, 'a_page.rst'), 'wt') as fobj: fobj.write(PAGE_HEADER + """ :clearnotebook:`.` (the default name). :fullnotebook:`.` (default name again). """) class TestSameNamePy(Proj1Builder): should_error = True @classmethod def modify_source(cls): with open(pjoin(cls.page_source, 'a_page.rst'), 'wt') as fobj: fobj.write(PAGE_HEADER + """ :clearnotebook:`.` (the default name). :pyfile:`code file ` (same name as notebook) """) nb2plots-0.7.2/nb2plots/tests/test_regression.py000066400000000000000000000021321450750300000217510ustar00rootroot00000000000000""" Test whether doc examples same as previously """ from os.path import join as pjoin, dirname from nb2plots.from_notebook import convert_nb_fname from nb2plots.converters import to_py, to_notebook from nb2plots.testing import stripeq from nb2plots.testing.convutils import fcontents from nb2plots.testing.nbtesters import assert_nb_equiv HERE = dirname(__file__) DATA = pjoin(HERE, 'data') def test_regression(): # Test documentation worked example input_nb_fname = pjoin(DATA, 'example_notebook.ipynb') output_rst_fname = pjoin(DATA, 'converted_example.rst') # Convert to ReST, add trailing CR from output script rst = convert_nb_fname(input_nb_fname) + '\n' assert stripeq(rst.encode('utf8'), fcontents(output_rst_fname)) # Convert ReST to output formats py_file = to_py.from_rst(rst) assert (py_file.encode('utf8') == fcontents(pjoin(DATA, 'converted_plus_notebooks.py'))) ipy_file = to_notebook.from_rst(rst) assert_nb_equiv(ipy_file, fcontents(pjoin(DATA, 'converted_plus_notebooks.ipynb')) .decode('utf8')) nb2plots-0.7.2/nb2plots/tests/test_runroles.py000066400000000000000000000135301450750300000214460ustar00rootroot00000000000000""" Tests for runroles module """ import re from os.path import isfile, join as pjoin from nb2plots import runroles as rr from nb2plots.runroles import convert_timeout from nb2plots import doctree2nb from nb2plots import doctree2py from nb2plots.converters import to_pxml from nb2plots.testing import mockapp from nb2plots.testing import PlotsBuilder import pytest def test_runroles_setup(*args): # Test extension setup works as expected app = mockapp.get_app() rr.setup(app) connects = [('doctree-resolved', rr.collect_runfiles), ('build-finished', rr.write_runfiles)] roles = list(rr.NAME2ROLE.items()) translators = [('ipynb', doctree2nb.Translator), ('pyfile', doctree2py.Translator)] for method_name, args, kwargs in app.method_calls: if (method_name == 'connect' and args[0:2] in connects): connects.remove(args[0:2]) if (method_name == 'add_role' and args[0:2] in roles): roles.remove(args[0:2]) if (method_name == 'set_translator' and args[0:2] in translators): translators.remove(args[0:2]) assert len(connects) == 0, 'Connections failed' assert len(roles) == 0, 'Roles failed' assert len(translators) == 0, 'Translators failed' def test_convert_timeout(): assert convert_timeout('4') == 4 assert convert_timeout('30') == 30 assert convert_timeout('-1') == -1 assert convert_timeout('None') == None assert convert_timeout('none') == None assert convert_timeout('noNe') == None with pytest.raises(ValueError): convert_timeout('-2') def test_runrole_doctrees(): # Test that run roles generate expected doctrees expected_re_fmt = """\ Text then {descr} then text.""" def assert_rst_pxml(pxml_params, rst_source): code_type = pxml_params['code_type'] pxml = to_pxml.from_rst(rst_source) if not 'ext' in pxml_params: pxml_params['ext'] = 'py' if code_type == 'pyfile' else 'ipynb' pxml_regex = expected_re_fmt.format( role_type=code_type, **pxml_params) assert re.match(pxml_regex, pxml) assert_rst_pxml( dict(code_type='clearnotebook', filebase='contents', base='/contents', descr=r'Download this page as a Jupyter notebook \(no outputs\)'), "Text then :clearnotebook:`.` then text.") assert_rst_pxml( dict(code_type='fullnotebook', filebase='contents', base='/contents', descr=('Download this page as a Jupyter notebook ' r'\(with outputs\)')), "Text then :fullnotebook:`.` then text.") assert_rst_pxml( dict(code_type='pyfile', filebase='contents', base='/contents', descr='Download this page as a Python code file'), "Text then :pyfile:`.` then text.") for code_type in ('clearnotebook', 'fullnotebook', 'pyfile'): assert_rst_pxml( dict(code_type=code_type, filebase='contents', base='/contents', descr='message to taste'), "Text then :{}:`message to taste` then text.".format(code_type)) assert_rst_pxml( dict(code_type=code_type, filebase='foo', base='foo', ext='ipynb', descr='message to taste'), "Text then :{}:`message to taste ` then text." .format(code_type)) # It is annoying, but there must be a first text description for the # angle brackets part to refer to the output file name. This is how # ReST role processing usually works. assert_rst_pxml( dict(code_type=code_type, filebase='contents', base='/contents', descr=''), "Text then :{}:`` then text.".format(code_type)) class TestSubdirBuild(PlotsBuilder): """ Test that output files from subdirectories have correct location """ rst_sources = {'foo/a_page': """\ A section ######### Some text. :clearnotebook:`notebook here` Text is endless. :pyfile:`code here` Bare path is relative to containing directory: :pyfile:`code here ` Can have relative parts too: :clearnotebook:`notebook here <../my_nb.ipynb>` Prepended / refers to root of project: :pyfile:`code here ` """} def test_output(self): for suffix in ('.py', '.ipynb'): assert isfile(pjoin(self.out_dir, 'foo', 'a_page' + suffix)) assert isfile(pjoin(self.out_dir, 'foo', 'my_code.py')) assert isfile(pjoin(self.out_dir, 'my_nb.ipynb')) assert isfile(pjoin(self.out_dir, 'more_code.py')) class TestPyfileAlias(PlotsBuilder): """ Test that 'codefile' alias works for pyfile """ rst_sources = {'a_page': """\ A section ######### :codefile:`code here` >>> True True """} def test_output(self): assert isfile(pjoin(self.out_dir, 'a_page.py')) class TestDuplicatesOK(PlotsBuilder): """ Test that same and different filename for same code type works. """ rst_sources = {'a_page': """\ Title ##### :fullnotebook:`name ` :fullnotebook:`name ` :fullnotebook:`name ` """} def test_output(self): assert isfile(pjoin(self.out_dir, 'foo.ipynb')) assert isfile(pjoin(self.out_dir, 'bar.ipynb')) class TestDuplicatesNotOK(PlotsBuilder): """ Test that same filename for different code type fails. """ rst_sources = {'a_page': """\ Title ##### :fullnotebook:`name ` :clearnotebook:`name ` """} should_error = True nb2plots-0.7.2/nb2plots/tests/test_scripts.py000066400000000000000000000067761450750300000213020ustar00rootroot00000000000000# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """ Test scripts Test running scripts """ from pathlib import Path import re from scripttester import ScriptTester from nb2plots.testing.convutils import unsmart, unsmart_nb from nb2plots.testing.nbtesters import assert_nb_equiv runner = ScriptTester('nb2plots', win_bin_ext='.bat') run_command = runner.run_command TESTS_PATH = Path(__file__).parent RST_MD_PATH = TESTS_PATH / 'rst_md_files' def script_test(func): # Decorator to label test as a script_test func.script_test = True return func @script_test def test_rst2md(): # test rst2md script over all .rst files checking against .md files for rst_path in RST_MD_PATH.glob('*.rst'): md_path = rst_path.with_suffix('.md') expected_md = md_path.read_bytes() # Skip files containing text "skip". These are files for which the # source ReST is not valid in plain docutils, such as those containing # Sphinx directives and roles. if expected_md.strip() == b'skip': continue cmd = ['rst2md', str(rst_path)] code, stdout, stderr = run_command(cmd) assert stdout == expected_md @script_test def test_sphinx2md(): # test sphinx2md script over all .rst files checking against .smd / .md # files for rst_path in RST_MD_PATH.glob('*.rst'): # Try .smd filename first, otherwise ordinary .md md_path = rst_path.with_suffix('.smd') if not md_path.is_file(): md_path = rst_path.with_suffix('.md') expected_md = md_path.read_bytes() cmd = ['sphinx2md', str(rst_path)] code, stdout, stderr = run_command(cmd) assert (unsmart(stdout.decode('utf-8')) == expected_md.decode('utf-8')) @script_test def test_sphinx2nb(): # test sphinx2nb script over all .rst files checking against .ipynb files for rst_path in RST_MD_PATH.glob('*.rst'): nb_path = rst_path.with_suffix('.ipynb') expected = nb_path.read_text() cmd = ['sphinx2nb', str(rst_path)] code, stdout, stderr = run_command(cmd) assert_nb_equiv(unsmart_nb(stdout.decode('utf-8')), expected) @script_test def test_sphinx2py(): # test sphinx2py script over all .rst files checking against .ipynb files for rst_path in RST_MD_PATH.glob('*.rst'): py_path = rst_path.with_suffix('.py') expected = py_path.read_bytes() cmd = ['sphinx2py', str(rst_path)] code, stdout, stderr = run_command(cmd) assert (unsmart(stdout.decode('utf-8')) == expected.decode('utf-8')) @script_test def test_sphinx2pxml(): rst_path = RST_MD_PATH / 'sect_text.rst' cmd = ['sphinx2pxml', str(rst_path)] code, stdout, stderr = run_command(cmd) pattern = r"""
A section <paragraph> Some <emphasis> text .""" output = stdout.decode('utf-8') assert re.match(pattern, output) @script_test def test_nb2plots(): fname = 'example_notebook' data_path = TESTS_PATH / 'data' nb_path = data_path / (fname + '.ipynb') rst_path = data_path / 'converted_example.rst' expected = rst_path.read_text() cmd = ['nb2plots', str(nb_path)] code, stdout, stderr = run_command(cmd) output = stdout.decode('utf-8') assert output.strip() == expected.strip() ��nb2plots-0.7.2/nb2plots/tests/test_sphinx2md.py�����������������������������������������������������0000664�0000000�0000000�00000002373�14507503000�0021514�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������""" Test conversion of Sphinx format ReST to Markdown Test running writer over example files and chosen snippets. """ from os.path import join as pjoin, exists from glob import glob from nb2plots.converters import to_markdown from nb2plots.testing import DATA_PATH from nb2plots.testing.convutils import (convert_assert, fcontents, unsmart_converter) to_md_safe = unsmart_converter(to_markdown.from_rst) def assert_conv_equal(rst_str, md_expected): convert_assert(rst_str, to_md_safe, md_expected, None) def test_example_files(): # test sphinx2md script over all .rst files checking against .smd / .md # files for rst_fname in glob(pjoin(DATA_PATH, '*.rst')): rst_contents = fcontents(rst_fname, 't') # Try .smd filename first, otherwise ordinary .md md_fname = rst_fname[:-3] + 'smd' if not exists(md_fname): md_fname = rst_fname[:-3] + 'md' md_contents = fcontents(md_fname, 't') assert_conv_equal(rst_contents, md_contents) def test_default_mathdollar(): # Test mathdollar extension present by default. md = to_markdown.from_rst(r'Some text with $a = 1$ math.') expected = "Some text with $a = 1$ math.\n" assert md == expected ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������nb2plots-0.7.2/nb2plots/tests/test_strdiff.py�������������������������������������������������������0000664�0000000�0000000�00000001224�14507503000�0021233�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������""" Test strdiff module """ from nb2plots.strdiff import get_diff def test_get_diff(): assert get_diff('foo', 'foo') == "L0, OK: foo" assert get_diff('foo', 'baz') == "L0, S1: foo\nL0, S2: baz" assert (get_diff('foo\nfoo', 'bar\nfoo\nbaz') == """\ L0, S1: foo L0, S2: bar L1, OK: foo Remaining line in second string is: baz""") assert (get_diff('bar\nfoo\nbaz', 'foo\nfoo') == """\ L0, S1: bar L0, S2: foo L1, OK: foo Remaining line in first string is: baz""") assert (get_diff('bar\nfoo\nbaz\nbof', 'foo\nfoo') == """\ L0, S1: bar L0, S2: foo L1, OK: foo Remaining lines in first string are: baz bof""") ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������nb2plots-0.7.2/nb2plots/tests/test_timeout.py�������������������������������������������������������0000664�0000000�0000000�00000004522�14507503000�0021264�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������""" Test that timeout parameters work as expected """ from os.path import join as pjoin, isfile from nb2plots.testing import PlotsBuilder class _CheckTimeout(PlotsBuilder): """ Machinery for checking timeout """ rst_sources = {'a_page': r"""\ Title ##### .. code-links:: .. nbplot:: >>> from time import sleep >>> sleep(5) """} class TestNoTimeout(_CheckTimeout): """ The default timeout is fairly long, so a short wait is OK ``ExecutePreprocessor`` in ``nbconvert/preprocessors/execute.py`` suggests default is 30 seconds. """ def test_output(self): assert isfile(pjoin(self.out_dir, 'a_page_full.ipynb')) class TestCLOptsTimeout(_CheckTimeout): """ Set timeout to 1 second with code-link option, build should error """ rst_sources = {'a_page': r"""\ Title ##### .. code-links:: :timeout: 1 .. nbplot:: >>> from time import sleep >>> sleep(5) """} should_error = True class TestFTimeout(_CheckTimeout): """ Set timeout to 1 second with role option, build should error """ rst_sources = {'a_page': r"""\ Title ##### .. role:: longerfullnotebook(fullnotebook) :timeout: 1 Add :longerfullnotebook:`.` .. nbplot:: >>> from time import sleep >>> sleep(5) """} should_error = True class TestConfTimeout(_CheckTimeout): """ Set timeout to 1 second with conf.py option, build should error """ conf_source = (TestNoTimeout.conf_source + '\nfill_notebook_timeout = 1') should_error = True class TestConfigCLTimeout(TestNoTimeout): """ Code-links options overrides configuration option """ conf_source = (TestNoTimeout.conf_source + '\nfill_notebook_timeout = 1') rst_sources = {'a_page': r"""\ Title ##### .. code-links:: :timeout: 10 .. nbplot:: >>> from time import sleep >>> sleep(5) """} class TestBestTimeout(TestNoTimeout): """ Check that multiple links to same notebook use longest timeout """ rst_sources = {'a_page': r"""\ Title ##### .. code-links:: :timeout: 1 .. role:: shorterfullnotebook(fullnotebook) :timeout: 2 Add :shorterfullnotebook:`short <short.ipynb>` .. role:: longerfullnotebook(fullnotebook) :timeout: 10 Add :longerfullnotebook:`long <long.ipynb>` .. nbplot:: >>> from time import sleep >>> sleep(5) """} ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������nb2plots-0.7.2/requirements.txt���������������������������������������������������������������������0000664�0000000�0000000�00000000276�14507503000�0016546�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# See min-requirements for minimum requirements. # Update there and here. ipython[notebook]>=7.16.3 sphinx>=4 numpy>=1.20 matplotlib>=3.2 sphinxtesters>=0.2.3 texext>=0.6.6 nbconvert>=6.0.7 ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������nb2plots-0.7.2/scripts/�����������������������������������������������������������������������������0000775�0000000�0000000�00000000000�14507503000�0014744�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������nb2plots-0.7.2/scripts/nb2plots���������������������������������������������������������������������0000775�0000000�0000000�00000001204�14507503000�0016432�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#!python """ Convert notebook to Sphinx ReST format with nbplot directives Example: nb2plots example.ipynb Prints to stdout with UTF-8 encoding. """ # vim: ft=python import sys from argparse import ArgumentParser from nb2plots.from_notebook import convert_nb_fname def main(): parser = ArgumentParser( description="Convert notebook to ReST format with plot directives") parser.add_argument('notebook', help = 'notebook file to convert') args = parser.parse_args() rst_text = convert_nb_fname(args.notebook) + '\n' sys.stdout.buffer.write(rst_text.encode('utf-8')) if __name__ == '__main__': main() ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������nb2plots-0.7.2/scripts/rst2md�����������������������������������������������������������������������0000775�0000000�0000000�00000001060�14507503000�0016102�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#!python """ rst2md ====== A command line interface that uses the Markdown writer to output from ReStructuredText source. """ import locale try: locale.setlocale(locale.LC_ALL, '') except: pass from docutils.core import publish_cmdline, default_description from nb2plots.doctree2md import Writer description = ('Generates Markdown formatted text from standalone ' 'reStructuredText sources. ' + default_description) def main(): publish_cmdline(writer=Writer(), description=description) if __name__ == '__main__': main() ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������nb2plots-0.7.2/scripts/sphinx2md��������������������������������������������������������������������0000775�0000000�0000000�00000000437�14507503000�0016612�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#!python """ Convert single Sphinx ReST document to Markdown Example: sphinx2md example.rst Write Markdown to stdout as UTF-8. """ # vim: ft=python from nb2plots.commands import do_main if __name__ == '__main__': do_main("Convert Sphinx ReST file to Markdown", 'markdown') ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������nb2plots-0.7.2/scripts/sphinx2nb��������������������������������������������������������������������0000775�0000000�0000000�00000000446�14507503000�0016611�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#!python """ Convert single ReST document to Notebook JSON Example: sphinx2nb example.rst Write notebook JSON to stdout as UTF-8. """ # vim: ft=python from nb2plots.commands import do_main if __name__ == '__main__': do_main("Convert Sphinx ReST file to Notebook JSON", 'jupyter') ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������nb2plots-0.7.2/scripts/sphinx2pxml������������������������������������������������������������������0000775�0000000�0000000�00000000450�14507503000�0017165�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#!python """ Convert single Sphinx ReST document to Pseudo XML Example: sphinx2pxml example.rst Write Pseudo XML to stdout as UTF-8. """ # vim: ft=python from nb2plots.commands import do_main if __name__ == '__main__': do_main("Convert Sphinx ReST file to Pseudo XML", 'pseudoxml') ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������nb2plots-0.7.2/scripts/sphinx2py��������������������������������������������������������������������0000775�0000000�0000000�00000000452�14507503000�0016637�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#!python """ Convert single ReST document to Python .py file text Example: sphinx2py example.rst Write .py file text to stdout as UTF-8. """ # vim: ft=python from nb2plots.commands import do_main if __name__ == '__main__': do_main("Convert Sphinx ReST file to Python code", 'python') ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������nb2plots-0.7.2/setup.cfg����������������������������������������������������������������������������0000664�0000000�0000000�00000000520�14507503000�0015073�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������ # See the docstring in versioneer.py for instructions. Note that you must # re-run 'versioneer.py setup' after changing this section, and commit the # resulting files. [versioneer] VCS = git style = pep440 versionfile_source = nb2plots/_version.py versionfile_build = nb2plots/_version.py tag_prefix = "" parentdir_prefix = nb2plots- ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������nb2plots-0.7.2/setup.py�����������������������������������������������������������������������������0000775�0000000�0000000�00000010254�14507503000�0014774�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#!/usr/bin/env python # -*- coding: utf-8 -*- ''' Installation script for nb2plots package ''' import os from os.path import join as pjoin, split as psplit, splitext import re from setuptools import setup import versioneer # Get install requirements from requirements.txt file with open('requirements.txt', 'rt') as fobj: install_requires = [line.strip() for line in fobj if line.strip() and not line[0] in '#-'] # Get any extra test requirements with open('test-requirements.txt', 'rt') as fobj: test_requires = [line.strip() for line in fobj if line.strip() and not line[0] in '#-'] # Requires for distutils (only used in pypi interface?) break_ver = re.compile(r'(\S+?)(\[\S+\])?([=<>!]+\S+)') requires = [break_ver.sub(r'\1 (\3)', req) for req in install_requires] # See: https://github.com/matthew-brett/myscripter from distutils.command.install_scripts import install_scripts from distutils import log BAT_TEMPLATE = \ r"""@echo off REM wrapper to use shebang first line of {FNAME} set mypath=%~dp0 set pyscript="%mypath%{FNAME}" set /p line1=<%pyscript% if "%line1:~0,2%" == "#!" (goto :goodstart) echo First line of %pyscript% does not start with "#!" exit /b 1 :goodstart set py_exe=%line1:~2% call "%py_exe%" %pyscript% %* """ class my_install_scripts(install_scripts): """ Install .bat wrapper for scripts on Windows """ def run(self): install_scripts.run(self) if not os.name == "nt": return for filepath in self.get_outputs(): # If we can find an executable name in the #! top line of the # script file, make .bat wrapper for script. with open(filepath, 'rt') as fobj: first_line = fobj.readline() if not (first_line.startswith('#!') and 'python' in first_line.lower()): log.info("No #!python executable found, skipping .bat " "wrapper") continue pth, fname = psplit(filepath) froot, ext = splitext(fname) bat_file = pjoin(pth, froot + '.bat') bat_contents = BAT_TEMPLATE.replace('{FNAME}', fname) log.info("Making %s wrapper for %s" % (bat_file, filepath)) if self.dry_run: continue with open(bat_file, 'wt') as fobj: fobj.write(bat_contents) cmdclass = versioneer.get_cmdclass() cmdclass['install_scripts'] = my_install_scripts setup(name='nb2plots', version=versioneer.get_version(), cmdclass=cmdclass, description='Converting between ipython notebooks and sphinx docs', author='Matthew Brett', author_email='matthew.brett@gmail.com', maintainer='Matthew Brett', maintainer_email='matthew.brett@gmail.com', url='http://github.com/matthew-brett/nb2plots', packages=['nb2plots', 'nb2plots.tests', 'nb2plots.testing'], package_data = {'nb2plots': [ 'tests/data/*.rst', 'tests/rst_md_files/*', 'tests/data/*', 'tests/proj1/*.rst', 'tests/proj1/*.py', 'tests/proj1/_static/*', 'tests/otherpages/*', ]}, license='BSD license', classifiers = [ 'Development Status :: 2 - Pre-Alpha', 'Environment :: Console', 'Intended Audience :: Developers', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Topic :: Scientific/Engineering', 'Operating System :: Microsoft :: Windows', 'Operating System :: POSIX', 'Operating System :: Unix', 'Operating System :: MacOS', ], scripts = ['scripts/nb2plots', 'scripts/sphinx2nb', 'scripts/sphinx2py', 'scripts/sphinx2md', 'scripts/sphinx2pxml', 'scripts/rst2md'], long_description = open('README.rst', 'rt').read(), install_requires = install_requires, extras_require = {'test': test_requires}, python_requires='>=3.7', ) ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������nb2plots-0.7.2/test-requirements.txt����������������������������������������������������������������0000664�0000000�0000000�00000000116�14507503000�0017514�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# Requirements for running tests -r requirements.txt pytest mock scripttester ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������nb2plots-0.7.2/tools/�������������������������������������������������������������������������������0000775�0000000�0000000�00000000000�14507503000�0014415�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������nb2plots-0.7.2/tools/futz���������������������������������������������������������������������������0000664�0000000�0000000�00000000344�14507503000�0015331�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# Move to futzing directory, get started # Source this, otherwise it won't work FUTZ_DIR="$(dirname "${BASH_SOURCE[0]}")/../nb2plots/tests/futz" cd $FUTZ_DIR && make init echo "Now futz with files in proj1 directory and 'make'" ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������nb2plots-0.7.2/tox.ini������������������������������������������������������������������������������0000664�0000000�0000000�00000000307�14507503000�0014570�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������[tox] # Don't forget to adjust CI when changing this envlist = py{38,39,310,311} [testenv] commands = pytest {posargs} nb2plots/tests extras = test [testenv:py38-min] deps = -rmin-requirements.txt �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������nb2plots-0.7.2/versioneer.py������������������������������������������������������������������������0000664�0000000�0000000�00000236434�14507503000�0016024�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������ # Version: 0.22 """The Versioneer - like a rocketeer, but for versions. The Versioneer ============== * like a rocketeer, but for versions! * https://github.com/python-versioneer/python-versioneer * Brian Warner * License: Public Domain * Compatible with: Python 3.6, 3.7, 3.8, 3.9, 3.10 and pypy3 * [![Latest Version][pypi-image]][pypi-url] * [![Build Status][travis-image]][travis-url] This is a tool for managing a recorded version number in distutils/setuptools-based python projects. The goal is to remove the tedious and error-prone "update the embedded version string" step from your release process. Making a new release should be as easy as recording a new tag in your version-control system, and maybe making new tarballs. ## Quick Install * `pip install versioneer` to somewhere in your $PATH * add a `[versioneer]` section to your setup.cfg (see [Install](INSTALL.md)) * run `versioneer install` in your source tree, commit the results * Verify version information with `python setup.py version` ## Version Identifiers Source trees come from a variety of places: * a version-control system checkout (mostly used by developers) * a nightly tarball, produced by build automation * a snapshot tarball, produced by a web-based VCS browser, like github's "tarball from tag" feature * a release tarball, produced by "setup.py sdist", distributed through PyPI Within each source tree, the version identifier (either a string or a number, this tool is format-agnostic) can come from a variety of places: * ask the VCS tool itself, e.g. "git describe" (for checkouts), which knows about recent "tags" and an absolute revision-id * the name of the directory into which the tarball was unpacked * an expanded VCS keyword ($Id$, etc) * a `_version.py` created by some earlier build step For released software, the version identifier is closely related to a VCS tag. Some projects use tag names that include more than just the version string (e.g. "myproject-1.2" instead of just "1.2"), in which case the tool needs to strip the tag prefix to extract the version identifier. For unreleased software (between tags), the version identifier should provide enough information to help developers recreate the same tree, while also giving them an idea of roughly how old the tree is (after version 1.2, before version 1.3). Many VCS systems can report a description that captures this, for example `git describe --tags --dirty --always` reports things like "0.7-1-g574ab98-dirty" to indicate that the checkout is one revision past the 0.7 tag, has a unique revision id of "574ab98", and is "dirty" (it has uncommitted changes). The version identifier is used for multiple purposes: * to allow the module to self-identify its version: `myproject.__version__` * to choose a name and prefix for a 'setup.py sdist' tarball ## Theory of Operation Versioneer works by adding a special `_version.py` file into your source tree, where your `__init__.py` can import it. This `_version.py` knows how to dynamically ask the VCS tool for version information at import time. `_version.py` also contains `$Revision$` markers, and the installation process marks `_version.py` to have this marker rewritten with a tag name during the `git archive` command. As a result, generated tarballs will contain enough information to get the proper version. To allow `setup.py` to compute a version too, a `versioneer.py` is added to the top level of your source tree, next to `setup.py` and the `setup.cfg` that configures it. This overrides several distutils/setuptools commands to compute the version when invoked, and changes `setup.py build` and `setup.py sdist` to replace `_version.py` with a small static file that contains just the generated version data. ## Installation See [INSTALL.md](./INSTALL.md) for detailed installation instructions. ## Version-String Flavors Code which uses Versioneer can learn about its version string at runtime by importing `_version` from your main `__init__.py` file and running the `get_versions()` function. From the "outside" (e.g. in `setup.py`), you can import the top-level `versioneer.py` and run `get_versions()`. Both functions return a dictionary with different flavors of version information: * `['version']`: A condensed version string, rendered using the selected style. This is the most commonly used value for the project's version string. The default "pep440" style yields strings like `0.11`, `0.11+2.g1076c97`, or `0.11+2.g1076c97.dirty`. See the "Styles" section below for alternative styles. * `['full-revisionid']`: detailed revision identifier. For Git, this is the full SHA1 commit id, e.g. "1076c978a8d3cfc70f408fe5974aa6c092c949ac". * `['date']`: Date and time of the latest `HEAD` commit. For Git, it is the commit date in ISO 8601 format. This will be None if the date is not available. * `['dirty']`: a boolean, True if the tree has uncommitted changes. Note that this is only accurate if run in a VCS checkout, otherwise it is likely to be False or None * `['error']`: if the version string could not be computed, this will be set to a string describing the problem, otherwise it will be None. It may be useful to throw an exception in setup.py if this is set, to avoid e.g. creating tarballs with a version string of "unknown". Some variants are more useful than others. Including `full-revisionid` in a bug report should allow developers to reconstruct the exact code being tested (or indicate the presence of local changes that should be shared with the developers). `version` is suitable for display in an "about" box or a CLI `--version` output: it can be easily compared against release notes and lists of bugs fixed in various releases. The installer adds the following text to your `__init__.py` to place a basic version in `YOURPROJECT.__version__`: from ._version import get_versions __version__ = get_versions()['version'] del get_versions ## Styles The setup.cfg `style=` configuration controls how the VCS information is rendered into a version string. The default style, "pep440", produces a PEP440-compliant string, equal to the un-prefixed tag name for actual releases, and containing an additional "local version" section with more detail for in-between builds. For Git, this is TAG[+DISTANCE.gHEX[.dirty]] , using information from `git describe --tags --dirty --always`. For example "0.11+2.g1076c97.dirty" indicates that the tree is like the "1076c97" commit but has uncommitted changes (".dirty"), and that this commit is two revisions ("+2") beyond the "0.11" tag. For released software (exactly equal to a known tag), the identifier will only contain the stripped tag, e.g. "0.11". Other styles are available. See [details.md](details.md) in the Versioneer source tree for descriptions. ## Debugging Versioneer tries to avoid fatal errors: if something goes wrong, it will tend to return a version of "0+unknown". To investigate the problem, run `setup.py version`, which will run the version-lookup code in a verbose mode, and will display the full contents of `get_versions()` (including the `error` string, which may help identify what went wrong). ## Known Limitations Some situations are known to cause problems for Versioneer. This details the most significant ones. More can be found on Github [issues page](https://github.com/python-versioneer/python-versioneer/issues). ### Subprojects Versioneer has limited support for source trees in which `setup.py` is not in the root directory (e.g. `setup.py` and `.git/` are *not* siblings). The are two common reasons why `setup.py` might not be in the root: * Source trees which contain multiple subprojects, such as [Buildbot](https://github.com/buildbot/buildbot), which contains both "master" and "slave" subprojects, each with their own `setup.py`, `setup.cfg`, and `tox.ini`. Projects like these produce multiple PyPI distributions (and upload multiple independently-installable tarballs). * Source trees whose main purpose is to contain a C library, but which also provide bindings to Python (and perhaps other languages) in subdirectories. Versioneer will look for `.git` in parent directories, and most operations should get the right version string. However `pip` and `setuptools` have bugs and implementation details which frequently cause `pip install .` from a subproject directory to fail to find a correct version string (so it usually defaults to `0+unknown`). `pip install --editable .` should work correctly. `setup.py install` might work too. Pip-8.1.1 is known to have this problem, but hopefully it will get fixed in some later version. [Bug #38](https://github.com/python-versioneer/python-versioneer/issues/38) is tracking this issue. The discussion in [PR #61](https://github.com/python-versioneer/python-versioneer/pull/61) describes the issue from the Versioneer side in more detail. [pip PR#3176](https://github.com/pypa/pip/pull/3176) and [pip PR#3615](https://github.com/pypa/pip/pull/3615) contain work to improve pip to let Versioneer work correctly. Versioneer-0.16 and earlier only looked for a `.git` directory next to the `setup.cfg`, so subprojects were completely unsupported with those releases. ### Editable installs with setuptools <= 18.5 `setup.py develop` and `pip install --editable .` allow you to install a project into a virtualenv once, then continue editing the source code (and test) without re-installing after every change. "Entry-point scripts" (`setup(entry_points={"console_scripts": ..})`) are a convenient way to specify executable scripts that should be installed along with the python package. These both work as expected when using modern setuptools. When using setuptools-18.5 or earlier, however, certain operations will cause `pkg_resources.DistributionNotFound` errors when running the entrypoint script, which must be resolved by re-installing the package. This happens when the install happens with one version, then the egg_info data is regenerated while a different version is checked out. Many setup.py commands cause egg_info to be rebuilt (including `sdist`, `wheel`, and installing into a different virtualenv), so this can be surprising. [Bug #83](https://github.com/python-versioneer/python-versioneer/issues/83) describes this one, but upgrading to a newer version of setuptools should probably resolve it. ## Updating Versioneer To upgrade your project to a new release of Versioneer, do the following: * install the new Versioneer (`pip install -U versioneer` or equivalent) * edit `setup.cfg`, if necessary, to include any new configuration settings indicated by the release notes. See [UPGRADING](./UPGRADING.md) for details. * re-run `versioneer install` in your source tree, to replace `SRC/_version.py` * commit any changed files ## Future Directions This tool is designed to make it easily extended to other version-control systems: all VCS-specific components are in separate directories like src/git/ . The top-level `versioneer.py` script is assembled from these components by running make-versioneer.py . In the future, make-versioneer.py will take a VCS name as an argument, and will construct a version of `versioneer.py` that is specific to the given VCS. It might also take the configuration arguments that are currently provided manually during installation by editing setup.py . Alternatively, it might go the other direction and include code from all supported VCS systems, reducing the number of intermediate scripts. ## Similar projects * [setuptools_scm](https://github.com/pypa/setuptools_scm/) - a non-vendored build-time dependency * [minver](https://github.com/jbweston/miniver) - a lightweight reimplementation of versioneer * [versioningit](https://github.com/jwodder/versioningit) - a PEP 518-based setuptools plugin ## License To make Versioneer easier to embed, all its code is dedicated to the public domain. The `_version.py` that it creates is also in the public domain. Specifically, both are released under the Creative Commons "Public Domain Dedication" license (CC0-1.0), as described in https://creativecommons.org/publicdomain/zero/1.0/ . [pypi-image]: https://img.shields.io/pypi/v/versioneer.svg [pypi-url]: https://pypi.python.org/pypi/versioneer/ [travis-image]: https://img.shields.io/travis/com/python-versioneer/python-versioneer.svg [travis-url]: https://travis-ci.com/github/python-versioneer/python-versioneer """ # pylint:disable=invalid-name,import-outside-toplevel,missing-function-docstring # pylint:disable=missing-class-docstring,too-many-branches,too-many-statements # pylint:disable=raise-missing-from,too-many-lines,too-many-locals,import-error # pylint:disable=too-few-public-methods,redefined-outer-name,consider-using-with # pylint:disable=attribute-defined-outside-init,too-many-arguments import configparser import errno import json import os import re import subprocess import sys from typing import Callable, Dict import functools class VersioneerConfig: """Container for Versioneer configuration parameters.""" def get_root(): """Get the project root directory. We require that all commands are run from the project root, i.e. the directory that contains setup.py, setup.cfg, and versioneer.py . """ root = os.path.realpath(os.path.abspath(os.getcwd())) setup_py = os.path.join(root, "setup.py") versioneer_py = os.path.join(root, "versioneer.py") if not (os.path.exists(setup_py) or os.path.exists(versioneer_py)): # allow 'python path/to/setup.py COMMAND' root = os.path.dirname(os.path.realpath(os.path.abspath(sys.argv[0]))) setup_py = os.path.join(root, "setup.py") versioneer_py = os.path.join(root, "versioneer.py") if not (os.path.exists(setup_py) or os.path.exists(versioneer_py)): err = ("Versioneer was unable to run the project root directory. " "Versioneer requires setup.py to be executed from " "its immediate directory (like 'python setup.py COMMAND'), " "or in a way that lets it use sys.argv[0] to find the root " "(like 'python path/to/setup.py COMMAND').") raise VersioneerBadRootError(err) try: # Certain runtime workflows (setup.py install/develop in a setuptools # tree) execute all dependencies in a single python process, so # "versioneer" may be imported multiple times, and python's shared # module-import table will cache the first one. So we can't use # os.path.dirname(__file__), as that will find whichever # versioneer.py was first imported, even in later projects. my_path = os.path.realpath(os.path.abspath(__file__)) me_dir = os.path.normcase(os.path.splitext(my_path)[0]) vsr_dir = os.path.normcase(os.path.splitext(versioneer_py)[0]) if me_dir != vsr_dir: print("Warning: build in %s is using versioneer.py from %s" % (os.path.dirname(my_path), versioneer_py)) except NameError: pass return root def get_config_from_root(root): """Read the project setup.cfg file to determine Versioneer config.""" # This might raise OSError (if setup.cfg is missing), or # configparser.NoSectionError (if it lacks a [versioneer] section), or # configparser.NoOptionError (if it lacks "VCS="). See the docstring at # the top of versioneer.py for instructions on writing your setup.cfg . setup_cfg = os.path.join(root, "setup.cfg") parser = configparser.ConfigParser() with open(setup_cfg, "r") as cfg_file: parser.read_file(cfg_file) VCS = parser.get("versioneer", "VCS") # mandatory # Dict-like interface for non-mandatory entries section = parser["versioneer"] cfg = VersioneerConfig() cfg.VCS = VCS cfg.style = section.get("style", "") cfg.versionfile_source = section.get("versionfile_source") cfg.versionfile_build = section.get("versionfile_build") cfg.tag_prefix = section.get("tag_prefix") if cfg.tag_prefix in ("''", '""'): cfg.tag_prefix = "" cfg.parentdir_prefix = section.get("parentdir_prefix") cfg.verbose = section.get("verbose") return cfg class NotThisMethod(Exception): """Exception raised if a method is not valid for the current scenario.""" # these dictionaries contain VCS-specific tools LONG_VERSION_PY: Dict[str, str] = {} HANDLERS: Dict[str, Dict[str, Callable]] = {} def register_vcs_handler(vcs, method): # decorator """Create decorator to mark a method as the handler of a VCS.""" def decorate(f): """Store f in HANDLERS[vcs][method].""" HANDLERS.setdefault(vcs, {})[method] = f return f return decorate def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, env=None): """Call the given command(s).""" assert isinstance(commands, list) process = None popen_kwargs = {} if sys.platform == "win32": # This hides the console window if pythonw.exe is used startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW popen_kwargs["startupinfo"] = startupinfo for command in commands: try: dispcmd = str([command] + args) # remember shell=False, so use git.cmd on windows, not just git process = subprocess.Popen([command] + args, cwd=cwd, env=env, stdout=subprocess.PIPE, stderr=(subprocess.PIPE if hide_stderr else None), **popen_kwargs) break except OSError: e = sys.exc_info()[1] if e.errno == errno.ENOENT: continue if verbose: print("unable to run %s" % dispcmd) print(e) return None, None else: if verbose: print("unable to find command, tried %s" % (commands,)) return None, None stdout = process.communicate()[0].strip().decode() if process.returncode != 0: if verbose: print("unable to run %s (error)" % dispcmd) print("stdout was %s" % stdout) return None, process.returncode return stdout, process.returncode LONG_VERSION_PY['git'] = r''' # This file helps to compute a version number in source trees obtained from # git-archive tarball (such as those provided by githubs download-from-tag # feature). Distribution tarballs (built by setup.py sdist) and build # directories (produced by setup.py build) will contain a much shorter file # that just contains the computed version number. # This file is released into the public domain. Generated by # versioneer-0.22 (https://github.com/python-versioneer/python-versioneer) """Git implementation of _version.py.""" import errno import os import re import subprocess import sys from typing import Callable, Dict import functools def get_keywords(): """Get the keywords needed to look up the version information.""" # these strings will be replaced by git during git-archive. # setup.py/versioneer.py will grep for the variable names, so they must # each be defined on a line of their own. _version.py will just call # get_keywords(). git_refnames = "%(DOLLAR)sFormat:%%d%(DOLLAR)s" git_full = "%(DOLLAR)sFormat:%%H%(DOLLAR)s" git_date = "%(DOLLAR)sFormat:%%ci%(DOLLAR)s" keywords = {"refnames": git_refnames, "full": git_full, "date": git_date} return keywords class VersioneerConfig: """Container for Versioneer configuration parameters.""" def get_config(): """Create, populate and return the VersioneerConfig() object.""" # these strings are filled in when 'setup.py versioneer' creates # _version.py cfg = VersioneerConfig() cfg.VCS = "git" cfg.style = "%(STYLE)s" cfg.tag_prefix = "%(TAG_PREFIX)s" cfg.parentdir_prefix = "%(PARENTDIR_PREFIX)s" cfg.versionfile_source = "%(VERSIONFILE_SOURCE)s" cfg.verbose = False return cfg class NotThisMethod(Exception): """Exception raised if a method is not valid for the current scenario.""" LONG_VERSION_PY: Dict[str, str] = {} HANDLERS: Dict[str, Dict[str, Callable]] = {} def register_vcs_handler(vcs, method): # decorator """Create decorator to mark a method as the handler of a VCS.""" def decorate(f): """Store f in HANDLERS[vcs][method].""" if vcs not in HANDLERS: HANDLERS[vcs] = {} HANDLERS[vcs][method] = f return f return decorate def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, env=None): """Call the given command(s).""" assert isinstance(commands, list) process = None popen_kwargs = {} if sys.platform == "win32": # This hides the console window if pythonw.exe is used startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW popen_kwargs["startupinfo"] = startupinfo for command in commands: try: dispcmd = str([command] + args) # remember shell=False, so use git.cmd on windows, not just git process = subprocess.Popen([command] + args, cwd=cwd, env=env, stdout=subprocess.PIPE, stderr=(subprocess.PIPE if hide_stderr else None), **popen_kwargs) break except OSError: e = sys.exc_info()[1] if e.errno == errno.ENOENT: continue if verbose: print("unable to run %%s" %% dispcmd) print(e) return None, None else: if verbose: print("unable to find command, tried %%s" %% (commands,)) return None, None stdout = process.communicate()[0].strip().decode() if process.returncode != 0: if verbose: print("unable to run %%s (error)" %% dispcmd) print("stdout was %%s" %% stdout) return None, process.returncode return stdout, process.returncode def versions_from_parentdir(parentdir_prefix, root, verbose): """Try to determine the version from the parent directory name. Source tarballs conventionally unpack into a directory that includes both the project name and a version string. We will also support searching up two directory levels for an appropriately named parent directory """ rootdirs = [] for _ in range(3): dirname = os.path.basename(root) if dirname.startswith(parentdir_prefix): return {"version": dirname[len(parentdir_prefix):], "full-revisionid": None, "dirty": False, "error": None, "date": None} rootdirs.append(root) root = os.path.dirname(root) # up a level if verbose: print("Tried directories %%s but none started with prefix %%s" %% (str(rootdirs), parentdir_prefix)) raise NotThisMethod("rootdir doesn't start with parentdir_prefix") @register_vcs_handler("git", "get_keywords") def git_get_keywords(versionfile_abs): """Extract version information from the given file.""" # the code embedded in _version.py can just fetch the value of these # keywords. When used from setup.py, we don't want to import _version.py, # so we do it with a regexp instead. This function is not used from # _version.py. keywords = {} try: with open(versionfile_abs, "r") as fobj: for line in fobj: if line.strip().startswith("git_refnames ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["refnames"] = mo.group(1) if line.strip().startswith("git_full ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["full"] = mo.group(1) if line.strip().startswith("git_date ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["date"] = mo.group(1) except OSError: pass return keywords @register_vcs_handler("git", "keywords") def git_versions_from_keywords(keywords, tag_prefix, verbose): """Get version information from git keywords.""" if "refnames" not in keywords: raise NotThisMethod("Short version file found") date = keywords.get("date") if date is not None: # Use only the last line. Previous lines may contain GPG signature # information. date = date.splitlines()[-1] # git-2.2.0 added "%%cI", which expands to an ISO-8601 -compliant # datestamp. However we prefer "%%ci" (which expands to an "ISO-8601 # -like" string, which we must then edit to make compliant), because # it's been around since git-1.5.3, and it's too difficult to # discover which version we're using, or to work around using an # older one. date = date.strip().replace(" ", "T", 1).replace(" ", "", 1) refnames = keywords["refnames"].strip() if refnames.startswith("$Format"): if verbose: print("keywords are unexpanded, not using") raise NotThisMethod("unexpanded keywords, not a git-archive tarball") refs = {r.strip() for r in refnames.strip("()").split(",")} # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of # just "foo-1.0". If we see a "tag: " prefix, prefer those. TAG = "tag: " tags = {r[len(TAG):] for r in refs if r.startswith(TAG)} if not tags: # Either we're using git < 1.8.3, or there really are no tags. We use # a heuristic: assume all version tags have a digit. The old git %%d # expansion behaves like git log --decorate=short and strips out the # refs/heads/ and refs/tags/ prefixes that would let us distinguish # between branches and tags. By ignoring refnames without digits, we # filter out many common branch names like "release" and # "stabilization", as well as "HEAD" and "master". tags = {r for r in refs if re.search(r'\d', r)} if verbose: print("discarding '%%s', no digits" %% ",".join(refs - tags)) if verbose: print("likely tags: %%s" %% ",".join(sorted(tags))) for ref in sorted(tags): # sorting will prefer e.g. "2.0" over "2.0rc1" if ref.startswith(tag_prefix): r = ref[len(tag_prefix):] # Filter out refs that exactly match prefix or that don't start # with a number once the prefix is stripped (mostly a concern # when prefix is '') if not re.match(r'\d', r): continue if verbose: print("picking %%s" %% r) return {"version": r, "full-revisionid": keywords["full"].strip(), "dirty": False, "error": None, "date": date} # no suitable tags, so version is "0+unknown", but full hex is still there if verbose: print("no suitable tags, using unknown + full revision id") return {"version": "0+unknown", "full-revisionid": keywords["full"].strip(), "dirty": False, "error": "no suitable tags", "date": None} @register_vcs_handler("git", "pieces_from_vcs") def git_pieces_from_vcs(tag_prefix, root, verbose, runner=run_command): """Get version from 'git describe' in the root of the source tree. This only gets called if the git-archive 'subst' keywords were *not* expanded, and _version.py hasn't already been rewritten with a short version string, meaning we're inside a checked out source tree. """ GITS = ["git"] if sys.platform == "win32": GITS = ["git.cmd", "git.exe"] # GIT_DIR can interfere with correct operation of Versioneer. # It may be intended to be passed to the Versioneer-versioned project, # but that should not change where we get our version from. env = os.environ.copy() env.pop("GIT_DIR", None) runner = functools.partial(runner, env=env) _, rc = runner(GITS, ["rev-parse", "--git-dir"], cwd=root, hide_stderr=True) if rc != 0: if verbose: print("Directory %%s not under git control" %% root) raise NotThisMethod("'git rev-parse --git-dir' returned error") MATCH_ARGS = ["--match", "%%s*" %% tag_prefix] if tag_prefix else [] # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] # if there isn't one, this yields HEX[-dirty] (no NUM) describe_out, rc = runner(GITS, ["describe", "--tags", "--dirty", "--always", "--long", *MATCH_ARGS], cwd=root) # --long was added in git-1.5.5 if describe_out is None: raise NotThisMethod("'git describe' failed") describe_out = describe_out.strip() full_out, rc = runner(GITS, ["rev-parse", "HEAD"], cwd=root) if full_out is None: raise NotThisMethod("'git rev-parse' failed") full_out = full_out.strip() pieces = {} pieces["long"] = full_out pieces["short"] = full_out[:7] # maybe improved later pieces["error"] = None branch_name, rc = runner(GITS, ["rev-parse", "--abbrev-ref", "HEAD"], cwd=root) # --abbrev-ref was added in git-1.6.3 if rc != 0 or branch_name is None: raise NotThisMethod("'git rev-parse --abbrev-ref' returned error") branch_name = branch_name.strip() if branch_name == "HEAD": # If we aren't exactly on a branch, pick a branch which represents # the current commit. If all else fails, we are on a branchless # commit. branches, rc = runner(GITS, ["branch", "--contains"], cwd=root) # --contains was added in git-1.5.4 if rc != 0 or branches is None: raise NotThisMethod("'git branch --contains' returned error") branches = branches.split("\n") # Remove the first line if we're running detached if "(" in branches[0]: branches.pop(0) # Strip off the leading "* " from the list of branches. branches = [branch[2:] for branch in branches] if "master" in branches: branch_name = "master" elif not branches: branch_name = None else: # Pick the first branch that is returned. Good or bad. branch_name = branches[0] pieces["branch"] = branch_name # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] # TAG might have hyphens. git_describe = describe_out # look for -dirty suffix dirty = git_describe.endswith("-dirty") pieces["dirty"] = dirty if dirty: git_describe = git_describe[:git_describe.rindex("-dirty")] # now we have TAG-NUM-gHEX or HEX if "-" in git_describe: # TAG-NUM-gHEX mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) if not mo: # unparsable. Maybe git-describe is misbehaving? pieces["error"] = ("unable to parse git-describe output: '%%s'" %% describe_out) return pieces # tag full_tag = mo.group(1) if not full_tag.startswith(tag_prefix): if verbose: fmt = "tag '%%s' doesn't start with prefix '%%s'" print(fmt %% (full_tag, tag_prefix)) pieces["error"] = ("tag '%%s' doesn't start with prefix '%%s'" %% (full_tag, tag_prefix)) return pieces pieces["closest-tag"] = full_tag[len(tag_prefix):] # distance: number of commits since tag pieces["distance"] = int(mo.group(2)) # commit: short hex revision ID pieces["short"] = mo.group(3) else: # HEX: no tags pieces["closest-tag"] = None count_out, rc = runner(GITS, ["rev-list", "HEAD", "--count"], cwd=root) pieces["distance"] = int(count_out) # total number of commits # commit date: see ISO-8601 comment in git_versions_from_keywords() date = runner(GITS, ["show", "-s", "--format=%%ci", "HEAD"], cwd=root)[0].strip() # Use only the last line. Previous lines may contain GPG signature # information. date = date.splitlines()[-1] pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1) return pieces def plus_or_dot(pieces): """Return a + if we don't already have one, else return a .""" if "+" in pieces.get("closest-tag", ""): return "." return "+" def render_pep440(pieces): """Build up version string, with post-release "local version identifier". Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty Exceptions: 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += plus_or_dot(pieces) rendered += "%%d.g%%s" %% (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" else: # exception #1 rendered = "0+untagged.%%d.g%%s" %% (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" return rendered def render_pep440_branch(pieces): """TAG[[.dev0]+DISTANCE.gHEX[.dirty]] . The ".dev0" means not master branch. Note that .dev0 sorts backwards (a feature branch will appear "older" than the master branch). Exceptions: 1: no tags. 0[.dev0]+untagged.DISTANCE.gHEX[.dirty] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: if pieces["branch"] != "master": rendered += ".dev0" rendered += plus_or_dot(pieces) rendered += "%%d.g%%s" %% (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" else: # exception #1 rendered = "0" if pieces["branch"] != "master": rendered += ".dev0" rendered += "+untagged.%%d.g%%s" %% (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" return rendered def pep440_split_post(ver): """Split pep440 version string at the post-release segment. Returns the release segments before the post-release and the post-release version number (or -1 if no post-release segment is present). """ vc = str.split(ver, ".post") return vc[0], int(vc[1] or 0) if len(vc) == 2 else None def render_pep440_pre(pieces): """TAG[.postN.devDISTANCE] -- No -dirty. Exceptions: 1: no tags. 0.post0.devDISTANCE """ if pieces["closest-tag"]: if pieces["distance"]: # update the post release segment tag_version, post_version = pep440_split_post(pieces["closest-tag"]) rendered = tag_version if post_version is not None: rendered += ".post%%d.dev%%d" %% (post_version+1, pieces["distance"]) else: rendered += ".post0.dev%%d" %% (pieces["distance"]) else: # no commits, use the tag as the version rendered = pieces["closest-tag"] else: # exception #1 rendered = "0.post0.dev%%d" %% pieces["distance"] return rendered def render_pep440_post(pieces): """TAG[.postDISTANCE[.dev0]+gHEX] . The ".dev0" means dirty. Note that .dev0 sorts backwards (a dirty tree will appear "older" than the corresponding clean one), but you shouldn't be releasing software with -dirty anyways. Exceptions: 1: no tags. 0.postDISTANCE[.dev0] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += ".post%%d" %% pieces["distance"] if pieces["dirty"]: rendered += ".dev0" rendered += plus_or_dot(pieces) rendered += "g%%s" %% pieces["short"] else: # exception #1 rendered = "0.post%%d" %% pieces["distance"] if pieces["dirty"]: rendered += ".dev0" rendered += "+g%%s" %% pieces["short"] return rendered def render_pep440_post_branch(pieces): """TAG[.postDISTANCE[.dev0]+gHEX[.dirty]] . The ".dev0" means not master branch. Exceptions: 1: no tags. 0.postDISTANCE[.dev0]+gHEX[.dirty] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += ".post%%d" %% pieces["distance"] if pieces["branch"] != "master": rendered += ".dev0" rendered += plus_or_dot(pieces) rendered += "g%%s" %% pieces["short"] if pieces["dirty"]: rendered += ".dirty" else: # exception #1 rendered = "0.post%%d" %% pieces["distance"] if pieces["branch"] != "master": rendered += ".dev0" rendered += "+g%%s" %% pieces["short"] if pieces["dirty"]: rendered += ".dirty" return rendered def render_pep440_old(pieces): """TAG[.postDISTANCE[.dev0]] . The ".dev0" means dirty. Exceptions: 1: no tags. 0.postDISTANCE[.dev0] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += ".post%%d" %% pieces["distance"] if pieces["dirty"]: rendered += ".dev0" else: # exception #1 rendered = "0.post%%d" %% pieces["distance"] if pieces["dirty"]: rendered += ".dev0" return rendered def render_git_describe(pieces): """TAG[-DISTANCE-gHEX][-dirty]. Like 'git describe --tags --dirty --always'. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix) """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"]: rendered += "-%%d-g%%s" %% (pieces["distance"], pieces["short"]) else: # exception #1 rendered = pieces["short"] if pieces["dirty"]: rendered += "-dirty" return rendered def render_git_describe_long(pieces): """TAG-DISTANCE-gHEX[-dirty]. Like 'git describe --tags --dirty --always -long'. The distance/hash is unconditional. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix) """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] rendered += "-%%d-g%%s" %% (pieces["distance"], pieces["short"]) else: # exception #1 rendered = pieces["short"] if pieces["dirty"]: rendered += "-dirty" return rendered def render(pieces, style): """Render the given version pieces into the requested style.""" if pieces["error"]: return {"version": "unknown", "full-revisionid": pieces.get("long"), "dirty": None, "error": pieces["error"], "date": None} if not style or style == "default": style = "pep440" # the default if style == "pep440": rendered = render_pep440(pieces) elif style == "pep440-branch": rendered = render_pep440_branch(pieces) elif style == "pep440-pre": rendered = render_pep440_pre(pieces) elif style == "pep440-post": rendered = render_pep440_post(pieces) elif style == "pep440-post-branch": rendered = render_pep440_post_branch(pieces) elif style == "pep440-old": rendered = render_pep440_old(pieces) elif style == "git-describe": rendered = render_git_describe(pieces) elif style == "git-describe-long": rendered = render_git_describe_long(pieces) else: raise ValueError("unknown style '%%s'" %% style) return {"version": rendered, "full-revisionid": pieces["long"], "dirty": pieces["dirty"], "error": None, "date": pieces.get("date")} def get_versions(): """Get version information or return default if unable to do so.""" # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have # __file__, we can work backwards from there to the root. Some # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which # case we can only use expanded keywords. cfg = get_config() verbose = cfg.verbose try: return git_versions_from_keywords(get_keywords(), cfg.tag_prefix, verbose) except NotThisMethod: pass try: root = os.path.realpath(__file__) # versionfile_source is the relative path from the top of the source # tree (where the .git directory might live) to this file. Invert # this to find the root from __file__. for _ in cfg.versionfile_source.split('/'): root = os.path.dirname(root) except NameError: return {"version": "0+unknown", "full-revisionid": None, "dirty": None, "error": "unable to find root of source tree", "date": None} try: pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose) return render(pieces, cfg.style) except NotThisMethod: pass try: if cfg.parentdir_prefix: return versions_from_parentdir(cfg.parentdir_prefix, root, verbose) except NotThisMethod: pass return {"version": "0+unknown", "full-revisionid": None, "dirty": None, "error": "unable to compute version", "date": None} ''' @register_vcs_handler("git", "get_keywords") def git_get_keywords(versionfile_abs): """Extract version information from the given file.""" # the code embedded in _version.py can just fetch the value of these # keywords. When used from setup.py, we don't want to import _version.py, # so we do it with a regexp instead. This function is not used from # _version.py. keywords = {} try: with open(versionfile_abs, "r") as fobj: for line in fobj: if line.strip().startswith("git_refnames ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["refnames"] = mo.group(1) if line.strip().startswith("git_full ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["full"] = mo.group(1) if line.strip().startswith("git_date ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["date"] = mo.group(1) except OSError: pass return keywords @register_vcs_handler("git", "keywords") def git_versions_from_keywords(keywords, tag_prefix, verbose): """Get version information from git keywords.""" if "refnames" not in keywords: raise NotThisMethod("Short version file found") date = keywords.get("date") if date is not None: # Use only the last line. Previous lines may contain GPG signature # information. date = date.splitlines()[-1] # git-2.2.0 added "%cI", which expands to an ISO-8601 -compliant # datestamp. However we prefer "%ci" (which expands to an "ISO-8601 # -like" string, which we must then edit to make compliant), because # it's been around since git-1.5.3, and it's too difficult to # discover which version we're using, or to work around using an # older one. date = date.strip().replace(" ", "T", 1).replace(" ", "", 1) refnames = keywords["refnames"].strip() if refnames.startswith("$Format"): if verbose: print("keywords are unexpanded, not using") raise NotThisMethod("unexpanded keywords, not a git-archive tarball") refs = {r.strip() for r in refnames.strip("()").split(",")} # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of # just "foo-1.0". If we see a "tag: " prefix, prefer those. TAG = "tag: " tags = {r[len(TAG):] for r in refs if r.startswith(TAG)} if not tags: # Either we're using git < 1.8.3, or there really are no tags. We use # a heuristic: assume all version tags have a digit. The old git %d # expansion behaves like git log --decorate=short and strips out the # refs/heads/ and refs/tags/ prefixes that would let us distinguish # between branches and tags. By ignoring refnames without digits, we # filter out many common branch names like "release" and # "stabilization", as well as "HEAD" and "master". tags = {r for r in refs if re.search(r'\d', r)} if verbose: print("discarding '%s', no digits" % ",".join(refs - tags)) if verbose: print("likely tags: %s" % ",".join(sorted(tags))) for ref in sorted(tags): # sorting will prefer e.g. "2.0" over "2.0rc1" if ref.startswith(tag_prefix): r = ref[len(tag_prefix):] # Filter out refs that exactly match prefix or that don't start # with a number once the prefix is stripped (mostly a concern # when prefix is '') if not re.match(r'\d', r): continue if verbose: print("picking %s" % r) return {"version": r, "full-revisionid": keywords["full"].strip(), "dirty": False, "error": None, "date": date} # no suitable tags, so version is "0+unknown", but full hex is still there if verbose: print("no suitable tags, using unknown + full revision id") return {"version": "0+unknown", "full-revisionid": keywords["full"].strip(), "dirty": False, "error": "no suitable tags", "date": None} @register_vcs_handler("git", "pieces_from_vcs") def git_pieces_from_vcs(tag_prefix, root, verbose, runner=run_command): """Get version from 'git describe' in the root of the source tree. This only gets called if the git-archive 'subst' keywords were *not* expanded, and _version.py hasn't already been rewritten with a short version string, meaning we're inside a checked out source tree. """ GITS = ["git"] if sys.platform == "win32": GITS = ["git.cmd", "git.exe"] # GIT_DIR can interfere with correct operation of Versioneer. # It may be intended to be passed to the Versioneer-versioned project, # but that should not change where we get our version from. env = os.environ.copy() env.pop("GIT_DIR", None) runner = functools.partial(runner, env=env) _, rc = runner(GITS, ["rev-parse", "--git-dir"], cwd=root, hide_stderr=True) if rc != 0: if verbose: print("Directory %s not under git control" % root) raise NotThisMethod("'git rev-parse --git-dir' returned error") MATCH_ARGS = ["--match", "%s*" % tag_prefix] if tag_prefix else [] # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] # if there isn't one, this yields HEX[-dirty] (no NUM) describe_out, rc = runner(GITS, ["describe", "--tags", "--dirty", "--always", "--long", *MATCH_ARGS], cwd=root) # --long was added in git-1.5.5 if describe_out is None: raise NotThisMethod("'git describe' failed") describe_out = describe_out.strip() full_out, rc = runner(GITS, ["rev-parse", "HEAD"], cwd=root) if full_out is None: raise NotThisMethod("'git rev-parse' failed") full_out = full_out.strip() pieces = {} pieces["long"] = full_out pieces["short"] = full_out[:7] # maybe improved later pieces["error"] = None branch_name, rc = runner(GITS, ["rev-parse", "--abbrev-ref", "HEAD"], cwd=root) # --abbrev-ref was added in git-1.6.3 if rc != 0 or branch_name is None: raise NotThisMethod("'git rev-parse --abbrev-ref' returned error") branch_name = branch_name.strip() if branch_name == "HEAD": # If we aren't exactly on a branch, pick a branch which represents # the current commit. If all else fails, we are on a branchless # commit. branches, rc = runner(GITS, ["branch", "--contains"], cwd=root) # --contains was added in git-1.5.4 if rc != 0 or branches is None: raise NotThisMethod("'git branch --contains' returned error") branches = branches.split("\n") # Remove the first line if we're running detached if "(" in branches[0]: branches.pop(0) # Strip off the leading "* " from the list of branches. branches = [branch[2:] for branch in branches] if "master" in branches: branch_name = "master" elif not branches: branch_name = None else: # Pick the first branch that is returned. Good or bad. branch_name = branches[0] pieces["branch"] = branch_name # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] # TAG might have hyphens. git_describe = describe_out # look for -dirty suffix dirty = git_describe.endswith("-dirty") pieces["dirty"] = dirty if dirty: git_describe = git_describe[:git_describe.rindex("-dirty")] # now we have TAG-NUM-gHEX or HEX if "-" in git_describe: # TAG-NUM-gHEX mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) if not mo: # unparsable. Maybe git-describe is misbehaving? pieces["error"] = ("unable to parse git-describe output: '%s'" % describe_out) return pieces # tag full_tag = mo.group(1) if not full_tag.startswith(tag_prefix): if verbose: fmt = "tag '%s' doesn't start with prefix '%s'" print(fmt % (full_tag, tag_prefix)) pieces["error"] = ("tag '%s' doesn't start with prefix '%s'" % (full_tag, tag_prefix)) return pieces pieces["closest-tag"] = full_tag[len(tag_prefix):] # distance: number of commits since tag pieces["distance"] = int(mo.group(2)) # commit: short hex revision ID pieces["short"] = mo.group(3) else: # HEX: no tags pieces["closest-tag"] = None count_out, rc = runner(GITS, ["rev-list", "HEAD", "--count"], cwd=root) pieces["distance"] = int(count_out) # total number of commits # commit date: see ISO-8601 comment in git_versions_from_keywords() date = runner(GITS, ["show", "-s", "--format=%ci", "HEAD"], cwd=root)[0].strip() # Use only the last line. Previous lines may contain GPG signature # information. date = date.splitlines()[-1] pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1) return pieces def do_vcs_install(manifest_in, versionfile_source, ipy): """Git-specific installation logic for Versioneer. For Git, this means creating/changing .gitattributes to mark _version.py for export-subst keyword substitution. """ GITS = ["git"] if sys.platform == "win32": GITS = ["git.cmd", "git.exe"] files = [manifest_in, versionfile_source] if ipy: files.append(ipy) try: my_path = __file__ if my_path.endswith(".pyc") or my_path.endswith(".pyo"): my_path = os.path.splitext(my_path)[0] + ".py" versioneer_file = os.path.relpath(my_path) except NameError: versioneer_file = "versioneer.py" files.append(versioneer_file) present = False try: with open(".gitattributes", "r") as fobj: for line in fobj: if line.strip().startswith(versionfile_source): if "export-subst" in line.strip().split()[1:]: present = True break except OSError: pass if not present: with open(".gitattributes", "a+") as fobj: fobj.write(f"{versionfile_source} export-subst\n") files.append(".gitattributes") run_command(GITS, ["add", "--"] + files) def versions_from_parentdir(parentdir_prefix, root, verbose): """Try to determine the version from the parent directory name. Source tarballs conventionally unpack into a directory that includes both the project name and a version string. We will also support searching up two directory levels for an appropriately named parent directory """ rootdirs = [] for _ in range(3): dirname = os.path.basename(root) if dirname.startswith(parentdir_prefix): return {"version": dirname[len(parentdir_prefix):], "full-revisionid": None, "dirty": False, "error": None, "date": None} rootdirs.append(root) root = os.path.dirname(root) # up a level if verbose: print("Tried directories %s but none started with prefix %s" % (str(rootdirs), parentdir_prefix)) raise NotThisMethod("rootdir doesn't start with parentdir_prefix") SHORT_VERSION_PY = """ # This file was generated by 'versioneer.py' (0.22) from # revision-control system data, or from the parent directory name of an # unpacked source archive. Distribution tarballs contain a pre-generated copy # of this file. import json version_json = ''' %s ''' # END VERSION_JSON def get_versions(): return json.loads(version_json) """ def versions_from_file(filename): """Try to determine the version from _version.py if present.""" try: with open(filename) as f: contents = f.read() except OSError: raise NotThisMethod("unable to read _version.py") mo = re.search(r"version_json = '''\n(.*)''' # END VERSION_JSON", contents, re.M | re.S) if not mo: mo = re.search(r"version_json = '''\r\n(.*)''' # END VERSION_JSON", contents, re.M | re.S) if not mo: raise NotThisMethod("no version_json in _version.py") return json.loads(mo.group(1)) def write_to_version_file(filename, versions): """Write the given version number to the given _version.py file.""" os.unlink(filename) contents = json.dumps(versions, sort_keys=True, indent=1, separators=(",", ": ")) with open(filename, "w") as f: f.write(SHORT_VERSION_PY % contents) print("set %s to '%s'" % (filename, versions["version"])) def plus_or_dot(pieces): """Return a + if we don't already have one, else return a .""" if "+" in pieces.get("closest-tag", ""): return "." return "+" def render_pep440(pieces): """Build up version string, with post-release "local version identifier". Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty Exceptions: 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += plus_or_dot(pieces) rendered += "%d.g%s" % (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" else: # exception #1 rendered = "0+untagged.%d.g%s" % (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" return rendered def render_pep440_branch(pieces): """TAG[[.dev0]+DISTANCE.gHEX[.dirty]] . The ".dev0" means not master branch. Note that .dev0 sorts backwards (a feature branch will appear "older" than the master branch). Exceptions: 1: no tags. 0[.dev0]+untagged.DISTANCE.gHEX[.dirty] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: if pieces["branch"] != "master": rendered += ".dev0" rendered += plus_or_dot(pieces) rendered += "%d.g%s" % (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" else: # exception #1 rendered = "0" if pieces["branch"] != "master": rendered += ".dev0" rendered += "+untagged.%d.g%s" % (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" return rendered def pep440_split_post(ver): """Split pep440 version string at the post-release segment. Returns the release segments before the post-release and the post-release version number (or -1 if no post-release segment is present). """ vc = str.split(ver, ".post") return vc[0], int(vc[1] or 0) if len(vc) == 2 else None def render_pep440_pre(pieces): """TAG[.postN.devDISTANCE] -- No -dirty. Exceptions: 1: no tags. 0.post0.devDISTANCE """ if pieces["closest-tag"]: if pieces["distance"]: # update the post release segment tag_version, post_version = pep440_split_post(pieces["closest-tag"]) rendered = tag_version if post_version is not None: rendered += ".post%d.dev%d" % (post_version+1, pieces["distance"]) else: rendered += ".post0.dev%d" % (pieces["distance"]) else: # no commits, use the tag as the version rendered = pieces["closest-tag"] else: # exception #1 rendered = "0.post0.dev%d" % pieces["distance"] return rendered def render_pep440_post(pieces): """TAG[.postDISTANCE[.dev0]+gHEX] . The ".dev0" means dirty. Note that .dev0 sorts backwards (a dirty tree will appear "older" than the corresponding clean one), but you shouldn't be releasing software with -dirty anyways. Exceptions: 1: no tags. 0.postDISTANCE[.dev0] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += ".post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" rendered += plus_or_dot(pieces) rendered += "g%s" % pieces["short"] else: # exception #1 rendered = "0.post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" rendered += "+g%s" % pieces["short"] return rendered def render_pep440_post_branch(pieces): """TAG[.postDISTANCE[.dev0]+gHEX[.dirty]] . The ".dev0" means not master branch. Exceptions: 1: no tags. 0.postDISTANCE[.dev0]+gHEX[.dirty] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += ".post%d" % pieces["distance"] if pieces["branch"] != "master": rendered += ".dev0" rendered += plus_or_dot(pieces) rendered += "g%s" % pieces["short"] if pieces["dirty"]: rendered += ".dirty" else: # exception #1 rendered = "0.post%d" % pieces["distance"] if pieces["branch"] != "master": rendered += ".dev0" rendered += "+g%s" % pieces["short"] if pieces["dirty"]: rendered += ".dirty" return rendered def render_pep440_old(pieces): """TAG[.postDISTANCE[.dev0]] . The ".dev0" means dirty. Exceptions: 1: no tags. 0.postDISTANCE[.dev0] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += ".post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" else: # exception #1 rendered = "0.post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" return rendered def render_git_describe(pieces): """TAG[-DISTANCE-gHEX][-dirty]. Like 'git describe --tags --dirty --always'. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix) """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"]: rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) else: # exception #1 rendered = pieces["short"] if pieces["dirty"]: rendered += "-dirty" return rendered def render_git_describe_long(pieces): """TAG-DISTANCE-gHEX[-dirty]. Like 'git describe --tags --dirty --always -long'. The distance/hash is unconditional. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix) """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) else: # exception #1 rendered = pieces["short"] if pieces["dirty"]: rendered += "-dirty" return rendered def render(pieces, style): """Render the given version pieces into the requested style.""" if pieces["error"]: return {"version": "unknown", "full-revisionid": pieces.get("long"), "dirty": None, "error": pieces["error"], "date": None} if not style or style == "default": style = "pep440" # the default if style == "pep440": rendered = render_pep440(pieces) elif style == "pep440-branch": rendered = render_pep440_branch(pieces) elif style == "pep440-pre": rendered = render_pep440_pre(pieces) elif style == "pep440-post": rendered = render_pep440_post(pieces) elif style == "pep440-post-branch": rendered = render_pep440_post_branch(pieces) elif style == "pep440-old": rendered = render_pep440_old(pieces) elif style == "git-describe": rendered = render_git_describe(pieces) elif style == "git-describe-long": rendered = render_git_describe_long(pieces) else: raise ValueError("unknown style '%s'" % style) return {"version": rendered, "full-revisionid": pieces["long"], "dirty": pieces["dirty"], "error": None, "date": pieces.get("date")} class VersioneerBadRootError(Exception): """The project root directory is unknown or missing key files.""" def get_versions(verbose=False): """Get the project version from whatever source is available. Returns dict with two keys: 'version' and 'full'. """ if "versioneer" in sys.modules: # see the discussion in cmdclass.py:get_cmdclass() del sys.modules["versioneer"] root = get_root() cfg = get_config_from_root(root) assert cfg.VCS is not None, "please set [versioneer]VCS= in setup.cfg" handlers = HANDLERS.get(cfg.VCS) assert handlers, "unrecognized VCS '%s'" % cfg.VCS verbose = verbose or cfg.verbose assert cfg.versionfile_source is not None, \ "please set versioneer.versionfile_source" assert cfg.tag_prefix is not None, "please set versioneer.tag_prefix" versionfile_abs = os.path.join(root, cfg.versionfile_source) # extract version from first of: _version.py, VCS command (e.g. 'git # describe'), parentdir. This is meant to work for developers using a # source checkout, for users of a tarball created by 'setup.py sdist', # and for users of a tarball/zipball created by 'git archive' or github's # download-from-tag feature or the equivalent in other VCSes. get_keywords_f = handlers.get("get_keywords") from_keywords_f = handlers.get("keywords") if get_keywords_f and from_keywords_f: try: keywords = get_keywords_f(versionfile_abs) ver = from_keywords_f(keywords, cfg.tag_prefix, verbose) if verbose: print("got version from expanded keyword %s" % ver) return ver except NotThisMethod: pass try: ver = versions_from_file(versionfile_abs) if verbose: print("got version from file %s %s" % (versionfile_abs, ver)) return ver except NotThisMethod: pass from_vcs_f = handlers.get("pieces_from_vcs") if from_vcs_f: try: pieces = from_vcs_f(cfg.tag_prefix, root, verbose) ver = render(pieces, cfg.style) if verbose: print("got version from VCS %s" % ver) return ver except NotThisMethod: pass try: if cfg.parentdir_prefix: ver = versions_from_parentdir(cfg.parentdir_prefix, root, verbose) if verbose: print("got version from parentdir %s" % ver) return ver except NotThisMethod: pass if verbose: print("unable to compute version") return {"version": "0+unknown", "full-revisionid": None, "dirty": None, "error": "unable to compute version", "date": None} def get_version(): """Get the short version string for this project.""" return get_versions()["version"] def get_cmdclass(cmdclass=None): """Get the custom setuptools/distutils subclasses used by Versioneer. If the package uses a different cmdclass (e.g. one from numpy), it should be provide as an argument. """ if "versioneer" in sys.modules: del sys.modules["versioneer"] # this fixes the "python setup.py develop" case (also 'install' and # 'easy_install .'), in which subdependencies of the main project are # built (using setup.py bdist_egg) in the same python process. Assume # a main project A and a dependency B, which use different versions # of Versioneer. A's setup.py imports A's Versioneer, leaving it in # sys.modules by the time B's setup.py is executed, causing B to run # with the wrong versioneer. Setuptools wraps the sub-dep builds in a # sandbox that restores sys.modules to it's pre-build state, so the # parent is protected against the child's "import versioneer". By # removing ourselves from sys.modules here, before the child build # happens, we protect the child from the parent's versioneer too. # Also see https://github.com/python-versioneer/python-versioneer/issues/52 cmds = {} if cmdclass is None else cmdclass.copy() # we add "version" to both distutils and setuptools try: from setuptools import Command except ImportError: from distutils.core import Command class cmd_version(Command): description = "report generated version string" user_options = [] boolean_options = [] def initialize_options(self): pass def finalize_options(self): pass def run(self): vers = get_versions(verbose=True) print("Version: %s" % vers["version"]) print(" full-revisionid: %s" % vers.get("full-revisionid")) print(" dirty: %s" % vers.get("dirty")) print(" date: %s" % vers.get("date")) if vers["error"]: print(" error: %s" % vers["error"]) cmds["version"] = cmd_version # we override "build_py" in both distutils and setuptools # # most invocation pathways end up running build_py: # distutils/build -> build_py # distutils/install -> distutils/build ->.. # setuptools/bdist_wheel -> distutils/install ->.. # setuptools/bdist_egg -> distutils/install_lib -> build_py # setuptools/install -> bdist_egg ->.. # setuptools/develop -> ? # pip install: # copies source tree to a tempdir before running egg_info/etc # if .git isn't copied too, 'git describe' will fail # then does setup.py bdist_wheel, or sometimes setup.py install # setup.py egg_info -> ? # we override different "build_py" commands for both environments if 'build_py' in cmds: _build_py = cmds['build_py'] elif "setuptools" in sys.modules: from setuptools.command.build_py import build_py as _build_py else: from distutils.command.build_py import build_py as _build_py class cmd_build_py(_build_py): def run(self): root = get_root() cfg = get_config_from_root(root) versions = get_versions() _build_py.run(self) # now locate _version.py in the new build/ directory and replace # it with an updated value if cfg.versionfile_build: target_versionfile = os.path.join(self.build_lib, cfg.versionfile_build) print("UPDATING %s" % target_versionfile) write_to_version_file(target_versionfile, versions) cmds["build_py"] = cmd_build_py if 'build_ext' in cmds: _build_ext = cmds['build_ext'] elif "setuptools" in sys.modules: from setuptools.command.build_ext import build_ext as _build_ext else: from distutils.command.build_ext import build_ext as _build_ext class cmd_build_ext(_build_ext): def run(self): root = get_root() cfg = get_config_from_root(root) versions = get_versions() _build_ext.run(self) if self.inplace: # build_ext --inplace will only build extensions in # build/lib<..> dir with no _version.py to write to. # As in place builds will already have a _version.py # in the module dir, we do not need to write one. return # now locate _version.py in the new build/ directory and replace # it with an updated value target_versionfile = os.path.join(self.build_lib, cfg.versionfile_build) print("UPDATING %s" % target_versionfile) write_to_version_file(target_versionfile, versions) cmds["build_ext"] = cmd_build_ext if "cx_Freeze" in sys.modules: # cx_freeze enabled? from cx_Freeze.dist import build_exe as _build_exe # nczeczulin reports that py2exe won't like the pep440-style string # as FILEVERSION, but it can be used for PRODUCTVERSION, e.g. # setup(console=[{ # "version": versioneer.get_version().split("+", 1)[0], # FILEVERSION # "product_version": versioneer.get_version(), # ... class cmd_build_exe(_build_exe): def run(self): root = get_root() cfg = get_config_from_root(root) versions = get_versions() target_versionfile = cfg.versionfile_source print("UPDATING %s" % target_versionfile) write_to_version_file(target_versionfile, versions) _build_exe.run(self) os.unlink(target_versionfile) with open(cfg.versionfile_source, "w") as f: LONG = LONG_VERSION_PY[cfg.VCS] f.write(LONG % {"DOLLAR": "$", "STYLE": cfg.style, "TAG_PREFIX": cfg.tag_prefix, "PARENTDIR_PREFIX": cfg.parentdir_prefix, "VERSIONFILE_SOURCE": cfg.versionfile_source, }) cmds["build_exe"] = cmd_build_exe del cmds["build_py"] if 'py2exe' in sys.modules: # py2exe enabled? from py2exe.distutils_buildexe import py2exe as _py2exe class cmd_py2exe(_py2exe): def run(self): root = get_root() cfg = get_config_from_root(root) versions = get_versions() target_versionfile = cfg.versionfile_source print("UPDATING %s" % target_versionfile) write_to_version_file(target_versionfile, versions) _py2exe.run(self) os.unlink(target_versionfile) with open(cfg.versionfile_source, "w") as f: LONG = LONG_VERSION_PY[cfg.VCS] f.write(LONG % {"DOLLAR": "$", "STYLE": cfg.style, "TAG_PREFIX": cfg.tag_prefix, "PARENTDIR_PREFIX": cfg.parentdir_prefix, "VERSIONFILE_SOURCE": cfg.versionfile_source, }) cmds["py2exe"] = cmd_py2exe # we override different "sdist" commands for both environments if 'sdist' in cmds: _sdist = cmds['sdist'] elif "setuptools" in sys.modules: from setuptools.command.sdist import sdist as _sdist else: from distutils.command.sdist import sdist as _sdist class cmd_sdist(_sdist): def run(self): versions = get_versions() self._versioneer_generated_versions = versions # unless we update this, the command will keep using the old # version self.distribution.metadata.version = versions["version"] return _sdist.run(self) def make_release_tree(self, base_dir, files): root = get_root() cfg = get_config_from_root(root) _sdist.make_release_tree(self, base_dir, files) # now locate _version.py in the new base_dir directory # (remembering that it may be a hardlink) and replace it with an # updated value target_versionfile = os.path.join(base_dir, cfg.versionfile_source) print("UPDATING %s" % target_versionfile) write_to_version_file(target_versionfile, self._versioneer_generated_versions) cmds["sdist"] = cmd_sdist return cmds CONFIG_ERROR = """ setup.cfg is missing the necessary Versioneer configuration. You need a section like: [versioneer] VCS = git style = pep440 versionfile_source = src/myproject/_version.py versionfile_build = myproject/_version.py tag_prefix = parentdir_prefix = myproject- You will also need to edit your setup.py to use the results: import versioneer setup(version=versioneer.get_version(), cmdclass=versioneer.get_cmdclass(), ...) Please read the docstring in ./versioneer.py for configuration instructions, edit setup.cfg, and re-run the installer or 'python versioneer.py setup'. """ SAMPLE_CONFIG = """ # See the docstring in versioneer.py for instructions. Note that you must # re-run 'versioneer.py setup' after changing this section, and commit the # resulting files. [versioneer] #VCS = git #style = pep440 #versionfile_source = #versionfile_build = #tag_prefix = #parentdir_prefix = """ OLD_SNIPPET = """ from ._version import get_versions __version__ = get_versions()['version'] del get_versions """ INIT_PY_SNIPPET = """ from . import {0} __version__ = {0}.get_versions()['version'] """ def do_setup(): """Do main VCS-independent setup function for installing Versioneer.""" root = get_root() try: cfg = get_config_from_root(root) except (OSError, configparser.NoSectionError, configparser.NoOptionError) as e: if isinstance(e, (OSError, configparser.NoSectionError)): print("Adding sample versioneer config to setup.cfg", file=sys.stderr) with open(os.path.join(root, "setup.cfg"), "a") as f: f.write(SAMPLE_CONFIG) print(CONFIG_ERROR, file=sys.stderr) return 1 print(" creating %s" % cfg.versionfile_source) with open(cfg.versionfile_source, "w") as f: LONG = LONG_VERSION_PY[cfg.VCS] f.write(LONG % {"DOLLAR": "$", "STYLE": cfg.style, "TAG_PREFIX": cfg.tag_prefix, "PARENTDIR_PREFIX": cfg.parentdir_prefix, "VERSIONFILE_SOURCE": cfg.versionfile_source, }) ipy = os.path.join(os.path.dirname(cfg.versionfile_source), "__init__.py") if os.path.exists(ipy): try: with open(ipy, "r") as f: old = f.read() except OSError: old = "" module = os.path.splitext(os.path.basename(cfg.versionfile_source))[0] snippet = INIT_PY_SNIPPET.format(module) if OLD_SNIPPET in old: print(" replacing boilerplate in %s" % ipy) with open(ipy, "w") as f: f.write(old.replace(OLD_SNIPPET, snippet)) elif snippet not in old: print(" appending to %s" % ipy) with open(ipy, "a") as f: f.write(snippet) else: print(" %s unmodified" % ipy) else: print(" %s doesn't exist, ok" % ipy) ipy = None # Make sure both the top-level "versioneer.py" and versionfile_source # (PKG/_version.py, used by runtime code) are in MANIFEST.in, so # they'll be copied into source distributions. Pip won't be able to # install the package without this. manifest_in = os.path.join(root, "MANIFEST.in") simple_includes = set() try: with open(manifest_in, "r") as f: for line in f: if line.startswith("include "): for include in line.split()[1:]: simple_includes.add(include) except OSError: pass # That doesn't cover everything MANIFEST.in can do # (http://docs.python.org/2/distutils/sourcedist.html#commands), so # it might give some false negatives. Appending redundant 'include' # lines is safe, though. if "versioneer.py" not in simple_includes: print(" appending 'versioneer.py' to MANIFEST.in") with open(manifest_in, "a") as f: f.write("include versioneer.py\n") else: print(" 'versioneer.py' already in MANIFEST.in") if cfg.versionfile_source not in simple_includes: print(" appending versionfile_source ('%s') to MANIFEST.in" % cfg.versionfile_source) with open(manifest_in, "a") as f: f.write("include %s\n" % cfg.versionfile_source) else: print(" versionfile_source already in MANIFEST.in") # Make VCS-specific changes. For git, this means creating/changing # .gitattributes to mark _version.py for export-subst keyword # substitution. do_vcs_install(manifest_in, cfg.versionfile_source, ipy) return 0 def scan_setup_py(): """Validate the contents of setup.py against Versioneer's expectations.""" found = set() setters = False errors = 0 with open("setup.py", "r") as f: for line in f.readlines(): if "import versioneer" in line: found.add("import") if "versioneer.get_cmdclass()" in line: found.add("cmdclass") if "versioneer.get_version()" in line: found.add("get_version") if "versioneer.VCS" in line: setters = True if "versioneer.versionfile_source" in line: setters = True if len(found) != 3: print("") print("Your setup.py appears to be missing some important items") print("(but I might be wrong). Please make sure it has something") print("roughly like the following:") print("") print(" import versioneer") print(" setup( version=versioneer.get_version(),") print(" cmdclass=versioneer.get_cmdclass(), ...)") print("") errors += 1 if setters: print("You should remove lines like 'versioneer.VCS = ' and") print("'versioneer.versionfile_source = ' . This configuration") print("now lives in setup.cfg, and should be removed from setup.py") print("") errors += 1 return errors if __name__ == "__main__": cmd = sys.argv[1] if cmd == "setup": errors = do_setup() errors += scan_setup_py() if errors: sys.exit(1) ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������