Skip to content

Commit

Permalink
preserve newlines (#681)
Browse files Browse the repository at this point in the history
* preserve newlines

* fixup test
  • Loading branch information
MarcoGorelli committed Nov 25, 2021
1 parent a3907f8 commit 45eaafc
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 4 deletions.
3 changes: 2 additions & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ repos:
rev: v4.0.1
hooks:
- id: end-of-file-fixer
exclude: ^tests/data/
- id: requirements-txt-fixer
- id: trailing-whitespace
- id: debug-statements
Expand Down Expand Up @@ -91,4 +92,4 @@ repos:
rev: 0.5.0
hooks:
- id: nbstripout
exclude: ^tests/data/databricks_notebook\.ipynb$
exclude: ^tests/data/(databricks_notebook|notebook_for_testing)\.ipynb$
8 changes: 6 additions & 2 deletions nbqa/replace_source.py
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,8 @@ def mutate(
Whether mutation actually happened.
"""
with open(notebook, encoding="utf-8") as handle:
notebook_json = json.loads(handle.read())
notebook_txt = handle.read()
notebook_json = json.loads(notebook_txt)
original_notebook_json = copy.deepcopy(notebook_json)

cells = _get_cells(temp_file, len(notebook_info.temporary_lines), md=md)
Expand All @@ -208,7 +209,10 @@ def mutate(

temp_notebook = os.path.join(os.path.dirname(temp_file), os.path.basename(notebook))
with open(temp_notebook, "w", encoding="utf-8") as handle:
handle.write(f"{json.dumps(notebook_json, indent=1, ensure_ascii=False)}\n")
if notebook_txt.endswith("\n"):
handle.write(f"{json.dumps(notebook_json, indent=1, ensure_ascii=False)}\n")
else:
handle.write(f"{json.dumps(notebook_json, indent=1, ensure_ascii=False)}")
move(temp_notebook, notebook)
return True

Expand Down
2 changes: 1 addition & 1 deletion tests/data/notebook_for_testing.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -139,4 +139,4 @@
},
"nbformat": 4,
"nbformat_minor": 4
}
}

0 comments on commit 45eaafc

Please sign in to comment.