pyglet_demo/engine/config.py

52 lines
1.5 KiB
Python

import json
from collections import UserDict
import os
import sys
from . import file as filemanager
class SettingsLoader(UserDict):
def __init__(self: object, files: list) -> None:
self.data = {}
self.files = files
self.reload()
def load_settings_file(self: object, file: str) -> None:
if not filemanager.exists('conf', file):
return
ext = os.path.splitext(file)[1]
with filemanager.fd_open('conf', file) as fd:
if ext == '.json':
self.data.update(json.load(fd))
else:
raise ValueError("Cannot open this type of settings file")
def reload(self: object) -> None:
self.data = {}
for f in self.files:
self.load_settings_file(f)
class SettingsReadOnly(SettingsLoader):
pass
class SettingsMutable(SettingsLoader):
pass
class SettingsWritable(SettingsMutable):
def __init__(self: object, files: list, outfile: str):
super().__init__(files)
self.outfile = outfile
def save(self: object):
defaults = SettingsReadOnly([x for x in self.files if x != self.outfile])
outdata = {}
for k in self.data.keys():
if not k in defaults:
outdata[k] = self.data[k]
if outdata or filemanager.exists('conf', self.outfile):
with filemanager.fd_write('conf', self.outfile) as fd:
json.dump(outdata, fd, indent=4)
init = SettingsWritable(['default.json', 'user.json'], 'user.json')