From 9092102fce52cf156c2816ebd3c9dbeb4fc6e58c Mon Sep 17 00:00:00 2001 From: Greenscreener Date: Wed, 19 Jul 2023 19:30:17 +0200 Subject: [PATCH] =?UTF-8?q?Vylep=C5=A1en=C3=BD=20error=20handling,=20?= =?UTF-8?q?=C5=BE=C3=A1dn=C3=A1=20chyba=20u=C5=BE=20nen=C3=AD=20Exception,?= =?UTF-8?q?=20warningy=20pou=C5=BE=C3=ADvaj=C3=AD=20python=C3=AD=20warning?= =?UTF-8?q?s=20#3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/formatitko/context.py | 4 ++-- src/formatitko/html_generator.py | 7 +++++-- src/formatitko/images.py | 10 ++++++++-- src/formatitko/katex.py | 13 ++++++++++--- 4 files changed, 25 insertions(+), 9 deletions(-) diff --git a/src/formatitko/context.py b/src/formatitko/context.py index d262ec2..24f98ee 100644 --- a/src/formatitko/context.py +++ b/src/formatitko/context.py @@ -1,7 +1,7 @@ from panflute import Doc, Div import os - +import warnings # 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, @@ -68,7 +68,7 @@ class Context: def set_metadata(self, key: str, value): 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 keys = key.split(".") for k in keys[:-1]: diff --git a/src/formatitko/html_generator.py b/src/formatitko/html_generator.py index 32e5b2c..ec11a87 100644 --- a/src/formatitko/html_generator.py +++ b/src/formatitko/html_generator.py @@ -7,6 +7,7 @@ from typing import Union, Dict import re import os import io +import warnings from pygments import highlight 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)) 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'): # Syntax highlighting using pygments for cl in e.classes: @@ -116,8 +118,9 @@ class HTMLGenerator(OutputGenerator): continue break else: - lexer = None - print(f"WARN: Syntax highligher does not have lexer for element with these classes: {e.classes}") + warnings.warn(f"Syntax highligher does not have lexer for element with these classes: {e.classes}", UserWarning) + + if lexer: formatter = HtmlFormatter(style=e.attributes["style"]) result = highlight(e.text, lexer, formatter) self.writeraw(result) diff --git a/src/formatitko/images.py b/src/formatitko/images.py index 421c9e9..f084302 100644 --- a/src/formatitko/images.py +++ b/src/formatitko/images.py @@ -7,6 +7,12 @@ from PIL import Image class FileInWrongDirError(Exception): pass +class InkscapeError(Exception): + pass + +class ImageMagickError(Exception): + pass + class ImageProcessor: def __init__(self, public_dir: str, web_path: str, cache_dir: str, *lookup_dirs: List[str]): self.public_dir = public_dir @@ -67,7 +73,7 @@ class ImageProcessor: height_arg = ['--export-height', str(height)] if height 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: - 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. else: @@ -75,7 +81,7 @@ class ImageProcessor: density_arg = ['-density', str(dpi)] if dpi 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: - raise Exception(f"Could not convert '{full_path}' to '{format}'") + raise ImageMagickError(f"Could not convert '{full_path}' to '{format}'") return target_name diff --git a/src/formatitko/katex.py b/src/formatitko/katex.py index d4c9bf5..711b1d3 100644 --- a/src/formatitko/katex.py +++ b/src/formatitko/katex.py @@ -9,6 +9,13 @@ from typing import Dict class KatexError(Exception): pass +class NPMNotFoundError(Exception): + pass + +class KatexServerError(Exception): + pass + + class KatexClient: def __init__(self): # Create temporary directory for socket @@ -24,7 +31,7 @@ class KatexClient: subprocess.run(["npm", "install"], cwd=srcdir+"/katex-server", check=True) except subprocess.CalledProcessError as e: 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: raise e @@ -34,7 +41,7 @@ class KatexClient: ok = self._server_process.stdout.readline() 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) @@ -49,7 +56,7 @@ class KatexClient: response = json.loads(data) if "error" in response: - raise Exception(response["error"]) + raise KatexServerError(response["error"]) if "error" in response["results"][0]: raise KatexError(response["results"][0]["error"]) else: