Skip to content

Commit

Permalink
refactor: reformat the lib according to the new pre-commits
Browse files Browse the repository at this point in the history
  • Loading branch information
12rambau authored Dec 29, 2023
1 parent 51738b1 commit 402aeca
Show file tree
Hide file tree
Showing 11 changed files with 109 additions and 144 deletions.
17 changes: 6 additions & 11 deletions jupyter_sphinx/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,7 @@
from .execute import ExecuteJupyterCells, JupyterKernel
from .thebelab import ThebeButton, ThebeButtonNode, ThebeOutputNode, ThebeSourceNode

REQUIRE_URL_DEFAULT = (
"https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.4/require.min.js"
)
REQUIRE_URL_DEFAULT = "https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.4/require.min.js"
THEBELAB_URL_DEFAULT = "https://unpkg.com/thebelab@^0.4.0"

logger = logging.getLogger(__name__)
Expand Down Expand Up @@ -92,23 +90,20 @@ def visit_thebe_source(self, node):

# Sphinx callback functions
def builder_inited(app):
"""
"""Init the build.
2 cases
case 1: ipywidgets 7, with require
case 2: ipywidgets 7, no require
case 2: ipywidgets 7, no require.
"""
require_url = app.config.jupyter_sphinx_require_url
if require_url:
app.add_js_file(require_url)
embed_url = (
app.config.jupyter_sphinx_embed_url
or ipywidgets.embed.DEFAULT_EMBED_REQUIREJS_URL
app.config.jupyter_sphinx_embed_url or ipywidgets.embed.DEFAULT_EMBED_REQUIREJS_URL
)
else:
embed_url = (
app.config.jupyter_sphinx_embed_url
or ipywidgets.embed.DEFAULT_EMBED_SCRIPT_URL
)
embed_url = app.config.jupyter_sphinx_embed_url or ipywidgets.embed.DEFAULT_EMBED_SCRIPT_URL
if embed_url:
app.add_js_file(embed_url)

Expand Down
5 changes: 1 addition & 4 deletions jupyter_sphinx/_version.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
"""
store the current version info of the project.
"""
"""store the current version info of the project."""
import re
from typing import List

Expand Down
32 changes: 11 additions & 21 deletions jupyter_sphinx/ast.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
"""Manipulating the Sphinx AST with Jupyter objects"""
"""Manipulating the Sphinx AST with Jupyter objects."""

import json
import warnings
Expand Down Expand Up @@ -34,9 +34,7 @@ def load_content(cell, location, logger):
env.note_dependency(rel_filename)
if cell.content:
logger.warning(
'Ignoring inline code in Jupyter cell included from "{}"'.format(
rel_filename
),
'Ignoring inline code in Jupyter cell included from "{}"'.format(rel_filename),
location=location,
)
try:
Expand All @@ -60,9 +58,7 @@ def get_highlights(cell, content, location, logger):
hl_lines = parselinenos(emphasize_linespec, nlines)
if any(i >= nlines for i in hl_lines):
logger.warning(
"Line number spec is out of range(1-{}): {}".format(
nlines, emphasize_linespec
),
"Line number spec is out of range(1-{}): {}".format(nlines, emphasize_linespec),
location=location,
)
hl_lines = [i + 1 for i in hl_lines if i < nlines]
Expand All @@ -78,7 +74,7 @@ class JupyterCell(Directive):
executed when the directive is parsed, but later during a doctree
transformation.
Arguments
Arguments:
---------
filename : str (optional)
If provided, a path to a file containing code.
Expand Down Expand Up @@ -166,7 +162,7 @@ def run(self):
class CellInput(Directive):
"""Define a code cell to be included verbatim but not executed.
Arguments
Arguments:
---------
filename : str (optional)
If provided, a path to a file containing code.
Expand Down Expand Up @@ -237,7 +233,7 @@ def run(self):
class CellOutput(Directive):
"""Define an output cell to be included verbatim.
Arguments
Arguments:
---------
filename : str (optional)
If provided, a path to a file containing output.
Expand Down Expand Up @@ -323,12 +319,10 @@ def __init__(self, rawsource="", *children, **attributes):
super().__init__("", *children, mimetypes=attributes["mimetypes"])

def render_as(self, visitor):
"""Determine which node to show based on the visitor"""
"""Determine which node to show based on the visitor."""
try:
# Or should we go to config via the node?
priority = visitor.builder.env.app.config[
"render_priority_" + visitor.builder.format
]
priority = visitor.builder.env.app.config["render_priority_" + visitor.builder.format]
except (AttributeError, KeyError):
# Not sure what do to, act as a container and show everything just in case.
return super()
Expand Down Expand Up @@ -367,9 +361,7 @@ def __init__(self, rawsource="", *children, **attributes):
super().__init__("", view_spec=attributes["view_spec"])

def html(self):
return ipywidgets.embed.widget_view_template.format(
view_spec=json.dumps(self["view_spec"])
)
return ipywidgets.embed.widget_view_template.format(view_spec=json.dumps(self["view_spec"]))


class JupyterWidgetStateNode(docutils.nodes.Element):
Expand Down Expand Up @@ -414,7 +406,7 @@ def cell_output_to_nodes(outputs, write_stderr, out_dir, thebe_config, inline=Fa
inline: False
Whether the nodes will be placed in-line with the text.
Returns
Returns:
-------
to_add : list of docutils nodes
Each output, converted into a docutils node.
Expand Down Expand Up @@ -509,9 +501,7 @@ def output2sphinx(data, mime_type, metadata, out_dir, inline=False):
math_node = math_block

if mime_type == "text/html":
return docutils.nodes.raw(
text=data, format="html", classes=["output", "text_html"]
)
return docutils.nodes.raw(text=data, format="html", classes=["output", "text_html"])
elif mime_type == "text/plain":
return literal_node(
text=data,
Expand Down
51 changes: 25 additions & 26 deletions jupyter_sphinx/css/jupyter-sphinx.css
Original file line number Diff line number Diff line change
Expand Up @@ -23,15 +23,14 @@ After a build, this stylesheet is loaded from ./_static/jupyter-sphinx.css .
*/


div.jupyter_container {
padding: .4em;
margin: 0 0 .4em 0;
background-color: #FFFF;
border: 1px solid #CCC;
-moz-box-shadow: 2px 2px 4px rgba(87, 87, 87, 0.2);
-webkit-box-shadow: 2px 2px 4px rgba(87, 87, 87, 0.2);
box-shadow: 2px 2px 4px rgba(87, 87, 87, 0.2);
padding: 0.4em;
margin: 0 0 0.4em 0;
background-color: #ffff;
border: 1px solid #ccc;
-moz-box-shadow: 2px 2px 4px rgba(87, 87, 87, 0.2);
-webkit-box-shadow: 2px 2px 4px rgba(87, 87, 87, 0.2);
box-shadow: 2px 2px 4px rgba(87, 87, 87, 0.2);
}
.jupyter_container div.code_cell {
border: 1px solid #cfcfcf;
Expand Down Expand Up @@ -59,8 +58,8 @@ div.jupyter_container div.highlight {
background-color: #f7f7f7; /* for haiku */
}
div.jupyter_container {
padding: 0;
margin: 0;
padding: 0;
margin: 0;
}

/* Prevent alabaster breaking highlight alignment */
Expand All @@ -70,10 +69,10 @@ div.jupyter_container .hll {
}

/* overrides for sphinx_rtd_theme */
.rst-content .jupyter_container div[class^='highlight'],
.document .jupyter_container div[class^='highlight'],
.rst-content .jupyter_container div[class^="highlight"],
.document .jupyter_container div[class^="highlight"],
.rst-content .jupyter_container pre.literal-block {
border:none;
border: none;
margin: 0;
padding: 0;
background: none;
Expand All @@ -86,21 +85,21 @@ div.jupyter_container .hll {
text-align: center;
}
.jupyter_container .stderr {
background-color: #FCC;
border: none;
padding: 3px;
background-color: #fcc;
border: none;
padding: 3px;
}
.jupyter_container .output {
border: none;
border: none;
}
.jupyter_container div.output pre {
background-color: white;
background: none;
padding: 4px;
border: none;
box-shadow: none;
-webkit-box-shadow: none; /* for nature */
-moz-box-shadow: none; /* for nature */
background-color: white;
background: none;
padding: 4px;
border: none;
box-shadow: none;
-webkit-box-shadow: none; /* for nature */
-moz-box-shadow: none; /* for nature */
}
.jupyter_container .code_cell td.linenos {
text-align: right;
Expand All @@ -114,10 +113,10 @@ div.jupyter_container .hll {
/* combine sequential jupyter cells,
by moving sequential ones up higher on y-axis */
div.jupyter_container + div.jupyter_container {
margin: -.5em 0 .4em 0;
margin: -0.5em 0 0.4em 0;
}

/* Fix for sphinx_rtd_theme spacing after jupyter_container #91 */
.rst-content .jupyter_container {
margin: 0 0 24px 0;
margin: 0 0 24px 0;
}
24 changes: 6 additions & 18 deletions jupyter_sphinx/execute.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ def LoggerAdapterWrapper(logger_adapter):
class JupyterKernel(Directive):
"""Specify a new Jupyter Kernel.
Arguments
Arguments:
---------
kernel_name : str (optional)
The name of the kernel in which to execute future Jupyter cells, as
Expand Down Expand Up @@ -166,16 +166,10 @@ def apply(self):

# Raise error if cells raised exceptions and were not marked as doing so
for node, cell in zip(nodes, notebook.cells):
errors = [
output
for output in cell.outputs
if output["output_type"] == "error"
]
errors = [output for output in cell.outputs if output["output_type"] == "error"]
allowed_errors = node.attributes.get("raises") or []
raises_provided = node.attributes["raises"] is not None
if (
raises_provided and not allowed_errors
): # empty 'raises': suppress all errors
if raises_provided and not allowed_errors: # empty 'raises': suppress all errors
pass
elif errors and not any(e["ename"] in allowed_errors for e in errors):
raise ExtensionError(
Expand All @@ -192,9 +186,7 @@ def apply(self):
if output["output_type"] == "stream" and output["name"] == "stderr"
]
if stderr and not node.attributes["stderr"]:
js.logger.warning(
"Cell printed to stderr:\n{}".format(stderr[0]["text"])
)
js.logger.warning("Cell printed to stderr:\n{}".format(stderr[0]["text"]))

# Insert input/output into placeholders for non-executed cells
for node, cell in zip(nodes, notebook.cells):
Expand Down Expand Up @@ -224,9 +216,7 @@ def apply(self):
# The literal_block node with the source
source = node.children[0].children[0]
nlines = source.rawsource.count("\n") + 1
show_numbering = (
linenos_config or source["linenos"] or source["linenostart"]
)
show_numbering = linenos_config or source["linenos"] or source["linenostart"]

if show_numbering:
source["linenos"] = True
Expand All @@ -251,9 +241,7 @@ def apply(self):
# Write certain cell outputs (e.g. images) to separate files, and
# modify the metadata of the associated cells in 'notebook' to
# include the path to the output file.
write_notebook_output(
notebook, str(output_dir), file_name, self.env.docname
)
write_notebook_output(notebook, str(output_dir), file_name, self.env.docname)

try:
cm_language = notebook.metadata.language_info.codemirror_mode.name
Expand Down
19 changes: 8 additions & 11 deletions jupyter_sphinx/thebelab.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@


class ThebeSourceNode(docutils.nodes.container):
"""Container that holds the cell source when thebelab is enabled"""
"""Container that holds the cell source when thebelab is enabled."""

def __init__(self, rawsource="", *children, **attributes):
super().__init__("", **attributes)
Expand All @@ -30,7 +30,7 @@ def depart_html(self):


class ThebeOutputNode(docutils.nodes.container):
"""Container that holds all the output nodes when thebelab is enabled"""
"""Container that holds all the output nodes when thebelab is enabled."""

def visit_html(self):
return '<div class="thebelab-output" data-output="true">'
Expand All @@ -40,7 +40,7 @@ def depart_html(self):


class ThebeButtonNode(docutils.nodes.Element):
"""Appended to the doctree by the ThebeButton directive
"""Appended to the doctree by the ThebeButton directive.
Renders as a button to enable thebelab on the page.
Expand All @@ -61,9 +61,9 @@ def html(self):


class ThebeButton(Directive):
"""Specify a button to activate thebelab on the page
"""Specify a button to activate thebelab on the page.
Arguments
Arguments:
---------
text : str (optional)
If provided, the button text to display
Expand All @@ -83,7 +83,7 @@ def run(self):


def add_thebelab_library(doctree, env):
"""Adds the thebelab configuration and library to the doctree"""
"""Adds the thebelab configuration and library to the doctree."""
thebe_config = env.config.jupyter_sphinx_thebelab_config
if isinstance(thebe_config, dict):
pass
Expand All @@ -101,14 +101,11 @@ def add_thebelab_library(doctree, env):
try:
thebe_config = json.loads(filename.read_text())
except ValueError:
js.logger.warning(
"The supplied thebelab configuration file is not in JSON format."
)
js.logger.warning("The supplied thebelab configuration file is not in JSON format.")
return
else:
js.logger.warning(
"The supplied thebelab configuration should be either"
" a filename or a dictionary."
"The supplied thebelab configuration should be either" " a filename or a dictionary."
)
return

Expand Down
Loading

0 comments on commit 402aeca

Please sign in to comment.