Skip to content

Commit 095679b

Browse files
committed
RF: move fallback for pretty json saving into save_json, simplify treat_infofile
Since save_json first removes file, we should be ok and no set_readonly(.., False) should longer be needed
1 parent 60eae9c commit 095679b

File tree

1 file changed

+20
-22
lines changed

1 file changed

+20
-22
lines changed

heudiconv/utils.py

Lines changed: 20 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -203,11 +203,25 @@ def save_json(filename, data, indent=2, sort_keys=True, pretty=False):
203203
204204
"""
205205
assure_no_file_exists(filename)
206+
dumps_kw = dict(sort_keys=sort_keys, indent=indent)
207+
j = None
208+
if pretty:
209+
try:
210+
j = json_dumps_pretty(data, **dumps_kw)
211+
except AssertionError as exc:
212+
pretty = False
213+
lgr.warning(
214+
"Prettyfication of .json failed (%s). "
215+
"Original .json will be kept as is. Please share (if you "
216+
"could) "
217+
"that file (%s) with HeuDiConv developers"
218+
% (str(exc), filename)
219+
)
220+
if not pretty:
221+
j = _canonical_dumps(data, **dumps_kw)
222+
assert j is not None # one way or another it should have been set to a str
206223
with open(filename, 'w') as fp:
207-
fp.write(
208-
(json_dumps_pretty if pretty else _canonical_dumps)(
209-
data, sort_keys=sort_keys, indent=indent)
210-
)
224+
fp.write(j)
211225

212226

213227
def json_dumps_pretty(j, indent=2, sort_keys=True):
@@ -252,25 +266,9 @@ def json_dumps_pretty(j, indent=2, sort_keys=True):
252266
def treat_infofile(filename):
253267
"""Tune up generated .json file (slim down, pretty-print for humans).
254268
"""
255-
with open(filename) as f:
256-
j = json.load(f)
257-
269+
j = load_json(filename)
258270
j_slim = slim_down_info(j)
259-
dumps_kw = dict(indent=2, sort_keys=True)
260-
try:
261-
j_pretty = json_dumps_pretty(j_slim, **dumps_kw)
262-
except AssertionError as exc:
263-
lgr.warning(
264-
"Prettyfication of .json failed (%s). "
265-
"Original .json will be kept as is. Please share (if you could) "
266-
"that file (%s) with HeuDiConv developers"
267-
% (str(exc), filename)
268-
)
269-
j_pretty = json.dumps(j_slim, **dumps_kw)
270-
271-
set_readonly(filename, False)
272-
with open(filename, 'wt') as fp:
273-
fp.write(j_pretty)
271+
save_json(filename, j_slim, sort_keys=True, pretty=True)
274272
set_readonly(filename)
275273

276274

0 commit comments

Comments
 (0)