nb2plots-0.6/0000755000076500000240000000000013235422500013065 5ustar mb312staff00000000000000nb2plots-0.6/doc-requirements.txt0000644000076500000240000000011113027544026017114 0ustar mb312staff00000000000000# Requirements for building docs -r requirements.txt ghp-import numpydoc nb2plots-0.6/LICENSE0000644000076500000240000001555513235402474014115 0ustar mb312staff00000000000000.. _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-2018, 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.6/MANIFEST.in0000644000076500000240000000043713031546453014637 0ustar mb312staff00000000000000include 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.6/nb2plots/0000755000076500000240000000000013235422500014630 5ustar mb312staff00000000000000nb2plots-0.6/nb2plots/__init__.py0000644000076500000240000000060213235401241016736 0ustar mb312staff00000000000000# nb2plots package from ._version import get_versions __version__ = get_versions()['version'] del get_versions 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.6/nb2plots/_version.py0000644000076500000240000000075713235422500017037 0ustar mb312staff00000000000000 # This file was generated by 'versioneer.py' (0.17) 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 = ''' { "date": "2018-02-03T21:09:07+0000", "dirty": false, "error": null, "full-revisionid": "8873eeca7d7ad617dcac9aa317ee0a7079e17c79", "version": "0.6" } ''' # END VERSION_JSON def get_versions(): return json.loads(version_json) nb2plots-0.6/nb2plots/codelinks.py0000644000076500000240000001023713235401241017157 0ustar mb312staff00000000000000""" 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 of any cell 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.6/nb2plots/commands.py0000644000076500000240000000212513152035171017005 0ustar mb312staff00000000000000""" Support for command-line scripts """ import sys from argparse import ArgumentParser from .converters import NbConverter def bin_stdout(): """ Bytes stream for writing to stdout """ return sys.stdout.buffer if sys.version_info[0] > 2 else sys.stdout 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) bin_stdout().write(output.encode('utf-8')) nb2plots-0.6/nb2plots/converters.py0000644000076500000240000001120713143676147017415 0ustar mb312staff00000000000000""" 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) out_fname = pjoin(app.tmp_dir, 'contents.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('contents', app.builder) else: dt = app.env.get_doctree('contents') 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(['contents']) 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 = """\ 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.6/nb2plots/doctree2md.py0000644000076500000240000004340513154327717017256 0ustar mb312staff00000000000000# -*- coding: utf-8 -*- """Simple Markdown writer for reStructuredText. See: * https://daringfireball.net/projects/markdown/syntax * https://guides.github.com/pdfs/markdown-cheatsheet-online.pdf """ from __future__ import unicode_literals 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 code_type = node['classes'][1] if 'code' in node['classes'] else '' 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.6/nb2plots/doctree2nb.py0000644000076500000240000000160713154330754017246 0ustar mb312staff00000000000000""" Convert doctree to Jupyter notebook """ from __future__ import unicode_literals from docutils import nodes from .ipython_shim import 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.6/nb2plots/doctree2py.py0000644000076500000240000000664113234616775017313 0ustar mb312staff00000000000000""" Writer to convert doctree to Python .py file """ from __future__ import unicode_literals 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.6/nb2plots/from_notebook.py0000644000076500000240000000770213027544026020062 0ustar mb312staff00000000000000#!python """ Convert from notebook to rst page with plot directives """ import re from jinja2 import DictLoader from .ipython_shim import nbformat, nbconvert, traitlets, config 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.tpl' -%} {% 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 -%} """}) 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('\[\]') MPL_OBJ_OUT = re.compile('') 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.6/nb2plots/ipython_shim.py0000644000076500000240000000065713027544026017733 0ustar mb312staff00000000000000""" Shim for IPython before and after the big split """ try: import traitlets import traitlets.config as config except ImportError: from IPython.utils import traitlets from IPython import config try: import nbformat except ImportError: from IPython import nbformat try: import nbconvert except ImportError: from IPython import nbconvert # Use notebook format version 4 by default nbf = nbformat.v4 nb2plots-0.6/nb2plots/mpl_interactive.py0000644000076500000240000000333013235401241020365 0ustar mb312staff00000000000000""" 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.6/nb2plots/nbplots.py0000644000076500000240000011525413235401241016672 0ustar mb312staff00000000000000""" 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. """ from __future__ import (absolute_import, division, print_function, unicode_literals) import six from collections import defaultdict, Sequence 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 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] six.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): new_node = self.dont_doctest_block(node.rawsource, node.rawsource) 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 def remove_coding(text): """ Remove the coding comment, which six.exec_ doesn't like. """ sub_re = re.compile("^#\s*-\*-\s*coding:\s*.*-\*-$", flags=re.MULTILINE) return sub_re.sub("", text) #------------------------------------------------------------------------------ # 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. if six.PY2: pwd = os.getcwdu() else: 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() if six.PY3 else io.BytesIO() # 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: six.exec_(six.text_type(pre_code), ns) ns['print'] = _dummy_print if "__main__" in code: six.exec_("__name__ = '__main__'", ns) code = remove_coding(code) if raises is None: six.exec_(code, ns) else: # Code should raise exception try: six.exec_(code, ns) except raises: pass if function_name: six.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, six.string_types): # 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, six.string_types): 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.6/nb2plots/runroles.py0000644000076500000240000003024313234727533017072 0ustar mb312staff00000000000000""" 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 from sphinx.util.nodes import split_explicit_title, set_role_source_info from sphinx.errors import ExtensionError # Use notebook format version 4 from .ipython_shim import nbf, nbconvert as nbc from . import doctree2nb, doctree2py from .sphinx2foos import PythonBuilder, NotebookBuilder from .converters import UnicodeOutput 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` """ builder = self.builder_class(app) 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 res = nbc.exporter.ResourcesDict() res['metadata'] = nbc.exporter.ResourcesDict() 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('pyfile', doctree2py.Translator) app.set_translator('ipynb', doctree2nb.Translator) nb2plots-0.6/nb2plots/sphinx2foos.py0000644000076500000240000000302613136622273017476 0ustar mb312staff00000000000000""" Sphinx builders for output formats """ from sphinx.builders.text import TextBuilder from . import doctree2md, doctree2py, doctree2nb class MarkdownBuilder(TextBuilder): name = 'markdown' format = 'markdown' out_suffix = '.md' writer_class = doctree2md.Writer def __init__(self, app): """ Initialize Markdown (and friends) builder """ super(MarkdownBuilder, self).__init__(app) # 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.6/nb2plots/strdiff.py0000644000076500000240000000221713031546453016655 0ustar mb312staff00000000000000""" 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.6/nb2plots/testing/0000755000076500000240000000000013235422500016305 5ustar mb312staff00000000000000nb2plots-0.6/nb2plots/testing/__init__.py0000644000076500000240000000132213235401241020413 0ustar mb312staff00000000000000""" 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')) def setup_test(): """ Set numpy print options to "legacy" for new versions of numpy """ from distutils.version import LooseVersion if LooseVersion(np.__version__) >= LooseVersion('1.14'): np.set_printoptions(legacy="1.13") class PlotsBuilder(SourcesBuilder): """ Class to build pages with nbplots default extensions Used by several test functions. """ conf_source = 'extensions = ["nb2plots", "sphinx.ext.doctest"]' nb2plots-0.6/nb2plots/testing/convutils.py0000644000076500000240000000451213235401241020706 0ustar mb312staff00000000000000""" 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.6/nb2plots/testing/mockapp.py0000644000076500000240000000050113235401241020304 0ustar mb312staff00000000000000""" 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.6/nb2plots/testing/nbtesters.py0000644000076500000240000000070013235401241020664 0ustar mb312staff00000000000000""" Utils for testing notebooks """ from nb2plots.ipython_shim import nbf 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'] assert actual_nb == expected_nb nb2plots-0.6/nb2plots/tests/0000755000076500000240000000000013235422500015772 5ustar mb312staff00000000000000nb2plots-0.6/nb2plots/tests/__init__.py0000644000076500000240000000003113027544026020104 0ustar mb312staff00000000000000# nb2plots.tests package nb2plots-0.6/nb2plots/tests/conftest.py0000644000076500000240000000037713235401241020177 0ustar mb312staff00000000000000""" Configuration for py.test test run """ def pytest_ignore_collect(path, config): """ Skip the origin Gohlke transforms for doctests. That file needs some specific doctest setup. """ return path.basename in ('conf.py', 'rst_md_files') nb2plots-0.6/nb2plots/tests/data/0000755000076500000240000000000013235422500016703 5ustar mb312staff00000000000000nb2plots-0.6/nb2plots/tests/data/converted_example.rst0000644000076500000240000000076013031546453023154 0ustar mb312staff00000000000000 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.6/nb2plots/tests/data/converted_plus_notebooks.ipynb0000644000076500000240000000157313031546453025103 0ustar mb312staff00000000000000{ "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.6/nb2plots/tests/data/converted_plus_notebooks.py0000644000076500000240000000060213031546453024402 0ustar mb312staff00000000000000# ## 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.6/nb2plots/tests/data/example_notebook.ipynb0000644000076500000240000003353113031546453023316 0ustar mb312staff00000000000000{ "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\nalrm34F3gKZmtsrMrjGzG8zs+qIiPhVYbmafAk8CXVPxvNli+3Z44glo2hQWLYIpU+CNN+Dqq+Gg\ngxJ7rP33h44dYeJEWLAANm+GI46A//ov2Lo1LfFFJCZSMqTjnOtchmtuTsVzZZv5831hr1kTXn4Z\njj8+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OUV9Hb8QKgfeAoZXUycH7ROPhzwGlmNiJwpoQ459YWfdwATCReW6esAVY7\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.6/nb2plots/tests/data/small.ipynb0000644000076500000240000014064413027544026021076 0ustar mb312staff00000000000000{ "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", "W5xPkpZWwgpwDrATuAzYVcW+cT9P26KeV2tdD7CBta4H2MBa1wNsYK3rATax1vUAG1jreoANrHU9\n", "wAbWZvmLbVbRW/pczd7NBIZKVZtNcUlaYONUdNt1c9GLWpJmZpIVPcwXZZKkbUpYSTgPuBX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rPm2eQ04veNRTgbOTHIfgxp7W5LP\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/AgxBgj8UVZXrTgC8uatElDBFpbtMa1tmKoAqFHQ1oeFFawC2olFpBCNK1UYkNx+ffF\n", "3MhwOGfnnnNm5r5n5vtJTs6Z3XvO/nN299rvuXZmrlQVkqT+Wul6AEnS/rlQS1LPuVBLUs+5UEtS\n", "z7lQS1LPuVBLUs+1WqiTXJjk7ubtgmkPJ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JM8F3lJVVwNU1S+r6n86Hmu904AfVtUDI6+cvgOAw5LsAA5l8A9I\n", "l14N3FJVj1fVPuAbwHs2u3i7f/DGeTKMGkleyaD4b+12kl9tMdwJPAzcUFW3dz0TcDnwMXrwj8aQ\n", "Ar6e5PYkH+p6GOBY4KdJrm62Ga5IckjXQ63zXuDzXQ9RVQ8BnwLuB34M/Kyqbux2Kr4LvDXJC5Ic\n", "yiBMXrHZxdtdqMd5MoyAJIcDu4ELm7LuVFU9WVWvB44C3pjkNV3Ok+SdwCPNdx9h4z9jXXhzVb2B\n", "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": 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/2OuA5r7c/ti11W21a9u95\n", "HfDvve7mx9ky5597HfAfvw5D6bupbePo0jXcNwD4BiL6EIA/C+AHAICIXkhEb15s/h0A/zsRPQLg\n", "FwD8d8z86IXjTk1NTd1zuijDZeZP4gRaXf8eAH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NXUkTuFNTU1NX0v8PO5GQprdkcNkAAAAASUVORK5C\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.6/nb2plots/tests/data/small.rst0000644000076500000240000000225613027544026020561 0ustar mb312staff00000000000000 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.6/nb2plots/tests/otherpages/0000755000076500000240000000000013235422500020133 5ustar mb312staff00000000000000nb2plots-0.6/nb2plots/tests/otherpages/some_plots.rst0000644000076500000240000000234213027544026023061 0ustar mb312staff00000000000000########## 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.6/nb2plots/tests/proj1/0000755000076500000240000000000013235422500017025 5ustar mb312staff00000000000000nb2plots-0.6/nb2plots/tests/proj1/.gitignore0000644000076500000240000000001013027544026021013 0ustar mb312staff00000000000000_build/ nb2plots-0.6/nb2plots/tests/proj1/_static/0000755000076500000240000000000013235422500020453 5ustar mb312staff00000000000000nb2plots-0.6/nb2plots/tests/proj1/_static/.gitignore0000644000076500000240000000000013027544026022440 0ustar mb312staff00000000000000nb2plots-0.6/nb2plots/tests/proj1/_static/README.txt0000644000076500000240000000046213027544026022162 0ustar mb312staff00000000000000############################### 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.6/nb2plots/tests/proj1/a_page.rst0000644000076500000240000000024313234613257021004 0ustar mb312staff00000000000000######### A section ######### Some text. :clearnotebook:`notebook here` More text. :fullnotebook:`full ` Text is endless. :pyfile:`code here` nb2plots-0.6/nb2plots/tests/proj1/conf.py0000644000076500000240000002024413031546453020336 0ustar mb312staff00000000000000# -*- 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 from distutils.version import LooseVersion # 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. if LooseVersion(sphinx.__version__) >= LooseVersion('1.3'): html_theme = 'classic' else: html_theme = 'default' # 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.6/nb2plots/tests/proj1/index.rst0000644000076500000240000000064613027544026020703 0ustar mb312staff00000000000000.. 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.6/nb2plots/tests/proj1/README.md0000644000076500000240000000016113027544026020311 0ustar mb312staff00000000000000# Test project for sphinx extensions A tiny sphinx project from ``sphinx-quickstart`` with all default answers. nb2plots-0.6/nb2plots/tests/rst_md_files/0000755000076500000240000000000013235422500020444 5ustar mb312staff00000000000000nb2plots-0.6/nb2plots/tests/rst_md_files/blockquotes.ipynb0000644000076500000240000000105113027544026024046 0ustar mb312staff00000000000000{ "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.6/nb2plots/tests/rst_md_files/blockquotes.md0000644000076500000240000000052013027544026023325 0ustar mb312staff00000000000000> 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.6/nb2plots/tests/rst_md_files/blockquotes.py0000644000076500000240000000053613031546453023365 0ustar mb312staff00000000000000# > 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.6/nb2plots/tests/rst_md_files/blockquotes.rst0000644000076500000240000000053213027544026023540 0ustar mb312staff00000000000000 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.6/nb2plots/tests/rst_md_files/code.ipynb0000644000076500000240000000072213027544026022431 0ustar mb312staff00000000000000{ "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.6/nb2plots/tests/rst_md_files/code.md0000644000076500000240000000024713027544026021712 0ustar mb312staff00000000000000Here 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.6/nb2plots/tests/rst_md_files/code.py0000644000076500000240000000030513031546453021736 0ustar mb312staff00000000000000# 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.6/nb2plots/tests/rst_md_files/code.rst0000644000076500000240000000030713027544026022117 0ustar mb312staff00000000000000Here 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.6/nb2plots/tests/rst_md_files/comment.ipynb0000644000076500000240000000042513027544026023161 0ustar mb312staff00000000000000{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "Some text\n", "\n", "\n", "More text." ] } ], "metadata": {}, "nbformat": 4, "nbformat_minor": 1 }nb2plots-0.6/nb2plots/tests/rst_md_files/comment.md0000644000076500000240000000010513027544026022433 0ustar mb312staff00000000000000Some text More text. nb2plots-0.6/nb2plots/tests/rst_md_files/comment.py0000644000076500000240000000012113031546453022462 0ustar mb312staff00000000000000# Some text # # # More text. nb2plots-0.6/nb2plots/tests/rst_md_files/comment.rst0000644000076500000240000000010613027544026022644 0ustar mb312staff00000000000000Some text .. A multiline comment with blank lines More text. nb2plots-0.6/nb2plots/tests/rst_md_files/cross_references.ipynb0000644000076500000240000000111213031546453025044 0ustar mb312staff00000000000000{ "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.6/nb2plots/tests/rst_md_files/cross_references.md0000644000076500000240000000000513031546453024323 0ustar mb312staff00000000000000skip nb2plots-0.6/nb2plots/tests/rst_md_files/cross_references.py0000644000076500000240000000052113031546453024356 0ustar mb312staff00000000000000# ## 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.6/nb2plots/tests/rst_md_files/cross_references.rst0000644000076500000240000000067213031546453024545 0ustar mb312staff00000000000000.. _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.6/nb2plots/tests/rst_md_files/cross_references.smd0000644000076500000240000000047313031546453024517 0ustar mb312staff00000000000000## 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.6/nb2plots/tests/rst_md_files/definitions.ipynb0000644000076500000240000000072013027544026024030 0ustar mb312staff00000000000000{ "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.6/nb2plots/tests/rst_md_files/definitions.md0000644000076500000240000000032313027544026023306 0ustar mb312staff00000000000000Start 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.6/nb2plots/tests/rst_md_files/definitions.py0000644000076500000240000000034613031546453023344 0ustar mb312staff00000000000000# 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.6/nb2plots/tests/rst_md_files/definitions.rst0000644000076500000240000000032113027544026023514 0ustar mb312staff00000000000000Start 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.6/nb2plots/tests/rst_md_files/docinfo.ipynb0000644000076500000240000000227013027544026023140 0ustar mb312staff00000000000000{ "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.6/nb2plots/tests/rst_md_files/docinfo.md0000644000076500000240000000113713027544026022420 0ustar mb312staff00000000000000% 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.6/nb2plots/tests/rst_md_files/docinfo.py0000644000076500000240000000133113031546453022445 0ustar mb312staff00000000000000# ## 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.6/nb2plots/tests/rst_md_files/docinfo.rst0000644000076500000240000000113713027544026022630 0ustar mb312staff00000000000000Docinfo 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.6/nb2plots/tests/rst_md_files/docinfo.smd0000644000076500000240000000122513027544026022601 0ustar mb312staff00000000000000## 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.6/nb2plots/tests/rst_md_files/doctests.ipynb0000644000076500000240000000165213031546453023353 0ustar mb312staff00000000000000{ "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.6/nb2plots/tests/rst_md_files/doctests.md0000644000076500000240000000045313031546453022630 0ustar mb312staff00000000000000Here 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.6/nb2plots/tests/rst_md_files/doctests.py0000644000076500000240000000033713031546453022661 0ustar mb312staff00000000000000# 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.6/nb2plots/tests/rst_md_files/doctests.rst0000644000076500000240000000040113031546453023031 0ustar mb312staff00000000000000Here 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.6/nb2plots/tests/rst_md_files/escaping.ipynb0000644000076500000240000000071313031546453023311 0ustar mb312staff00000000000000{ "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.6/nb2plots/tests/rst_md_files/escaping.md0000644000076500000240000000030013031546453022560 0ustar mb312staff00000000000000Here 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.6/nb2plots/tests/rst_md_files/escaping.py0000644000076500000240000000032513031546453022617 0ustar mb312staff00000000000000# 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.6/nb2plots/tests/rst_md_files/escaping.rst0000644000076500000240000000031713031546453023000 0ustar mb312staff00000000000000Here 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.6/nb2plots/tests/rst_md_files/index.ipynb0000644000076500000240000000035013031546453022624 0ustar mb312staff00000000000000{ "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.6/nb2plots/tests/rst_md_files/index.md0000644000076500000240000000000513031546453022100 0ustar mb312staff00000000000000skip nb2plots-0.6/nb2plots/tests/rst_md_files/index.py0000644000076500000240000000011113031546453022126 0ustar mb312staff00000000000000# This is a normal reST paragraph that contains several index # entries. nb2plots-0.6/nb2plots/tests/rst_md_files/index.rst0000644000076500000240000000015413031546453022315 0ustar mb312staff00000000000000This is a normal reST :index:`paragraph` that contains several :index:`index entries `. nb2plots-0.6/nb2plots/tests/rst_md_files/index.smd0000644000076500000240000000010513031546453022264 0ustar mb312staff00000000000000This is a normal reST paragraph that contains several index entries. nb2plots-0.6/nb2plots/tests/rst_md_files/links.ipynb0000644000076500000240000000070013027544027022634 0ustar mb312staff00000000000000{ "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.6/nb2plots/tests/rst_md_files/links.md0000644000076500000240000000031213027544027022112 0ustar mb312staff00000000000000# 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.6/nb2plots/tests/rst_md_files/links.py0000644000076500000240000000033513031546453022147 0ustar mb312staff00000000000000# ## 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.6/nb2plots/tests/rst_md_files/links.rst0000644000076500000240000000041413027544027022325 0ustar mb312staff00000000000000.. _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.6/nb2plots/tests/rst_md_files/links.smd0000644000076500000240000000031413027544027022277 0ustar mb312staff00000000000000## 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.6/nb2plots/tests/rst_md_files/lists.ipynb0000644000076500000240000000156313027544027022662 0ustar mb312staff00000000000000{ "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.6/nb2plots/tests/rst_md_files/lists.md0000644000076500000240000000103413027544027022132 0ustar mb312staff000000000000001. 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.6/nb2plots/tests/rst_md_files/lists.py0000644000076500000240000000107713031546453022171 0ustar mb312staff00000000000000# 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.6/nb2plots/tests/rst_md_files/lists.rst0000644000076500000240000000104313027544027022342 0ustar mb312staff000000000000001. 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.6/nb2plots/tests/rst_md_files/literals.ipynb0000644000076500000240000000107413031546453023340 0ustar mb312staff00000000000000{ "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.6/nb2plots/tests/rst_md_files/literals.md0000644000076500000240000000044313031546453022616 0ustar mb312staff00000000000000# 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.6/nb2plots/tests/rst_md_files/literals.py0000644000076500000240000000047513031546453022653 0ustar mb312staff00000000000000# ## 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.6/nb2plots/tests/rst_md_files/literals.rst0000644000076500000240000000047113031546453023027 0ustar mb312staff00000000000000############# 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.6/nb2plots/tests/rst_md_files/literals.smd0000644000076500000240000000044413031546453023002 0ustar mb312staff00000000000000## 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.6/nb2plots/tests/rst_md_files/math_markup.ipynb0000644000076500000240000000056213032241430024016 0ustar mb312staff00000000000000{ "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.6/nb2plots/tests/rst_md_files/math_markup.md0000644000076500000240000000016413032241430023273 0ustar mb312staff00000000000000# Title Some text with $a = 1$ where line continues. A math block: $$ c = 2 d = 5 $$ Text after the math block. nb2plots-0.6/nb2plots/tests/rst_md_files/math_markup.py0000644000076500000240000000021113032241430023314 0ustar mb312staff00000000000000# ## Title # # Some text with $a = 1$ where line continues. # # A math block: # # $$ # c = 2 # d = 5 # $$ # # Text after the math block. nb2plots-0.6/nb2plots/tests/rst_md_files/math_markup.rst0000644000076500000240000000021313032241430023476 0ustar mb312staff00000000000000Title ##### Some text with :math:`a = 1` where line continues. A math block: .. math:: c = 2 d = 5 Text after the math block. nb2plots-0.6/nb2plots/tests/rst_md_files/math_markup.smd0000644000076500000240000000016513032241430023457 0ustar mb312staff00000000000000## Title Some text with $a = 1$ where line continues. A math block: $$ c = 2 d = 5 $$ Text after the math block. nb2plots-0.6/nb2plots/tests/rst_md_files/nbplot.ipynb0000644000076500000240000000331213154332274023014 0ustar mb312staff00000000000000{ "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.6/nb2plots/tests/rst_md_files/nbplot.md0000644000076500000240000000000513031546453022267 0ustar mb312staff00000000000000skip nb2plots-0.6/nb2plots/tests/rst_md_files/nbplot.py0000644000076500000240000000107013154331144022315 0ustar mb312staff00000000000000# ## 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.6/nb2plots/tests/rst_md_files/nbplot.rst0000644000076500000240000000126013154331362022500 0ustar mb312staff00000000000000########### 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.6/nb2plots/tests/rst_md_files/nbplot.smd0000644000076500000240000000120513154331235022451 0ustar mb312staff00000000000000## 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.6/nb2plots/tests/rst_md_files/only.ipynb0000644000076500000240000000044613031546453022504 0ustar mb312staff00000000000000{ "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.6/nb2plots/tests/rst_md_files/only.md0000644000076500000240000000000513031546453021752 0ustar mb312staff00000000000000skip nb2plots-0.6/nb2plots/tests/rst_md_files/only.py0000644000076500000240000000014113031546453022003 0ustar mb312staff00000000000000# Text. # # After HTML-specific text. # # Specific to Markdown # # After Markdown-specific text. nb2plots-0.6/nb2plots/tests/rst_md_files/only.rst0000644000076500000240000000022413031546453022165 0ustar mb312staff00000000000000Text. .. only:: html Specific to HTML After HTML-specific text. .. only:: markdown Specific to Markdown After Markdown-specific text. nb2plots-0.6/nb2plots/tests/rst_md_files/only.smd0000644000076500000240000000012613031546453022141 0ustar mb312staff00000000000000Text. After HTML-specific text. Specific to Markdown After Markdown-specific text. nb2plots-0.6/nb2plots/tests/rst_md_files/sect_text.ipynb0000644000076500000240000000030713027544027023521 0ustar mb312staff00000000000000{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "## A section\n", "\n", "Some *text*." ] } ], "metadata": {}, "nbformat": 4, "nbformat_minor": 1 }nb2plots-0.6/nb2plots/tests/rst_md_files/sect_text.md0000644000076500000240000000003213027544027022773 0ustar mb312staff00000000000000# A section Some *text*. nb2plots-0.6/nb2plots/tests/rst_md_files/sect_text.py0000644000076500000240000000004013031546453023022 0ustar mb312staff00000000000000# ## A section # # Some *text*. nb2plots-0.6/nb2plots/tests/rst_md_files/sect_text.rst0000644000076500000240000000005413027544027023207 0ustar mb312staff00000000000000######### A section ######### Some *text*. nb2plots-0.6/nb2plots/tests/rst_md_files/sect_text.smd0000644000076500000240000000003313027544027023157 0ustar mb312staff00000000000000## A section Some *text*. nb2plots-0.6/nb2plots/tests/rst_md_files/sections.ipynb0000644000076500000240000000130613027544027023346 0ustar mb312staff00000000000000{ "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.6/nb2plots/tests/rst_md_files/sections.md0000644000076500000240000000042713027544027022630 0ustar mb312staff00000000000000# 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.6/nb2plots/tests/rst_md_files/sections.py0000644000076500000240000000051513031546453022656 0ustar mb312staff00000000000000# ## 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.6/nb2plots/tests/rst_md_files/sections.rst0000644000076500000240000000063013027544027023034 0ustar mb312staff00000000000000########### 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.6/nb2plots/tests/rst_md_files/sections.smd0000644000076500000240000000043613027544027023013 0ustar mb312staff00000000000000## 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.6/nb2plots/tests/rst_md_files/substitution.ipynb0000644000076500000240000000031213031546453024267 0ustar mb312staff00000000000000{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "Here is a some *actual* text substituted value." ] } ], "metadata": {}, "nbformat": 4, "nbformat_minor": 2 }nb2plots-0.6/nb2plots/tests/rst_md_files/substitution.md0000644000076500000240000000006013031546453023546 0ustar mb312staff00000000000000Here is a some *actual* text substituted value. nb2plots-0.6/nb2plots/tests/rst_md_files/substitution.py0000644000076500000240000000006213031546453023600 0ustar mb312staff00000000000000# Here is a some *actual* text substituted value. nb2plots-0.6/nb2plots/tests/rst_md_files/substitution.rst0000644000076500000240000000012613031546453023761 0ustar mb312staff00000000000000Here is a |subst-var| substituted value. .. |subst-var| replace:: some *actual* text nb2plots-0.6/nb2plots/tests/rst_md_files/subtitle.ipynb0000644000076500000240000000044413027544027023354 0ustar mb312staff00000000000000{ "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.6/nb2plots/tests/rst_md_files/subtitle.md0000644000076500000240000000007713027544027022635 0ustar mb312staff00000000000000# A title ## A subtitle Some text. ## A section More text. nb2plots-0.6/nb2plots/tests/rst_md_files/subtitle.py0000644000076500000240000000012013031546453022652 0ustar mb312staff00000000000000# ## A title # # ### A subtitle # # Some text. # # ### A section # # More text. nb2plots-0.6/nb2plots/tests/rst_md_files/subtitle.rst0000644000076500000240000000016113027544027023037 0ustar mb312staff00000000000000####### A title ####### ********** A subtitle ********** Some text. ********* A section ********* More text. nb2plots-0.6/nb2plots/tests/rst_md_files/subtitle.smd0000644000076500000240000000010213027544027023005 0ustar mb312staff00000000000000## A title ### A subtitle Some text. ### A section More text. nb2plots-0.6/nb2plots/tests/test_builders.py0000644000076500000240000001240013235401241021210 0ustar mb312staff00000000000000""" Tests for Markdown and other builders """ from __future__ import unicode_literals from os.path import join as pjoin, isfile 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 = ('extensions = ["nb2plots"]\n' 'markdown_http_base = "https://dynevor.org"') 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](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_page.rst). Then [another page](https://dynevor.org/_downloads/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). """ 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 = ('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:: """} def test_output(self): for suffix in ('.py', '.ipynb', '_full.ipynb'): assert isfile(pjoin(self.out_dir, 'foo', 'a_page' + suffix)) nb2plots-0.6/nb2plots/tests/test_codelinks.py0000644000076500000240000000726313235401241021365 0ustar mb312staff00000000000000""" 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("""\ 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("""\ 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("""\ 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("""\ 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.6/nb2plots/tests/test_config.py0000644000076500000240000000217513235401241020654 0ustar mb312staff00000000000000# -*- 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.6/nb2plots/tests/test_converters.py0000644000076500000240000000130113235401241021567 0ustar mb312staff00000000000000""" Test bare Converter class """ import re from nb2plots.converters import Converter 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(r"""
More fancy title <paragraph> More compelling text """, pxml) is not None �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������nb2plots-0.6/nb2plots/tests/test_doctree2md.py������������������������������������������������������0000644�0000765�0000024�00000005451�13235401241�021437� 0����������������������������������������������������������������������������������������������������ustar �mb312���������������������������staff���������������������������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 """ from __future__ import (division, print_function, absolute_import, unicode_literals) 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.6/nb2plots/tests/test_doctree2nb.py������������������������������������������������������0000644�0000765�0000024�00000010351�13235401241�021431� 0����������������������������������������������������������������������������������������������������ustar �mb312���������������������������staff���������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������""" Test conversion of doctree to Jupyter notebook """ from os.path import join as pjoin from glob import glob from nb2plots.converters import to_notebook from nb2plots.ipython_shim import nbf # 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 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 assert_rst_cells_equal(rst_text, cells): actual = to_notebook.from_rst(rst_text) expected = cells2json(cells) assert actual == 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.6/nb2plots/tests/test_doctree2py.py������������������������������������������������������0000644�0000765�0000024�00000002675�13235401241�021474� 0����������������������������������������������������������������������������������������������������ustar �mb312���������������������������staff���������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������""" Test conversion of Sphinx format ReST to Python .py files Test running writer over example files and chosen snippets. """ from __future__ import (division, print_function, absolute_import, unicode_literals) 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.6/nb2plots/tests/test_from_notebook.py���������������������������������������������������0000644�0000765�0000024�00000012221�13235401241�022243� 0����������������������������������������������������������������������������������������������������ustar �mb312���������������������������staff���������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������""" Testing from_notebook module """ from os.path import dirname, join as pjoin from ..ipython_shim import nbformat from ..from_notebook import (convert_nb, convert_nb_fname, to_doctests, has_mpl_inline, CODE_WITH_OUTPUT) 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 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 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 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 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 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 out + '\n' == 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.6/nb2plots/tests/test_mpl_interactive.py�������������������������������������������������0000644�0000765�0000024�00000002055�13235401241�022571� 0����������������������������������������������������������������������������������������������������ustar �mb312���������������������������staff���������������������������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.6/nb2plots/tests/test_nbplots.py���������������������������������������������������������0000644�0000765�0000024�00000063103�13235401241�021066� 0����������������������������������������������������������������������������������������������������ustar �mb312���������������������������staff���������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������""" Tests for build using nbplot extension """ from __future__ import unicode_literals from os.path import (join as pjoin, dirname, isdir) import re import os from docutils.nodes import paragraph, title from nb2plots.nbplots import (run_code, parse_parts, nbplot_container, nbplot_epilogue) from sphinxtesters import SourcesBuilder from nb2plots.testing import PlotsBuilder from nb2plots.testing.nbtesters import assert_nb_equiv import pytest HERE = dirname(__file__) 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"> <section ids="a-title" names="a\\ title"> <title> A title <target ids="a-ref" names="a-ref"> <nbplot_container> <doctest_block.*> >>> a = 1 <nbplot_epilogue> <.*> <paragraph> See\s <reference internal="True" refid="a-ref"> <inline.*?> the ref \.""", re.DOTALL) assert expected_regexp.match(built) class TestFlags(PlotsBuilder): """ Check flags get set correctly """ builder = 'pseudoxml' 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') assert """ <title> A title <literal_block xml:space="preserve"> {'a': 1, 'b': 2} <paragraph> Some text <literal_block xml:space="preserve"> {'a': 1, 'b': 2, 'c': 3}""" in 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') assert (""" <title> A title <literal_block xml:space="preserve"> {'a': 1, 'b': 2, 'flag1': 5, 'flag2': 6} <paragraph> Some text <literal_block xml:space="preserve"> {'a': 1, 'b': 2, 'c': 3, 'flag1': 5, 'flag2': 6}""" in 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 xml:space="preserve"> >>> # always >>> a = 'default' <nbplot_epilogue> <comment xml:space="preserve"> <comment xml:space="preserve"> <comment xml:space="preserve"> <paragraph> Some text <nbplot_container> <doctest_block xml:space="preserve"> >>> 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 xml:space="preserve"> >>> 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 xml:space="preserve"> >>> # doctest only run when skip flag False, always rendered >>> b == 'skip appears to be False' True""") 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 xml:space="preserve"> >>> # always >>> a = 'default' <nbplot_epilogue> <comment xml:space="preserve"> <comment xml:space="preserve"> <comment xml:space="preserve"> <paragraph> Some text <nbplot_container> <doctest_block xml:space="preserve"> >>> 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 xml:space="preserve"> >>> 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 xml:space="preserve"> >>> # only when skip flag True >>> b == 'skip appears to be True' True""") 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.6/nb2plots/tests/test_proj1.py�����������������������������������������������������������0000644�0000765�0000024�00000005234�13235401241�020441� 0����������������������������������������������������������������������������������������������������ustar �mb312���������������������������staff���������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������""" Tests for proj1 build using sphinx extensions """ from os.path import (join as pjoin, dirname, isdir, exists) from sphinxtesters import ModifiedPageBuilder HERE = dirname(__file__) PAGE_HEADER = """\ A title ======= """ class Proj1Builder(ModifiedPageBuilder): """ Build using 'proj1' directory as template to modify """ page_source_template = pjoin(HERE, 'proj1') # default_page used in 'replace_page' class method default_page = 'a_page.rst' 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.6/nb2plots/tests/test_regression.py0000644000076500000240000000205613235401241021565 0ustar mb312staff00000000000000""" 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.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 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.6/nb2plots/tests/test_runroles.py0000644000076500000240000001352613235401241021262 0ustar mb312staff00000000000000""" 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='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 ' '\(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.6/nb2plots/tests/test_scripts.py0000644000076500000240000000633713235401241021102 0ustar mb312staff00000000000000# 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 __future__ import division, print_function, absolute_import from os.path import (join as pjoin, exists) from glob import glob import re from scripttester import ScriptTester from nb2plots.testing import DATA_PATH from nb2plots.testing.convutils import fcontents, unsmart, unsmart_nb from nb2plots.testing.nbtesters import assert_nb_equiv runner = ScriptTester('nb2plots', win_bin_ext='.bat') run_command = runner.run_command 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_fname in glob(pjoin(DATA_PATH, '*.rst')): md_fname = rst_fname[:-3] + 'md' with open(md_fname, 'rb') as fobj: expected_md = fobj.read() # 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', rst_fname] 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_fname in glob(pjoin(DATA_PATH, '*.rst')): # Try .smd filename first, otherwise ordinary .md md_fname = rst_fname[:-3] + 'smd' if not exists(md_fname): md_fname = rst_fname[:-3] + 'md' expected_md = fcontents(md_fname) cmd = ['sphinx2md', rst_fname] 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_fname in glob(pjoin(DATA_PATH, '*.rst')): nb_fname = rst_fname[:-3] + 'ipynb' expected = fcontents(nb_fname, 't') cmd = ['sphinx2nb', rst_fname] 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_fname in glob(pjoin(DATA_PATH, '*.rst')): py_fname = rst_fname[:-3] + 'py' expected = fcontents(py_fname, 'b') cmd = ['sphinx2py', rst_fname] code, stdout, stderr = run_command(cmd) assert (unsmart(stdout.decode('utf-8')) == expected.decode('utf-8')) @script_test def test_sphinx2pxml(): rst_fname = pjoin(DATA_PATH, 'sect_text.rst') cmd = ['sphinx2pxml', rst_fname] code, stdout, stderr = run_command(cmd) pattern = r"""
A section <paragraph> Some <emphasis> text .""" output = stdout.decode('utf-8') assert re.match(pattern, output) �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������nb2plots-0.6/nb2plots/tests/test_sphinx2md.py�������������������������������������������������������0000644�0000765�0000024�00000002550�13235401241�021320� 0����������������������������������������������������������������������������������������������������ustar �mb312���������������������������staff���������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������""" Test conversion of Sphinx format ReST to Markdown Test running writer over example files and chosen snippets. """ from __future__ import (division, print_function, absolute_import, unicode_literals) 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.6/nb2plots/tests/test_strdiff.py���������������������������������������������������������0000644�0000765�0000024�00000001224�13235401241�021042� 0����������������������������������������������������������������������������������������������������ustar �mb312���������������������������staff���������������������������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.6/nb2plots/tests/test_timeout.py���������������������������������������������������������0000644�0000765�0000024�00000004522�13235401241�021073� 0����������������������������������������������������������������������������������������������������ustar �mb312���������������������������staff���������������������������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(2) """} 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(2) """} 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(2) """} 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(2) """} 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(3) """} ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������nb2plots-0.6/nb2plots.egg-info/���������������������������������������������������������������������0000755�0000765�0000024�00000000000�13235422500�016322� 5����������������������������������������������������������������������������������������������������ustar �mb312���������������������������staff���������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������nb2plots-0.6/nb2plots.egg-info/dependency_links.txt�������������������������������������������������0000644�0000765�0000024�00000000001�13235422500�022370� 0����������������������������������������������������������������������������������������������������ustar �mb312���������������������������staff���������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������ �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������nb2plots-0.6/nb2plots.egg-info/PKG-INFO�������������������������������������������������������������0000644�0000765�0000024�00000020265�13235422500�017424� 0����������������������������������������������������������������������������������������������������ustar �mb312���������������������������staff���������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������Metadata-Version: 1.1 Name: nb2plots Version: 0.6 Summary: Converting between ipython notebooks and sphinx docs Home-page: http://github.com/matthew-brett/nb2plots Author: Matthew Brett Author-email: matthew.brett@gmail.com License: BSD license Description-Content-Type: UNKNOWN Description: ################################################## 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.com/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. `travis-ci <https://travis-ci.org/matthew-brett/nb2plots>`_ kindly tests the code automatically under Python versions 2.7, and 3.3 through 3.5. 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.com/nb2plots/nbplots.html .. _code-links documentation: https://matthew-brett.github.com/nb2plots/code_links.html .. _worked example: https://matthew-brett.github.com/nb2plots/worked_example.html .. _documentation: https://matthew-brett.github.com/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 Platform: UNKNOWN Classifier: Development Status :: 2 - Pre-Alpha Classifier: Environment :: Console Classifier: Intended Audience :: Developers Classifier: Intended Audience :: Science/Research Classifier: License :: OSI Approved :: BSD License Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 3 Classifier: Topic :: Scientific/Engineering Classifier: Operating System :: Microsoft :: Windows Classifier: Operating System :: POSIX Classifier: Operating System :: Unix Classifier: Operating System :: MacOS �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������nb2plots-0.6/nb2plots.egg-info/requires.txt���������������������������������������������������������0000644�0000765�0000024�00000000203�13235422500�020715� 0����������������������������������������������������������������������������������������������������ustar �mb312���������������������������staff���������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������ipython[notebook]>=3.0 sphinx>=1.4 numpy>=1.6.1 matplotlib>=1.1.0 six>=1.7.0 sphinxtesters texext [test] pytest mock scripttester ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������nb2plots-0.6/nb2plots.egg-info/SOURCES.txt����������������������������������������������������������0000644�0000765�0000024�00000012657�13235422500�020221� 0����������������������������������������������������������������������������������������������������ustar �mb312���������������������������staff���������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������LICENSE MANIFEST.in README.rst doc-requirements.txt requirements.txt setup.cfg setup.py test-requirements.txt versioneer.py nb2plots/__init__.py nb2plots/_version.py nb2plots/codelinks.py nb2plots/commands.py nb2plots/converters.py nb2plots/doctree2md.py nb2plots/doctree2nb.py nb2plots/doctree2py.py nb2plots/from_notebook.py nb2plots/ipython_shim.py nb2plots/mpl_interactive.py nb2plots/nbplots.py nb2plots/runroles.py nb2plots/sphinx2foos.py nb2plots/strdiff.py nb2plots.egg-info/PKG-INFO nb2plots.egg-info/SOURCES.txt nb2plots.egg-info/dependency_links.txt nb2plots.egg-info/requires.txt nb2plots.egg-info/top_level.txt nb2plots/testing/__init__.py nb2plots/testing/convutils.py nb2plots/testing/mockapp.py nb2plots/testing/nbtesters.py nb2plots/tests/__init__.py nb2plots/tests/conftest.py nb2plots/tests/test_builders.py nb2plots/tests/test_codelinks.py nb2plots/tests/test_config.py nb2plots/tests/test_converters.py nb2plots/tests/test_doctree2md.py nb2plots/tests/test_doctree2nb.py nb2plots/tests/test_doctree2py.py nb2plots/tests/test_from_notebook.py nb2plots/tests/test_mpl_interactive.py nb2plots/tests/test_nbplots.py nb2plots/tests/test_proj1.py nb2plots/tests/test_regression.py nb2plots/tests/test_runroles.py nb2plots/tests/test_scripts.py nb2plots/tests/test_sphinx2md.py nb2plots/tests/test_strdiff.py nb2plots/tests/test_timeout.py nb2plots/tests/data/converted_example.rst nb2plots/tests/data/converted_plus_notebooks.ipynb nb2plots/tests/data/converted_plus_notebooks.py nb2plots/tests/data/example_notebook.ipynb nb2plots/tests/data/small.ipynb nb2plots/tests/data/small.rst nb2plots/tests/otherpages/some_plots.rst nb2plots/tests/proj1/.gitignore nb2plots/tests/proj1/README.md nb2plots/tests/proj1/a_page.rst nb2plots/tests/proj1/conf.py nb2plots/tests/proj1/index.rst nb2plots/tests/proj1/_static/.gitignore nb2plots/tests/proj1/_static/README.txt nb2plots/tests/rst_md_files/blockquotes.ipynb nb2plots/tests/rst_md_files/blockquotes.md nb2plots/tests/rst_md_files/blockquotes.py nb2plots/tests/rst_md_files/blockquotes.rst nb2plots/tests/rst_md_files/code.ipynb nb2plots/tests/rst_md_files/code.md nb2plots/tests/rst_md_files/code.py nb2plots/tests/rst_md_files/code.rst nb2plots/tests/rst_md_files/comment.ipynb nb2plots/tests/rst_md_files/comment.md nb2plots/tests/rst_md_files/comment.py nb2plots/tests/rst_md_files/comment.rst nb2plots/tests/rst_md_files/cross_references.ipynb nb2plots/tests/rst_md_files/cross_references.md nb2plots/tests/rst_md_files/cross_references.py nb2plots/tests/rst_md_files/cross_references.rst nb2plots/tests/rst_md_files/cross_references.smd nb2plots/tests/rst_md_files/definitions.ipynb nb2plots/tests/rst_md_files/definitions.md nb2plots/tests/rst_md_files/definitions.py nb2plots/tests/rst_md_files/definitions.rst nb2plots/tests/rst_md_files/docinfo.ipynb nb2plots/tests/rst_md_files/docinfo.md nb2plots/tests/rst_md_files/docinfo.py nb2plots/tests/rst_md_files/docinfo.rst nb2plots/tests/rst_md_files/docinfo.smd nb2plots/tests/rst_md_files/doctests.ipynb nb2plots/tests/rst_md_files/doctests.md nb2plots/tests/rst_md_files/doctests.py nb2plots/tests/rst_md_files/doctests.rst nb2plots/tests/rst_md_files/escaping.ipynb nb2plots/tests/rst_md_files/escaping.md nb2plots/tests/rst_md_files/escaping.py nb2plots/tests/rst_md_files/escaping.rst nb2plots/tests/rst_md_files/index.ipynb nb2plots/tests/rst_md_files/index.md nb2plots/tests/rst_md_files/index.py nb2plots/tests/rst_md_files/index.rst nb2plots/tests/rst_md_files/index.smd nb2plots/tests/rst_md_files/links.ipynb nb2plots/tests/rst_md_files/links.md nb2plots/tests/rst_md_files/links.py nb2plots/tests/rst_md_files/links.rst nb2plots/tests/rst_md_files/links.smd nb2plots/tests/rst_md_files/lists.ipynb nb2plots/tests/rst_md_files/lists.md nb2plots/tests/rst_md_files/lists.py nb2plots/tests/rst_md_files/lists.rst nb2plots/tests/rst_md_files/literals.ipynb nb2plots/tests/rst_md_files/literals.md nb2plots/tests/rst_md_files/literals.py nb2plots/tests/rst_md_files/literals.rst nb2plots/tests/rst_md_files/literals.smd nb2plots/tests/rst_md_files/math_markup.ipynb nb2plots/tests/rst_md_files/math_markup.md nb2plots/tests/rst_md_files/math_markup.py nb2plots/tests/rst_md_files/math_markup.rst nb2plots/tests/rst_md_files/math_markup.smd nb2plots/tests/rst_md_files/nbplot.ipynb nb2plots/tests/rst_md_files/nbplot.md nb2plots/tests/rst_md_files/nbplot.py nb2plots/tests/rst_md_files/nbplot.rst nb2plots/tests/rst_md_files/nbplot.smd nb2plots/tests/rst_md_files/only.ipynb nb2plots/tests/rst_md_files/only.md nb2plots/tests/rst_md_files/only.py nb2plots/tests/rst_md_files/only.rst nb2plots/tests/rst_md_files/only.smd nb2plots/tests/rst_md_files/sect_text.ipynb nb2plots/tests/rst_md_files/sect_text.md nb2plots/tests/rst_md_files/sect_text.py nb2plots/tests/rst_md_files/sect_text.rst nb2plots/tests/rst_md_files/sect_text.smd nb2plots/tests/rst_md_files/sections.ipynb nb2plots/tests/rst_md_files/sections.md nb2plots/tests/rst_md_files/sections.py nb2plots/tests/rst_md_files/sections.rst nb2plots/tests/rst_md_files/sections.smd nb2plots/tests/rst_md_files/substitution.ipynb nb2plots/tests/rst_md_files/substitution.md nb2plots/tests/rst_md_files/substitution.py nb2plots/tests/rst_md_files/substitution.rst nb2plots/tests/rst_md_files/subtitle.ipynb nb2plots/tests/rst_md_files/subtitle.md nb2plots/tests/rst_md_files/subtitle.py nb2plots/tests/rst_md_files/subtitle.rst nb2plots/tests/rst_md_files/subtitle.smd scripts/nb2plots scripts/rst2md scripts/sphinx2md scripts/sphinx2nb scripts/sphinx2pxml scripts/sphinx2py���������������������������������������������������������������������������������nb2plots-0.6/nb2plots.egg-info/top_level.txt��������������������������������������������������������0000644�0000765�0000024�00000000011�13235422500�021044� 0����������������������������������������������������������������������������������������������������ustar �mb312���������������������������staff���������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������nb2plots �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������nb2plots-0.6/PKG-INFO�������������������������������������������������������������������������������0000644�0000765�0000024�00000020265�13235422500�014167� 0����������������������������������������������������������������������������������������������������ustar �mb312���������������������������staff���������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������Metadata-Version: 1.1 Name: nb2plots Version: 0.6 Summary: Converting between ipython notebooks and sphinx docs Home-page: http://github.com/matthew-brett/nb2plots Author: Matthew Brett Author-email: matthew.brett@gmail.com License: BSD license Description-Content-Type: UNKNOWN Description: ################################################## 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.com/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. `travis-ci <https://travis-ci.org/matthew-brett/nb2plots>`_ kindly tests the code automatically under Python versions 2.7, and 3.3 through 3.5. 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.com/nb2plots/nbplots.html .. _code-links documentation: https://matthew-brett.github.com/nb2plots/code_links.html .. _worked example: https://matthew-brett.github.com/nb2plots/worked_example.html .. _documentation: https://matthew-brett.github.com/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 Platform: UNKNOWN Classifier: Development Status :: 2 - Pre-Alpha Classifier: Environment :: Console Classifier: Intended Audience :: Developers Classifier: Intended Audience :: Science/Research Classifier: License :: OSI Approved :: BSD License Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 3 Classifier: Topic :: Scientific/Engineering Classifier: Operating System :: Microsoft :: Windows Classifier: Operating System :: POSIX Classifier: Operating System :: Unix Classifier: Operating System :: MacOS �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������nb2plots-0.6/README.rst�����������������������������������������������������������������������������0000644�0000765�0000024�00000013715�13235422050�014563� 0����������������������������������������������������������������������������������������������������ustar �mb312���������������������������staff���������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������################################################## 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.com/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. `travis-ci <https://travis-ci.org/matthew-brett/nb2plots>`_ kindly tests the code automatically under Python versions 2.7, and 3.3 through 3.5. 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.com/nb2plots/nbplots.html .. _code-links documentation: https://matthew-brett.github.com/nb2plots/code_links.html .. _worked example: https://matthew-brett.github.com/nb2plots/worked_example.html .. _documentation: https://matthew-brett.github.com/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.6/requirements.txt�����������������������������������������������������������������������0000644�0000765�0000024�00000000173�13143700331�016351� 0����������������������������������������������������������������������������������������������������ustar �mb312���������������������������staff���������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# Minimum requirements # ipython[notebook]>=3.0 sphinx>=1.4 numpy>=1.6.1 matplotlib>=1.1.0 six>=1.7.0 sphinxtesters texext �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������nb2plots-0.6/scripts/�������������������������������������������������������������������������������0000755�0000765�0000024�00000000000�13235422500�014554� 5����������������������������������������������������������������������������������������������������ustar �mb312���������������������������staff���������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������nb2plots-0.6/scripts/nb2plots�����������������������������������������������������������������������0000755�0000765�0000024�00000001335�13152035171�016251� 0����������������������������������������������������������������������������������������������������ustar �mb312���������������������������staff���������������������������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 from __future__ import division, print_function, absolute_import from argparse import ArgumentParser from nb2plots.commands import bin_stdout 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' bin_stdout().write(rst_text.encode('utf-8')) if __name__ == '__main__': main() ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������nb2plots-0.6/scripts/rst2md�������������������������������������������������������������������������0000755�0000765�0000024�00000001060�13027544027�015722� 0����������������������������������������������������������������������������������������������������ustar �mb312���������������������������staff���������������������������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.6/scripts/sphinx2md����������������������������������������������������������������������0000755�0000765�0000024�00000000437�13031546453�016432� 0����������������������������������������������������������������������������������������������������ustar �mb312���������������������������staff���������������������������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.6/scripts/sphinx2nb����������������������������������������������������������������������0000755�0000765�0000024�00000000446�13031546453�016431� 0����������������������������������������������������������������������������������������������������ustar �mb312���������������������������staff���������������������������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.6/scripts/sphinx2pxml��������������������������������������������������������������������0000755�0000765�0000024�00000000450�13031546453�017005� 0����������������������������������������������������������������������������������������������������ustar �mb312���������������������������staff���������������������������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.6/scripts/sphinx2py����������������������������������������������������������������������0000755�0000765�0000024�00000000452�13031546453�016457� 0����������������������������������������������������������������������������������������������������ustar �mb312���������������������������staff���������������������������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.6/setup.cfg������������������������������������������������������������������������������0000644�0000765�0000024�00000000315�13235422500�014705� 0����������������������������������������������������������������������������������������������������ustar �mb312���������������������������staff���������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������[versioneer] vcs = git style = pep440 versionfile_source = nb2plots/_version.py versionfile_build = nb2plots/_version.py tag_prefix = "" parentdir_prefix = nb2plots- [egg_info] tag_build = tag_date = 0 �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������nb2plots-0.6/setup.py�������������������������������������������������������������������������������0000755�0000765�0000024�00000010242�13235401241�014600� 0����������������������������������������������������������������������������������������������������ustar �mb312���������������������������staff���������������������������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 import setuptools from distutils.core 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} ) ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������nb2plots-0.6/test-requirements.txt������������������������������������������������������������������0000644�0000765�0000024�00000000116�13235401241�017323� 0����������������������������������������������������������������������������������������������������ustar �mb312���������������������������staff���������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# Requirements for running tests -r requirements.txt pytest mock scripttester ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������nb2plots-0.6/versioneer.py��������������������������������������������������������������������������0000644�0000765�0000024�00000205753�13027544027�015644� 0����������������������������������������������������������������������������������������������������ustar �mb312���������������������������staff���������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������ # Version: 0.17 """The Versioneer - like a rocketeer, but for versions. The Versioneer ============== * like a rocketeer, but for versions! * https://github.com/warner/python-versioneer * Brian Warner * License: Public Domain * Compatible With: python2.6, 2.7, 3.2, 3.3, 3.4, 3.5, and pypy * [![Latest Version] (https://pypip.in/version/versioneer/badge.svg?style=flat) ](https://pypi.python.org/pypi/versioneer/) * [![Build Status] (https://travis-ci.org/warner/python-versioneer.png?branch=master) ](https://travis-ci.org/warner/python-versioneer) This is a tool for managing a recorded version number in distutils-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 to your $PATH * add a `[versioneer]` section to your setup.cfg (see below) * run `versioneer install` in your source tree, commit the results ## 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 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/warner/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 langauges) 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/warner/python-versioneer/issues/38) is tracking this issue. The discussion in [PR #61](https://github.com/warner/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/warner/python-versioneer/issues/83) describes this one, but upgrading to a newer version of setuptools should probably resolve it. ### Unicode version strings While Versioneer works (and is continually tested) with both Python 2 and Python 3, it is not entirely consistent with bytes-vs-unicode distinctions. Newer releases probably generate unicode version strings on py2. It's not clear that this is wrong, but it may be surprising for applications when then write these strings to a network connection or include them in bytes-oriented APIs like cryptographic checksums. [Bug #71](https://github.com/warner/python-versioneer/issues/71) investigates this question. ## 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. ## 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/ . """ from __future__ import print_function try: import configparser except ImportError: import ConfigParser as configparser import errno import json import os import re import subprocess import sys 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. me = os.path.realpath(os.path.abspath(__file__)) me_dir = os.path.normcase(os.path.splitext(me)[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(me), 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 EnvironmentError (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.SafeConfigParser() with open(setup_cfg, "r") as f: parser.readfp(f) VCS = parser.get("versioneer", "VCS") # mandatory def get(parser, name): if parser.has_option("versioneer", name): return parser.get("versioneer", name) return None cfg = VersioneerConfig() cfg.VCS = VCS cfg.style = get(parser, "style") or "" cfg.versionfile_source = get(parser, "versionfile_source") cfg.versionfile_build = get(parser, "versionfile_build") cfg.tag_prefix = get(parser, "tag_prefix") if cfg.tag_prefix in ("''", '""'): cfg.tag_prefix = "" cfg.parentdir_prefix = get(parser, "parentdir_prefix") cfg.verbose = get(parser, "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 = {} HANDLERS = {} def register_vcs_handler(vcs, method): # decorator """Decorator to mark a method as the handler for a particular 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) p = None for c in commands: try: dispcmd = str([c] + args) # remember shell=False, so use git.cmd on windows, not just git p = subprocess.Popen([c] + args, cwd=cwd, env=env, stdout=subprocess.PIPE, stderr=(subprocess.PIPE if hide_stderr else None)) break except EnvironmentError: 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 = p.communicate()[0].strip() if sys.version_info[0] >= 3: stdout = stdout.decode() if p.returncode != 0: if verbose: print("unable to run %s (error)" % dispcmd) print("stdout was %s" % stdout) return None, p.returncode return stdout, p.returncode LONG_VERSION_PY['git'] = ''' # 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.17 (https://github.com/warner/python-versioneer) """Git implementation of _version.py.""" import errno import os import re import subprocess import sys 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 = {} HANDLERS = {} def register_vcs_handler(vcs, method): # decorator """Decorator to mark a method as the handler for a particular 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) p = None for c in commands: try: dispcmd = str([c] + args) # remember shell=False, so use git.cmd on windows, not just git p = subprocess.Popen([c] + args, cwd=cwd, env=env, stdout=subprocess.PIPE, stderr=(subprocess.PIPE if hide_stderr else None)) break except EnvironmentError: 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 = p.communicate()[0].strip() if sys.version_info[0] >= 3: stdout = stdout.decode() if p.returncode != 0: if verbose: print("unable to run %%s (error)" %% dispcmd) print("stdout was %%s" %% stdout) return None, p.returncode return stdout, p.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 i 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} else: 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: f = open(versionfile_abs, "r") for line in f.readlines(): 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) f.close() except EnvironmentError: pass return keywords @register_vcs_handler("git", "keywords") def git_versions_from_keywords(keywords, tag_prefix, verbose): """Get version information from git keywords.""" if not keywords: raise NotThisMethod("no keywords at all, weird") date = keywords.get("date") if date is not None: # 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 = set([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 = set([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 = set([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):] 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, run_command=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"] out, rc = run_command(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") # 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 = run_command(GITS, ["describe", "--tags", "--dirty", "--always", "--long", "--match", "%%s*" %% tag_prefix], 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 = run_command(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 # 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: # unparseable. 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 = run_command(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 = run_command(GITS, ["show", "-s", "--format=%%ci", "HEAD"], cwd=root)[0].strip() 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_pre(pieces): """TAG[.post.devDISTANCE] -- No -dirty. Exceptions: 1: no tags. 0.post.devDISTANCE """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"]: rendered += ".post.dev%%d" %% pieces["distance"] else: # exception #1 rendered = "0.post.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_old(pieces): """TAG[.postDISTANCE[.dev0]] . The ".dev0" means dirty. Eexceptions: 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-pre": rendered = render_pep440_pre(pieces) elif style == "pep440-post": rendered = render_pep440_post(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 i 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: f = open(versionfile_abs, "r") for line in f.readlines(): 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) f.close() except EnvironmentError: pass return keywords @register_vcs_handler("git", "keywords") def git_versions_from_keywords(keywords, tag_prefix, verbose): """Get version information from git keywords.""" if not keywords: raise NotThisMethod("no keywords at all, weird") date = keywords.get("date") if date is not None: # 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 = set([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 = set([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 = set([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):] 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, run_command=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"] out, rc = run_command(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") # 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 = run_command(GITS, ["describe", "--tags", "--dirty", "--always", "--long", "--match", "%s*" % tag_prefix], 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 = run_command(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 # 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: # unparseable. 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 = run_command(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 = run_command(GITS, ["show", "-s", "--format=%ci", "HEAD"], cwd=root)[0].strip() 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: me = __file__ if me.endswith(".pyc") or me.endswith(".pyo"): me = os.path.splitext(me)[0] + ".py" versioneer_file = os.path.relpath(me) except NameError: versioneer_file = "versioneer.py" files.append(versioneer_file) present = False try: f = open(".gitattributes", "r") for line in f.readlines(): if line.strip().startswith(versionfile_source): if "export-subst" in line.strip().split()[1:]: present = True f.close() except EnvironmentError: pass if not present: f = open(".gitattributes", "a+") f.write("%s export-subst\n" % versionfile_source) f.close() 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 i 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} else: 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.17) 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 EnvironmentError: 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_pre(pieces): """TAG[.post.devDISTANCE] -- No -dirty. Exceptions: 1: no tags. 0.post.devDISTANCE """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"]: rendered += ".post.dev%d" % pieces["distance"] else: # exception #1 rendered = "0.post.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_old(pieces): """TAG[.postDISTANCE[.dev0]] . The ".dev0" means dirty. Eexceptions: 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-pre": rendered = render_pep440_pre(pieces) elif style == "pep440-post": rendered = render_pep440_post(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(): """Get the custom setuptools/distutils subclasses used by Versioneer.""" 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/warner/python-versioneer/issues/52 cmds = {} # we add "version" to both distutils and setuptools 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 "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 "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? try: from py2exe.distutils_buildexe import py2exe as _py2exe # py3 except ImportError: from py2exe.build_exe import py2exe as _py2exe # py2 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 "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 = """ INIT_PY_SNIPPET = """ from ._version import get_versions __version__ = get_versions()['version'] del get_versions """ def do_setup(): """Main VCS-independent setup function for installing Versioneer.""" root = get_root() try: cfg = get_config_from_root(root) except (EnvironmentError, configparser.NoSectionError, configparser.NoOptionError) as e: if isinstance(e, (EnvironmentError, 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 EnvironmentError: old = "" if INIT_PY_SNIPPET not in old: print(" appending to %s" % ipy) with open(ipy, "a") as f: f.write(INIT_PY_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 EnvironmentError: 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) �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������