diff --git a/src/blackbook/__init__.py b/src/blackbook/__init__.py index 3d707a2..af6c43c 100644 --- a/src/blackbook/__init__.py +++ b/src/blackbook/__init__.py @@ -16,21 +16,37 @@ def gen_notebook_files_in_dir(path: pathlib.Path) -> Iterator[pathlib.Path]: def format_notebook_content(path: pathlib.Path) -> Optional[dict]: content = path.read_text() - nb = json.loads(content) - - modification_found = False - for cell in nb["cells"]: - try: - string = "".join(cell["source"]) - formatted_string = black.format_str( - string, line_length=black.DEFAULT_LINE_LENGTH - ) - if formatted_string != string: - modification_found = True - cell["source"] = [s + "\n" for s in formatted_string.split("\n")][:-1] - except black.InvalidInput: + + try: # Some ipynb files will not contain json + + nb = json.loads(content) + modification_found = False + + try: # Some ipynb files will have no cells + + for cell in nb["cells"]: + + try: # Some ipynb files will not have valid source code + string = "".join(cell["source"]) + formatted_string = black.format_str( + string, line_length=black.DEFAULT_LINE_LENGTH + ) + if formatted_string != string: + modification_found = True + cell["source"] = [ + s + "\n" for s in formatted_string.split("\n") + ][:-1] + + except black.InvalidInput: + pass + + if modification_found: + return nb + + except KeyError: pass - if modification_found: - return nb + except json.JSONDecodeError: + pass + return None diff --git a/tests/data/formatted/empty.ipynb b/tests/data/formatted/empty.ipynb new file mode 100644 index 0000000..e69de29 diff --git a/tests/data/formatted/no_cells.ipynb b/tests/data/formatted/no_cells.ipynb new file mode 100644 index 0000000..dad6ef3 --- /dev/null +++ b/tests/data/formatted/no_cells.ipynb @@ -0,0 +1,5 @@ +{ + "nbformat_minor": 0, + "nbformat": 4, + "metadata": {} +} diff --git a/tests/test_gen_notebook_files_in_dir.py b/tests/test_gen_notebook_files_in_dir.py index c9dc3c1..fb9d6ac 100644 --- a/tests/test_gen_notebook_files_in_dir.py +++ b/tests/test_gen_notebook_files_in_dir.py @@ -8,7 +8,12 @@ def test_gen_notebook_files_in_dir(): nbs = blackbook.gen_notebook_files_in_dir(path) expected_nbs_names = sorted( - [("unformatted", "spaces.ipynb"), ("formatted", "spaces.ipynb")] + [ + ("unformatted", "spaces.ipynb"), + ("formatted", "empty.ipynb"), + ("formatted", "no_cells.ipynb"), + ("formatted", "spaces.ipynb"), + ] ) assert ( sorted([nb.parts[-2:] for nb in nbs if "checkpoint" not in str(nb)])