filesystem: JsonEditor: use NamedTemporaryFile

A plain NamedTemporaryFile is sufficient here: we only need a single
file, not a directory to hold it.  Using NamedTemporaryFile is simpler
(no subdirectory to manage) and gives us a .json suffix for free,
which editors use for syntax highlighting.

Change-Id: If3b0bd0fcc90732407dbd03b9cc883f7abeb948e
This commit is contained in:
Vadim Yanitskiy
2026-03-31 05:15:09 +07:00
parent 5e2fd148f8
commit 5828c92c66

View File

@@ -30,6 +30,7 @@ import tempfile
import json import json
import abc import abc
import inspect import inspect
import os
import cmd2 import cmd2
from cmd2 import CommandSet, with_default_category from cmd2 import CommandSet, with_default_category
@@ -567,7 +568,7 @@ class JsonEditor:
self._cmd = cmd self._cmd = cmd
self._orig_json = orig_json self._orig_json = orig_json
self._ef = ef self._ef = ef
self._tmpdir = None self._file = None
@staticmethod @staticmethod
def _strip_comments(text: str) -> str: def _strip_comments(text: str) -> str:
@@ -606,18 +607,21 @@ class JsonEditor:
text_file.write(f'// {line}\n') text_file.write(f'// {line}\n')
def __enter__(self) -> object: def __enter__(self) -> object:
"""Write JSON + examples to a temp file, run the editor, return parsed result.""" """Write JSON + examples to a temp file, run the editor, return parsed result.
self._tmpdir = tempfile.TemporaryDirectory(prefix='pysim_')
filename = '%s/file' % self._tmpdir.name The temp file is kept on JSONDecodeError so the user can correct and
with open(filename, 'w') as text_file: re-open it manually. It is removed by __exit__() on success."""
json.dump(self._orig_json, text_file, indent=4, cls=JsonEncoder) self._file = tempfile.NamedTemporaryFile(prefix='pysim_', suffix='.json',
self._append_examples_as_comments(text_file) mode='w', delete=False)
self._cmd.run_editor(filename) json.dump(self._orig_json, self._file, indent=4, cls=JsonEncoder)
with open(filename, 'r') as text_file: self._append_examples_as_comments(self._file)
self._file.close()
self._cmd.run_editor(self._file.name)
with open(self._file.name, 'r') as text_file:
return json.loads(self._strip_comments(text_file.read())) return json.loads(self._strip_comments(text_file.read()))
def __exit__(self, *args): def __exit__(self, *args):
self._tmpdir.cleanup() os.unlink(self._file.name)
class CardEF(CardFile): class CardEF(CardFile):