Skip to content

Commit

Permalink
Merge pull request #40 from datarootsio/pager-and-kernelname
Browse files Browse the repository at this point in the history
Add pager option and display kernel name when showing notebooks
  • Loading branch information
murilo-cunha authored Oct 20, 2022
2 parents 0084a02 + 304fead commit eed4746
Show file tree
Hide file tree
Showing 6 changed files with 56 additions and 20 deletions.
13 changes: 10 additions & 3 deletions databooks/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -297,7 +297,9 @@ def fix(
"-i",
help="Interactively resolve the conflicts (not implemented)",
),
verbose: bool = Option(False, help="Log processed files in console"),
verbose: bool = Option(
False, "--verbose", "-v", help="Log processed files in console"
),
config: Optional[Path] = Option(
None,
"--config",
Expand Down Expand Up @@ -359,7 +361,12 @@ def show(
..., is_eager=True, help="Path(s) of notebook files with conflicts"
),
ignore: List[str] = Option(["!*"], help="Glob expression(s) of files to ignore"),
verbose: bool = Option(False, help="Increase verbosity for debugging"),
pager: bool = Option(
False, "--pager", "-p", help="Use pager instead of printing to terminal"
),
verbose: bool = Option(
False, "--verbose", "-v", help="Increase verbosity for debugging"
),
multiple: bool = Option(False, "--yes", "-y", help="Show multiple files"),
config: Optional[Path] = Option(
None,
Expand All @@ -385,7 +392,7 @@ def show(
if not Confirm.ask(f"Show {len(nb_paths)} notebooks?"):
raise Exit()

print_nbs(nb_paths)
print_nbs(nb_paths, use_pager=pager)


@app.command()
Expand Down
29 changes: 23 additions & 6 deletions databooks/data_models/notebook.py
Original file line number Diff line number Diff line change
Expand Up @@ -207,20 +207,37 @@ class JupyterNotebook(DatabooksBase, extra=Extra.forbid):
metadata: NotebookMetadata
cells: Cells[Cell]

def __rich__(self) -> RenderResult:
def __rich_console__(
self, console: Console, options: ConsoleOptions
) -> RenderResult:
"""Rich display notebook."""

def _rich(kernel: str) -> Text:
"""Display with `kernel` theme, horizontal padding and right-justified."""
return Text(kernel, style="kernel", justify="right")

kernelspec = self.metadata.dict().get("kernelspec", {})
# Check if this is a `DiffCells`
if isinstance(kernelspec, tuple):
first, last = (ks.get("language", "text") for ks in kernelspec)
nb_lang = first if first == last else "text"
if isinstance(kernelspec, tuple): # check if this is a `DiffCells`
lang_first, lang_last = (ks.get("language", "text") for ks in kernelspec)
nb_lang = lang_first if lang_first == lang_last else "text"
if any("display_name" in ks.keys() for ks in kernelspec):
kernel_first, kernel_last = [
_rich(ks["display_name"]) for ks in kernelspec
]
yield Columns(
[kernel_first, kernel_last],
expand=True,
width=options.max_width // 3,
) if kernel_first != kernel_last else kernel_first
else:
nb_lang = kernelspec.get("language", "text")
if "display_name" in kernelspec.keys():
yield _rich(kernelspec["display_name"])

for cell in self.cells:
if isinstance(cell, CodeCell):
cell.metadata = CellMetadata(**cell.metadata.dict(), lang=nb_lang)
return self.cells
yield self.cells

@classmethod
def parse_file(cls, path: Path | str, **parse_kwargs: Any) -> JupyterNotebook:
Expand Down
15 changes: 11 additions & 4 deletions databooks/tui.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""Terminal user interface (TUI) helper functions and components."""
from contextlib import nullcontext
from pathlib import Path
from typing import Any, List

Expand All @@ -7,7 +8,7 @@

from databooks import JupyterNotebook

DATABOOKS_TUI = Theme({"in_count": "blue", "out_count": "orange3", "error": "on red"})
DATABOOKS_TUI = Theme({"in_count": "blue", "out_count": "orange3", "kernel": "bold"})

databooks_console = Console(theme=DATABOOKS_TUI)

Expand All @@ -19,7 +20,13 @@ def print_nb(path: Path, console: Console = databooks_console) -> None:
console.print(notebook)


def print_nbs(paths: List[Path], **kwargs_print_nb: Any) -> None:
def print_nbs(
paths: List[Path],
console: Console = databooks_console,
use_pager: bool = False,
**kwargs_print_nb: Any
) -> None:
"""Show rich representation of notebooks in terminal."""
for path in paths:
print_nb(path, **kwargs_print_nb)
with console.pager(styles=True) if use_pager else nullcontext(): # type: ignore
for path in paths:
print_nb(path, console=console, **kwargs_print_nb)
5 changes: 3 additions & 2 deletions docs/CLI.md
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ $ databooks fix [OPTIONS] PATHS...
* `--cells-head / --no-cells-head`: Whether to keep the cells from the head/base notebook. Omit to keep both
* `--cell-fields-ignore TEXT`: Cell fields to remove before comparing cells [default: id, execution_count]
* `-i, --interactive`: Interactively resolve the conflicts (not implemented) [default: False]
* `--verbose / --no-verbose`: Log processed files in console [default: False]
* `-v, --verbose`: Log processed files in console [default: False]
* `-c, --config PATH`: Get CLI options from configuration file
* `--help`: Show this message and exit

Expand Down Expand Up @@ -167,7 +167,8 @@ $ databooks show [OPTIONS] PATHS...
**Options**:

* `--ignore TEXT`: Glob expression(s) of files to ignore [default: !*]
* `--verbose / --no-verbose`: Increase verbosity for debugging [default: False]
* `-p, --pager`: Use pager instead of printing to terminal [default: False]
* `-v, --verbose`: Increase verbosity for debugging [default: False]
* `-y, --yes`: Show multiple files [default: False]
* `-c, --config PATH`: Get CLI options from configuration file
* `--help`: Show this message and exit
Expand Down
1 change: 1 addition & 0 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -383,6 +383,7 @@ def test_show() -> None:
assert result.output == dedent(
"""\
──────────────────────────────── tui-demo.ipynb ────────────────────────────────
Python 3 (ipykernel)
╭──────────────────────────────────────────────────────────────────────────────╮
│ ╔══════════════════════════════════════════════════════════════════════════╗ │
│ ║ databooks demo! ║ │
Expand Down
13 changes: 8 additions & 5 deletions tests/test_tui.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@

from rich.console import Console, ConsoleRenderable

from databooks import JupyterNotebook
from databooks.data_models.cell import CellMetadata, RawCell
from databooks.data_models.notebook import JupyterNotebook, NotebookMetadata
from databooks.tui import print_nb
from tests.test_data_models.test_notebook import TestJupyterNotebook

Expand All @@ -14,6 +14,7 @@

rich_nb = dedent(
"""\
Python 3 (ipykernel)
╭────────────────────────────────────────────────╮
│ ╔════════════════════════════════════════════╗ │
│ ║ databooks demo! ║ │
Expand Down Expand Up @@ -183,7 +184,7 @@ def test_raw_cell() -> None:

def test_notebook() -> None:
"""Prints notebook (identical to printing all cells)."""
assert render(nb) == render(nb.cells) == rich_nb
assert render(nb) == rich_nb


def test_print_nb() -> None:
Expand All @@ -209,6 +210,7 @@ def test_diff_nb() -> None:
diff = notebook_1 - notebook_2
assert render(diff) == dedent(
"""\
kernel_display_name
In [1]:
╭────────────────────────────────────────────────╮
│ test_source │
Expand All @@ -232,6 +234,9 @@ def test_multiple_diff_nb() -> None:
"""Show rich representation of 'diff' notebook."""
notebook_1 = TestJupyterNotebook().jupyter_notebook
notebook_2 = TestJupyterNotebook().jupyter_notebook
notebook_2.metadata = NotebookMetadata(
kernelspec=dict(display_name="another_kernel", name="kernel_name"),
)
extra_cell = RawCell(
metadata=CellMetadata(random_meta=["meta"]),
source="extra",
Expand All @@ -245,11 +250,9 @@ def test_multiple_diff_nb() -> None:
notebook_2.cells = notebook_2.cells + [extra_cell, extra_cell, extra_cell]

diff = notebook_1 - notebook_2
from databooks.tui import databooks_console

databooks_console.print(diff)
assert render(diff) == dedent(
"""\
kernel_display_name another_kernel
In [1]:
╭────────────────────────────────────────────────╮
│ test_source │
Expand Down

0 comments on commit eed4746

Please sign in to comment.