Files
arcaea-apk-assets/arcaea_apk_assets/parsers/_shared.py
2025-07-06 18:43:00 +08:00

81 lines
1.8 KiB
Python

"""
Copyright (C) 2025 283375
This file is part of "arcaea-apk-assets" (stated as "this program" below).
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation, either version 3 of the License, or (at your option) any later
version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with
this program. If not, see <https://www.gnu.org/licenses/>.
"""
from __future__ import annotations
import re
from typeguard import typechecked
@typechecked
def is_string_blank(string: str) -> bool:
"""
Check if a string equals to a blank string after stripped.
>>> is_string_blank("abc")
False
>>> is_string_blank("")
True
>>> is_string_blank(" ")
True
>>> is_string_blank(" a ")
False
"""
return string.strip() == ""
@typechecked
def blank_str_to_none(string: str | None) -> str | None:
"""
Convert a blank string (see :func:`~is_string_blank`) to None, otherwise return the
original string.
>>> blank_str_to_none("") is None
True
>>> blank_str_to_none("abc") == "abc"
True
>>> blank_str_to_none(" ") is None
True
>>> blank_str_to_none(" abc ") == " abc "
True
>>> blank_str_to_none(None) is None
True
"""
if string is None:
return None
return None if is_string_blank(string) else string
@typechecked
def replace_single_newline(text: str | None) -> str | None:
if text is None:
return None
return re.sub(r"\n+", lambda m: "\n" * (len(m.group()) - 1), text)