Debian Codegraph @

texk/texlive/linked_scripts/memoize/memoize-extract.py

raw
1 #!/usr/bin/env python3
2 #
3 # This file is a part of Memoize, a TeX package for externalization of
4 # graphics and memoization of compilation results in general, available at
5 # https://ctan.org/pkg/memoize and https://github.com/sasozivanovic/memoize.
6 #
7 # Copyright (c) 2020- Saso Zivanovic <[email protected]>
8 #
9 # This work may be distributed and/or modified under the conditions of the
10 # LaTeX Project Public License, either version 1.3c of this license or (at
11 # your option) any later version. The latest version of this license is in
12 # https://www.latex-project.org/lppl.txt and version 1.3c or later is part of
13 # all distributions of LaTeX version 2008 or later.
14 #
15 # This work has the LPPL maintenance status `maintained'.
16 # The Current Maintainer of this work is Saso Zivanovic.
17 #
18 # The files belonging to this work and covered by LPPL are listed in
19 # <texmf>/doc/generic/memoize/FILES.
20
21 __version__ = '2024/12/02 v1.4.1'
22
23 import argparse, re, sys, os, subprocess, itertools, traceback, platform
24 from pathlib import Path, PurePath
25 # We will only try to import the PDF processing library once we set up the
26 # error log.
27
28 # \paragraph{Messages}
29
30 # The messages are written both to the extraction log and the terminal (we
31 # output to stdout rather than stderr so that messages on the TeX terminal and
32 # document |.log| appear in chronological order). Messages are automatically
33 # adapted to the TeX |--format|.
34
35 # The format of the messages. It depends on the given |--format|; the last
36 # entry is for t the terminal output.
37
38 ERROR = {
39 'latex': r'\PackageError{{{package_name}}}{{{short}}}{{{long}}}',
40 'plain': r'\errhelp{{{long}}}\errmessage{{{package_name}: {short}}}',
41 'context': r'\errhelp{{{long}}}\errmessage{{{package_name}: {short}}}',
42 None: '{header}{short}.\n{long}',
43 }
44
45 WARNING = {
46 'latex': r'\PackageWarning{{{package_name}}}{{{texindent}{text}}}',
47 'plain': r'\message{{{package_name}: {texindent}{text}}}',
48 'context': r'\message{{{package_name}: {texindent}{text}}}',
49 None: r'{header}{indent}{text}.',
50 }
51
52 INFO = {
53 'latex': r'\PackageInfo{{{package_name}}}{{{texindent}{text}}}',
54 'plain': r'\message{{{package_name}: {texindent}{text}}}',
55 'context': r'\message{{{package_name}: {texindent}{text}}}',
56 None: r'{header}{indent}{text}.',
57 }
58
59 # Some variables used in the message routines; note that |header| will be
60 # redefined once we parse the arguments.
61
62 package_name = 'memoize (python-based extraction)'
63 exit_code = 0
64 log = None
65 header = ''
66 indent = ''
67 texindent = ''
68
69 # The message routines.
70
71 def error(short, long):
72 if not args.quiet:
73 print(ERROR[None].format(short = short, long = long, header = header))
74 if log:
75 short = short.replace('\\', '\\string\\')
76 long = long.replace('\\', '\\string\\')
77 print(
78 ERROR[args.format].format(
79 short = short, long = long, package_name = package_name),
80 file = log)
81 global exit_code
82 exit_code = 11
83 endinput()
84
85 def warning(text):
86 if text and not args.quiet:
87 print(WARNING[None].format(text = text, header = header, indent = indent))
88 if log:
89 text = text.replace('\\', '\\string\\')
90 print(
91 WARNING[args.format].format(
92 text = text, texindent = texindent, package_name = package_name),
93 file = log)
94 global exit_code
95 exit_code = 10
96
97 def info(text):
98 if text and not args.quiet:
99 print(INFO[None].format(text = text, header = header, indent = indent))
100 if log:
101 text = text.replace('\\', '\\string\\')
102 print(
103 INFO[args.format].format(
104 text = text, texindent = texindent, package_name = package_name),
105 file = log)
106
107 # Mark the log as complete and exit.
108 def endinput():
109 if log:
110 print(r'\endinput', file = log)
111 log.close()
112 sys.exit(exit_code)
113
114 # \paragraph{Permission-related functions}
115
116 # |paranoia_in|/|out| should work exactly as
117 # |kpsewhich -safe-in-name|/|-safe-out-name|.
118 def paranoia_in(f, remark = ''):
119 if f and not _paranoia(f, openin_any):
120 error(f"I'm not allowed to read from '{f}' (openin_any = {openin_any})",
121 remark)
122
123 def paranoia_out(f, remark = ''):
124 if f and not _paranoia(f, openout_any):
125 error(f"I'm not allowed to write to '{f}' (openout_any = {openout_any})",
126 remark)
127
128 def _paranoia(f, mode):
129 # |mode| is the value of |openin_any| or |openout_any|. |f| is a
130 # |pathlib.Path| object.
131 return (
132 # In mode `any' (|a|, |y| or |1|), we may access any file.
133 mode in 'ay1'
134 or (
135 # Otherwise, we are at least in the restricted mode, so we should not
136 # open dot files on Unix-like systems (except file called |.tex|).
137 not (os.name == 'posix' and f.stem.startswith('.') and f.stem != '.tex')
138 and (
139 # If we are precisely in the restricted mode (|r|, |n|, |0|),
140 # then there are no further restrictions.
141 mode in 'rn0'
142 # Otherwise, we are in the paranoid mode (officially |p|, but
143 # any other value is interpreted as |p| as well). There are
144 # two further restrictions in the paranoid mode.
145 or (
146 # We're not allowed to go to a parent directory.
147 '..' not in f.parts
148 and
149 # If the given path is absolute, is should be a descendant
150 # of either |TEXMF_OUTPUT_DIRECTORY| or |TEXMFOUTPUT|.
151 (not f.is_absolute()
152 or
153 is_ancestor(texmf_output_directory, f)
154 or
155 is_ancestor(texmfoutput, f)
156 )))))
157
158 # On Windows, we disallow ``semi-absolute'' paths, i.e.\ paths starting with
159 # the |\| but lacking the drive. On Windows, |pathlib|'s |is_absolute| returns
160 # |True| only for paths starting with |\| and containing the drive.
161 def sanitize_filename(f):
162 if f and platform.system() == 'Windows' and not (f.is_absolute() or not f.drive):
163 error(f"\"Semi-absolute\" paths are disallowed: '{f}'", r"The path must "
164 r"either contain both the drive letter and start with '\', "
165 r"or none of these; paths like 'C:foo' and '\foo' are disallowed")
166
167 def access_in(f):
168 return os.access(f, os.R_OK)
169
170 # This function can fail on Windows, reporting a non-writable file or dir as
171 # writable, because |os.access| does not work with Windows' |icacls|
172 # permissions. Consequence: we might try to write to a read-only current or
173 # output directory instead of switching to the temporary directory. Paranoia
174 # is unaffected, as it doesn't use |access_*| functions.
175 def access_out(f):
176 try:
177 exists = f.exists()
178 # Presumably, we get this error when the parent directory is not
179 # executable.
180 except PermissionError:
181 return
182 if exists:
183 # An existing file should be writable, and if it's a directory, it
184 # should also be executable.
185 return os.access(f, os.W_OK) and (not f.is_dir() or os.access(f, os.X_OK))
186 else:
187 # For a non-existing file, the parent directory should be writable.
188 # (This is the only place where function |pathlib.parent| is used, so
189 # it's ok that it returns the logical parent.)
190 return os.access(f.parent, os.W_OK)
191
192 # This function finds the location for an input file, respecting
193 # |TEXMF_OUTPUT_DIRECTORY| and |TEXMFOUTPUT|, and the permissions in the
194 # filesystem. It returns an absolute file as-is. For a relative file, it
195 # tries |TEXMF_OUTPUT_DIRECTORY| (if defined), the current directory (always),
196 # and |TEXMFOUTPUT| directory (if defined), in this order. The first readable
197 # file found is returned; if no readable file is found, the file in the current
198 # directory is returned.
199 def find_in(f):
200 sanitize_filename(f)
201 if f.is_absolute():
202 return f
203 for df in (texmf_output_directory / f if texmf_output_directory else None,
204 f,
205 texmfoutput / f if texmfoutput else None):
206 if df and access_in(df):
207 return df
208 return f
209
210 # This function finds the location for an output file, respecting
211 # |TEXMF_OUTPUT_DIRECTORY| and |TEXMFOUTPUT|, and the permissions in the
212 # filesystem. It returns an absolute file as-is. For a relative file, it
213 # tries |TEXMF_OUTPUT_DIRECTORY| (if defined), the current directory (unless
214 # |TEXMF_OUTPUT_DIRECTORY| is defined), and |TEXMFOUTPUT| directory (if
215 # defined), in this order. The first writable file found is returned; if no
216 # writable file is found, the file in either the current or the output
217 # directory is returned.
218 def find_out(f):
219 sanitize_filename(f)
220 if f.is_absolute():
221 return f
222 for df in (texmf_output_directory / f if texmf_output_directory else None,
223 f if not texmf_output_directory else None,
224 texmfoutput / f if texmfoutput else None):
225 if df and access_out(df):
226 return df
227 return texmf_output_directory / f if texmf_output_directory else f
228
229 # This function assumes that both paths are absolute; ancestor may be |None|,
230 # signaling a non-path.
231 def is_ancestor(ancestor, descendant):
232 if not ancestor:
233 return
234 a = ancestor.parts
235 d = descendant.parts
236 return len(a) < len(d) and a == d[0:len(a)]
237
238 # A paranoid |Path.mkdir|. The given folder is preprocessed by |find_out|.
239 def mkdir(folder):
240 folder = find_out(Path(folder))
241 if not folder.exists():
242 paranoia_out(folder)
243 # Using |folder.mkdir| is fine because we know that
244 # |TEXMF_OUTPUT_DIRECTORY|/|TEXMFOUTPUT|, if given, exists, and that
245 # ``folder'' contains no |..|.
246 folder.mkdir(parents = True, exist_ok = True)
247 # This does not get logged when the function is invoked via |--mkdir|,
248 # as it is not clear what the log name should be.
249 info(f"Created directory {folder}")
250
251 _re_unquote = re.compile(r'"(.*?)"')
252 def unquote(fn):
253 return _re_unquote.sub(r'\1', fn)
254
255 # \paragraph{Kpathsea}
256
257 # Get the values of |openin_any|, |openout_any|, |TEXMFOUTPUT| and
258 # |TEXMF_OUTPUT_DIRECTORY|.
259
260 kpsewhich_output = subprocess.run(['kpsewhich',
261 f'-expand-var='
262 f'openin_any=$openin_any,'
263 f'openout_any=$openout_any,'
264 f'TEXMFOUTPUT=$TEXMFOUTPUT'],
265 capture_output = True
266 ).stdout.decode().strip()
267 if not kpsewhich_output:
268 # No TeX? (Note that |kpsewhich| should exist in MiKTeX as well.) In
269 # absence of |kpathsea| information, we get very paranoid, but still try to
270 # get |TEXMFOUTPUT| from an environment variable.
271 openin_any, openout_any = 'p', 'p'
272 texmfoutput, texmf_output_directory = None, None
273 # Unfortunately, this warning can't make it into the log. But then again,
274 # the chances of a missing |kpsewhich| are very slim, and its absence would
275 # show all over the place anyway.
276 warning('I failed to execute "kpsewhich"; , is there no TeX system installed? '
277 'Assuming openin_any = openout_any = "p" '
278 '(i.e. restricting all file operations to non-hidden files '
279 'in the current directory of its subdirectories).')
280 else:
281 m = re.fullmatch(r'openin_any=(.*),openout_any=(.*),TEXMFOUTPUT=(.*)',
282 kpsewhich_output)
283 openin_any, openout_any, texmfoutput = m.groups()
284 texmf_output_directory = os.environ.get('TEXMF_OUTPUT_DIRECTORY', None)
285 if openin_any == '$openin_any':
286 # When the |open*_any| variables are not expanded, we assume we're
287 # running MiKTeX. The two config settings below correspond to TeXLive's
288 # |openin_any| and |openout_any|; afaik, there is no analogue to
289 # |TEXMFOUTPUT|.
290 initexmf_output = subprocess.run(
291 ['initexmf', '--show-config-value=[Core]AllowUnsafeInputFiles',
292 '--show-config-value=[Core]AllowUnsafeOutputFiles'],
293 capture_output = True).stdout.decode().strip()
294 openin_any, openout_any = initexmf_output.split()
295 openin_any = 'a' if openin_any == 'true' else 'p'
296 openout_any = 'a' if openout_any == 'true' else 'p'
297 texmfoutput = None
298 texmf_output_directory = None
299
300 # An output directory should exist, and may not point to the root on Linux. On
301 # Windows, it may point to the root, because we only allow absolute filenames
302 # containing the drive, e.g.\ |F:\|; see |is_absolute|.
303 def sanitize_output_dir(d_str):
304 d = Path(d_str) if d_str else None
305 sanitize_filename(d)
306 return d if d and d.is_dir() and \
307 (not d.is_absolute() or len(d.parts) != 1 or d.drive) else None
308
309 texmfoutput = sanitize_output_dir(texmfoutput)
310 texmf_output_directory = sanitize_output_dir(texmf_output_directory)
311
312 class NotExtracted(UserWarning):
313 pass
314
315 # We don't delve into the real script when loaded from the testing code.
316 if __name__ == '__main__':
317
318 # \paragraph{Arguments}
319
320 parser = argparse.ArgumentParser(
321 description = "Extract extern pages produced by package Memoize "
322 "out of the document PDF.",
323 epilog = "For details, see the man page or the Memoize documentation.",
324 prog = 'memoize-extract.py',
325 )
326 parser.add_argument('-P', '--pdf', help = 'extract from file PDF')
327 parser.add_argument('-p', '--prune', action = 'store_true',
328 help = 'remove the extern pages after extraction')
329 parser.add_argument('-k', '--keep', action = 'store_true',
330 help = 'do not mark externs as extracted')
331 parser.add_argument('-F', '--format', choices = ['latex', 'plain', 'context'],
332 help = 'the format of the TeX document invoking extraction')
333 parser.add_argument('-f', '--force', action = 'store_true',
334 help = 'extract even if the size-check fails')
335 parser.add_argument('-q', '--quiet', action = 'store_true',
336 help = "describe what's happening")
337 parser.add_argument('-m', '--mkdir', action = 'store_true',
338 help = 'create a directory (and exit); '
339 'mmz argument is interpreted as directory name')
340 parser.add_argument('-V', '--version', action = 'version',
341 version = f"%(prog)s of Memoize " + __version__)
342 parser.add_argument('mmz', help = 'the record file produced by Memoize: '
343 'doc.mmz when compiling doc.tex '
344 '(doc and doc.tex are accepted as well)')
345
346 args = parser.parse_args()
347
348 header = parser.prog + ': ' if args.format else ''
349
350 # Start a new line in the TeX terminal output.
351 if args.format:
352 print()
353
354 # \paragraph{Initialization}
355
356 # With |--mkdir|, argument |mmz| is interpreted as the directory to create.
357 if args.mkdir:
358 mkdir(args.mmz)
359 sys.exit()
360
361 # Normalize the |mmz| argument into a |.mmz| filename.
362 mmz_file = Path(args.mmz)
363 if mmz_file.suffix == '.tex':
364 mmz_file = mmz_file.with_suffix('.mmz')
365 elif mmz_file.suffix != '.mmz':
366 mmz_file = mmz_file.with_name(mmz_file.name + '.mmz')
367
368 # Once we have the |.mmz| filename, we can open the log.
369 if args.format:
370 log_file = find_out(mmz_file.with_suffix('.mmz.log'))
371 paranoia_out(log_file)
372 info(f"Logging to '{log_file}'");
373 log = open(log_file, 'w')
374
375 # Now that we have opened the log file, we can try loading the PDF
376 # processing library.
377 try:
378 import pdfrw
379 except ModuleNotFoundError:
380 error("Python module 'pdfrw' was not found",
381 'Have you followed the instructions is section 1.1 of the manual?')
382
383 # Catch any errors in the script and output them to the log.
384 try:
385
386 # Find the |.mmz| file we will read, but retain the original filename
387 # in |given_mmz_file|, as we will still need it.
388 given_mmz_file = mmz_file
389 mmz_file = find_in(mmz_file)
390 paranoia_in(mmz_file)
391 if not args.keep:
392 paranoia_out(mmz_file,
393 remark = 'This file is rewritten unless option --keep is given.')
394 try:
395 mmz = open(mmz_file)
396 except FileNotFoundError:
397 info(f"File '{given_mmz_file}' does not exist, "
398 f"assuming there's nothing to do")
399 endinput()
400
401 # Determine the PDF filename: it is either given via |--pdf|, or
402 # constructed from the |.mmz| filename.
403 pdf_file = find_in(Path(args.pdf)
404 if args.pdf else given_mmz_file.with_suffix('.pdf'))
405 paranoia_in(pdf_file)
406 if args.prune:
407 paranoia_out(pdf_file,
408 remark = 'I would have to rewrite this file '
409 'because option --prune was given.')
410
411 # Various initializations.
412
413 re_prefix = re.compile(r'\\mmzPrefix *{(?P<prefix>.*?)}')
414 re_split_prefix = re.compile(r'(?P<dir_prefix>.*/)?(?P<name_prefix>.*?)')
415 re_newextern = re.compile(
416 r'\\mmzNewExtern *{(?P<extern_path>.*?)}{(?P<page_n>[0-9]+)}'
417 r'{(?P<expected_width>[0-9.]*)pt}{(?P<expected_height>[0-9.]*)pt}')
418 re_extern_path = re.compile(
419 r'(?P<dir_prefix>.*/)?(?P<name_prefix>.*?)'
420 r'(?P<code_md5sum>[0-9A-F]{32})-'
421 r'(?P<context_md5sum>[0-9A-F]{32})(?:-[0-9]+)?.pdf')
422 pdf = None
423 extern_pages = []
424 new_mmz = []
425 tolerance = 0.01
426 dir_to_make = None
427 info(f"Extracting new externs listed in '{mmz_file}' from '{pdf_file}'")
428 done_message = "Done (there was nothing to extract)"
429 indent = ' '
430 texindent = r'\space\space '
431
432 # \paragraph{Process \texttt{.mmz}}
433
434 for line in mmz:
435 try:
436 if m_p := re_prefix.match(line):
437 # Found |\mmzPrefix|: create the extern directory, but only
438 # later, if an extern file is actually produced. We parse
439 # the prefix in two steps because we have to unquote the
440 # entire prefix.
441 prefix = unquote(m_p['prefix'])
442 if not (m_sp := re_split_prefix.match(prefix)):
443 warning(f"Cannot parse line {line.strip()}")
444 dir_to_make = m_sp['dir_prefix']
445 elif m_ne := re_newextern.match(line):
446 # Found |\mmzNewExtern|: extract the extern page into an
447 # extern file.
448 done_message = "Done"
449 # The extern filename, as specified in |.mmz|:
450 unquoted_extern_path = unquote(m_ne['extern_path'])
451 extern_file = Path(unquoted_extern_path)
452 # We parse the extern filename in a separate step because
453 # we have to unquote the entire path.
454 if not (m_ep := re_extern_path.match(unquoted_extern_path)):
455 warning(f"Cannot parse line {line.strip()}")
456 # The actual extern filename:
457 extern_file_out = find_out(extern_file)
458 paranoia_out(extern_file_out)
459 page_n = int(m_ne['page_n'])-1
460 # Check whether c-memo and cc-memo exist (in any input
461 # directory).
462 c_memo = extern_file.with_name(
463 m_ep['name_prefix'] + m_ep['code_md5sum'] + '.memo')
464 cc_memo = extern_file.with_name(
465 m_ep['name_prefix'] + m_ep['code_md5sum']
466 + '-' + m_ep['context_md5sum'] + '.memo')
467 c_memo_in = find_in(c_memo)
468 cc_memo_in = find_in(cc_memo)
469 if not (access_in(c_memo_in) and access_in(cc_memo_in)) \
470 and not args.force:
471 warning(f"I refuse to extract page {page_n+1} into extern "
472 f"'{extern_file}', because the associated c-memo "
473 f"'{c_memo}' and/or cc-memo '{cc_memo}' "
474 f"does not exist")
475 raise NotExtracted()
476 # Load the PDF. We only do this now so that we don't load
477 # it if there is nothing to extract.
478 if not pdf:
479 if not access_in(pdf_file):
480 warning(f"Cannot open '{pdf_file}'")
481 endinput()
482 try:
483 # All safe, |paranoia_in| was already called above.
484 pdf = pdfrw.PdfReader(pdf_file)
485 except pdfrw.errors.PdfParseError as err:
486 error(rf"File '{pdf_file}' seems corrupted. Perhaps you "
487 rf"have to load Memoize earlier in the preamble",
488 rf"In particular, Memoize must be loaded before "
489 rf"TikZ library 'fadings' and any package "
490 rf"deploying it, and in Beamer, load Memoize "
491 rf"by writing \RequirePackage{{memoize}} before "
492 rf"\documentclass{{beamer}}. "
493 rf"This was the error thrown by Python: \n{err}")
494 # Does the page exist?
495 if page_n >= len(pdf.pages):
496 error(rf"I cannot extract page {page_n} from '{pdf_file}', "
497 rf"as it contains only {len(pdf.pages)} page" +
498 ('s' if len(pdf.pages) > 1 else ''), '')
499 # Check whether the page size matches the |.mmz|
500 # expectations.
501 page = pdf.pages[page_n]
502 expected_width_pt = float(m_ne['expected_width'])
503 expected_height_pt = float(m_ne['expected_height'])
504 mb = page['/MediaBox']
505 width_bp = float(mb[2]) - float(mb[0])
506 height_bp = float(mb[3]) - float(mb[1])
507 width_pt = width_bp / 72 * 72.27
508 height_pt = height_bp / 72 * 72.27
509 if (abs(width_pt - expected_width_pt) > tolerance
510 or abs(height_pt - expected_height_pt) > tolerance) \
511 and not args.force:
512 warning(
513 f"I refuse to extract page {page_n+1} from '{pdf_file}' "
514 f"because its size ({width_pt}pt x {height_pt}pt) "
515 f"is not what I expected "
516 f"({expected_width_pt}pt x {expected_height_pt}pt)")
517 raise NotExtracted()
518 # All tests were successful, let's create the extern file.
519 # First, the containing directory, if necessary.
520 if dir_to_make:
521 mkdir(dir_to_make)
522 dir_to_make = None
523 # Now the extern file. Note that |paranoia_out| was
524 # already called above.
525 info(f"Page {page_n+1} --> {extern_file_out}")
526 extern = pdfrw.PdfWriter(extern_file_out)
527 extern.addpage(page)
528 extern.write()
529 # This page will get pruned.
530 if args.prune:
531 extern_pages.append(page_n)
532 # Comment out this |\mmzNewExtern|.
533 if not args.keep:
534 line = '%' + line
535 except NotExtracted:
536 pass
537 finally:
538 if not args.keep:
539 new_mmz.append(line)
540 mmz.close()
541 indent = ''
542 texindent = ''
543 info(done_message)
544
545 # Write out the |.mmz| file with |\mmzNewExtern| lines commented
546 # out. (All safe, |paranoia_out| was already called above.)
547 if not args.keep:
548 with open(mmz_file, 'w') as mmz:
549 for line in new_mmz:
550 print(line, file = mmz, end = '')
551
552 # Remove the extracted pages from the original PDF. (All safe,
553 # |paranoia_out| was already called above.)
554 if args.prune and extern_pages:
555 pruned_pdf = pdfrw.PdfWriter(pdf_file)
556 pruned_pdf.addpages(
557 page for n, page in enumerate(pdf.pages) if n not in extern_pages)
558 pruned_pdf.write()
559 info(f"The following extern pages were pruned out of the PDF: " +
560 ",".join(str(page+1) for page in extern_pages))
561
562 # Report that extraction was successful.
563 endinput()
564
565 # Catch any errors in the script and output them to the log.
566 except Exception as err:
567 error(f'Python error: {err}', traceback.format_exc())
568
569 # Local Variables:
570 # fill-column: 79
571 # after-save-hook: py2dtx
572 # End: