mirror of
https://github.com/ihabunek/toot.git
synced 2024-09-29 04:35:54 -04:00
Implement reading from a settings file
This commit is contained in:
parent
de087b414c
commit
ed0baf0770
1
setup.py
1
setup.py
@ -38,6 +38,7 @@ setup(
|
|||||||
"beautifulsoup4>=4.5.0,<5.0",
|
"beautifulsoup4>=4.5.0,<5.0",
|
||||||
"wcwidth>=0.1.7",
|
"wcwidth>=0.1.7",
|
||||||
"urwid>=2.0.0,<3.0",
|
"urwid>=2.0.0,<3.0",
|
||||||
|
"tomlkit>=0.10.0,<1.0"
|
||||||
],
|
],
|
||||||
entry_points={
|
entry_points={
|
||||||
'console_scripts': [
|
'console_scripts': [
|
||||||
|
52
toot/settings.py
Normal file
52
toot/settings.py
Normal file
@ -0,0 +1,52 @@
|
|||||||
|
from functools import lru_cache
|
||||||
|
from os.path import exists, join
|
||||||
|
from typing import Optional, Type, TypeVar
|
||||||
|
from tomlkit import parse
|
||||||
|
from toot.config import get_config_dir
|
||||||
|
|
||||||
|
|
||||||
|
TOOT_SETTINGS_FILE_NAME = "settings.toml"
|
||||||
|
|
||||||
|
|
||||||
|
def get_settings_path():
|
||||||
|
return join(get_config_dir(), TOOT_SETTINGS_FILE_NAME)
|
||||||
|
|
||||||
|
|
||||||
|
SETTINGS_FILE = get_settings_path()
|
||||||
|
|
||||||
|
|
||||||
|
def load_settings() -> dict:
|
||||||
|
if not exists(SETTINGS_FILE):
|
||||||
|
return {}
|
||||||
|
|
||||||
|
with open(SETTINGS_FILE) as f:
|
||||||
|
return parse(f.read())
|
||||||
|
|
||||||
|
|
||||||
|
@lru_cache(maxsize=None)
|
||||||
|
def get_settings():
|
||||||
|
return load_settings()
|
||||||
|
|
||||||
|
|
||||||
|
def get_setting(key: str, type: Type, default=None):
|
||||||
|
"""
|
||||||
|
Get a setting value. The key should be a dot-separated string,
|
||||||
|
e.g. "commands.post.editor" which will correspond to the "editor" setting
|
||||||
|
inside the `[commands.post]` section.
|
||||||
|
"""
|
||||||
|
settings = get_settings()
|
||||||
|
return _get_setting(settings, key.split("."), type, default)
|
||||||
|
|
||||||
|
|
||||||
|
def _get_setting(dct, keys, type: Type, default=None):
|
||||||
|
if len(keys) == 0:
|
||||||
|
if isinstance(dct, type):
|
||||||
|
return dct
|
||||||
|
else:
|
||||||
|
return default
|
||||||
|
|
||||||
|
key = keys[0]
|
||||||
|
if isinstance(dct, dict) and key in dct:
|
||||||
|
return _get_setting(dct[key], keys[1:], type, default)
|
||||||
|
|
||||||
|
return default
|
Loading…
Reference in New Issue
Block a user