def __init__(self, app_dir: str = ''): """ finds the location of the required config files based on operating system, can be overridden load configs from this location and sets them ready for reading :param app_dir: app's data directory """ if app_dir: app_dir = os.path.expanduser(app_dir) if not os.path.exists(app_dir): dialog.FatalError(app_dir, "does not exist") else: local_config_dir = os.path.expanduser('~/.config') if sys.platform == 'darwin': local_config_dir = os.path.expanduser( '~/Library/Application Support') elif sys.platform == 'win32': local_config_dir = os.getenv('APPDATA') or '' if not os.path.exists(local_config_dir): dialog.FatalError("Couldn't find your config directory") app_dir = os.path.join(local_config_dir, 'PyPad') if not os.path.exists(app_dir): try: os.mkdir(app_dir) except PermissionError: dialog.FatalError("Couldn't write to", local_config_dir) self.config_path = os.path.join(app_dir, 'config.json') if not os.path.exists(self.config_path): sample_dir = os.path.join( os.path.dirname(os.path.realpath(__file__)), 'resources/config.json') try: shutil.copyfile(sample_dir, self.config_path) except PermissionError: dialog.FatalError("Couldn't write to", self.config_path) except FileNotFoundError: dialog.FatalError("Couldn't read", sample_dir) self.load() self.font = self.font()
def save(self): """ write current config to disk """ try: with open(self.config_path, 'w') as file: text = json.dumps(self.main) file.write(text) except FileNotFoundError: dialog.FatalError("Couldn't find", self.config_path)
def load(self): """ load config from disk """ try: with open(self.config_path, 'r') as file: text = file.read() self.main = json.loads(text) with open( os.path.join(os.path.dirname(__file__), 'resources/config.json'), 'r') as file: text = file.read() self.fallback = json.loads(text) except FileNotFoundError: dialog.FatalError("Couldn't find", self.config_path) self.merge()
def new_file(self): """ create a new file """ temp = '/tmp' if sys.platform == 'win32': temp = os.getenv('temp') or '' if not os.path.exists(temp): dialog.FatalError("Couldn't find your config directory") path = os.path.join( temp, 'pypad-' + str(uuid.uuid4()).split('-')[0] + '.txt') # try: # open(path, 'a').close() # except PermissionError: # dialog.FatalError("Couldn't write to", path) self.path = path self.editor.setPlainText('')
def get(self, name=None, default=None, fallback: bool = True): """ get a config value :param name: key to fetch :param default: value to fallback to if the key is not found :param fallback: should it fetch from the fallback config if the value is not found :return: requested config value """ section = self.merged if fallback else self.main if name is None: return section if isinstance(name, list) or isinstance(name, tuple): name = '.'.join(name) keys = name.split('.') try: for key in keys: section = section[key] return section except KeyError: if default is not None: return default dialog.FatalError("Couldn't find", name)