Added nested_delete and config_delete

This commit is contained in:
2024-05-26 15:40:29 +02:00
parent ce691b2eda
commit 7032bef956
10 changed files with 279 additions and 126 deletions

View File

@@ -8,7 +8,7 @@ try:
except ImportError:
from json import dumps, loads
from libbot.sync import nested_set
from .sync._nested import nested_delete, nested_set
async def json_read(path: Union[str, Path]) -> Any:
@@ -22,6 +22,7 @@ async def json_read(path: Union[str, Path]) -> Any:
"""
async with aiofiles.open(str(path), mode="r", encoding="utf-8") as f:
data = await f.read()
return loads(data)
@@ -73,8 +74,10 @@ async def config_get(
```
"""
this_key = await json_read(config_file)
for dict_key in path:
this_key = this_key[dict_key]
return this_key[key]
@@ -88,8 +91,31 @@ async def config_set(
* value (`Any`): Any JSON serializable data
* *path (`str`): Path to the key of the target
* config_file (`Union[str, Path]`, *optional*): Path-like object or path as a string of a location of the config file. Defaults to `"config.json"`
### Raises:
* `KeyError`: Key is not found under path provided
"""
await json_write(
nested_set(await json_read(config_file), value, *(*path, key)), config_file
)
return
async def config_delete(
key: str, *path: str, config_file: Union[str, Path] = "config.json"
) -> None:
"""Set config's key by its path
### Args:
* key (`str`): Key to delete
* *path (`str`): Path to the key of the target
* config_file (`Union[str, Path]`, *optional*): Path-like object or path as a string of a location of the config file. Defaults to `"config.json"`
### Raises:
* `KeyError`: Key is not found under path provided
"""
config_data = await json_read(config_file)
nested_delete(config_data, *(*path, key))
await json_write(config_data, config_file)