Browse Source

Vylepšený error handling, žádná chyba už není Exception, warningy používají pythoní warnings #3

pull/28/head
Jan Černohorský 1 year ago
parent
commit
9092102fce
  1. 4
      src/formatitko/context.py
  2. 7
      src/formatitko/html_generator.py
  3. 10
      src/formatitko/images.py
  4. 13
      src/formatitko/katex.py

4
src/formatitko/context.py

@ -1,7 +1,7 @@
from panflute import Doc, Div from panflute import Doc, Div
import os import os
import warnings
# This class is used to keep state while transforming the document using # This class is used to keep state while transforming the document using
# transform.py. For the context to be available to the html and TeX generators, # transform.py. For the context to be available to the html and TeX generators,
@ -68,7 +68,7 @@ class Context:
def set_metadata(self, key: str, value): def set_metadata(self, key: str, value):
if key == "language": if key == "language":
print("WARN: Setting language this way doesn't propagate to TeX. Either use the Front Matter or specify it additionally using the \\languagexx macro.") warnings.warn("Setting language this way doesn't propagate to TeX. Either use the Front Matter or specify it additionally using the \\languagexx macro.", UserWarning)
meta = self.doc.metadata meta = self.doc.metadata
keys = key.split(".") keys = key.split(".")
for k in keys[:-1]: for k in keys[:-1]:

7
src/formatitko/html_generator.py

@ -7,6 +7,7 @@ from typing import Union, Dict
import re import re
import os import os
import io import io
import warnings
from pygments import highlight from pygments import highlight
from pygments.lexers import get_lexer_by_name from pygments.lexers import get_lexer_by_name
@ -107,6 +108,7 @@ class HTMLGenerator(OutputGenerator):
self.generate_simple_block_tag(e, "main", self.common_attributes(e)) self.generate_simple_block_tag(e, "main", self.common_attributes(e))
def generate_CodeBlock(self, e: CodeBlock): def generate_CodeBlock(self, e: CodeBlock):
lexer = None
if e.classes and len(e.classes) > 0 and (e.attributes["highlight"] == True or e.attributes["highlight"] == 'True'): if e.classes and len(e.classes) > 0 and (e.attributes["highlight"] == True or e.attributes["highlight"] == 'True'):
# Syntax highlighting using pygments # Syntax highlighting using pygments
for cl in e.classes: for cl in e.classes:
@ -116,8 +118,9 @@ class HTMLGenerator(OutputGenerator):
continue continue
break break
else: else:
lexer = None warnings.warn(f"Syntax highligher does not have lexer for element with these classes: {e.classes}", UserWarning)
print(f"WARN: Syntax highligher does not have lexer for element with these classes: {e.classes}")
if lexer:
formatter = HtmlFormatter(style=e.attributes["style"]) formatter = HtmlFormatter(style=e.attributes["style"])
result = highlight(e.text, lexer, formatter) result = highlight(e.text, lexer, formatter)
self.writeraw(result) self.writeraw(result)

10
src/formatitko/images.py

@ -7,6 +7,12 @@ from PIL import Image
class FileInWrongDirError(Exception): class FileInWrongDirError(Exception):
pass pass
class InkscapeError(Exception):
pass
class ImageMagickError(Exception):
pass
class ImageProcessor: class ImageProcessor:
def __init__(self, public_dir: str, web_path: str, cache_dir: str, *lookup_dirs: List[str]): def __init__(self, public_dir: str, web_path: str, cache_dir: str, *lookup_dirs: List[str]):
self.public_dir = public_dir self.public_dir = public_dir
@ -67,7 +73,7 @@ class ImageProcessor:
height_arg = ['--export-height', str(height)] if height is not None else [] height_arg = ['--export-height', str(height)] if height is not None else []
dpi_arg = ['--export-dpi', str(dpi)] if dpi is not None else [] dpi_arg = ['--export-dpi', str(dpi)] if dpi is not None else []
if subprocess.run(['inkscape', full_path, '-o', target_path, *width_arg, *height_arg, *dpi_arg]).returncode != 0: if subprocess.run(['inkscape', full_path, '-o', target_path, *width_arg, *height_arg, *dpi_arg]).returncode != 0:
raise Exception(f"Could not convert '{full_path}' to '{format}'") raise InkscapeError(f"Could not convert '{full_path}' to '{format}'")
# Convert everything else using ImageMagick. # Convert everything else using ImageMagick.
else: else:
@ -75,7 +81,7 @@ class ImageProcessor:
density_arg = ['-density', str(dpi)] if dpi is not None else [] density_arg = ['-density', str(dpi)] if dpi is not None else []
quality_arg = ['-quality', str(quality)] if quality is not None else [] quality_arg = ['-quality', str(quality)] if quality is not None else []
if subprocess.run(['convert', *density_arg, full_path, *resize_arg, *quality_arg, target_path]).returncode != 0: if subprocess.run(['convert', *density_arg, full_path, *resize_arg, *quality_arg, target_path]).returncode != 0:
raise Exception(f"Could not convert '{full_path}' to '{format}'") raise ImageMagickError(f"Could not convert '{full_path}' to '{format}'")
return target_name return target_name

13
src/formatitko/katex.py

@ -9,6 +9,13 @@ from typing import Dict
class KatexError(Exception): class KatexError(Exception):
pass pass
class NPMNotFoundError(Exception):
pass
class KatexServerError(Exception):
pass
class KatexClient: class KatexClient:
def __init__(self): def __init__(self):
# Create temporary directory for socket # Create temporary directory for socket
@ -24,7 +31,7 @@ class KatexClient:
subprocess.run(["npm", "install"], cwd=srcdir+"/katex-server", check=True) subprocess.run(["npm", "install"], cwd=srcdir+"/katex-server", check=True)
except subprocess.CalledProcessError as e: except subprocess.CalledProcessError as e:
if e.returncode == 127: if e.returncode == 127:
raise Exception("npm not found. Node.js is required to use KaTeX.") raise NPMNotFoundError("npm not found. Node.js is required to use KaTeX.")
else: else:
raise e raise e
@ -34,7 +41,7 @@ class KatexClient:
ok = self._server_process.stdout.readline() ok = self._server_process.stdout.readline()
if ok != b"OK\n": if ok != b"OK\n":
raise Exception("Failed to connect to katex-server") raise KatexServerError("Failed to connect to katex-server")
self._client.connect(self._socket_file) self._client.connect(self._socket_file)
@ -49,7 +56,7 @@ class KatexClient:
response = json.loads(data) response = json.loads(data)
if "error" in response: if "error" in response:
raise Exception(response["error"]) raise KatexServerError(response["error"])
if "error" in response["results"][0]: if "error" in response["results"][0]:
raise KatexError(response["results"][0]["error"]) raise KatexError(response["results"][0]["error"])
else: else:

Loading…
Cancel
Save