fixeria has uploaded this change for review.

View Change

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
---
M pySim/filesystem.py
1 file changed, 14 insertions(+), 10 deletions(-)

git pull ssh://gerrit.osmocom.org:29418/pysim refs/changes/53/42553/1
diff --git a/pySim/filesystem.py b/pySim/filesystem.py
index 626bace..d62e71a 100644
--- a/pySim/filesystem.py
+++ b/pySim/filesystem.py
@@ -30,6 +30,7 @@
import json
import abc
import inspect
+import os

import cmd2
from cmd2 import CommandSet, with_default_category
@@ -567,7 +568,7 @@
self._cmd = cmd
self._orig_json = orig_json
self._ef = ef
- self._tmpdir = None
+ self._file = None

@staticmethod
def _strip_comments(text: str) -> str:
@@ -595,18 +596,21 @@
text_file.write(f'// {line}\n')

def __enter__(self) -> object:
- """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
- with open(filename, 'w') as text_file:
- json.dump(self._orig_json, text_file, indent=4, cls=JsonEncoder)
- self._append_examples_as_comments(text_file)
- self._cmd.run_editor(filename)
- with open(filename, 'r') as text_file:
+ """Write JSON + examples to a temp file, run the editor, return parsed result.
+
+ The temp file is kept on JSONDecodeError so the user can correct and
+ re-open it manually. It is removed by __exit__() on success."""
+ self._file = tempfile.NamedTemporaryFile(prefix='pysim', suffix='.json',
+ mode='w', delete=False)
+ json.dump(self._orig_json, self._file, indent=4, cls=JsonEncoder)
+ 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()))

def __exit__(self, *args):
- self._tmpdir.cleanup()
+ os.unlink(self._file.name)


class CardEF(CardFile):

To view, visit change 42553. To unsubscribe, or for help writing mail filters, visit settings.

Gerrit-MessageType: newchange
Gerrit-Project: pysim
Gerrit-Branch: master
Gerrit-Change-Id: If3b0bd0fcc90732407dbd03b9cc883f7abeb948e
Gerrit-Change-Number: 42553
Gerrit-PatchSet: 1
Gerrit-Owner: fixeria <vyanitskiy@sysmocom.de>