Created
February 14, 2019 03:10
-
-
Save ericdill/c68c220fad6b5488a0f610003626b6de to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def _load(path, fsrw_class=None): | |
"""Returns a dictionary of configuration by reading from the configuration | |
file.""" | |
if fsrw_class is None: | |
fsrw_class = FileSystemReaderWriter | |
config_file = fsrw_class(path) | |
config_file.ensure_file_exists() | |
config_text = config_file.read_lines() | |
line = u"".join(config_text).strip() | |
if line == u"": | |
overrides = {} | |
else: | |
overrides = json.loads(line) | |
return overrides | |
class FileSystemReaderWriter(object): | |
def __init__(self, path): | |
from .utils import expand_path | |
assert path is not None | |
self.path = expand_path(path) | |
def ensure_path_exists(self): | |
self._ensure_path_exists(self.path) | |
def ensure_file_exists(self): | |
self._ensure_path_exists(os.path.dirname(self.path)) | |
if not os.path.exists(self.path): | |
open(self.path, 'w').close() | |
def read_lines(self): | |
if os.path.isfile(self.path): | |
with open(self.path, "r") as f: | |
return f.readlines() | |
else: | |
return "" | |
def overwrite_with_line(self, line): | |
with open(self.path, "w+") as f: | |
f.writelines(line) | |
def _ensure_path_exists(self, path): | |
try: | |
os.makedirs(path) | |
except OSError: | |
if not os.path.isdir(path): | |
raise | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment