Debian Codegraph @

texk/texlive/linked_scripts/minted/latexminted.py

raw
1 #!/usr/bin/env python3
2 # -*- coding: utf-8 -*-
3 #
4 # Copyright (c) 2024-2025, Geoffrey M. Poore
5 # All rights reserved.
6 #
7 # Licensed under the LaTeX Project Public License version 1.3c:
8 # https://www.latex-project.org/lppl.txt
9 #
10
11
12 '''
13 This Python executable is intended for installation within a TeX distribution,
14 along with Python wheels for the following Python packages:
15
16 * latexminted: https://pypi.org/project/latexminted/
17
18 * latexrestricted: https://pypi.org/project/latexrestricted/
19
20 * latex2pydata: https://pypi.org/project/latex2pydata/
21
22 * Pygments: https://pypi.org/project/Pygments/
23
24 The combined executable plus wheels provide everything that is needed for the
25 Python side of the minted LaTeX package. No additional Python libraries are
26 required.
27
28 The wheels require Python >= 3.8. If this executable is launched with an
29 earlier Python version, then it will attempt to locate a more recent Python
30 installation and run itself with that Python version in a subprocess. The
31 search for more recent Python versions looks for executables of the form
32 `python3.x` on PATH.
33
34 If the latexminted Python package is installed separately, outside TeX, then
35 it will create a separate `latexminted` executable as part of the installation
36 process. That makes it possible to install latexminted and dependencies
37 separately and then customize Pygments with additional packages that provide
38 plugins. However, running that separate `latexminted` executable is not
39 straightforward under Windows. Under Windows, if this executable finds a
40 suitable `latexminted` executable elsewhere, outside a TeX installation, then
41 this executable will run that separate `latexminted` executable in a
42 subprocess and exit. There are two reasons for this approach:
43
44 1. Under Windows with TeX Live, the default restricted shell escape can only
45 run executables such as `latexminted` that are part of the TeX
46 installation; the executable that runs is not the first executable on
47 PATH. That is part of TeX Live's security measures to prevent running
48 executables in the current working directory, which is typically writable
49 by LaTeX and is the first place Windows checks when searching for
50 executables. This script and the latexrestricted Python package enforce
51 equivalent security, but do so in a less restrictive manner by expanding
52 executable names into executable paths with Python's `shutil.which()` and
53 then comparing the result with locations writable by LaTeX.
54
55 2. Under non-Windows operating systems, it is possible to modify PATH so that
56 the desired `latexminted` executable is first. Under Windows, the system
57 PATH is prepended to the user PATH, so a system-wide TeX installation will
58 prevent a user-installed `latexminted` executable from being accessible.
59
60 Requirements for locating and running a separate `latexminted` executable
61 under Windows:
62
63 * The separate executable must be the first `latexminted.exe` found on PATH,
64 or it must be the first `latexminted.exe` on PATH that is located under
65 the user home directory.
66
67 * The separate executable must be outside a TeX installation. There is a
68 check for a `tex.exe` executable in the same directory as
69 `latexminted.exe`. There is a check for the case-insensitive strings
70 "texlive", "miktex", and "tinytex" in the path to the `latexminted`
71 executable. With TeX Live, the path to the `latexminted` executable is
72 also compared to the environment variable `SELFAUTOLOC`.
73
74 * The separate executable must be outside the current working directory,
75 TEXMFOUTPUT, and TEXMF_OUTPUT_DIRECTORY.
76
77 * The current directory, TEXMFOUTPUT, and TEXMF_OUTPUT_DIRECTORY cannot be
78 subdirectories of the directory in which the executable is located.
79 '''
80
81
82 # This is the version of the `latexminted.py` launcher script, which is
83 # bundled with the `minted` package for installation within TeX distributions.
84 # This is NOT the version of the `latexminted` library. The library version
85 # is what matters for compatibility purposes, and the library version is what
86 # is returned from running `latexminted --version`.
87 __launcher_version__ = '20250306'
88
89
90 import os
91 import pathlib
92 import shutil
93 import subprocess
94 import sys
95
96
97
98
99 # This is an abbreviated variant of `AnyPath` from latexrestricted:
100 # https://github.com/gpoore/latexrestricted/blob/main/latexrestricted/_anypath.py
101 class Path(type(pathlib.Path())):
102 __slots__ = (
103 '_cache_key',
104 )
105
106 if sys.version_info[:2] < (3, 9):
107 def is_relative_to(self, other):
108 try:
109 self.relative_to(other)
110 return True
111 except ValueError:
112 return False
113
114 @property
115 def cache_key(self):
116 try:
117 return self._cache_key
118 except AttributeError:
119 self._cache_key = (type(self), self)
120 return self._cache_key
121
122 _resolved_set = set()
123
124 def resolve(self):
125 resolved = super().resolve()
126 self._resolved_set.add(resolved.cache_key)
127 return resolved
128
129 def is_resolved(self) -> bool:
130 return self.cache_key in self._resolved_set
131
132
133
134
135 # Define function that determines whether subprocess executable paths are
136 # permitted.
137 prohibited_path_roots = set()
138 prohibited_path_roots.add(Path.cwd())
139 env_TEXMFOUTPUT = os.getenv('TEXMFOUTPUT')
140 env_TEXMF_OUTPUT_DIRECTORY = os.getenv('TEXMF_OUTPUT_DIRECTORY')
141 for env_var in (env_TEXMFOUTPUT, env_TEXMF_OUTPUT_DIRECTORY):
142 if env_var:
143 env_var_path = Path(env_var)
144 prohibited_path_roots.add(env_var_path)
145 prohibited_path_roots.add(env_var_path.resolve())
146
147 did_init_prohibited_path_roots = False
148 def is_permitted_executable_path(executable_path, executable_path_resolved):
149 global did_init_prohibited_path_roots
150 if not did_init_prohibited_path_roots:
151 did_init_prohibited_path_roots = True
152 init_prohibited_path_roots()
153 if not executable_path_resolved.is_resolved():
154 raise Exception('Second argument must be resolved path')
155 if any(e.is_relative_to(p) or p.is_relative_to(e)
156 for e in set([executable_path.parent, executable_path_resolved.parent])
157 for p in prohibited_path_roots):
158 return False
159 return True
160
161 # TeX Live allows setting `TEXMFOUTPUT` in LaTeX configuration.
162 # Retrieving that value with kpsewhich follows the approach in latexrestricted:
163 # https://github.com/gpoore/latexrestricted/blob/main/latexrestricted/_latex_config.py
164 env_SELFAUTOLOC = os.getenv('SELFAUTOLOC')
165 env_TEXSYSTEM = os.getenv('TEXSYSTEM')
166 def init_prohibited_path_roots():
167 if not env_TEXMFOUTPUT and env_SELFAUTOLOC and (not env_TEXSYSTEM or env_TEXSYSTEM.lower() != 'miktex'):
168 if sys.platform == 'win32':
169 # Under Windows, shell escape executables will often be launched
170 # with the TeX Live `runscript.exe` executable wrapper. This
171 # overwrites `SELFAUTOLOC` from TeX with the location of the
172 # wrapper, so `SELFAUTOLOC` may not be correct.
173 which_tlmgr = shutil.which('tlmgr') # No `.exe`; likely `.bat`
174 if not which_tlmgr:
175 sys.exit('Failed to find TeX Live "tlmgr" executable on PATH')
176 which_tlmgr_resolved = Path(which_tlmgr).resolve()
177 texlive_bin_path = which_tlmgr_resolved.parent
178 # Make sure executable is *.exe, not *.bat or *.cmd:
179 # https://docs.python.org/3/library/subprocess.html#security-considerations
180 which_kpsewhich = shutil.which('kpsewhich.exe', path=str(texlive_bin_path))
181 if not which_kpsewhich:
182 sys.exit(
183 'Failed to find a TeX Live "tlmgr" executable with accompanying "kpsewhich" executable on PATH'
184 )
185 which_kpsewhich_path = Path(which_kpsewhich)
186 which_kpsewhich_resolved = which_kpsewhich_path.resolve()
187 if not texlive_bin_path == which_kpsewhich_resolved.parent:
188 sys.exit(' '.join([
189 '"tlmgr" executable from PATH resolved to "{}" '.format(which_tlmgr_resolved.as_posix()),
190 'while "kpsewhich" resolved to "{}";'.format(which_kpsewhich_resolved.as_posix()),
191 '"tlmgr" and "kpsewhich" should be in the same location',
192 ]))
193 if not which_kpsewhich_resolved.name.lower().endswith('.exe'):
194 sys.exit(' '.join([
195 'Executable "kpsewhich" resolved to "{}",'.format(which_kpsewhich_resolved.as_posix()),
196 'but *.exe is required',
197 ]))
198 else:
199 which_kpsewhich = shutil.which('kpsewhich', path=env_SELFAUTOLOC)
200 if not which_kpsewhich:
201 sys.exit(' '.join([
202 'Environment variable SELFAUTOLOC has value "{}",'.format(env_SELFAUTOLOC),
203 'but a "kpsewhich" executable was not found at that location',
204 ]))
205 which_kpsewhich_path = Path(which_kpsewhich)
206 which_kpsewhich_resolved = which_kpsewhich_path.resolve()
207 if not is_permitted_executable_path(which_kpsewhich_path, which_kpsewhich_resolved):
208 # As in the latexrestricted case, this doesn't initially check for
209 # the TeX Live scenario where `TEXMFOUTPUT` is set in a
210 # `texmf.cnf` config file to a location that includes the
211 # `kpsewhich` executable. There isn't a good way to get the value
212 # of `TEXMFOUTPUT` without running `kpsewhich` in that case.
213 sys.exit(
214 'Executable "kpsewhich" is located under the current directory, TEXMFOUTPUT, or '
215 'TEXMF_OUTPUT_DIRECTORY, or one of these locations is under the same directory as the executable'
216 )
217 kpsewhich_cmd = [which_kpsewhich_resolved.as_posix(), '--var-value', 'TEXMFOUTPUT']
218 try:
219 kpsewhich_proc = subprocess.run(kpsewhich_cmd, shell=False, capture_output=True)
220 except PermissionError:
221 sys.exit('Insufficient permission to run "{}"'.format(which_kpsewhich_resolved.as_posix()))
222 kpsewhich_TEXMFOUTPUT = kpsewhich_proc.stdout.strip().decode(sys.stdout.encoding) or None
223 if kpsewhich_TEXMFOUTPUT:
224 kpsewhich_TEXMFOUTPUT_path = Path(kpsewhich_TEXMFOUTPUT)
225 prohibited_path_roots.add(kpsewhich_TEXMFOUTPUT_path)
226 prohibited_path_roots.add(kpsewhich_TEXMFOUTPUT_path.resolve())
227 if not is_permitted_executable_path(which_kpsewhich_path, which_kpsewhich_resolved):
228 # It is now possible to check for the TeX Live scenario where
229 # `TEXMFOUTPUT` is set in a `texmf.cnf` config file to a location
230 # that includes the `kpsewhich` executable. Giving an error
231 # message after already running `kpsewhich` isn't ideal, but there
232 # isn't a good alternative. As in the latexrestricted case, the
233 # impact on overall security is negligible because an unsafe value
234 # of `TEXMFOUTPUT` means that all TeX-related executables are
235 # potentially compromised.
236 sys.exit(
237 'Executable "kpsewhich" is located under the current directory, TEXMFOUTPUT, or '
238 'TEXMF_OUTPUT_DIRECTORY, or one of these locations is under the same directory as the executable'
239 )
240
241
242
243
244 # If Python version is < 3.8, try to locate a more recent version and then
245 # relaunch this script with that Python version in a subprocess.
246 if sys.version_info[:2] < (3, 8):
247 for minor_version in range(13, 7, -1):
248 if sys.platform == 'win32':
249 # Batch files must be prohibited:
250 # https://docs.python.org/3/library/subprocess.html#security-considerations
251 which_python = shutil.which('python3.{}.exe'.format(minor_version))
252 else:
253 which_python = shutil.which('python3.{}'.format(minor_version))
254 if which_python:
255 which_python_path = Path(which_python)
256 which_python_resolved = which_python_path.resolve()
257 if sys.platform == 'win32' and not which_python_resolved.name.lower().endswith('.exe'):
258 continue
259 if is_permitted_executable_path(which_python_path, which_python_resolved):
260 python_cmd = [which_python_resolved.as_posix(), __file__] + sys.argv[1:]
261 python_proc = subprocess.run(python_cmd, shell=False, capture_output=True)
262 sys.stderr.buffer.write(python_proc.stderr)
263 sys.stdout.buffer.write(python_proc.stdout)
264 sys.exit(python_proc.returncode)
265 sys.exit('latexminted requires Python >= 3.8, but a compatible Python executable was not found on PATH')
266
267
268
269
270 # Check for required wheel dependencies and add them to Python's `sys.path`.
271 script_resolved = Path(__file__).resolve()
272 required_wheel_packages = (
273 'latexminted',
274 'latexrestricted',
275 'latex2pydata',
276 'pygments',
277 )
278 wheel_paths = [p for p in script_resolved.parent.glob('*.whl') if p.name.startswith(required_wheel_packages)]
279 if not wheel_paths:
280 sys.exit('latexminted failed to find bundled wheels *.whl')
281 for pkg in required_wheel_packages:
282 if not any(whl.name.startswith(pkg) for whl in wheel_paths):
283 sys.exit('latexminted failed to find all required bundled wheels *.whl')
284 for wheel_path in wheel_paths:
285 sys.path.insert(0, wheel_path.as_posix())
286
287
288
289
290 # Under Windows, check PATH for a `latexminted` executable outside a TeX
291 # installation. If a `latexminted` executable is found in a suitable location
292 # with sufficient precedence, run it in a subprocess and exit.
293 #
294 # The environment variable `LATEXMINTED_SUBPROCESS` is used to prevent an
295 # endless recursion of subprocesses in the event that a `latexminted`
296 # executable *inside* a TeX installation somehow manages to pass the tests for
297 # an executable *outside* a TeX installation.
298 if sys.platform == 'win32' and not os.getenv('LATEXMINTED_SUBPROCESS'):
299 os.environ['LATEXMINTED_SUBPROCESS'] = '1'
300 fallback_path_search = True
301 if env_SELFAUTOLOC:
302 env_SELFAUTOLOC_resolved = Path(env_SELFAUTOLOC).resolve()
303 else:
304 env_SELFAUTOLOC_resolved = None
305 which_latexminted = shutil.which('latexminted.exe')
306 if which_latexminted:
307 which_latexminted_path = Path(which_latexminted)
308 which_latexminted_resolved = which_latexminted_path.resolve()
309 if not which_latexminted_resolved.name.lower().endswith('.exe'):
310 sys.exit(' '.join([
311 'Executable "latexminted" resolved to "{}",'.format(which_latexminted_resolved.as_posix()),
312 'but *.exe is required',
313 ]))
314 if which_latexminted_resolved == script_resolved:
315 pass
316 elif (which_latexminted_resolved.parent / 'tex.exe').exists():
317 pass
318 elif any(x in which_latexminted_resolved.as_posix().lower() for x in ('texlive', 'miktex', 'tinytex')):
319 pass
320 elif env_SELFAUTOLOC_resolved and which_latexminted_resolved.is_relative_to(env_SELFAUTOLOC_resolved):
321 pass
322 elif is_permitted_executable_path(which_latexminted_path, which_latexminted_resolved):
323 latexminted_cmd = [which_latexminted_resolved.as_posix()] + sys.argv[1:]
324 latexminted_proc = subprocess.run(latexminted_cmd, shell=False, capture_output=True)
325 sys.stderr.buffer.write(latexminted_proc.stderr)
326 sys.stdout.buffer.write(latexminted_proc.stdout)
327 sys.exit(latexminted_proc.returncode)
328 else:
329 # If there was a `latexminted` executable on PATH outside a TeX
330 # installation, but it wasn't permitted due to its location, don't
331 # perform fallback search.
332 fallback_path_search = False
333 if fallback_path_search:
334 # Windows appends user PATH to system PATH, so the system PATH may
335 # prevent finding a user installation of `latexminted`. Search
336 # through PATH elements under user home directory to check for
337 # `latexminted.exe` outside a TeX installation.
338 home_path = Path.home()
339 env_PATH = os.environ.get('PATH', '')
340 for path_elem in env_PATH.split(os.pathsep):
341 if not path_elem or not Path(path_elem).is_relative_to(home_path):
342 continue
343 which_latexminted = shutil.which('latexminted.exe', path=path_elem)
344 if not which_latexminted:
345 continue
346 which_latexminted_path = Path(which_latexminted)
347 which_latexminted_resolved = which_latexminted_path.resolve()
348 if which_latexminted_resolved == script_resolved:
349 break
350 elif (which_latexminted_resolved.parent / 'tex.exe').exists():
351 break
352 elif any(x in which_latexminted_resolved.as_posix().lower() for x in ('texlive', 'miktex', 'tinytex')):
353 break
354 elif env_SELFAUTOLOC_resolved and which_latexminted_resolved.is_relative_to(env_SELFAUTOLOC_resolved):
355 break
356 elif is_permitted_executable_path(which_latexminted_path, which_latexminted_resolved):
357 latexminted_cmd = [which_latexminted_resolved.as_posix()] + sys.argv[1:]
358 try:
359 latexminted_proc = subprocess.run(latexminted_cmd, shell=False, capture_output=True)
360 except PermissionError:
361 break
362 sys.stderr.buffer.write(latexminted_proc.stderr)
363 sys.stdout.buffer.write(latexminted_proc.stdout)
364 sys.exit(latexminted_proc.returncode)
365 else:
366 break
367
368
369
370
371 from latexminted.cmdline import main
372 main()