Coverage for trlcdoc/cli.py: 98%

108 statements  

« prev     ^ index     » next       coverage.py v7.17.5, created at 2026-11-28 14:00 +0000

1"""Command line interface of trlcdoc.""" 

2 

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/>. 

18 

19# Imports ********************************************************************** 

20 

21import argparse 

22import logging 

23from pathlib import Path 

24 

25from . import __version__ 

26from .config import Config, find_config, load_config 

27from .convert import convert_documents 

28from .html import build_html, show_html 

29from .log import TRACE, setup_logging 

30from .pages import check_toctrees 

31from .plantuml import provide_plantuml, stop_picoweb 

32from .testrun import run_tests 

33from .trace import build_trace_report 

34from .util import TrlcdocError, remove_output 

35 

36# Variables ******************************************************************** 

37 

38# Steps in execution order. 'all' runs every step the configuration needs, except clean and show. 

39STEPS = ["clean", "check", "plantuml", "tests", "convert", "trace", "html", "show"] 

40 

41COPYRIGHT = "Copyright (c) 2026 Norbert Schulz" 

42REPOSITORY = "https://github.com/nhjschulz/trlc-doc" 

43DESCRIPTION = """Build project documentation for TRLC/LOBSTER based projects: requirements, architecture, 

44tests, test results, tracing report and HTML site.""" 

45 

46# Exit code after Ctrl+C, as the shell reports a process ended by SIGINT. 

47EXIT_INTERRUPTED = 130 

48 

49LOG = logging.getLogger(__name__) 

50 

51# Classes ********************************************************************** 

52 

53# Functions ******************************************************************** 

54 

55 

56def _parse_args(argv: list[str] | None) -> argparse.Namespace: 

57 # lobster-trace: SwRequirements.sw_req_cli 

58 # lobster-trace: SwRequirements.sw_req_cli_help 

59 # lobster-trace: SwRequirements.sw_req_cli_version 

60 # lobster-trace: SwRequirements.sw_req_steps 

61 # lobster-trace: SwRequirements.sw_req_config_file 

62 # lobster-trace: SwRequirements.sw_req_output_option 

63 # lobster-trace: SwRequirements.sw_req_verbose_output 

64 """Parse the command line arguments. 

65 

66 Args: 

67 argv (list[str] | None): Arguments, defaults to sys.argv[1:]. 

68 

69 Returns: 

70 argparse.Namespace: The parsed arguments. 

71 """ 

72 parser = argparse.ArgumentParser( 

73 prog="trlcdoc", 

74 description=DESCRIPTION, 

75 epilog=f"Version {__version__} - {COPYRIGHT} - GPL-3.0-or-later - see {REPOSITORY} for further information.", 

76 formatter_class=argparse.RawDescriptionHelpFormatter, 

77 ) 

78 

79 parser.add_argument( 

80 "steps", nargs="*", metavar="step", help=f"steps to run: {', '.join(STEPS)} or all (default: all)" 

81 ) 

82 parser.add_argument( 

83 "--version", action="version", version=f"%(prog)s {__version__}", help="show the trlcdoc version and exit" 

84 ) 

85 parser.add_argument( 

86 "-v", 

87 "--verbose", 

88 action="count", 

89 default=0, 

90 help="show decisions, tool details and timings, -vv also per-item details", 

91 ) 

92 parser.add_argument( 

93 "-c", 

94 "--config", 

95 type=Path, 

96 help="project configuration (default: trlcdoc.yaml in the current folder or a parent)", 

97 ) 

98 parser.add_argument( 

99 "-o", 

100 "--output", 

101 type=Path, 

102 help="output folder, overrides paths.output of the configuration (relative to the current folder)", 

103 ) 

104 parser.add_argument( 

105 "--online", action="store_true", help="link the tracing report to the repository instead of local files" 

106 ) 

107 parser.add_argument( 

108 "--format", 

109 choices=["rst", "markdown"], 

110 default="rst", 

111 help="output format of the convert step (default: rst, needed for html)", 

112 ) 

113 args = parser.parse_args(argv) 

114 

115 args.steps = args.steps or ["all"] 

116 unknown = [step for step in args.steps if step not in (*STEPS, "all")] 

117 if unknown: 

118 parser.error(f"unknown step(s) {', '.join(unknown)}, choose from {', '.join(STEPS)}, all") 

119 return args 

120 

121 

122def _selected_steps(cfg: Config, requested: list[str]) -> list[str]: 

123 # lobster-trace: SwRequirements.sw_req_steps 

124 # lobster-trace: SwRequirements.sw_req_step_order 

125 # lobster-trace: SwRequirements.sw_req_verbose_output 

126 """Determine the steps to run, in execution order. 

127 

128 Args: 

129 cfg (Config): Project configuration. 

130 requested (list[str]): Steps from the command line. 

131 

132 Returns: 

133 list[str]: The steps to run. 

134 """ 

135 selected = {step for step in STEPS if step in requested} 

136 if "all" in requested: 

137 selected.update( 

138 step 

139 for step in STEPS 

140 if step not in ("clean", "show") 

141 and not (step == "tests" and cfg.tests is None) 

142 and not (step == "trace" and cfg.trace is None) 

143 ) 

144 if cfg.tests is None: 

145 LOG.debug("Step tests skipped: the configuration has no 'tests' section.") 

146 if cfg.trace is None: 

147 LOG.debug("Step trace skipped: the configuration has no 'trace' section.") 

148 # Converting and rendering need the PlantUML jar. 

149 if selected & {"convert", "html"} and "plantuml" not in selected: 

150 LOG.debug("Step plantuml added: convert and html need PlantUML.") 

151 selected.add("plantuml") 

152 steps = [step for step in STEPS if step in selected] 

153 LOG.debug("Steps: %s", ", ".join(steps)) 

154 return steps 

155 

156 

157def _run_step(step: str, cfg: Config, args: argparse.Namespace) -> bool: 

158 # lobster-trace: SwRequirements.sw_req_steps 

159 # lobster-trace: SwRequirements.sw_req_clean 

160 # lobster-trace: SwRequirements.sw_req_show 

161 # lobster-trace: SwRequirements.sw_req_exit_code 

162 # lobster-trace: SwRequirements.sw_req_toctree_check 

163 """Run one step. 

164 

165 Args: 

166 step (str): Step name. 

167 cfg (Config): Project configuration. 

168 args (argparse.Namespace): Command line arguments. 

169 

170 Returns: 

171 bool: True if the step found no problems in the project content 

172 (failed tests, missing trace links, wrong table of contents). Build errors raise TrlcdocError. 

173 

174 Raises: 

175 TrlcdocError: If the step cannot be completed. 

176 """ 

177 ok = True 

178 LOG.info("\n===== trlcdoc %s =====", step) 

179 

180 # _parse_args() accepts only the names in STEPS, so every step has a case. 

181 match step: 

182 case "clean": 

183 if remove_output(cfg.output): 

184 LOG.info("Removing %s", cfg.output) 

185 else: 

186 LOG.info("Nothing to clean in %s", cfg.output) 

187 

188 case "check": 

189 LOG.info("Configuration %s is valid, output: %s", cfg.config_file, cfg.output) 

190 toctree_findings = check_toctrees(cfg) 

191 if toctree_findings: 

192 LOG.info("Table of contents of the project start page:") 

193 for finding in toctree_findings: 

194 LOG.info(" %s", finding) 

195 ok = not toctree_findings 

196 

197 case "plantuml": 

198 provide_plantuml(cfg) 

199 

200 case "tests": 

201 if cfg.tests is None: 

202 raise TrlcdocError("The configuration has no 'tests' section.") 

203 ok = run_tests(cfg) 

204 

205 case "convert": 

206 convert_documents(cfg, args.format) 

207 

208 case "trace": 

209 if cfg.trace is None: 

210 raise TrlcdocError("The configuration has no 'trace' section.") 

211 ok = build_trace_report(cfg, args.online) == 0 

212 

213 case "html": 

214 build_html(cfg) 

215 

216 case "show": 

217 show_html(cfg) 

218 

219 return ok 

220 

221 

222def main(argv: list[str] | None = None) -> int: 

223 # lobster-trace: SwRequirements.sw_req_cli 

224 # lobster-trace: SwRequirements.sw_req_config_validation 

225 # lobster-trace: SwRequirements.sw_req_exit_code 

226 # lobster-trace: SwRequirements.sw_req_output_option 

227 # lobster-trace: SwRequirements.sw_req_plantuml_picoweb 

228 # lobster-trace: SwRequirements.sw_req_verbose_output 

229 """Run the requested trlcdoc steps and stop the PlantUML picoweb server at the end. 

230 

231 Args: 

232 argv (list[str] | None): Arguments, defaults to sys.argv[1:]. 

233 

234 Returns: 

235 int: 0 if all steps succeeded and the content has no findings, 

236 1 on findings (failed tests, missing trace links), 2 on build errors, 130 if interrupted. 

237 """ 

238 args = _parse_args(argv) 

239 setup_logging(args.verbose) 

240 exit_code = 0 

241 try: 

242 config_file = args.config if args.config is not None else find_config(Path.cwd()) 

243 cfg = load_config(config_file, args.output) 

244 LOG.debug("Configuration %s, project root %s, output %s", cfg.config_file, cfg.root, cfg.output) 

245 if LOG.isEnabledFor(TRACE): 

246 for doc in cfg.documents: 

247 LOG.log(TRACE, "Document %s: type %s, page %s", doc["id"], doc["type"], cfg.page_name(doc)) 

248 findings: list[str] = [] 

249 for step in _selected_steps(cfg, args.steps): 

250 if not _run_step(step, cfg, args): 

251 findings.append(step) 

252 if findings: 

253 LOG.info("\ntrlcdoc finished with findings in: %s", ", ".join(findings)) 

254 exit_code = 1 

255 else: 

256 LOG.info("\ntrlcdoc finished successfully.") 

257 except TrlcdocError as err: 

258 LOG.error("\ntrlcdoc error: %s", err) 

259 exit_code = 2 

260 except KeyboardInterrupt: 

261 LOG.error("\ntrlcdoc interrupted") 

262 exit_code = EXIT_INTERRUPTED 

263 finally: 

264 stop_picoweb() 

265 return exit_code 

266 

267 

268# Main *************************************************************************