Skip to content

Commit

Permalink
Only sort keys if id is inserted (#35)
Browse files Browse the repository at this point in the history
  • Loading branch information
hoxbro authored Oct 9, 2023
1 parent 9e88666 commit 3fc05e8
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 19 deletions.
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
]
}

0 comments on commit 3fc05e8

Please sign in to comment.