Skip to content

Commit

Permalink
Sort the final output for a deterministic order (#43)
Browse files Browse the repository at this point in the history
* Sort the final output

* Add fallback keys
  • Loading branch information
egeakman authored Jun 16, 2024
1 parent bcdacd8 commit 861e22b
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 2 deletions.
27 changes: 27 additions & 0 deletions src/utils/sort.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
class Sort:
@staticmethod
def sort_nested(data, sort_keys=None):
"""
TODO: This is probably too generic and not the best way, but it works for now
"""
if sort_keys is None:
sort_keys = ["start", "code", "title", "name"]

def get_sort_key(item):
return tuple(item.get(key, "") for key in sort_keys)

if isinstance(data, dict):
return {
key: Sort.sort_nested(value, sort_keys)
for key, value in sorted(data.items())
}
elif isinstance(data, list):
if all(isinstance(item, dict) for item in data):
return sorted(
(Sort.sort_nested(item, sort_keys) for item in data),
key=get_sort_key,
)
else:
return sorted(Sort.sort_nested(item, sort_keys) for item in data)
else:
return data
9 changes: 7 additions & 2 deletions src/utils/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
from src.misc import Room
from src.models.europython import EuroPythonSession, EuroPythonSpeaker, Schedule
from src.models.pretalx import PretalxScheduleBreak, PretalxSpeaker, PretalxSubmission
from src.utils.sort import Sort


class Utils:
Expand Down Expand Up @@ -172,10 +173,14 @@ def write_to_file(
if not direct_dump:
with open(output_file, "w") as fd:
json.dump(
{k: json.loads(v.model_dump_json()) for k, v in data.items()},
Sort.sort_nested(
{k: json.loads(v.model_dump_json()) for k, v in data.items()}
),
fd,
indent=2,
)
else:
with open(output_file, "w") as fd:
json.dump(json.loads(data.model_dump_json()), fd, indent=2)
json.dump(
Sort.sort_nested(json.loads(data.model_dump_json())), fd, indent=2
)

0 comments on commit 861e22b

Please sign in to comment.