Skip to content

Commit 861e22b

Browse files
authored
Sort the final output for a deterministic order (#43)
* Sort the final output * Add fallback keys
1 parent bcdacd8 commit 861e22b

File tree

2 files changed

+34
-2
lines changed

2 files changed

+34
-2
lines changed

src/utils/sort.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
class Sort:
2+
@staticmethod
3+
def sort_nested(data, sort_keys=None):
4+
"""
5+
TODO: This is probably too generic and not the best way, but it works for now
6+
"""
7+
if sort_keys is None:
8+
sort_keys = ["start", "code", "title", "name"]
9+
10+
def get_sort_key(item):
11+
return tuple(item.get(key, "") for key in sort_keys)
12+
13+
if isinstance(data, dict):
14+
return {
15+
key: Sort.sort_nested(value, sort_keys)
16+
for key, value in sorted(data.items())
17+
}
18+
elif isinstance(data, list):
19+
if all(isinstance(item, dict) for item in data):
20+
return sorted(
21+
(Sort.sort_nested(item, sort_keys) for item in data),
22+
key=get_sort_key,
23+
)
24+
else:
25+
return sorted(Sort.sort_nested(item, sort_keys) for item in data)
26+
else:
27+
return data

src/utils/utils.py

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
from src.misc import Room
1010
from src.models.europython import EuroPythonSession, EuroPythonSpeaker, Schedule
1111
from src.models.pretalx import PretalxScheduleBreak, PretalxSpeaker, PretalxSubmission
12+
from src.utils.sort import Sort
1213

1314

1415
class Utils:
@@ -172,10 +173,14 @@ def write_to_file(
172173
if not direct_dump:
173174
with open(output_file, "w") as fd:
174175
json.dump(
175-
{k: json.loads(v.model_dump_json()) for k, v in data.items()},
176+
Sort.sort_nested(
177+
{k: json.loads(v.model_dump_json()) for k, v in data.items()}
178+
),
176179
fd,
177180
indent=2,
178181
)
179182
else:
180183
with open(output_file, "w") as fd:
181-
json.dump(json.loads(data.model_dump_json()), fd, indent=2)
184+
json.dump(
185+
Sort.sort_nested(json.loads(data.model_dump_json())), fd, indent=2
186+
)

0 commit comments

Comments
 (0)