add custom PyTeX exceptions to be thrown and catched during build to prevent ugly python error messaged

This commit is contained in:
Maximilian Keßler 2022-01-12 21:35:47 +01:00
parent 4a0e095899
commit 1df567da82
6 changed files with 62 additions and 9 deletions

View file

@ -5,6 +5,7 @@ from typing import Optional
import git
from PyTeX.config.constants import BUILD_INFO_FILENAME
from PyTeX.errors import *
from .utils import BuildInfo, pytex_msg, TexFileToFormat
@ -34,7 +35,7 @@ def build(
text = f.readlines()
extra_header = [line.rstrip() for line in text]
else:
raise FileNotFoundError('Path to extra header content is invalid.')
raise ExtraHeaderFileNotFoundError
current_build_info = BuildInfo(
include_timestamp=include_timestamp,
include_pytex_version=include_pytex_version,
@ -46,6 +47,9 @@ def build(
pytex_repo=git.Repo(__file__, search_parent_directories=True),
packages_repo=git.Repo(src_dir, search_parent_directories=True)
)
print(r'[PyTeX] This is PyTex version {pytex_version}'.format(
pytex_version=current_build_info.pytex_version
))
input_dir = src_dir if src_dir else input_file.parent
output_dir = build_dir if build_dir else input_file.parent

View file

@ -2,6 +2,7 @@ import argparse
import pathlib
from PyTeX.config import FILENAME_TYPE_PREPEND_AUTHOR, FILENAME_TYPE_RAW_NAME
from PyTeX.errors import PyTexError
from .build import build
@ -108,4 +109,8 @@ def parse_and_build(arglist: [str]):
for arg in args.keys():
if type(args[arg]) == pathlib.PosixPath:
args[arg] = args[arg].resolve()
try:
build(**args)
except PyTexError as e:
print(e)
exit(1)

View file

@ -3,6 +3,7 @@ from typing import Optional, List
from PyTeX.build.git_hook import is_recent, get_latest_commit
from PyTeX import PackageFormatter, ClassFormatter, DictionaryFormatter
from PyTeX.errors import *
from .pytex_msg import pytex_msg
from .build_information import BuildInfo
@ -51,10 +52,7 @@ class TexFileToFormat:
def format(self) -> dict:
if self.dirty or self.pytex_dirty:
if not self.allow_dirty:
raise Exception(
'{file} is dirty, but writing dirty files not allowed.'.format(
file=self.src_path.name if self.dirty else 'Submodule PyTeX')
)
raise SubmoduleDirtyForbiddenError
# TODO: add this to the header...?
return self.__format() # Dirty files are always built, since we have no information about them
elif self.build_all:
@ -77,7 +75,7 @@ class TexFileToFormat:
elif '.pydict' in self.src_path.name:
latex_file_type = 'dictionary'
else:
raise Exception('Programming error. Please contact the developer.')
raise ProgrammingError
new_header.append(line.format(
source_file=self.src_path.name,
latex_file_type=latex_file_type
@ -124,7 +122,7 @@ class TexFileToFormat:
header=self._header
)
else:
raise Exception('Programming error. Please contact the developer.')
raise ProgrammingError
pytex_msg('Writing file {}'.format(formatter.file_name))
formatter.make_default_macros()
formatter.format_file(self.src_path, self.build_path)

10
errors/__init__.py Normal file
View file

@ -0,0 +1,10 @@
from .errors import PyTexError, SubmoduleDirtyForbiddenError, ProgrammingError, ExtraHeaderFileNotFoundError, \
UnknownTexVersionError
__all__ = [
'PyTexError',
'SubmoduleDirtyForbiddenError',
'ProgrammingError',
'ExtraHeaderFileNotFoundError',
'UnknownTexVersionError'
]

35
errors/errors.py Normal file
View file

@ -0,0 +1,35 @@
class PyTexError(Exception):
def __init__(self, message, *args, **kwargs):
self.message = message
def __str__(self):
return r'{prefix} ERROR: {message}'.format(
prefix='[PyTeX]',
message=self.message
)
class SubmoduleDirtyForbiddenError(PyTexError):
def __init__(self):
super().__init__(
"Submodule PyTeX is dirty, but writing dirty files is not allowed. "
"Call PyTeX with '--allow-dirty' option, or commit the submodule changes.")
class ExtraHeaderFileNotFoundError(PyTexError):
def __init__(self):
super().__init__('Path to extra header content is invalid.')
class ProgrammingError(PyTexError):
def __init__(self):
super().__init__("A FATAL programming error has occurred. Please contact the developer.")
class UnknownTexVersionError(PyTexError):
def __init__(self, tex_version: str):
super().__init__(
f"Unknown TeX version {tex_version}given. Only 'LaTeX2e' and 'LaTeX3' "
f"are currently supported"
)

View file

@ -5,6 +5,7 @@ from typing import Dict, Optional, List
from datetime import *
from PyTeX.base import Attributes, Args
from PyTeX.errors import UnknownTexVersionError
class TexFormatter:
@ -34,7 +35,7 @@ class TexFormatter:
elif tex_version == 'LaTeX3':
self.prefix = '__' + self.name_lowercase.replace('-', '_') + '_'
else:
raise Exception('Unknown TeX version')
raise UnknownTexVersionError(tex_version)
@staticmethod
def __command_name2keyword(keyword: str):