1
0
mirror of https://github.com/home-assistant/supervisor.git synced 2025-12-24 12:29:08 +00:00

Robust json file handling with default reset on runtime (#321)

* Update json.py

* Update validate.py

* Update validate.py

* Update snapshots.py

* Update validate.py

* Update homeassistant.py

* Update validate.py

* Update snapshot.py

* Update snapshot.py

* Update snapshot.py

* Update json.py

* Update json.py

* Update json.py

* Update validate.py

* Update snapshots.py

* Update validate.py

* Update validate.py

* improve config updates

* fix lint

* update build

* fix schema

* fix validate

* fix lint

* fix some styles

* fix

* fix snapshot

* fix errors

* Update API
This commit is contained in:
Pascal Vizeli
2018-01-18 23:33:05 +01:00
committed by GitHub
parent 70a721a47d
commit 6f2cf2ef85
19 changed files with 136 additions and 103 deletions

View File

@@ -10,14 +10,9 @@ _LOGGER = logging.getLogger(__name__)
def write_json_file(jsonfile, data):
"""Write a json file."""
try:
json_str = json.dumps(data, indent=2)
with jsonfile.open('w') as conf_file:
conf_file.write(json_str)
except (OSError, json.JSONDecodeError):
return False
return True
json_str = json.dumps(data, indent=2)
with jsonfile.open('w') as conf_file:
conf_file.write(json_str)
def read_json_file(jsonfile):
@@ -35,7 +30,10 @@ class JsonConfig(object):
self._schema = schema
self._data = {}
# init or load data
self.read_data()
def read_data(self):
"""Read json file & validate."""
if self._file.is_file():
try:
self._data = read_json_file(self._file)
@@ -43,27 +41,33 @@ class JsonConfig(object):
_LOGGER.warning("Can't read %s", self._file)
self._data = {}
# validate
# Validate
try:
self._data = self._schema(self._data)
except vol.Invalid as ex:
_LOGGER.error("Can't parse %s: %s",
self._file, humanize_error(self._data, ex))
# reset data to default
# Reset data to default
_LOGGER.warning("Reset %s to default", self._file)
self._data = self._schema({})
def save(self):
def save_data(self):
"""Store data to config file."""
# validate
# Validate
try:
self._data = self._schema(self._data)
except vol.Invalid as ex:
_LOGGER.error("Can't parse data: %s",
humanize_error(self._data, ex))
return False
# Load last valid data
_LOGGER.warning("Reset %s to last version", self._file)
self.save_data()
return
# write
if not write_json_file(self._file, self._data):
_LOGGER.error("Can't store config in %s", self._file)
return False
return True
try:
write_json_file(self._file, self._data)
except (OSError, json.JSONDecodeError) as err:
_LOGGER.error("Can't store config in %s: %s", self._file, err)