TISbackup/libtisbackup/iniparse/utils.py

53 lines
1.4 KiB
Python
Raw Normal View History

from typing import TYPE_CHECKING, List
2022-04-25 10:02:43 +02:00
from . import compat
2024-11-28 23:46:48 +01:00
from .ini import EmptyLine, LineContainer
2022-04-25 10:02:43 +02:00
if TYPE_CHECKING:
from .ini import LineType
2013-05-23 10:19:43 +02:00
def tidy(cfg: compat.RawConfigParser):
2013-05-23 10:19:43 +02:00
"""Clean up blank lines.
This functions makes the configuration look clean and
handwritten - consecutive empty lines and empty lines at
the start of the file are removed, and one is guaranteed
to be at the end of the file.
"""
if isinstance(cfg, compat.RawConfigParser):
cfg = cfg.data
cont = cfg._data.contents
i = 1
while i < len(cont):
if isinstance(cont[i], LineContainer):
tidy_section(cont[i])
i += 1
elif isinstance(cont[i - 1], EmptyLine) and isinstance(cont[i], EmptyLine):
2013-05-23 10:19:43 +02:00
del cont[i]
else:
i += 1
# Remove empty first line
if cont and isinstance(cont[0], EmptyLine):
del cont[0]
# Ensure a last line
if cont and not isinstance(cont[-1], EmptyLine):
cont.append(EmptyLine())
2022-04-25 10:02:43 +02:00
def tidy_section(lc: "LineContainer"):
cont: List[LineType] = lc.contents
i: int = 1
2013-05-23 10:19:43 +02:00
while i < len(cont):
if isinstance(cont[i - 1], EmptyLine) and isinstance(cont[i], EmptyLine):
2013-05-23 10:19:43 +02:00
del cont[i]
else:
i += 1
# Remove empty first line
if len(cont) > 1 and isinstance(cont[1], EmptyLine):
del cont[1]