Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Only sort keys if id is inserted #35

Merged
merged 1 commit into from
Oct 9, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions src/clean_notebook/clean.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ def clean_single_notebook(
nb = json.loads(raw)
set_id = _check_set_id(nb)

cleaned = False
cleaned, sort_keys = False, False
for cell in nb["cells"].copy():
cleaned |= _update_value(cell, "outputs", [])
cleaned |= _update_value(cell, "execution_count", None)
Expand All @@ -45,6 +45,7 @@ def clean_single_notebook(
del cell["attachments"]
cleaned = True
if set_id and cell.get("id") is None:
sort_keys |= "id" not in cell
cell["id"] = str(uuid.uuid4())
cleaned = True

Expand All @@ -57,7 +58,7 @@ def clean_single_notebook(

if cleaned and not dryrun:
with open(file, "w", encoding="utf8", newline=newline) as f:
json.dump(nb, f, indent=1, ensure_ascii=False, sort_keys=True)
json.dump(nb, f, indent=1, ensure_ascii=False, sort_keys=sort_keys)
f.write(newline) # empty line at the end of the file
print(f"Cleaned notebook: {file}")
elif cleaned:
Expand Down
34 changes: 17 additions & 17 deletions tests/data/clean_colab.ipynb
Original file line number Diff line number Diff line change
@@ -1,4 +1,12 @@
{
"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"language_info": {
"name": "python",
"pygments_lexer": "ipython3"
}
},
"cells": [
{
"cell_type": "code",
Expand All @@ -13,29 +21,21 @@
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"print(\"saved from colab\")"
]
],
"metadata": {},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
""
]
}
],
"metadata": {
"language_info": {
"name": "python",
"pygments_lexer": "ipython3"
],
"metadata": {},
"execution_count": null,
"outputs": []
}
},
"nbformat": 4,
"nbformat_minor": 0
]
}