Better comparison for app state changes

This commit is contained in:
Ivan Kravets
2019-07-01 20:42:23 +03:00
parent bf77d70d82
commit 6d9de80f12
2 changed files with 13 additions and 11 deletions

View File

@ -14,9 +14,9 @@
import codecs import codecs
import hashlib import hashlib
import json
import os import os
import uuid import uuid
from copy import deepcopy
from os import environ, getenv, listdir, remove from os import environ, getenv, listdir, remove
from os.path import abspath, dirname, expanduser, isdir, isfile, join from os.path import abspath, dirname, expanduser, isdir, isfile, join
from time import time from time import time
@ -94,27 +94,28 @@ class State(object):
if not self.path: if not self.path:
self.path = join(get_project_core_dir(), "appstate.json") self.path = join(get_project_core_dir(), "appstate.json")
self._state = {} self._state = {}
self._prev_state = {} self._prev_state_raw = ""
self._lockfile = None self._lockfile = None
def __enter__(self): def __enter__(self):
try: try:
self._lock_state_file() self._lock_state_file()
if isfile(self.path): if isfile(self.path):
self._state = util.load_json(self.path) with open(self.path) as fp:
self._prev_state_raw = fp.read().strip()
self._state = json.loads(self._prev_state_raw)
assert isinstance(self._state, dict) assert isinstance(self._state, dict)
except (AssertionError, UnicodeDecodeError, except (AssertionError, ValueError, UnicodeDecodeError):
exception.PlatformioException):
self._state = {} self._state = {}
self._prev_state = deepcopy(self._state) self._prev_state_raw = ""
return self._state return self._state
def __exit__(self, type_, value, traceback): def __exit__(self, type_, value, traceback):
new_state = dump_json_to_unicode(self._state) new_state_raw = dump_json_to_unicode(self._state)
if self._prev_state != new_state: if self._prev_state_raw != new_state_raw:
try: try:
with open(self.path, "w") as fp: with open(self.path, "w") as fp:
fp.write(new_state) fp.write(new_state_raw)
except IOError: except IOError:
raise exception.HomeDirPermissionsError(get_project_core_dir()) raise exception.HomeDirPermissionsError(get_project_core_dir())
self._unlock_state_file() self._unlock_state_file()

View File

@ -58,7 +58,8 @@ if PY2:
return obj return obj
return json.dumps(obj, return json.dumps(obj,
encoding=get_filesystem_encoding(), encoding=get_filesystem_encoding(),
ensure_ascii=False).encode("utf8") ensure_ascii=False,
sort_keys=True).encode("utf8")
_magic_check = re.compile('([*?[])') _magic_check = re.compile('([*?[])')
_magic_check_bytes = re.compile(b'([*?[])') _magic_check_bytes = re.compile(b'([*?[])')
@ -104,4 +105,4 @@ else:
def dump_json_to_unicode(obj): def dump_json_to_unicode(obj):
if isinstance(obj, string_types): if isinstance(obj, string_types):
return obj return obj
return json.dumps(obj, ensure_ascii=False) return json.dumps(obj, ensure_ascii=False, sort_keys=True)