|
2 | 2 |
|
3 | 3 | import logging |
4 | 4 | import pprint |
| 5 | +from enum import Enum |
5 | 6 | from pathlib import Path |
6 | 7 | from typing import Any |
7 | 8 |
|
8 | 9 | import yaml |
9 | 10 | from jinja2 import Template |
| 11 | +from pydantic import ( |
| 12 | + BaseModel, |
| 13 | + ConfigDict, |
| 14 | + Field, |
| 15 | + model_validator, |
| 16 | +) |
| 17 | +from ruamel.yaml import YAML |
10 | 18 |
|
11 | 19 | from .errors import ConfigurationError |
12 | | -from .logging import truncate_strings |
| 20 | +from .logging import LoggingMixin, truncate_strings |
13 | 21 | from .types import PathSpec |
14 | 22 |
|
15 | 23 | __all__ = ["PDFBakerConfiguration", "deep_merge", "render_config"] |
16 | 24 |
|
17 | 25 | logger = logging.getLogger(__name__) |
18 | 26 |
|
19 | 27 |
|
| 28 | +# ##################################################################### |
| 29 | +# New Pydantic models |
| 30 | +# ##################################################################### |
| 31 | + |
| 32 | +# TODO: show names instead of index numbers for error locations |
| 33 | +# https://docs.pydantic.dev/latest/errors/errors/#customize-error-messages |
| 34 | + |
| 35 | + |
| 36 | +class NewPathSpec(BaseModel): |
| 37 | + """File/Directory location in YAML config.""" |
| 38 | + |
| 39 | + # Relative paths may not exist until resolved against root, |
| 40 | + # so we have to check existence later |
| 41 | + # path: FilePath | DirectoryPath |
| 42 | + path: Path |
| 43 | + name: str = Field(default_factory=lambda data: data["path"].stem) |
| 44 | + |
| 45 | + @model_validator(mode="before") |
| 46 | + @classmethod |
| 47 | + def ensure_pathspec(cls, data: Any) -> Any: |
| 48 | + """Coerce what was given""" |
| 49 | + if isinstance(data, str): |
| 50 | + data = {"name": data} |
| 51 | + if isinstance(data, dict) and "path" not in data: |
| 52 | + data["path"] = Path(data["name"]) |
| 53 | + return data |
| 54 | + |
| 55 | + |
| 56 | +class ImageSpec(NewPathSpec): |
| 57 | + """Image specification.""" |
| 58 | + |
| 59 | + type: str | None = None |
| 60 | + data: str | None = None |
| 61 | + |
| 62 | + |
| 63 | +class StyleDict(BaseModel): |
| 64 | + """Style configuration.""" |
| 65 | + |
| 66 | + highlight_color: str | None = None |
| 67 | + |
| 68 | + |
| 69 | +class DirectoriesConfig(BaseModel): |
| 70 | + """Directories configuration.""" |
| 71 | + |
| 72 | + root: NewPathSpec |
| 73 | + build: NewPathSpec |
| 74 | + dist: NewPathSpec |
| 75 | + documents: NewPathSpec |
| 76 | + pages: NewPathSpec |
| 77 | + templates: NewPathSpec |
| 78 | + images: NewPathSpec |
| 79 | + |
| 80 | + @model_validator(mode="after") |
| 81 | + def resolve_paths(self) -> Any: |
| 82 | + """Resolve all paths relative to the root directory.""" |
| 83 | + self.root.path = self.root.path.resolve() |
| 84 | + for field_name, value in self.__dict__.items(): |
| 85 | + if field_name != "root" and isinstance(value, NewPathSpec): |
| 86 | + value.path = (self.root.path / value.path).resolve() |
| 87 | + return self |
| 88 | + |
| 89 | + |
| 90 | +class PageConfig(BaseModel, LoggingMixin): |
| 91 | + """Page configuration.""" |
| 92 | + |
| 93 | + directories: DirectoriesConfig |
| 94 | + template: NewPathSpec |
| 95 | + model_config = ConfigDict( |
| 96 | + strict=True, # don't try to coerce values |
| 97 | + extra="allow", # will go in __pydantic_extra__ dict |
| 98 | + ) |
| 99 | + |
| 100 | + |
| 101 | +class DocumentConfig(BaseModel, LoggingMixin): |
| 102 | + """Document configuration. |
| 103 | +
|
| 104 | + Lazy-loads page configs. |
| 105 | + """ |
| 106 | + |
| 107 | + directories: DirectoriesConfig |
| 108 | + pages: list[Path | PageConfig] |
| 109 | + model_config = ConfigDict( |
| 110 | + strict=True, # don't try to coerce values |
| 111 | + extra="allow", # will go in __pydantic_extra__ dict |
| 112 | + ) |
| 113 | + |
| 114 | + |
| 115 | +class DocumentVariantConfig(DocumentConfig): |
| 116 | + """Document variant configuration.""" |
| 117 | + |
| 118 | + |
| 119 | +class TemplateRenderer(Enum): |
| 120 | + """Possible values for template_renderers.""" |
| 121 | + |
| 122 | + RENDER_HIGHLIGHT = "render_highlight" |
| 123 | + |
| 124 | + |
| 125 | +class TemplateFilter(Enum): |
| 126 | + """Possible values for template_filters.""" |
| 127 | + |
| 128 | + WORDWRAP = "wordwrap" |
| 129 | + |
| 130 | + |
| 131 | +class SVG2PDFBackend(Enum): |
| 132 | + """Possible values for svg2pdf_backend.""" |
| 133 | + |
| 134 | + CAIROSVG = "cairosvg" |
| 135 | + INKSCAPE = "inkscape" |
| 136 | + |
| 137 | + |
| 138 | +class BakerConfig(BaseModel, LoggingMixin): |
| 139 | + """Baker configuration. |
| 140 | +
|
| 141 | + Lazy-loads document configs. |
| 142 | + """ |
| 143 | + |
| 144 | + directories: DirectoriesConfig |
| 145 | + # TODO: lazy/forgiving documents parsing |
| 146 | + # documents: list[Path | DocumentConfig] |
| 147 | + documents: list[str] |
| 148 | + template_renderers: list[TemplateRenderer] = [TemplateRenderer.RENDER_HIGHLIGHT] |
| 149 | + template_filters: list[TemplateFilter] = [TemplateFilter.WORDWRAP] |
| 150 | + svg2pdf_backend: SVG2PDFBackend | None = SVG2PDFBackend.CAIROSVG |
| 151 | + compress_pdf: bool = False |
| 152 | + model_config = ConfigDict( |
| 153 | + strict=True, # don't try to coerce values |
| 154 | + extra="allow", # will go in __pydantic_extra__ dict |
| 155 | + ) |
| 156 | + |
| 157 | + @model_validator(mode="before") |
| 158 | + @classmethod |
| 159 | + def load_config(cls, data: Any) -> Any: |
| 160 | + """Load documents from YAML file.""" |
| 161 | + if isinstance(data, dict) and "config_file" in data: |
| 162 | + config_file = data.pop("config_file") |
| 163 | + config_data = YAML().load(config_file.read_text()) |
| 164 | + config_data.update(data) # let kwargs override values from YAML |
| 165 | + return config_data |
| 166 | + return data |
| 167 | + |
| 168 | + @model_validator(mode="before") |
| 169 | + @classmethod |
| 170 | + def set_default_directories(cls, data: Any) -> Any: |
| 171 | + """Set default directories.""" |
| 172 | + if isinstance(data, dict): |
| 173 | + directories = data.setdefault("directories", {}) |
| 174 | + directories.setdefault("root", ".") |
| 175 | + directories.setdefault("build", "build") |
| 176 | + directories.setdefault("dist", "dist") |
| 177 | + directories.setdefault("documents", ".") |
| 178 | + directories.setdefault("pages", "pages") |
| 179 | + directories.setdefault("templates", "templates") |
| 180 | + directories.setdefault("images", "images") |
| 181 | + return data |
| 182 | + |
| 183 | + @property |
| 184 | + def custom_config(self) -> dict[str, Any]: |
| 185 | + """Dictionary of all custom user-defined configuration.""" |
| 186 | + return self.__pydantic_extra__ |
| 187 | + |
| 188 | + |
| 189 | +class BakerOptions(BaseModel): |
| 190 | + """Options for controlling PDFBaker behavior. |
| 191 | +
|
| 192 | + Attributes: |
| 193 | + quiet: Show errors only |
| 194 | + verbose: Show debug information |
| 195 | + trace: Show trace information (even more detailed than debug) |
| 196 | + keep_build: Keep build artifacts after processing |
| 197 | + default_config_overrides: Dictionary of values to override the built-in defaults |
| 198 | + before loading the main configuration |
| 199 | + """ |
| 200 | + |
| 201 | + quiet: bool = False |
| 202 | + verbose: bool = False |
| 203 | + trace: bool = False |
| 204 | + keep_build: bool = False |
| 205 | + default_config_overrides: dict[str, Any] | None = None |
| 206 | + |
| 207 | + |
| 208 | +# ##################################################################### |
| 209 | + |
| 210 | + |
20 | 211 | def deep_merge(base: dict[str, Any], update: dict[str, Any]) -> dict[str, Any]: |
21 | 212 | """Deep merge two dictionaries.""" |
22 | 213 | result = base.copy() |
|
0 commit comments