"""Header format utils.
Example: Check if header is available.
.. code-block:: python
>>> from whatstk.utils.hformat import is_supported
>>> is_supported('%y-%m-%d, %H:%M:%S - %name:')
(True, True)
"""
import os
import json
from typing import Tuple, List, Dict
this_directory = os.path.abspath(os.path.dirname(__file__))
assets_folder = "assets"
hformat_support_filename = "header_format_support.json"
hformat_support_filepath = os.path.join(this_directory, assets_folder, hformat_support_filename)
[docs]def is_supported(hformat: str, encoding: str = "utf8") -> Tuple[bool, bool]:
"""Check if header `hformat` is currently supported.
Args:
hformat (str): Header format.
encoding (str, optional): Encoding to use for UTF when reading/writing (ex. ‘utf-8’).
`List of Python standard encodings
<https://docs.python.org/3/library/codecs.html#standard-encodings>`_.
Returns:
tuple:
* bool: True if header is supported.
* bool: True if header is supported with `auto_header` feature.
"""
with open(hformat_support_filepath, "r", encoding=encoding) as f:
h = json.load(f)
if "%P" in hformat or "%p" in hformat:
hformat = hformat.replace("%P", "%p").replace("%H", "%I")
hformat = hformat.replace("%Y", "%y")
auto_header_support = 0
support = 0
for hh in h:
if hformat == hh["format"]:
support = 1
auto_header_support = hh["auto_header"]
return bool(support), bool(auto_header_support)
[docs]def is_supported_verbose(hformat: str) -> str:
"""Check if header `hformat` is currently supported (both manually and using `auto_header`).
Result is shown as a string.
Args:
hformat (str): Information message.
Example:
Check if format ``'%y-%m-%d, %H:%M - %name:'`` is supported.
.. code-block:: python
>>> from whatstk.whatsapp.hformat import is_supported_verbose
>>> is_supported_verbose('%y-%m-%d, %H:%M - %name:')
"The header '%y-%m-%d, %H:%M - %name:' is supported. `auto_header` for this header is supported."
"""
support, auto_header_support = is_supported(hformat)
msg = "The header '{}' is {}supported. `auto_header` for this header is {}supported.".format(
hformat,
"not " if not support else "",
"not " if not auto_header_support else "",
)
return msg