core/homeassistant/components/diagnostics/util.py

44 lines
1.1 KiB
Python
Raw Normal View History

2022-01-20 22:02:47 +00:00
"""Diagnostic utilities."""
from __future__ import annotations
from collections.abc import Iterable, Mapping
from typing import Any, TypeVar, cast, overload
2022-01-20 22:02:47 +00:00
from homeassistant.core import callback
from .const import REDACTED
T = TypeVar("T")
2022-01-20 22:02:47 +00:00
@overload
def async_redact_data(data: Mapping, to_redact: Iterable[Any]) -> dict: # type: ignore
...
@overload
def async_redact_data(data: T, to_redact: Iterable[Any]) -> T:
...
2022-01-20 22:02:47 +00:00
@callback
def async_redact_data(data: T, to_redact: Iterable[Any]) -> T:
2022-01-20 22:02:47 +00:00
"""Redact sensitive data in a dict."""
if not isinstance(data, (Mapping, list)):
return data
if isinstance(data, list):
return cast(T, [async_redact_data(val, to_redact) for val in data])
2022-01-20 22:02:47 +00:00
redacted = {**data}
for key, value in redacted.items():
if key in to_redact:
redacted[key] = REDACTED
elif isinstance(value, Mapping):
2022-01-20 22:02:47 +00:00
redacted[key] = async_redact_data(value, to_redact)
elif isinstance(value, list):
redacted[key] = [async_redact_data(item, to_redact) for item in value]
return cast(T, redacted)