postext 1.70.5__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- postext/__init__.py +123 -0
- postext/__main__.py +8 -0
- postext/_binary.py +280 -0
- postext/_client.py +629 -0
- postext/_errors.py +44 -0
- postext/_report.py +321 -0
- postext/_version.py +4 -0
- postext/py.typed +0 -0
- postext-1.70.5.dist-info/METADATA +151 -0
- postext-1.70.5.dist-info/RECORD +12 -0
- postext-1.70.5.dist-info/WHEEL +4 -0
- postext-1.70.5.dist-info/licenses/LICENSE +21 -0
postext/_client.py
ADDED
|
@@ -0,0 +1,629 @@
|
|
|
1
|
+
"""The commands of the postext command line as Python methods.
|
|
2
|
+
|
|
3
|
+
Each method builds the command's arguments, runs the executable with
|
|
4
|
+
``--json`` and returns the parsed report; a failure raises. Paths may be
|
|
5
|
+
``str`` or ``os.PathLike``; a book (or a Word document) may also be given
|
|
6
|
+
as ``bytes``, which go to a temporary file for the run.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import contextlib
|
|
12
|
+
import json
|
|
13
|
+
import os
|
|
14
|
+
import subprocess
|
|
15
|
+
import sys
|
|
16
|
+
import tempfile
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
from typing import (
|
|
19
|
+
TYPE_CHECKING,
|
|
20
|
+
Any,
|
|
21
|
+
Dict,
|
|
22
|
+
Iterable,
|
|
23
|
+
List,
|
|
24
|
+
Mapping,
|
|
25
|
+
Optional,
|
|
26
|
+
Sequence,
|
|
27
|
+
Tuple,
|
|
28
|
+
Type,
|
|
29
|
+
TypeVar,
|
|
30
|
+
Union,
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
from ._binary import find_binary
|
|
34
|
+
from ._errors import PostextError, ProblemsFound, UsageError
|
|
35
|
+
from ._report import CheckReport, ImageReport, ImportDocxReport, InfoReport, Report, UnpackReport
|
|
36
|
+
from ._version import __version__
|
|
37
|
+
|
|
38
|
+
if TYPE_CHECKING:
|
|
39
|
+
from typing_extensions import TypedDict, Unpack
|
|
40
|
+
|
|
41
|
+
PathLike = Union[str, "os.PathLike[str]"]
|
|
42
|
+
#: A book: a ``.postext`` file, a book folder, a Markdown file, or the
|
|
43
|
+
#: bytes of a ``.postext`` bundle.
|
|
44
|
+
BookInput = Union[PathLike, bytes]
|
|
45
|
+
Books = Union[BookInput, Sequence[BookInput]]
|
|
46
|
+
Chapters = Union[int, str, range, Sequence[Union[int, str, range]]]
|
|
47
|
+
Settings = Union[Mapping[str, Any], Sequence[str]]
|
|
48
|
+
|
|
49
|
+
#: ``out="-"`` (or ``STDOUT``): the command writes to stdout and the bytes
|
|
50
|
+
#: come back in ``Report.content``.
|
|
51
|
+
STDOUT = "-"
|
|
52
|
+
|
|
53
|
+
R = TypeVar("R", bound=Report)
|
|
54
|
+
|
|
55
|
+
if TYPE_CHECKING:
|
|
56
|
+
|
|
57
|
+
class BookOptions(TypedDict, total=False):
|
|
58
|
+
"""Options of every command that reads a book."""
|
|
59
|
+
|
|
60
|
+
locale: str
|
|
61
|
+
"""Language to read a multilingual book in (``es``, ``en``, ``pt-BR``…)."""
|
|
62
|
+
chapters: Chapters
|
|
63
|
+
"""Chapters to lay out, from 1: ``3``, ``"1,3-5"``, ``[1, 3]``, ``range(1, 4)``."""
|
|
64
|
+
set: Settings
|
|
65
|
+
"""Settings to change: ``{"page.dpi": 300, "bodyText.fontSize.value": 11}``."""
|
|
66
|
+
config: Union[PathLike, Mapping[str, Any]]
|
|
67
|
+
"""Configuration JSON (a file, or a dict) for loose Markdown, or merged over a book's."""
|
|
68
|
+
resources: PathLike
|
|
69
|
+
"""Pictures folder for loose Markdown."""
|
|
70
|
+
fonts: PathLike
|
|
71
|
+
"""Font files bundled with loose Markdown."""
|
|
72
|
+
name: str
|
|
73
|
+
"""Book title for loose Markdown."""
|
|
74
|
+
font_dirs: Union[PathLike, Sequence[PathLike]]
|
|
75
|
+
"""Extra folders to look for fonts the book does not carry."""
|
|
76
|
+
offline: bool
|
|
77
|
+
"""Never download fonts from Google Fonts."""
|
|
78
|
+
cache_dir: PathLike
|
|
79
|
+
"""Where downloaded fonts are kept."""
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
_BOOK_KEYS = ("locale", "chapters", "set", "config", "resources", "fonts", "name", "font_dirs", "offline", "cache_dir")
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _chapters(value: Chapters) -> str:
|
|
86
|
+
def one(v: Union[int, str, range]) -> str:
|
|
87
|
+
if isinstance(v, range):
|
|
88
|
+
if v.step != 1 or len(v) == 0:
|
|
89
|
+
raise ValueError(f"chapters: {v!r} is not a run of chapters")
|
|
90
|
+
return f"{v.start}-{v.stop - 1}" if len(v) > 1 else str(v.start)
|
|
91
|
+
return str(v)
|
|
92
|
+
|
|
93
|
+
if isinstance(value, (int, str, range)):
|
|
94
|
+
return one(value)
|
|
95
|
+
return ",".join(one(v) for v in value)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _setting(value: Any) -> str:
|
|
99
|
+
"""A ``--set`` value: the command line reads it as JSON when it parses
|
|
100
|
+
(numbers, booleans, lists, objects), else as text."""
|
|
101
|
+
if isinstance(value, str):
|
|
102
|
+
return value
|
|
103
|
+
return json.dumps(value, ensure_ascii=False, separators=(",", ":"))
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _settings(value: Settings) -> List[str]:
|
|
107
|
+
if isinstance(value, Mapping):
|
|
108
|
+
return [f"{k}={_setting(v)}" for k, v in value.items()]
|
|
109
|
+
if isinstance(value, str):
|
|
110
|
+
return [value]
|
|
111
|
+
return [str(v) for v in value]
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _flag(name: str, value: Optional[bool]) -> List[str]:
|
|
115
|
+
if value is None:
|
|
116
|
+
return []
|
|
117
|
+
return [f"--{name}" if value else f"--no-{name}"]
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def _opt(name: str, value: Any) -> List[str]:
|
|
121
|
+
if value is None:
|
|
122
|
+
return []
|
|
123
|
+
if isinstance(value, bool):
|
|
124
|
+
return _flag(name, value)
|
|
125
|
+
return [f"--{name}", os.fspath(value) if isinstance(value, os.PathLike) else str(value)]
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _many(value: Union[PathLike, Sequence[PathLike], None]) -> List[str]:
|
|
129
|
+
if value is None:
|
|
130
|
+
return []
|
|
131
|
+
if isinstance(value, (str, os.PathLike)):
|
|
132
|
+
return [os.fspath(value)]
|
|
133
|
+
return [os.fspath(v) for v in value]
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def _split_stdout(stdout: bytes, want_content: bool) -> Tuple[Optional[Dict[str, Any]], Optional[bytes]]:
|
|
137
|
+
"""The JSON report and, with ``-o -``, the bytes before it. The report is
|
|
138
|
+
the last thing on stdout and opens with ``{\\n "ok": ``; no nested key
|
|
139
|
+
sits at that indentation, so its last occurrence is the report's start."""
|
|
140
|
+
start = stdout.rfind(b'{\n "ok": ') if want_content else 0
|
|
141
|
+
if want_content and start == -1:
|
|
142
|
+
return None, stdout
|
|
143
|
+
text = stdout[start:].decode("utf-8", "replace").strip()
|
|
144
|
+
if not text:
|
|
145
|
+
return None, stdout[:start] if want_content else None
|
|
146
|
+
try:
|
|
147
|
+
report = json.loads(text)
|
|
148
|
+
except ValueError:
|
|
149
|
+
return None, stdout if want_content else None
|
|
150
|
+
return (report if isinstance(report, dict) else None), (stdout[:start] if want_content else None)
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def _stderr_error(stderr: str) -> str:
|
|
154
|
+
lines = [ln for ln in stderr.splitlines() if ln.strip()]
|
|
155
|
+
errors = [ln[6:] if ln.startswith("error ") else ln for ln in lines if ln.startswith("error")]
|
|
156
|
+
return "; ".join(errors) or (lines[-1] if lines else "postext failed")
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
class Postext:
|
|
160
|
+
"""Runs one postext executable.
|
|
161
|
+
|
|
162
|
+
``binary``: the executable (default: ``POSTEXT_BIN``, else the one of
|
|
163
|
+
this platform, downloaded on first use). ``cwd``, ``env`` and
|
|
164
|
+
``timeout`` (seconds) apply to every run. ``offline`` and ``font_dirs``
|
|
165
|
+
are the defaults of the book options of the same names.
|
|
166
|
+
|
|
167
|
+
The module-level functions (``postext.pdf`` …) use a default instance.
|
|
168
|
+
"""
|
|
169
|
+
|
|
170
|
+
def __init__(
|
|
171
|
+
self,
|
|
172
|
+
binary: Optional[PathLike] = None,
|
|
173
|
+
*,
|
|
174
|
+
cwd: Optional[PathLike] = None,
|
|
175
|
+
env: Optional[Mapping[str, str]] = None,
|
|
176
|
+
timeout: Optional[float] = None,
|
|
177
|
+
offline: Optional[bool] = None,
|
|
178
|
+
font_dirs: Union[PathLike, Sequence[PathLike], None] = None,
|
|
179
|
+
) -> None:
|
|
180
|
+
self._binary = Path(os.fspath(binary)) if binary is not None else None
|
|
181
|
+
self.cwd = cwd
|
|
182
|
+
self.env = dict(env) if env is not None else None
|
|
183
|
+
self.timeout = timeout
|
|
184
|
+
self.offline = offline
|
|
185
|
+
self.font_dirs = font_dirs
|
|
186
|
+
|
|
187
|
+
# ------------------------------------------------------------------
|
|
188
|
+
# Running
|
|
189
|
+
|
|
190
|
+
@property
|
|
191
|
+
def binary(self) -> Path:
|
|
192
|
+
"""The executable (found, or downloaded, on first use)."""
|
|
193
|
+
if self._binary is None:
|
|
194
|
+
self._binary = find_binary()
|
|
195
|
+
return self._binary
|
|
196
|
+
|
|
197
|
+
def version(self) -> str:
|
|
198
|
+
"""The executable's version line: ``postext 1.70.4 (engine 1.70.4, darwin-arm64)``."""
|
|
199
|
+
return self.run(["--version"], capture=True).stdout.decode().strip()
|
|
200
|
+
|
|
201
|
+
def run(self, args: Sequence[PathLike], *, capture: bool = True, check: bool = False) -> "subprocess.CompletedProcess[bytes]":
|
|
202
|
+
"""Run the executable with ``args`` as given, nothing added.
|
|
203
|
+
|
|
204
|
+
``capture=False`` leaves stdout and stderr on the terminal (for
|
|
205
|
+
``build --watch`` and the like). ``check=True`` raises
|
|
206
|
+
:class:`subprocess.CalledProcessError` on a non-zero exit code.
|
|
207
|
+
"""
|
|
208
|
+
env = None
|
|
209
|
+
if self.env is not None:
|
|
210
|
+
env = {**os.environ, **self.env}
|
|
211
|
+
return subprocess.run(
|
|
212
|
+
[str(self.binary), *[os.fspath(a) for a in args]],
|
|
213
|
+
cwd=os.fspath(self.cwd) if self.cwd is not None else None,
|
|
214
|
+
env=env,
|
|
215
|
+
stdin=subprocess.DEVNULL,
|
|
216
|
+
capture_output=capture,
|
|
217
|
+
timeout=self.timeout,
|
|
218
|
+
check=check,
|
|
219
|
+
)
|
|
220
|
+
|
|
221
|
+
def _book_args(self, opts: Mapping[str, Any], temp: "_Temp") -> List[str]:
|
|
222
|
+
unknown = set(opts) - set(_BOOK_KEYS)
|
|
223
|
+
if unknown:
|
|
224
|
+
raise TypeError(f"unexpected option(s): {', '.join(sorted(unknown))}")
|
|
225
|
+
args: List[str] = []
|
|
226
|
+
args += _opt("locale", opts.get("locale"))
|
|
227
|
+
if opts.get("chapters") is not None:
|
|
228
|
+
args += ["--chapters", _chapters(opts["chapters"])]
|
|
229
|
+
for s in _settings(opts.get("set") or {}):
|
|
230
|
+
args += ["--set", s]
|
|
231
|
+
config = opts.get("config")
|
|
232
|
+
if isinstance(config, Mapping):
|
|
233
|
+
config = temp.write("config.json", json.dumps(config, ensure_ascii=False).encode("utf-8"))
|
|
234
|
+
args += _opt("config", config)
|
|
235
|
+
args += _opt("resources", opts.get("resources"))
|
|
236
|
+
args += _opt("fonts", opts.get("fonts"))
|
|
237
|
+
args += _opt("name", opts.get("name"))
|
|
238
|
+
font_dirs = opts.get("font_dirs", self.font_dirs)
|
|
239
|
+
for d in _many(font_dirs):
|
|
240
|
+
args += ["--font-dir", d]
|
|
241
|
+
offline = opts.get("offline", self.offline)
|
|
242
|
+
if offline:
|
|
243
|
+
args += ["--offline"]
|
|
244
|
+
args += _opt("cache-dir", opts.get("cache_dir"))
|
|
245
|
+
return args
|
|
246
|
+
|
|
247
|
+
def _execute(
|
|
248
|
+
self,
|
|
249
|
+
command: str,
|
|
250
|
+
args: List[str],
|
|
251
|
+
report_type: Type[R],
|
|
252
|
+
*,
|
|
253
|
+
content: bool = False,
|
|
254
|
+
raise_on_problems: bool = True,
|
|
255
|
+
) -> R:
|
|
256
|
+
proc = self.run([command, *args, "--json", "--no-color"], capture=True)
|
|
257
|
+
stderr = proc.stderr.decode("utf-8", "replace")
|
|
258
|
+
data, payload = _split_stdout(proc.stdout, content)
|
|
259
|
+
report = report_type.from_json(data, content=payload, stderr=stderr) if data is not None else None
|
|
260
|
+
code = proc.returncode
|
|
261
|
+
if code == 0:
|
|
262
|
+
if report is None:
|
|
263
|
+
raise PostextError(f"postext {command} printed no report", exit_code=0, stderr=stderr)
|
|
264
|
+
return report
|
|
265
|
+
message = (report.error if report and report.error else None) or _stderr_error(stderr)
|
|
266
|
+
if code == 2:
|
|
267
|
+
raise UsageError(message, exit_code=code, report=report, stderr=stderr)
|
|
268
|
+
if code == 3 and report is not None:
|
|
269
|
+
if not raise_on_problems:
|
|
270
|
+
return report
|
|
271
|
+
found = ", ".join(str(w) for w in report.warnings[:3]) or message
|
|
272
|
+
raise ProblemsFound(f"postext {command}: {found}", exit_code=code, report=report, stderr=stderr)
|
|
273
|
+
raise PostextError(message, exit_code=code, report=report, stderr=stderr)
|
|
274
|
+
|
|
275
|
+
def _book_command(
|
|
276
|
+
self,
|
|
277
|
+
command: str,
|
|
278
|
+
books: Books,
|
|
279
|
+
own: List[str],
|
|
280
|
+
opts: Mapping[str, Any],
|
|
281
|
+
report_type: Type[R],
|
|
282
|
+
*,
|
|
283
|
+
out: Optional[PathLike] = None,
|
|
284
|
+
single_file: bool = True,
|
|
285
|
+
raise_on_problems: bool = True,
|
|
286
|
+
suffix: str = ".postext",
|
|
287
|
+
takes_out: bool = True,
|
|
288
|
+
) -> R:
|
|
289
|
+
with _Temp() as temp:
|
|
290
|
+
inputs = temp.inputs(books, suffix)
|
|
291
|
+
if takes_out and out is None and temp.used:
|
|
292
|
+
if not single_file:
|
|
293
|
+
raise ValueError(f"{command}: give out= when the book is bytes (it is read from a temporary file)")
|
|
294
|
+
out = STDOUT
|
|
295
|
+
args = list(inputs)
|
|
296
|
+
if takes_out and out is not None:
|
|
297
|
+
args += ["--out", os.fspath(out)]
|
|
298
|
+
args += own + self._book_args(opts, temp)
|
|
299
|
+
return self._execute(
|
|
300
|
+
command,
|
|
301
|
+
args,
|
|
302
|
+
report_type,
|
|
303
|
+
content=out is not None and os.fspath(out) == STDOUT,
|
|
304
|
+
raise_on_problems=raise_on_problems,
|
|
305
|
+
)
|
|
306
|
+
|
|
307
|
+
# ------------------------------------------------------------------
|
|
308
|
+
# Commands
|
|
309
|
+
|
|
310
|
+
def pdf(
|
|
311
|
+
self,
|
|
312
|
+
book: Books,
|
|
313
|
+
*,
|
|
314
|
+
out: Optional[PathLike] = None,
|
|
315
|
+
accessible: Optional[bool] = None,
|
|
316
|
+
color_space: Optional[str] = None,
|
|
317
|
+
pdfx: Optional[str] = None,
|
|
318
|
+
profile: Optional[PathLike] = None,
|
|
319
|
+
outlines: Optional[bool] = None,
|
|
320
|
+
page_negative: Optional[bool] = None,
|
|
321
|
+
**options: "Unpack[BookOptions]",
|
|
322
|
+
) -> Report:
|
|
323
|
+
"""Typeset the book into a PDF (``out``, default: beside the book;
|
|
324
|
+
``"-"`` returns its bytes in ``Report.content``).
|
|
325
|
+
|
|
326
|
+
``color_space``: ``rgb``, ``cmyk`` or ``grayscale``; ``pdfx``:
|
|
327
|
+
``none``, ``x1a`` or ``x4``; ``profile``: ``fogra39``, ``fogra51``,
|
|
328
|
+
``swop5``, ``gracol2006``… or an ``.icc`` file.
|
|
329
|
+
"""
|
|
330
|
+
own = _flag("accessible", accessible) + _opt("color-space", color_space) + _opt("pdfx", pdfx)
|
|
331
|
+
own += _opt("profile", profile) + _flag("outlines", outlines) + _flag("page-negative", page_negative)
|
|
332
|
+
return self._book_command("pdf", book, own, options, Report, out=out)
|
|
333
|
+
|
|
334
|
+
def html(
|
|
335
|
+
self,
|
|
336
|
+
book: Books,
|
|
337
|
+
*,
|
|
338
|
+
out: Optional[PathLike] = None,
|
|
339
|
+
mode: Optional[str] = None,
|
|
340
|
+
assets: Optional[str] = None,
|
|
341
|
+
**options: "Unpack[BookOptions]",
|
|
342
|
+
) -> Report:
|
|
343
|
+
"""The laid-out pages as HTML: a path ending in ``.html`` (or ``"-"``)
|
|
344
|
+
gets one self-contained file, any other path a folder.
|
|
345
|
+
|
|
346
|
+
``mode``: ``single`` (one column) or ``multi`` (side by side);
|
|
347
|
+
``assets``: ``embed`` or ``folder``.
|
|
348
|
+
"""
|
|
349
|
+
own = _opt("mode", mode) + _opt("assets", assets)
|
|
350
|
+
return self._book_command("html", book, own, options, Report, out=out)
|
|
351
|
+
|
|
352
|
+
def epub(
|
|
353
|
+
self,
|
|
354
|
+
book: Books,
|
|
355
|
+
*,
|
|
356
|
+
out: Optional[PathLike] = None,
|
|
357
|
+
layout: Optional[str] = None,
|
|
358
|
+
cover: Optional[PathLike] = None,
|
|
359
|
+
**options: "Unpack[BookOptions]",
|
|
360
|
+
) -> Report:
|
|
361
|
+
"""An EPUB 3 book. ``layout``: ``fixed`` (default) or ``reflowable``."""
|
|
362
|
+
own = _opt("layout", layout) + _opt("cover", cover)
|
|
363
|
+
return self._book_command("epub", book, own, options, Report, out=out)
|
|
364
|
+
|
|
365
|
+
def image(
|
|
366
|
+
self,
|
|
367
|
+
book: Books,
|
|
368
|
+
*,
|
|
369
|
+
page: Union[int, str],
|
|
370
|
+
out: Optional[PathLike] = None,
|
|
371
|
+
format: Optional[str] = None,
|
|
372
|
+
dpi: Optional[float] = None,
|
|
373
|
+
quality: Optional[int] = None,
|
|
374
|
+
print_preview: Optional[bool] = None,
|
|
375
|
+
**options: "Unpack[BookOptions]",
|
|
376
|
+
) -> ImageReport:
|
|
377
|
+
"""One page as an image. ``page``: as printed (``"12"``, ``"iv"``) or
|
|
378
|
+
by position (``"#1"``; an ``int`` is a printed number).
|
|
379
|
+
``format``: ``png``, ``jpeg`` or ``webp``."""
|
|
380
|
+
own = ["--page", str(page)] + _opt("format", format) + _opt("dpi", dpi) + _opt("quality", quality)
|
|
381
|
+
own += _flag("print-preview", print_preview)
|
|
382
|
+
return self._book_command("image", book, own, options, ImageReport, out=out)
|
|
383
|
+
|
|
384
|
+
def images(
|
|
385
|
+
self,
|
|
386
|
+
book: Books,
|
|
387
|
+
*,
|
|
388
|
+
out: Optional[PathLike] = None,
|
|
389
|
+
pages: Optional[str] = None,
|
|
390
|
+
pattern: Optional[str] = None,
|
|
391
|
+
jobs: Optional[int] = None,
|
|
392
|
+
format: Optional[str] = None,
|
|
393
|
+
dpi: Optional[float] = None,
|
|
394
|
+
quality: Optional[int] = None,
|
|
395
|
+
print_preview: Optional[bool] = None,
|
|
396
|
+
**options: "Unpack[BookOptions]",
|
|
397
|
+
) -> Report:
|
|
398
|
+
"""Every page (or ``pages``: ``"1-10"``, ``"#1-#20"``) as images in the
|
|
399
|
+
folder ``out``. ``Report.outputs`` lists the files."""
|
|
400
|
+
own = _opt("pages", pages) + _opt("pattern", pattern) + _opt("jobs", jobs) + _opt("format", format)
|
|
401
|
+
own += _opt("dpi", dpi) + _opt("quality", quality) + _flag("print-preview", print_preview)
|
|
402
|
+
return self._book_command("images", book, own, options, Report, out=out, single_file=False)
|
|
403
|
+
|
|
404
|
+
def docx(
|
|
405
|
+
self,
|
|
406
|
+
book: Books,
|
|
407
|
+
*,
|
|
408
|
+
out: Optional[PathLike] = None,
|
|
409
|
+
variant: Optional[str] = None,
|
|
410
|
+
embed_fonts: Optional[bool] = None,
|
|
411
|
+
**options: "Unpack[BookOptions]",
|
|
412
|
+
) -> Report:
|
|
413
|
+
"""A Word document. ``variant``: ``semantic`` (native Word structures,
|
|
414
|
+
default) or ``formatted`` (the PDF's pages)."""
|
|
415
|
+
own = _opt("variant", variant) + _flag("embed-fonts", embed_fonts)
|
|
416
|
+
return self._book_command("docx", book, own, options, Report, out=out)
|
|
417
|
+
|
|
418
|
+
def import_docx(
|
|
419
|
+
self,
|
|
420
|
+
docx: BookInput,
|
|
421
|
+
book: Optional[Books] = None,
|
|
422
|
+
*,
|
|
423
|
+
out: Optional[PathLike] = None,
|
|
424
|
+
dry_run: Optional[bool] = None,
|
|
425
|
+
resources: Optional[PathLike] = None,
|
|
426
|
+
template: Optional[PathLike] = None,
|
|
427
|
+
split: Optional[bool] = None,
|
|
428
|
+
locale: Optional[str] = None,
|
|
429
|
+
config: Union[PathLike, Mapping[str, Any], None] = None,
|
|
430
|
+
name: Optional[str] = None,
|
|
431
|
+
quality_report: Optional[bool] = None,
|
|
432
|
+
auto_thumbnail: Optional[bool] = None,
|
|
433
|
+
raise_on_problems: bool = True,
|
|
434
|
+
) -> ImportDocxReport:
|
|
435
|
+
"""With ``book``: merge the edits made in Word to a file ``docx``
|
|
436
|
+
exported back into the book (``dry_run`` only reports them). Without:
|
|
437
|
+
turn any Word document into a new book at ``out`` (a folder or a
|
|
438
|
+
``.postext`` file).
|
|
439
|
+
|
|
440
|
+
An edit that could not be applied raises :class:`ProblemsFound`
|
|
441
|
+
unless ``raise_on_problems=False``.
|
|
442
|
+
"""
|
|
443
|
+
with _Temp() as temp:
|
|
444
|
+
args = temp.inputs(docx, ".docx")
|
|
445
|
+
if book is not None:
|
|
446
|
+
if isinstance(book, (bytes, bytearray)):
|
|
447
|
+
raise ValueError("import_docx: the book to merge into must be a path (its files are changed)")
|
|
448
|
+
args += _many(book) # type: ignore[arg-type]
|
|
449
|
+
elif out is None and temp.used:
|
|
450
|
+
raise ValueError("import_docx: give out= when the document is bytes")
|
|
451
|
+
args += _opt("out", out) + _flag("dry-run", dry_run) + _opt("resources", resources)
|
|
452
|
+
args += _opt("template", template) + _flag("split", split) + _opt("locale", locale)
|
|
453
|
+
if isinstance(config, Mapping):
|
|
454
|
+
config = temp.write("config.json", json.dumps(config, ensure_ascii=False).encode("utf-8"))
|
|
455
|
+
args += _opt("config", config) + _opt("name", name) + _flag("report", quality_report)
|
|
456
|
+
args += _flag("auto-thumbnail", auto_thumbnail)
|
|
457
|
+
return self._execute("import-docx", args, ImportDocxReport, raise_on_problems=raise_on_problems)
|
|
458
|
+
|
|
459
|
+
def pack(
|
|
460
|
+
self,
|
|
461
|
+
book: Books,
|
|
462
|
+
*,
|
|
463
|
+
out: Optional[PathLike] = None,
|
|
464
|
+
id: Optional[str] = None,
|
|
465
|
+
description: Optional[str] = None,
|
|
466
|
+
thumbnail: Optional[PathLike] = None,
|
|
467
|
+
auto_thumbnail: Optional[bool] = None,
|
|
468
|
+
**options: "Unpack[BookOptions]",
|
|
469
|
+
) -> Report:
|
|
470
|
+
"""Pack a book folder, or loose Markdown files (the chapters, in
|
|
471
|
+
order), into a ``.postext`` bundle."""
|
|
472
|
+
own = _opt("id", id) + _opt("description", description) + _opt("thumbnail", thumbnail)
|
|
473
|
+
own += _flag("auto-thumbnail", auto_thumbnail)
|
|
474
|
+
return self._book_command("pack", book, own, options, Report, out=out)
|
|
475
|
+
|
|
476
|
+
def unpack(self, bundle: BookInput, *, out: Optional[PathLike] = None, force: Optional[bool] = None) -> UnpackReport:
|
|
477
|
+
"""Extract a ``.postext`` bundle into the folder ``out``."""
|
|
478
|
+
with _Temp() as temp:
|
|
479
|
+
args = temp.inputs(bundle, ".postext")
|
|
480
|
+
if out is None and temp.used:
|
|
481
|
+
raise ValueError("unpack: give out= when the bundle is bytes")
|
|
482
|
+
args += _opt("out", out) + _flag("force", force)
|
|
483
|
+
return self._execute("unpack", args, UnpackReport)
|
|
484
|
+
|
|
485
|
+
def info(self, book: Books, *, pages: Optional[bool] = None, **options: "Unpack[BookOptions]") -> InfoReport:
|
|
486
|
+
"""Describe the book: chapters, resources, fonts, locales (``pages=True``
|
|
487
|
+
lays it out to count its pages)."""
|
|
488
|
+
return self._book_command("info", book, _flag("pages", pages), options, InfoReport, takes_out=False)
|
|
489
|
+
|
|
490
|
+
def check(
|
|
491
|
+
self,
|
|
492
|
+
book: Books,
|
|
493
|
+
*,
|
|
494
|
+
strict: Optional[bool] = None,
|
|
495
|
+
preflight: Optional[bool] = None,
|
|
496
|
+
raise_on_problems: bool = True,
|
|
497
|
+
**options: "Unpack[BookOptions]",
|
|
498
|
+
) -> CheckReport:
|
|
499
|
+
"""Lay the book out and report its problems. When it finds an error
|
|
500
|
+
(any warning with ``strict``) it raises :class:`ProblemsFound`, whose
|
|
501
|
+
``report`` lists them; ``raise_on_problems=False`` returns the
|
|
502
|
+
report instead (``report.passed`` is then ``False``)."""
|
|
503
|
+
own = _flag("strict", strict) + _flag("preflight", preflight)
|
|
504
|
+
return self._book_command("check", book, own, options, CheckReport, takes_out=False, raise_on_problems=raise_on_problems)
|
|
505
|
+
|
|
506
|
+
def build(
|
|
507
|
+
self,
|
|
508
|
+
book: Books,
|
|
509
|
+
*,
|
|
510
|
+
pdf: Optional[PathLike] = None,
|
|
511
|
+
html: Optional[PathLike] = None,
|
|
512
|
+
epub: Optional[PathLike] = None,
|
|
513
|
+
images: Optional[PathLike] = None,
|
|
514
|
+
docx: Optional[PathLike] = None,
|
|
515
|
+
docx_variant: Optional[str] = None,
|
|
516
|
+
docx_fonts: Optional[bool] = None,
|
|
517
|
+
pages: Optional[str] = None,
|
|
518
|
+
pattern: Optional[str] = None,
|
|
519
|
+
jobs: Optional[int] = None,
|
|
520
|
+
accessible: Optional[bool] = None,
|
|
521
|
+
color_space: Optional[str] = None,
|
|
522
|
+
pdfx: Optional[str] = None,
|
|
523
|
+
profile: Optional[PathLike] = None,
|
|
524
|
+
outlines: Optional[bool] = None,
|
|
525
|
+
page_negative: Optional[bool] = None,
|
|
526
|
+
mode: Optional[str] = None,
|
|
527
|
+
assets: Optional[str] = None,
|
|
528
|
+
layout: Optional[str] = None,
|
|
529
|
+
cover: Optional[PathLike] = None,
|
|
530
|
+
format: Optional[str] = None,
|
|
531
|
+
dpi: Optional[float] = None,
|
|
532
|
+
quality: Optional[int] = None,
|
|
533
|
+
print_preview: Optional[bool] = None,
|
|
534
|
+
**options: "Unpack[BookOptions]",
|
|
535
|
+
) -> Report:
|
|
536
|
+
"""Lay the book out once and write several outputs (``pdf``, ``html``,
|
|
537
|
+
``epub``, ``images``, ``docx`` paths). For ``--watch``, run the
|
|
538
|
+
executable yourself: ``Postext().run(["build", …, "--watch"], capture=False)``."""
|
|
539
|
+
own = _opt("pdf", pdf) + _opt("html", html) + _opt("epub", epub) + _opt("images", images) + _opt("docx", docx)
|
|
540
|
+
own += _opt("docx-variant", docx_variant) + _flag("docx-fonts", docx_fonts)
|
|
541
|
+
own += _opt("pages", pages) + _opt("pattern", pattern) + _opt("jobs", jobs)
|
|
542
|
+
own += _flag("accessible", accessible) + _opt("color-space", color_space) + _opt("pdfx", pdfx)
|
|
543
|
+
own += _opt("profile", profile) + _flag("outlines", outlines) + _flag("page-negative", page_negative)
|
|
544
|
+
own += _opt("mode", mode) + _opt("assets", assets) + _opt("layout", layout) + _opt("cover", cover)
|
|
545
|
+
own += _opt("format", format) + _opt("dpi", dpi) + _opt("quality", quality) + _flag("print-preview", print_preview)
|
|
546
|
+
return self._book_command("build", book, own, options, Report, takes_out=False, single_file=False)
|
|
547
|
+
|
|
548
|
+
# ------------------------------------------------------------------
|
|
549
|
+
# Bytes out
|
|
550
|
+
|
|
551
|
+
def pdf_bytes(self, book: Books, **kwargs: Any) -> bytes:
|
|
552
|
+
"""The PDF's bytes (``pdf(book, out="-", …).content``)."""
|
|
553
|
+
return _content(self.pdf(book, out=STDOUT, **kwargs))
|
|
554
|
+
|
|
555
|
+
def html_bytes(self, book: Books, **kwargs: Any) -> bytes:
|
|
556
|
+
"""The self-contained HTML file's bytes."""
|
|
557
|
+
return _content(self.html(book, out=STDOUT, **kwargs))
|
|
558
|
+
|
|
559
|
+
def epub_bytes(self, book: Books, **kwargs: Any) -> bytes:
|
|
560
|
+
"""The EPUB's bytes."""
|
|
561
|
+
return _content(self.epub(book, out=STDOUT, **kwargs))
|
|
562
|
+
|
|
563
|
+
def image_bytes(self, book: Books, *, page: Union[int, str], **kwargs: Any) -> bytes:
|
|
564
|
+
"""One page's image bytes (PNG unless ``format`` says otherwise)."""
|
|
565
|
+
return _content(self.image(book, page=page, out=STDOUT, **kwargs))
|
|
566
|
+
|
|
567
|
+
def docx_bytes(self, book: Books, **kwargs: Any) -> bytes:
|
|
568
|
+
"""The Word document's bytes."""
|
|
569
|
+
return _content(self.docx(book, out=STDOUT, **kwargs))
|
|
570
|
+
|
|
571
|
+
def pack_bytes(self, book: Books, **kwargs: Any) -> bytes:
|
|
572
|
+
"""The ``.postext`` bundle's bytes."""
|
|
573
|
+
return _content(self.pack(book, out=STDOUT, **kwargs))
|
|
574
|
+
|
|
575
|
+
|
|
576
|
+
def _content(report: Report) -> bytes:
|
|
577
|
+
return report.content or b""
|
|
578
|
+
|
|
579
|
+
|
|
580
|
+
class _Temp(contextlib.AbstractContextManager): # type: ignore[type-arg]
|
|
581
|
+
"""A temporary folder for the books given as bytes and the settings
|
|
582
|
+
given as dicts, removed after the run."""
|
|
583
|
+
|
|
584
|
+
def __init__(self) -> None:
|
|
585
|
+
self._dir: "Optional[tempfile.TemporaryDirectory[str]]" = None
|
|
586
|
+
self._count = 0
|
|
587
|
+
self.used = False
|
|
588
|
+
|
|
589
|
+
def write(self, name: str, data: bytes) -> str:
|
|
590
|
+
if self._dir is None:
|
|
591
|
+
self._dir = tempfile.TemporaryDirectory(prefix="postext-")
|
|
592
|
+
self._count += 1
|
|
593
|
+
path = Path(self._dir.name) / f"{self._count}-{name}"
|
|
594
|
+
path.write_bytes(data)
|
|
595
|
+
return str(path)
|
|
596
|
+
|
|
597
|
+
def inputs(self, books: Books, suffix: str) -> List[str]:
|
|
598
|
+
items: Iterable[BookInput]
|
|
599
|
+
if isinstance(books, (str, bytes, bytearray, os.PathLike)):
|
|
600
|
+
items = [books]
|
|
601
|
+
else:
|
|
602
|
+
items = books
|
|
603
|
+
out: List[str] = []
|
|
604
|
+
for item in items:
|
|
605
|
+
if isinstance(item, (bytes, bytearray)):
|
|
606
|
+
self.used = True
|
|
607
|
+
out.append(self.write(f"book{suffix}", bytes(item)))
|
|
608
|
+
else:
|
|
609
|
+
out.append(os.fspath(item))
|
|
610
|
+
if not out:
|
|
611
|
+
raise ValueError("no book given")
|
|
612
|
+
return out
|
|
613
|
+
|
|
614
|
+
def __exit__(self, *exc: Any) -> None:
|
|
615
|
+
if self._dir is not None:
|
|
616
|
+
self._dir.cleanup()
|
|
617
|
+
|
|
618
|
+
|
|
619
|
+
def _main(argv: Optional[Sequence[str]] = None) -> int:
|
|
620
|
+
"""``python -m postext …``: the command line itself."""
|
|
621
|
+
args = list(sys.argv[1:] if argv is None else argv)
|
|
622
|
+
try:
|
|
623
|
+
return Postext().run(args, capture=False).returncode
|
|
624
|
+
except PostextError as err:
|
|
625
|
+
print(f"postext: {err}", file=sys.stderr)
|
|
626
|
+
return 1
|
|
627
|
+
|
|
628
|
+
|
|
629
|
+
__all__ = ["Postext", "STDOUT", "BookInput", "Books", "__version__"]
|
postext/_errors.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import TYPE_CHECKING, Optional
|
|
4
|
+
|
|
5
|
+
if TYPE_CHECKING:
|
|
6
|
+
from ._report import Report
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class PostextError(Exception):
|
|
10
|
+
"""The command ran and failed (exit code 1, or another non-zero code).
|
|
11
|
+
|
|
12
|
+
``report`` is the parsed ``--json`` report when the command printed one,
|
|
13
|
+
``stderr`` what it wrote to the terminal.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
def __init__(
|
|
17
|
+
self,
|
|
18
|
+
message: str,
|
|
19
|
+
*,
|
|
20
|
+
exit_code: int = 1,
|
|
21
|
+
report: Optional["Report"] = None,
|
|
22
|
+
stderr: str = "",
|
|
23
|
+
) -> None:
|
|
24
|
+
super().__init__(message)
|
|
25
|
+
self.message = message
|
|
26
|
+
self.exit_code = exit_code
|
|
27
|
+
self.report = report
|
|
28
|
+
self.stderr = stderr
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class UsageError(PostextError):
|
|
32
|
+
"""The command was called wrongly: an unknown option, a bad value (exit code 2)."""
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class ProblemsFound(PostextError):
|
|
36
|
+
"""``check`` found problems, or ``import_docx`` could not apply an edit (exit code 3).
|
|
37
|
+
|
|
38
|
+
The report is complete: ``err.report.warnings`` lists what was found.
|
|
39
|
+
"""
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class BinaryNotFound(PostextError):
|
|
43
|
+
"""No postext executable: none for this platform, a download that failed,
|
|
44
|
+
or a ``POSTEXT_BIN`` that does not exist."""
|