| 1 |
"""Cleaning tools for AsusRouter.""" |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
|
| 5 |
from typing import Any |
| 6 |
|
| 7 |
|
| 8 |
def clean_content(content: str) -> str: |
| 9 |
"""Clean the content from useless data.""" |
| 10 |
|
| 11 |
# Remove the first character if it is a BOM |
| 12 |
if content.startswith("\ufeff"): |
| 13 |
content = content[1:] |
| 14 |
|
| 15 |
# Return the cleaned content |
| 16 |
return content |
| 17 |
|
| 18 |
|
| 19 |
def clean_dict(data: dict[str, Any]) -> dict[str, Any]: |
| 20 |
"""Clean a dict from useless data. |
| 21 |
|
| 22 |
This method performs recursively (to all the nested dicts) |
| 23 |
the following operations: |
| 24 |
- Convert all values which are empty strings ('') to None |
| 25 |
""" |
| 26 |
|
| 27 |
# Go through the dict and clean it |
| 28 |
for key, value in data.items(): |
| 29 |
# Check if the value is a dict |
| 30 |
if isinstance(value, dict): |
| 31 |
# Clean the dict |
| 32 |
data[key] = clean_dict(value) |
| 33 |
# Continue to the next value |
| 34 |
continue |
| 35 |
# Check if the value is a string and if it is empty |
| 36 |
if isinstance(value, str) and value == "": |
| 37 |
# Convert the value to None |
| 38 |
data[key] = None |
| 39 |
|
| 40 |
# Return the cleaned dict |
| 41 |
return data |
| 42 |
|
| 43 |
|
| 44 |
def clean_dict_key_prefix(data: dict[str, Any], prefix: str) -> dict[str, Any]: |
| 45 |
"""Clean dict keys from prefix and an underscore (prefix_). |
| 46 |
|
| 47 |
This method only cleans the keys, but cannot be used to clean nested dicts. |
| 48 |
""" |
| 49 |
|
| 50 |
cleaned_dict: dict[str, Any] = {} |
| 51 |
|
| 52 |
# Go through the dict and clean it |
| 53 |
for key, value in data.items(): |
| 54 |
# Check if the key starts with the prefix |
| 55 |
if key.startswith(f"{prefix}_"): |
| 56 |
# Remove the prefix and underscore |
| 57 |
new_key = key.replace(f"{prefix}_", "") |
| 58 |
# Add the new key to the dict |
| 59 |
cleaned_dict[new_key] = value |
| 60 |
|
| 61 |
continue |
| 62 |
cleaned_dict[key] = value |
| 63 |
|
| 64 |
# Return the cleaned dict |
| 65 |
return cleaned_dict |
| 66 |
|
| 67 |
|
| 68 |
def clean_dict_key( |
| 69 |
data: dict[str, Any], keys: str | list[str] |
| 70 |
) -> dict[str, Any]: |
| 71 |
"""Clean dict from the keys. |
| 72 |
|
| 73 |
This method can be used to clean nested dicts. |
| 74 |
""" |
| 75 |
|
| 76 |
cleaned_dict: dict[str, Any] = {} |
| 77 |
|
| 78 |
# Check if the keys is a string |
| 79 |
if isinstance(keys, str): |
| 80 |
keys = [keys] |
| 81 |
|
| 82 |
# Go through the dict and clean it |
| 83 |
for key, value in data.items(): |
| 84 |
# Check if the key is in the keys |
| 85 |
if key in keys: |
| 86 |
continue |
| 87 |
cleaned_dict[key] = ( |
| 88 |
clean_dict_key(value, keys) if isinstance(value, dict) else value |
| 89 |
) |
| 90 |
|
| 91 |
# Return the cleaned dict |
| 92 |
return cleaned_dict |