Skip to content

Commit

Permalink
better preflight response handler, exception unification
Browse files Browse the repository at this point in the history
  • Loading branch information
norbusan committed Sep 4, 2024
1 parent f490156 commit 42b686f
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 18 deletions.
43 changes: 29 additions & 14 deletions preflight_parser/preflight_parser/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,13 @@ class PostProcessType(str, Enum):
dvipdfmx = "dvipdfmx"


class ParseSyntaxError(Exception):
class PreflightException(Exception):
"""General exception when parsing preflight."""

pass


class ParseSyntaxError(PreflightException):
"""Syntax error when parsing a dict to an object."""

pass
Expand Down Expand Up @@ -339,7 +345,7 @@ def detect_postprocess(self) -> None:
elif self.output_type == OutputType.unknown:
self.postprocess = PostProcessType.unknown
else:
raise ValueError(f"unknown output type {self.output_type}")
raise PreflightException(f"unknown output type {self.output_type}")

def detect_output_type(self) -> None:
"""If possible, update the output type based on the content of the file."""
Expand Down Expand Up @@ -489,7 +495,7 @@ def collect_included_files(self, inc: list[str]) -> None:
include_options,
include_extra_argument,
)
raise ValueError
raise PreflightException(f"Unexpected number of file_argument value {incdef.file_argument}")
if incdef.multi_args:
for f in filearg.split(","):
fn = f[2:] if f.startswith("./") else f
Expand All @@ -499,7 +505,7 @@ def collect_included_files(self, inc: list[str]) -> None:
file_incspec[filearg] = incdef

else:
raise ValueError
raise PreflightException(f"Unexpected type of file_argument: {type(incdef.file_argument)}")

logging.debug(file_incspec)
self.mentioned_files |= file_incspec
Expand Down Expand Up @@ -559,7 +565,7 @@ def _find_entry_in_subgraph(
)
# keep found_language as LATEX
else:
raise ValueError(f"Unknown LanguageType {found_language}")
raise PreflightException(f"Unknown LanguageType {found_language}")

if found_output == OutputType.unknown:
found_output = kid_output
Expand Down Expand Up @@ -614,7 +620,7 @@ def _recursive_collect_files(self, what: FileType | str, visited: dict[str, bool
elif what == "issues":
idx = "issues"
else:
raise ValueError(f"no such file type: {what}")
raise PreflightException(f"no such file type: {what}")
found = getattr(self, idx)
visited[self.filename] = True
for n in self.children:
Expand Down Expand Up @@ -969,7 +975,7 @@ def update_nodes_with_kpse_info(
elif n.mentioned_files[f].type == FileType.other:
n.used_other_files.append(found)
else:
raise ValueError(f"Unknown file type {n.mentioned_files[f].type} for file {f}")
raise PreflightException(f"Unknown file type {n.mentioned_files[f].type} for file {f}")
n.update_engine_based_on_system_files()
return nodes

Expand Down Expand Up @@ -1015,7 +1021,7 @@ def compute_toplevel_files(roots: dict[str, ParsedTeXFile], nodes: dict[str, Par
elif lang == LanguageType.latex:
output = OutputType.pdf if found_output == OutputType.unknown else found_output
else:
raise ValueError(f"Unsupported language type {lang}")
raise PreflightException(f"Unsupported language type {lang}")
postprocess: PostProcessType
if output == OutputType.dvi:
postprocess = (
Expand Down Expand Up @@ -1064,12 +1070,7 @@ def deal_with_bibliographies(
tl_n.process.bibliography = BibProcessSpec(processor=BibCompiler.unknown, pre_generated=False)


def generate_preflight_response_json(rundir: str, **kwargs) -> str:
"""JSON representation of the preflight response."""
return generate_preflight_response(rundir).model_dump_json(exclude_none=True, exclude_defaults=True, **kwargs)


def generate_preflight_response(rundir: str) -> PreflightResponse:
def _generate_preflight_response_dict(rundir: str) -> PreflightResponse:
"""Parse submission and generated preflight response."""
# parse files
n: dict[str, ParsedTeXFile] | ToplevelFile = parse_dir(rundir)
Expand Down Expand Up @@ -1107,3 +1108,17 @@ def generate_preflight_response(rundir: str) -> PreflightResponse:
detected_toplevel_files=[tl for tl in toplevel_files.values()],
tex_files=[n for n in nodes.values()],
)

def generate_preflight_response(rundir: str, json: bool = False, **kwargs) -> PreflightResponse|str:
try:
pfr: PreflightResponse = _generate_preflight_response_dict(rundir)
except PreflightException as e:
pfr = PreflightResponse(
status = PreflightStatus(key=PreflightStatusValues.error, info=str(e)),
detected_toplevel_files=[],
tex_files=[]
)
if json:
return pfr.model_dump_json(exclude_none=True, exclude_defaults=True, **kwargs)
else:
return pfr
4 changes: 2 additions & 2 deletions preflight_parser/preflight_parser/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import argparse
import logging

from . import generate_preflight_response_json
from . import generate_preflight_response

parser = argparse.ArgumentParser()
parser.add_argument(
Expand All @@ -21,4 +21,4 @@
if args.log:
loglevel = getattr(logging, args.log.upper(), None)
logging.basicConfig(level=loglevel)
print(generate_preflight_response_json(args.subdir))
print(generate_preflight_response(args.subdir, json=True))
4 changes: 2 additions & 2 deletions preflight_parser/tests/test_preflight.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import os
import unittest

from preflight_parser import PreflightResponse, generate_preflight_response, generate_preflight_response_json
from preflight_parser import PreflightResponse, generate_preflight_response


class TestPreflight(unittest.TestCase):
Expand Down Expand Up @@ -86,7 +86,7 @@ def test_preflight_single_tex_4(self):
def test_preflight_roundtrip(self):
"""Test roundtrip behavior from json response via PreFlightResponse to json."""
dir_path = os.path.join(self.fixture_dir, "2311.03267")
pf_json: str = generate_preflight_response_json(dir_path)
pf_json: str = generate_preflight_response(dir_path, json=True)
pf_dict: dict = json.loads(pf_json)
pf: PreflightResponse = PreflightResponse(**pf_dict)
pf_json_roundtrip = pf.model_dump_json(exclude_none=True, exclude_defaults=True)
Expand Down

0 comments on commit 42b686f

Please sign in to comment.