pytex/PyTeX/format/generic_text.py

57 lines
1.7 KiB
Python
Raw Normal View History

2022-02-05 22:37:09 +01:00
from pathlib import Path
from typing import Union, List, Optional
2022-02-06 16:50:09 +01:00
from ..logger import logger
2022-02-05 22:37:09 +01:00
class GenericText:
def __init__(self, content: Union[List[str], Path]):
if isinstance(content, List):
self._content: Optional[List[str]] = content
self._path = None
else:
self._content: Optional[List[str]] = None
self._path = content
@property
2022-02-06 15:10:00 +01:00
def text(self) -> List[str]:
2022-02-05 22:37:09 +01:00
if self._content is None:
try:
with open(self._path, 'r') as file:
self._content = file.readlines()
except FileNotFoundError:
raise NotImplementedError
except:
raise NotImplementedError
return self._content
@text.setter
def text(self, content: Union[List[str], Path]) -> None:
if isinstance(content, List):
self._content = content
self._path = None
else:
self._content = None
self._path = content
2022-02-05 22:37:09 +01:00
def format(self, **kwargs) -> str:
2022-02-06 16:50:09 +01:00
lines = []
2022-02-05 22:37:09 +01:00
for line in self._content:
try:
2022-02-06 16:50:09 +01:00
line = '% ' + line.format(**kwargs).rjust(77) + '%'
if len(line) > 80:
logger.warning(
'Line too long') # TODO
lines.append(line)
2022-02-05 22:37:09 +01:00
except ValueError:
raise NotImplementedError
2022-02-06 16:50:09 +01:00
return '\n'.join(lines)
def __add__(self, other):
if isinstance(other, GenericText):
return GenericText(self.text + other.text)
else:
return GenericText(self.text + other)
def __iadd__(self, other):
self.text = self + other