Skip to content

Commit 4ff0eb3

Browse files
authored
Merge pull request #16 from ayasyrev/dev_0.2
v 0.2
2 parents bdbc9d0 + f83e94e commit 4ff0eb3

21 files changed

+213
-96
lines changed

noxfile.py

Lines changed: 3 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,8 @@
11
import nox
22

33

4-
@nox.session(python=["3.8", "3.9", "3.7"])
5-
def tests(session):
4+
@nox.session(python=["3.8", "3.9", "3.10", "3.11"])
5+
def tests(session: nox.Session) -> None:
66
args = session.posargs or ["--cov"]
7-
session.install(".", "pytest", "pytest-cov", "coverage[toml]")
7+
session.install(".", "pytest", "pytest-cov")
88
session.run("pytest", *args)
9-
10-
11-
locations = "nbdocs", "tests", "noxfile.py"
12-
13-
14-
@nox.session(python=["3.8", "3.9", "3.7"])
15-
def lint(session):
16-
args = session.posargs or locations
17-
session.install("flake8")
18-
session.run("flake8", *args)

noxfile_conda.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
import nox
2+
3+
4+
@nox.session(python=["3.8", "3.9", "3.10", "3.11"], venv_backend="mamba")
5+
def tests(session: nox.Session) -> None:
6+
args = session.posargs or ["--cov"]
7+
session.install("pytest", "pytest-cov")
8+
session.install("-e", ".")
9+
session.run("pytest", *args)

noxfile_conda_lint.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
import nox
2+
3+
locations = "src/nbdocs", "tests", "noxfile.py"
4+
5+
6+
@nox.session(python=["3.8", "3.9", "3.10", "3.11"], venv_backend="mamba")
7+
def lint(session: nox.Session) -> None:
8+
args = session.posargs or locations
9+
session.conda_install("flake8")
10+
session.run("flake8", *args)

noxfile_cov.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import nox
2+
3+
4+
@nox.session(python=["3.10"])
5+
def tests(session: nox.Session) -> None:
6+
args = session.posargs or ["--cov"]
7+
session.install(".", "pytest", "pytest-cov", "coverage[toml]")
8+
session.run("pytest", *args)
9+
10+
11+
@nox.session(python="3.10")
12+
def coverage(session: nox.Session) -> None:
13+
"""Upload coverage data."""
14+
session.install("coverage[toml]", "codecov")
15+
session.run("coverage", "xml", "--fail-under=0")
16+
session.run("codecov", *session.posargs)

noxfile_lint.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
import nox
2+
3+
4+
locations = "nbdocs", "tests", "noxfile.py"
5+
6+
7+
@nox.session(python=["3.8", "3.9", "3.10", "3.11"])
8+
def lint(session: nox.Session) -> None:
9+
args = session.posargs or locations
10+
session.install("flake8")
11+
session.run("flake8", *args)

requirements.txt

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
nbformat
22
nbconvert
33
typer
4-
rich
4+
rich
5+
pydantic

requirements_extra.txt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
1-
mcdocs
1+
mkdocs
22
mkdocs-material
33
pymdown-extensions

setup.cfg

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ classifiers =
1717
package_dir =
1818
= src
1919
packages = find:
20-
python_requires = >=3.7
20+
python_requires = >=3.8
2121

2222
[options.packages.find]
2323
where = src

src/nbdocs/clean.py

Lines changed: 44 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,37 +1,49 @@
11
from typing import List, Optional, Tuple, Union
22

3+
import nbformat
34
from nbconvert.exporters.exporter import ResourcesDict
4-
from nbconvert.preprocessors import ClearMetadataPreprocessor, Preprocessor
5+
from nbconvert.preprocessors.base import Preprocessor
6+
from nbconvert.preprocessors.clearmetadata import ClearMetadataPreprocessor
57
from nbformat import NotebookNode
6-
import nbformat
78

8-
from nbdocs.core import PathOrStr, read_nb, write_nb
9+
from nbdocs.core import PathOrStr, TPreprocessor, read_nb, write_nb
910

1011

1112
class ClearMetadataPreprocessorRes(ClearMetadataPreprocessor):
1213
"""ClearMetadata Preprocessor same as at nbconvert
1314
but return True at resources.changed if nb changed."""
1415

15-
def preprocess_cell(self, cell, resources, cell_index):
16+
def preprocess_cell(
17+
self,
18+
cell: NotebookNode,
19+
resources: ResourcesDict,
20+
cell_index: int,
21+
) -> Tuple[NotebookNode, ResourcesDict]:
1622
"""
1723
All the code cells are returned with an empty metadata field.
1824
"""
1925
if self.clear_cell_metadata:
20-
if cell.cell_type == 'code':
26+
if cell.cell_type == "code":
2127
# Remove metadata
22-
if 'metadata' in cell:
28+
if "metadata" in cell:
2329
current_metadata = cell.metadata
24-
cell.metadata = dict(self.nested_filter(cell.metadata.items(), self.preserve_cell_metadata_mask))
30+
cell.metadata = dict(
31+
self.nested_filter(
32+
cell.metadata.items(), self.preserve_cell_metadata_mask
33+
)
34+
)
2535
if cell.metadata != current_metadata:
2636
resources["changed"] = True
2737
return cell, resources
2838

29-
def preprocess(self, nb, resources):
39+
def preprocess(
40+
self, nb: NotebookNode, resources: ResourcesDict
41+
) -> Tuple[NotebookNode, ResourcesDict]:
3042
"""
3143
Preprocessing to apply on each notebook.
32-
44+
3345
Must return modified nb, resources.
34-
46+
3547
Parameters
3648
----------
3749
nb : NotebookNode
@@ -41,9 +53,13 @@ def preprocess(self, nb, resources):
4153
preprocessors to pass variables into the Jinja engine.
4254
"""
4355
if self.clear_notebook_metadata:
44-
if 'metadata' in nb:
56+
if "metadata" in nb:
4557
current_metadata = nb.metadata
46-
nb.metadata = dict(self.nested_filter(nb.metadata.items(), self.preserve_nb_metadata_mask))
58+
nb.metadata = dict(
59+
self.nested_filter(
60+
nb.metadata.items(), self.preserve_nb_metadata_mask
61+
)
62+
)
4763
if nb.metadata != current_metadata:
4864
resources["changed"] = True
4965
for index, cell in enumerate(nb.cells):
@@ -56,7 +72,12 @@ class ClearExecutionCountPreprocessor(Preprocessor):
5672
Clear execution_count from all code cells in a notebook.
5773
"""
5874

59-
def preprocess_cell(self, cell: NotebookNode, resources: ResourcesDict, index: int):
75+
def preprocess_cell(
76+
self,
77+
cell: NotebookNode,
78+
resources: ResourcesDict,
79+
index: int,
80+
) -> Tuple[NotebookNode, ResourcesDict]:
6081
"""
6182
Apply a transformation on each cell. See base.py for details.
6283
"""
@@ -78,8 +99,12 @@ class MetadataCleaner:
7899
"""
79100

80101
def __init__(self) -> None:
81-
self.cleaner_metadata = ClearMetadataPreprocessorRes(enabled=True)
82-
self.cleaner_execution_count = ClearExecutionCountPreprocessor(enabled=True)
102+
self.cleaner_metadata: TPreprocessor = ClearMetadataPreprocessorRes(
103+
enabled=True
104+
)
105+
self.cleaner_execution_count: TPreprocessor = ClearExecutionCountPreprocessor(
106+
enabled=True
107+
)
83108

84109
def __call__(
85110
self,
@@ -95,7 +120,9 @@ def __call__(
95120
return nb, resources
96121

97122

98-
def clean_nb(nb: NotebookNode, clear_execution_count: bool = True) -> Tuple[NotebookNode, ResourcesDict]:
123+
def clean_nb(
124+
nb: NotebookNode, clear_execution_count: bool = True
125+
) -> Tuple[NotebookNode, ResourcesDict]:
99126
"""Clean notebook metadata and execution_count.
100127
101128
Args:
@@ -125,7 +152,5 @@ def clean_nb_file(
125152
nb = read_nb(fn_item, as_version)
126153
nb, resources = cleaner(nb, clear_execution_count=clear_execution_count)
127154
if resources["changed"]:
128-
write_nb(
129-
nb, fn_item, as_version
130-
)
155+
write_nb(nb, fn_item, as_version)
131156
print(f"done: {fn_item}")

src/nbdocs/convert.py

Lines changed: 14 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
from nbconvert.exporters.exporter import ResourcesDict
66
from nbformat import NotebookNode
77

8-
from nbdocs.core import read_nb
8+
from nbdocs.core import TPreprocessor, read_nb
99
from nbdocs.process import (
1010
HideFlagsPreprocessor,
1111
MarkOutputPreprocessor,
@@ -22,8 +22,10 @@ class MdConverter:
2222
"""MdConverter constructor."""
2323

2424
def __init__(self) -> None:
25-
self.md_exporter = nbconvert.MarkdownExporter()
26-
self.md_exporter.register_preprocessor(RemoveEmptyCellPreprocessor, enabled=True)
25+
self.md_exporter: TPreprocessor = nbconvert.MarkdownExporter()
26+
self.md_exporter.register_preprocessor(
27+
RemoveEmptyCellPreprocessor, enabled=True
28+
)
2729
self.md_exporter.register_preprocessor(HideFlagsPreprocessor, enabled=True)
2830
self.md_exporter.register_preprocessor(MarkOutputPreprocessor, enabled=True)
2931

@@ -65,7 +67,8 @@ def convert2md(filenames: Union[Path, List[Path]], cfg: NbDocsCfg) -> None:
6567
md_convertor = MdConverter()
6668
for nb_fn in filenames:
6769
nb = read_nb(nb_fn)
68-
md, resources = md_convertor.nb2md(nb)
70+
resources = ResourcesDict(filename=nb_fn)
71+
md, resources = md_convertor.nb2md(nb, resources)
6972

7073
if image_names := resources["image_names"]:
7174
# dest_images = Path(cfg.docs_path) / cfg.images_path / f"{nb_fn.stem}_files"
@@ -97,6 +100,12 @@ def convert2md(filenames: Union[Path, List[Path]], cfg: NbDocsCfg) -> None:
97100
fh.write(md)
98101

99102

103+
def nb_newer(nb_name: Path, docs_path: Path) -> bool:
104+
"""return True if nb_name is newer than docs_path."""
105+
md_name = (docs_path / nb_name.name).with_suffix(".md")
106+
return not md_name.exists() or nb_name.stat().st_mtime > md_name.stat().st_mtime
107+
108+
100109
def filter_changed(nb_names: List[Path], cfg: NbDocsCfg) -> List[Path]:
101110
"""Filter list of Nb to changed only (compare modification date with dest name).
102111
@@ -109,9 +118,4 @@ def filter_changed(nb_names: List[Path], cfg: NbDocsCfg) -> List[Path]:
109118
List[Path]: List of Nb filename with newer modification time.
110119
"""
111120
docs_path = Path(cfg.docs_path)
112-
return [
113-
nb_name
114-
for nb_name in nb_names
115-
if not (md_name := (docs_path / nb_name.name).with_suffix(".md")).exists()
116-
or nb_name.stat().st_mtime >= md_name.stat().st_mtime
117-
]
121+
return [nb_name for nb_name in nb_names if nb_newer(nb_name, docs_path)]

src/nbdocs/core.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,16 @@
11
from pathlib import Path, PosixPath
2-
from typing import List, Union, TypeVar
2+
from typing import Callable, List, Tuple, TypeVar, Union
33

44
import nbformat
55
import typer
6+
from nbconvert.exporters.exporter import ResourcesDict
67
from nbformat import NotebookNode
78

89

910
PathOrStr = TypeVar("PathOrStr", Path, PosixPath, str)
11+
TPreprocessor = Callable[
12+
[NotebookNode, ResourcesDict], Tuple[NotebookNode, ResourcesDict]
13+
]
1014

1115

1216
def read_nb(
@@ -23,7 +27,6 @@ def read_nb(
2327
"""
2428
with Path(fn).open("r", encoding="utf-8") as fh:
2529
nb = nbformat.read(fh, as_version=as_version)
26-
nb.filename = fn
2730
return nb
2831

2932

@@ -41,7 +44,6 @@ def write_nb(
4144
Returns:
4245
Path: Filename of writed Nb.
4346
"""
44-
nb.pop("filename", None)
4547
filename = Path(fn)
4648
if filename.suffix != ".ipynb":
4749
filename = filename.with_suffix(".ipynb")

0 commit comments

Comments
 (0)