Coverage for trlcdoc/plantuml_client.py: 92%
39 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"""Render a PlantUML diagram with a PlantUML server, as `plantuml -pipe` does with the jar.
3sphinxcontrib-plantuml can only run a command: it passes the diagram on stdin and expects the image
4on stdout. This module is that command for a PlantUML server. It is started for every diagram, so it
5imports only what it needs.
7Usage: python -m trlcdoc.plantuml_client <server URL> [PlantUML options, e.g. -pipe -tsvg]
8"""
10# trlcdoc - A utility for producing project documentation from TRLC and LOBSTER contents.
11# Copyright (c) 2026 - 2026 Norbert Schulz github@schulznorbert.de
12#
13# This file is part of trlcdoc program.
14#
15# The trlcdoc program is free software: you can redistribute it and/or modify it under
16# the terms of the GNU General Public License as published by the Free Software Foundation,
17# either version 3 of the License, or (at your option) any later version.
18#
19# The trlcdoc program is distributed in the hope that it will be useful, but
20# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
21# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
22#
23# You should have received a copy of the GNU General Public License along with pyTRLCConverter.
24# If not, see <https://www.gnu.org/licenses/>.
26# Imports **********************************************************************
28import base64
29import sys
30import urllib.error
31import urllib.request
32import zlib
34# Variables ********************************************************************
36# PlantUML encodes the compressed diagram with its own base64 alphabet, see https://plantuml.com/text-encoding.
37BASE64_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
38PLANTUML_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_"
40# Seconds to wait for the image of one diagram.
41RENDER_TIMEOUT = 60
43# Classes **********************************************************************
45# Functions ********************************************************************
48def encode_diagram(text: str) -> str:
49 # lobster-trace: SwRequirements.sw_req_plantuml
50 """Encode a diagram for the URL of a PlantUML server.
52 Args:
53 text (str): PlantUML diagram source.
55 Returns:
56 str: The diagram, compressed with deflate and encoded with the PlantUML base64 alphabet.
57 """
58 # zlib adds a 2 byte header and a 4 byte checksum to the raw deflate data PlantUML expects.
59 compressed = zlib.compress(text.encode("utf-8"))[2:-4]
60 encoded = base64.b64encode(compressed).decode("ascii")
61 return encoded.translate(str.maketrans(BASE64_CHARS, PLANTUML_CHARS)).rstrip("=")
64def file_format(options: list[str]) -> str:
65 # lobster-trace: SwRequirements.sw_req_plantuml
66 """Get the image format from the PlantUML command line options.
68 Args:
69 options (list[str]): PlantUML options, e.g. ['-pipe', '-tsvg'] or ['-tlatex:nopreamble'].
71 Returns:
72 str: The format, png if no -t option is given, as with the jar.
73 """
74 fmt = "png"
75 for option in options:
76 if option.startswith("-t"):
77 fmt = option[2:].split(":")[0]
78 return fmt
81def main(argv: list[str] | None = None) -> int:
82 # lobster-trace: SwRequirements.sw_req_plantuml
83 """Read a diagram from stdin, render it with the PlantUML server and write the image to stdout.
85 Args:
86 argv (list[str] | None): Server URL and PlantUML options, defaults to sys.argv[1:].
88 Returns:
89 int: 0 on success, 1 if the server reports a diagram error or cannot be reached.
90 """
91 args = sys.argv[1:] if argv is None else argv
92 if not args:
93 print("Usage: python -m trlcdoc.plantuml_client <server URL> [PlantUML options]", file=sys.stderr)
94 return 1
95 server_url = args[0].rstrip("/")
96 text = sys.stdin.buffer.read().decode("utf-8")
97 url = f"{server_url}/{file_format(args[1:])}/{encode_diagram(text)}"
99 try:
100 with urllib.request.urlopen(url, timeout=RENDER_TIMEOUT) as response:
101 sys.stdout.buffer.write(response.read())
102 except urllib.error.HTTPError as err:
103 # A diagram error comes with an image that shows it, like the output of the jar.
104 sys.stdout.buffer.write(err.read())
105 print(f"PlantUML server {server_url}: {err.code} {err.reason}", file=sys.stderr)
106 return 1
107 except OSError as err:
108 print(f"PlantUML server {server_url} not reachable: {err}", file=sys.stderr)
109 return 1
110 return 0
113# Main *************************************************************************
115if __name__ == "__main__":
116 sys.exit(main())