Skip to content

Commit b01b51e

Browse files
committed
refactor migration
1 parent d25ab94 commit b01b51e

File tree

2 files changed

+28
-18
lines changed

2 files changed

+28
-18
lines changed

src/bloqade/analog/migrate.py

+13-14
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from typing import Any, Dict, List
1+
from typing import IO, Any, Dict, List
22
from dataclasses import field, dataclass
33

44
import simplejson as json
@@ -26,7 +26,7 @@ def walk(self, obj: Dict[str, Any] | List[Any]) -> Dict[str, Any] | List[Any]:
2626
if isinstance(obj, dict):
2727
return self.walk_dict(obj)
2828
elif isinstance(obj, list):
29-
return [self.walk(item) for item in obj]
29+
return list(map(self.walk, obj))
3030
else:
3131
return obj
3232

@@ -36,23 +36,22 @@ def convert(self, obj: Dict[str, Any] | List[Any]):
3636
return new_obj, self.has_done_something
3737

3838

39+
def _migrate(input_oi: IO[str], output_oi: IO[str], indent: int | None = None):
40+
obj = json.load(input_oi)
41+
new_obj, has_done_something = JSONWalker().convert(obj)
42+
43+
if has_done_something:
44+
json.dump(new_obj, output_oi, indent=indent)
45+
46+
3947
def migrate(
4048
filename: str,
4149
indent: int | None = None,
4250
overwrite: bool = False,
4351
):
44-
45-
with open(filename, "r") as io:
46-
obj = json.load(io)
47-
walker = JSONWalker()
48-
new_obj, has_done_something = walker.convert(obj)
49-
50-
if has_done_something:
51-
new_filename = (
52-
filename if overwrite else filename.replace(".json", "-analog.json")
53-
)
54-
with open(new_filename, "w") as io:
55-
json.dump(new_obj, io, indent=indent)
52+
new_filename = filename if overwrite else filename.replace(".json", "-analog.json")
53+
with open(filename, "r") as in_io, open(new_filename, "w") as out_io:
54+
_migrate(in_io, out_io, indent)
5655

5756

5857
def _entry():

tests/test_migrate.py

+15-4
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,12 @@
1-
from bloqade.analog.migrate import JSONWalker
1+
import io
2+
3+
import simplejson as json
4+
5+
from bloqade.analog.migrate import _migrate
26

37

48
def test_walk_dict():
5-
walker = JSONWalker()
9+
610
obj = {
711
"key1": "value1",
812
"bloqade.key2": "value2",
@@ -19,5 +23,12 @@ def test_walk_dict():
1923
"list": [{"key6": "value6"}, {"bloqade.analog.key7": "value7"}],
2024
}
2125

22-
result = walker.walk_dict(obj)
23-
assert result == expected
26+
obj_str = json.dumps(obj)
27+
expected_str = json.dumps(expected)
28+
29+
in_io = io.StringIO(obj_str)
30+
out_io = io.StringIO()
31+
32+
_migrate(in_io, out_io)
33+
34+
assert out_io.getvalue() == expected_str

0 commit comments

Comments
 (0)