Skip to content

Commit

Permalink
Fix some bugs for improperly formatted files. (#24)
Browse files Browse the repository at this point in the history
Closes #23
  • Loading branch information
drvinceknight authored and Nikoleta-v3 committed Jan 30, 2019
1 parent 6381de0 commit 56e8e18
Show file tree
Hide file tree
Showing 4 changed files with 42 additions and 16 deletions.
46 changes: 31 additions & 15 deletions src/blackbook/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Empty file.
5 changes: 5 additions & 0 deletions tests/data/formatted/no_cells.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"nbformat_minor": 0,
"nbformat": 4,
"metadata": {}
}
7 changes: 6 additions & 1 deletion tests/test_gen_notebook_files_in_dir.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)])
Expand Down

0 comments on commit 56e8e18

Please sign in to comment.