Coverage for trlcdoc/util.py: 95%
106 statements
« prev ^ index » next coverage.py v7.17.5, created at 2026-11-28 14:00 +0000
« prev ^ index » next coverage.py v7.17.5, created at 2026-11-28 14:00 +0000
1"""Common helpers of the trlcdoc steps."""
3# trlcdoc - A utility for producing project documentation from TRLC and LOBSTER contents.
4# Copyright (c) 2026 - 2026 Norbert Schulz github@schulznorbert.de
5#
6# This file is part of trlcdoc program.
7#
8# The trlcdoc program is free software: you can redistribute it and/or modify it under
9# the terms of the GNU General Public License as published by the Free Software Foundation,
10# either version 3 of the License, or (at your option) any later version.
11#
12# The trlcdoc program is distributed in the hope that it will be useful, but
13# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
15#
16# You should have received a copy of the GNU General Public License along with pyTRLCConverter.
17# If not, see <https://www.gnu.org/licenses/>.
19# Imports **********************************************************************
21import logging
22import os
23import re
24import shutil
25import signal
26import subprocess
27import sys
28import time
29from pathlib import Path
31from .log import TRACE, command_line, redact_env
33# Variables ********************************************************************
35# Marks a folder as trlcdoc output. trlcdoc only deletes folders containing it.
36MARKER_FILE = ".trlcdoc"
37MARKER_TEXT = "Generated by trlcdoc. The whole folder is removed by 'trlcdoc clean' !\n"
39LOG = logging.getLogger(__name__)
41# Classes **********************************************************************
44class TrlcdocError(Exception):
45 """Error that stops the documentation build with a message."""
48# Functions ********************************************************************
51def find_tool(name: str, hint: str = "Install the trlcdoc package dependencies.") -> str:
52 # lobster-trace: SwRequirements.sw_req_trlc_conversion
53 # lobster-trace: SwRequirements.sw_req_test_run
54 # lobster-trace: SwRequirements.sw_req_trace_report
55 # lobster-trace: SwRequirements.sw_req_external_tools
56 """Find a console script, preferring the one of the running Python environment.
58 Tools that are not installed with trlcdoc, e.g. Java, are searched on the PATH.
60 Args:
61 name (str): Name of the console script, e.g. 'lobster-trlc'.
62 hint (str): How to install the tool, added to the error message.
64 Returns:
65 str: Path of the executable.
67 Raises:
68 TrlcdocError: If the tool is not installed.
69 """
70 script_dir = Path(sys.executable).parent
71 candidates = [script_dir / name, script_dir / f"{name}.exe"]
72 tool = next((str(path) for path in candidates if path.is_file()), shutil.which(name))
73 if tool is None:
74 raise TrlcdocError(f"Tool '{name}' not found. {hint}")
75 return tool
78def find_graphviz(purpose: str) -> str:
79 # lobster-trace: SwRequirements.sw_req_external_tools
80 """Find the Graphviz dot program, so a missing Graphviz stops the build instead of leaving out diagrams.
82 Args:
83 purpose (str): What needs Graphviz, added to the error message, e.g. 'for the tracing policy diagram'.
85 Returns:
86 str: Path of the dot executable.
88 Raises:
89 TrlcdocError: If dot is not on the PATH.
90 """
91 return find_tool("dot", f"Graphviz is needed {purpose}, see https://graphviz.org.")
94def run(
95 cmd: list[str],
96 cwd: Path,
97 env: dict[str, str] | None = None,
98 stdin: str | None = None,
99 source: str | None = None,
100) -> int:
101 # lobster-trace: SwRequirements.sw_req_exit_code
102 """Run an external command and stop the build if it fails.
104 Args:
105 cmd (list[str]): Command and its arguments.
106 cwd (Path): Working directory.
107 env (dict[str, str] | None): Additional environment variables.
108 stdin (str | None): Text passed to the standard input of the command.
109 source (str | None): Configuration entry of the command, e.g. 'tests.command', named in the error
110 message if the program can't be started. None for the tools trlcdoc runs itself.
112 Returns:
113 int: The exit code, which is always 0.
115 Raises:
116 TrlcdocError: If the program can't be started or the command returns a non-zero exit code.
117 """
118 returncode = run_unchecked(cmd, cwd, env, stdin, source)
119 if returncode != 0:
120 raise TrlcdocError(f"Command failed with exit code {returncode}: {command_line(cmd)}")
121 return returncode
124def run_unchecked(
125 cmd: list[str],
126 cwd: Path,
127 env: dict[str, str] | None = None,
128 stdin: str | None = None,
129 source: str | None = None,
130) -> int:
131 # lobster-trace: SwRequirements.sw_req_test_run
132 # lobster-trace: SwRequirements.sw_req_verbose_output
133 # lobster-trace: SwRequirements.sw_req_exit_code
134 """Run an external command and return its exit code.
136 The command is always shown. Verbose output adds the working folder, the environment
137 variables the command gets from trlcdoc, the size of its input, its exit code and duration.
138 The output of the command is not captured, it goes directly to the console.
140 Args:
141 cmd (list[str]): Command and its arguments.
142 cwd (Path): Working directory.
143 env (dict[str, str] | None): Additional environment variables.
144 stdin (str | None): Text passed to the standard input of the command.
145 source (str | None): Configuration entry of the command, e.g. 'tests.command', named in the error
146 message if the program can't be started. None for the tools trlcdoc runs itself.
148 Returns:
149 int: The exit code of the command.
151 Raises:
152 TrlcdocError: If the program is not found or not executable.
153 """
154 full_env = dict(os.environ)
155 full_env.update(env or {})
156 LOG.info(" $ %s", command_line(cmd))
157 LOG.debug("cwd: %s", cwd)
158 for name, value in sorted(redact_env(env or {}).items()):
159 LOG.debug("env: %s=%s", name, value)
160 if stdin is not None:
161 LOG.debug("stdin: %d characters", len(stdin))
162 if LOG.isEnabledFor(TRACE):
163 for name, value in sorted(redact_env(full_env).items()):
164 LOG.log(TRACE, "environment: %s=%s", name, value)
166 # Python buffers its output, the command writes directly to the console: keep the order.
167 sys.stdout.flush()
168 sys.stderr.flush()
169 started = time.monotonic()
170 try:
171 result = subprocess.run(cmd, cwd=cwd, env=full_env, input=stdin, text=stdin is not None, check=False)
172 except (FileNotFoundError, PermissionError) as error:
173 raise _start_error(cmd[0], error, source, full_env) from error
174 returncode = result.returncode
175 LOG.debug("exit code %d%s after %.1f s", returncode, _signal_name(returncode), time.monotonic() - started)
176 return returncode
179def _start_error(program: str, error: OSError, source: str | None, env: dict[str, str]) -> TrlcdocError:
180 # lobster-trace: SwRequirements.sw_req_exit_code
181 """Create the build error for a program that can't be started.
183 Verbose output shows the PATH the program was searched in.
185 Args:
186 program (str): The program of the command.
187 error (OSError): The error of the start, FileNotFoundError or PermissionError.
188 source (str | None): Configuration entry of the command, None for the tools trlcdoc runs itself.
189 env (dict[str, str]): Environment of the command.
191 Returns:
192 TrlcdocError: The error naming the program and what to check.
193 """
194 LOG.debug("PATH: %s", env.get("PATH", ""))
195 problem = "not found" if isinstance(error, FileNotFoundError) else "not executable"
196 check = "check the command" if source is None else f"check {source} in the configuration"
197 return TrlcdocError(f"Program '{program}' {problem}, {check} and the PATH.")
200def _signal_name(returncode: int) -> str:
201 # lobster-trace: SwRequirements.sw_req_verbose_output
202 """Name the signal that ended a command.
204 Args:
205 returncode (int): Exit code of the command, negative for a signal on POSIX systems.
207 Returns:
208 str: The signal name in parentheses, e.g. ' (SIGKILL)', empty if no signal ended the command.
209 """
210 if returncode >= 0:
211 return ""
212 try:
213 return f" ({signal.Signals(-returncode).name})"
214 except ValueError:
215 return ""
218def _check_owned(output: Path) -> Path:
219 # lobster-trace: SwRequirements.sw_req_delete_protection
220 """Ensure the output folder was created by trlcdoc, before anything in it is deleted.
222 A missing or empty folder is accepted. Any other folder must contain the marker file.
224 Args:
225 output (Path): The output folder.
227 Returns:
228 Path: The output folder.
230 Raises:
231 TrlcdocError: If the folder exists with content but without the marker file.
232 """
233 if output.exists():
234 owned = output.is_dir() and ((output / MARKER_FILE).is_file() or not any(output.iterdir()))
235 if not owned:
236 raise TrlcdocError(
237 f"{output} is not a trlcdoc output folder (no {MARKER_FILE} marker file), refusing to "
238 "delete it. Check paths.output or remove the folder manually."
239 )
240 return output
243def prepare_output(output: Path) -> Path:
244 # lobster-trace: SwRequirements.sw_req_output_folder
245 # lobster-trace: SwRequirements.sw_req_delete_protection
246 """Create the output folder if needed and mark it as owned by trlcdoc.
248 Args:
249 output (Path): The output folder.
251 Returns:
252 Path: The output folder.
254 Raises:
255 TrlcdocError: If the folder exists with content but without the marker file.
256 """
257 _check_owned(output).mkdir(parents=True, exist_ok=True)
258 (output / MARKER_FILE).write_text(MARKER_TEXT, encoding="utf-8")
259 return output
262def clean_dir(folder: Path, output: Path) -> Path:
263 # lobster-trace: SwRequirements.sw_req_output_folder
264 # lobster-trace: SwRequirements.sw_req_delete_protection
265 """Create an empty folder inside the output folder, removing previous content.
267 Args:
268 folder (Path): The folder, a subfolder of the output folder.
269 output (Path): The output folder.
271 Returns:
272 Path: The folder.
274 Raises:
275 TrlcdocError: If the folder is not inside a trlcdoc output folder.
276 """
277 if folder == output or not folder.is_relative_to(output):
278 raise TrlcdocError(f"{folder} is not inside the output folder {output}, refusing to delete it.")
279 prepare_output(output)
280 if folder.exists():
281 shutil.rmtree(folder)
282 folder.mkdir(parents=True)
283 return folder
286def remove_output(output: Path) -> bool:
287 # lobster-trace: SwRequirements.sw_req_clean
288 # lobster-trace: SwRequirements.sw_req_delete_protection
289 """Remove the output folder with all its content.
291 Args:
292 output (Path): The output folder.
294 Returns:
295 bool: True if the folder existed and was removed.
297 Raises:
298 TrlcdocError: If the folder exists with content but without the marker file.
299 """
300 existed = _check_owned(output).exists()
301 if existed:
302 shutil.rmtree(output)
303 return existed
306def git_output(args: list[str], cwd: Path) -> str | None:
307 # lobster-trace: SwRequirements.sw_req_trace_report
308 """Run a git command and return its output.
310 Args:
311 args (list[str]): git arguments.
312 cwd (Path): Working directory.
314 Returns:
315 str | None: The stripped output, or None if git failed.
316 """
317 result = None
318 LOG.debug("git %s in %s", " ".join(args), cwd)
319 try:
320 proc = subprocess.run(["git", *args], cwd=cwd, capture_output=True, text=True, check=False)
321 if proc.returncode == 0:
322 result = proc.stdout.strip()
323 except OSError:
324 result = None
325 return result
328def git_root(path: Path) -> Path | None:
329 # lobster-trace: SwRequirements.sw_req_trace_report
330 # lobster-trace: SwRequirements.sw_req_markdown_links
331 """Get the root folder of the git repository that contains a folder.
333 The project root is a subfolder of the repository if several projects share one repository.
335 Args:
336 path (Path): A folder inside the repository, e.g. the project root.
338 Returns:
339 Path | None: The resolved repository root, or None if the folder is not in a git repository.
340 """
341 toplevel = git_output(["rev-parse", "--show-toplevel"], path)
342 return Path(toplevel).resolve() if toplevel else None
345def repository_url(repository: str, root: Path) -> str:
346 # lobster-trace: SwRequirements.sw_req_trace_report
347 # lobster-trace: SwRequirements.sw_req_markdown_links
348 """Get the repository URL for links to project files.
350 Args:
351 repository (str): Configured repository URL or 'auto' for the origin remote.
352 root (Path): Project root, the git working directory.
354 Returns:
355 str: HTTPS repository URL without '.git' suffix, the base of the file links.
357 Raises:
358 TrlcdocError: If 'auto' is configured and git has no origin remote.
359 """
360 url = repository
361 if url == "auto":
362 url = git_output(["remote", "get-url", "origin"], root)
363 if url is None:
364 raise TrlcdocError("project.repository is 'auto', but 'git remote get-url origin' failed.")
365 # git@github.com:owner/repo.git -> https://github.com/owner/repo.git
366 url = re.sub(r"^git@([^:]+):", r"https://\1/", url)
367 # https://github.com/owner/repo.git -> https://github.com/owner/repo
368 return re.sub(r"\.git$", "", url)
371# Main *************************************************************************