Skip to content

Commit cd0bf49

Browse files
refactor: import sort logic from tools/sort_ref_json instead of duplicating
1 parent a035172 commit cd0bf49

1 file changed

Lines changed: 12 additions & 31 deletions

File tree

flow360/_autohooks/sort_json.py

Lines changed: 12 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
"""Autohooks plugin: sort keys in staged JSON files under tests/."""
22

3-
import json
3+
import importlib.util
44
from pathlib import Path
55

66
from autohooks.api import ok
@@ -11,32 +11,16 @@
1111
)
1212
from autohooks.api.path import match
1313

14+
_TOOLS_DIR = Path(__file__).resolve().parent.parent.parent / "tools"
15+
_spec = importlib.util.spec_from_file_location("sort_ref_json", _TOOLS_DIR / "sort_ref_json.py")
16+
_module = importlib.util.module_from_spec(_spec)
17+
_spec.loader.exec_module(_module)
18+
process_file = _module.process_file
19+
1420
DEFAULT_INCLUDE = ("*.json",)
1521
TESTS_DIR = Path(__file__).resolve().parent.parent.parent / "tests"
1622

1723

18-
def _sort_keys(obj):
19-
"""Recursively sort dictionary keys. List order is preserved."""
20-
if isinstance(obj, dict):
21-
return {k: _sort_keys(v) for k, v in sorted(obj.items())}
22-
if isinstance(obj, list):
23-
return [_sort_keys(item) for item in obj]
24-
return obj
25-
26-
27-
def _sort_file(path: Path) -> bool:
28-
"""Sort keys in-place. Returns True if file was already sorted."""
29-
raw = path.read_text(encoding="utf-8")
30-
data = json.loads(raw)
31-
sorted_content = json.dumps(_sort_keys(data), indent=4) + "\n"
32-
33-
if raw == sorted_content:
34-
return True
35-
36-
path.write_text(sorted_content, encoding="utf-8")
37-
return False
38-
39-
4024
def precommit(config=None, report_progress=None, **kwargs): # pylint: disable=unused-argument
4125
"""Sort JSON keys in staged test reference files."""
4226
files = [
@@ -54,14 +38,11 @@ def precommit(config=None, report_progress=None, **kwargs): # pylint: disable=u
5438

5539
with stash_unstaged_changes(files):
5640
for f in files:
57-
try:
58-
already_sorted = _sort_file(f.absolute_path())
59-
if already_sorted:
60-
ok(f"Already sorted: {f.path}")
61-
else:
62-
ok(f"Sorted keys in: {f.path}")
63-
except (json.JSONDecodeError, UnicodeDecodeError):
64-
ok(f"Skipped (not valid JSON): {f.path}")
41+
already_sorted = process_file(f.absolute_path(), check=False)
42+
if already_sorted:
43+
ok(f"Already sorted: {f.path}")
44+
else:
45+
ok(f"Sorted keys in: {f.path}")
6546

6647
if report_progress:
6748
report_progress.update()

0 commit comments

Comments
 (0)