Skip to content

Commit

Permalink
Add config settings - not published
Browse files Browse the repository at this point in the history
  • Loading branch information
yorevs committed Apr 24, 2024
1 parent 5b7f228 commit 021a1b1
Showing 1 changed file with 57 additions and 0 deletions.
57 changes: 57 additions & 0 deletions modules/hspylib/src/main/hspylib/core/config/settings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
@project: HsPyLib
@package: hspylib.core.config
@file: settings.py
@created: Tue, 23 Apr 2024
@author: <B>H</B>ugo <B>S</B>aporetti <B>J</B>unior
@site: https://github.com/yorevs/hspylib
@license: MIT - Please refer to <https://opensource.org/licenses/MIT>
Copyright·(c)·2024,·HSPyLib
"""

import os
from typing import Any

from hspylib.core.config.properties import Properties
from hspylib.core.preconditions import check_argument
from hspylib.core.tools.commons import touch_file
from hspylib.core.tools.text_tools import ensure_endswith


class Settings(Properties):
"""The Settings class represents a persistent set of mutable settings. Each key and its corresponding value in the
settings dictionary.Format and rules follows the properties approach."""

def __init__(self, filename: str = None, profile: str | None = None, load_dir: str | None = None) -> None:
_, ext = os.path.splitext(filename)
check_argument(ext == ".properties", "Only '.properties' formatted files are permitted!")
self._load_dir = load_dir
self._filename = filename
touch_file(self.filepath)
super().__init__(filename, profile, load_dir)

@property
def filepath(self) -> str:
return ensure_endswith(f"{self._load_dir}/{self._filename}", ".properties")

def set(self, key: str, value: Any) -> None:
"""Add or set the setting and it's associated value."""
self._properties[key] = value

def remove(self, key: str) -> str:
"""Remove a setting specified by key."""
return self._properties.pop(key, None)

def clear(self) -> None:
"""Remove all settings."""
self._properties.clear()

def save(self) -> None:
"""Save current settings to the associated file."""
with open(self.filepath, "w") as f_settings:
f_settings.writelines([f"{key} = {value} \n" for (key, value) in self._properties.items()])
f_settings.flush()

0 comments on commit 021a1b1

Please sign in to comment.