1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280
|
#! /usr/bin/env python3
# Copyright 2009-2024 The VOTCA Development Team (http://www.votca.org)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import argparse
import itertools
import re
import subprocess
from pathlib import Path
from typing import Iterator, List, NamedTuple, Tuple
PROGTITLE = 'THE VOTCA::TOOLS help to doc converter'
VOTCAHEADER = f"""
==================================================
======== VOTCA (http://www.votca.org) ========
==================================================
{PROGTITLE}
please read and cite: PROJECT_CITATION
and submit bugs to PROJECT_CONTACT
votca_help2doc
"""
AUTHORS = "Written and maintained by the VOTCA Development Team <devs@votca.org>"
COPYRIGHT = """
Copyright 2009-2024 The VOTCA Development Team (http://www.votca.org)
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the
License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
either express or implied. See the License for the specific language governing
permissions and limitations under the License.
"""
DESCRIPTION = f"""{VOTCAHEADER}
Convert a Votca CLI's help message to RST or GROFF format."""
class Data(NamedTuple):
"""Data class containing the help's section."""
name: str
description: str
examples: str
options: str
usage: str
authors: str = AUTHORS
copyright: str = COPYRIGHT
def parse_user_arguments() -> argparse.Namespace:
"""Read the user arguments."""
parser = argparse.ArgumentParser("help2doc", usage=argparse.SUPPRESS,
description=DESCRIPTION, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("-n", "--name", required=True,
help="Name of the tool to extract the help message")
parser.add_argument("-o", "--out", help="Output file", default=None)
parser.add_argument("-f", "--format", help="Output format",
choices=["rst", "groff"], default="rst")
return parser.parse_args()
def take(it: Iterator[str], n: int) -> List[str]:
"""Take n elements from the Iterator an return them."""
return [next(it) for _ in range(n)]
def parse_help_message(msg: str, name: str) -> Data:
"""Parse the help message into an intermediate representation."""
lines = iter(msg.splitlines())
# Votca logo
take(lines, 7)
# remove Compilation info
lines = take_while_version(lines)
# description and optional examples
opts_lines, lines = take_until_options(lines)
description, examples = read_section_examples(opts_lines)
description, usage = search_for_usage(description)
# Options and optional examples
if examples:
options = "\n ".join(filter(lambda x: x, lines))
else:
options, examples = read_section_examples(lines)
options = format_options(options)
# Search for the `Used external keyword`
keyword = "Used external"
if keyword in usage:
usage_lines = usage.splitlines()
description += "\n".join(itertools.dropwhile(
lambda x: keyword not in x, usage_lines))
usage = "\n".join(itertools.takewhile(
lambda x: keyword not in x, usage_lines))
return Data(name, description, examples, options, usage)
def search_for_usage(desc: str) -> Tuple[str, str]:
"""Search for an `usage:` declaration in the description."""
keywords = {u for u in {"Usage:", "usage:"} if u in desc}
if not keywords:
return desc, ""
else:
key = keywords.pop()
data = desc.split(key)
return data[0], ''.join(data[1:])
def take_while_version(lines: Iterator[str]) -> Iterator[str]:
"""Remove the lines with version on it."""
value = next(lines)
if any(key in value for key in {"version", "bugs", "gromacs, 20"}):
return take_while_version(lines)
else:
return itertools.chain([value], lines)
def take_until_options(lines: Iterator[str]) -> Tuple[Iterator[str], Iterator[str]]:
"""Take lines until options."""
opts = []
old_lines = []
for value in lines:
if not any(x in value for x in {"options:", "arguments:"}):
opts.append(value)
else:
old_lines = itertools.chain([value], lines)
break
return iter(opts), iter(old_lines)
def format_options(options: str):
"""Format the options."""
s = []
for line in options.splitlines():
if line.endswith(":"):
s.append(f"{line}\n")
else:
s.append(line)
return "\n".join(s)
def generate_code_block(name: str) -> str:
"""Generate a code block section."""
return f"""
{name}
{'*' * len(name)}
.. highlight:: none
::
"""
def format_rst(sec: Data) -> str:
"""Format the section as RST."""
opts = "\n".join(f" {x}" for x in sec.options.splitlines())
examples = "\n".join(f" {x}" for x in sec.examples.splitlines())
options_code_block = generate_code_block("OPTIONS")
examples_code_block = generate_code_block("EXAMPLES")
usage = f"**Usage:** {sec.usage}" if sec.usage else ""
return f"""
NAME
****
**{sec.name}** - Part of the VOTCA package
SYNOPSIS
********
**{sec.name}** [OPTIONS]
**{sec.name}** [--help]
{usage}
DESCRIPTION
***********
{sec.description}
{examples_code_block if examples else ""}
{examples}
{options_code_block if opts else ""}
{opts}
"""
def format_groff(sec: Data) -> str:
"""Format the sections in GROFF format."""
return f""".TH "{sec.name.upper()}" "1" " {sec.name} User Manual" "VOTCA Development Team"
.nh
.ad l
.SH NAME
.PP
\\fB{sec.name}\\fP - Part of the VOTCA package
.SH SYNOPSIS
.PP
\\fB{sec.name}\\fP [OPTIONS]
.PP
\\fB{sec.name}\\fP [--help]
.SH DESCRIPTION
.PP
{sec.description}
{sec.examples}
.SH OPTIONS
.PP
{sec.options}
.SH AUTHORS
.PP
{sec.authors}
.SH COPYRIGHT
.PP
{sec.copyright}
"""
def read_section_examples(lines: Iterator[str]) -> Tuple[str, str]:
"""Check for examples and format them properly."""
express = re.compile(r'^example', flags=re.IGNORECASE)
desc = "\n".join(itertools.takewhile(
lambda x: re.match(express, x) is None, lines))
# extract example section
examples = "\n ".join(lines)
if examples:
examples = " " + examples
return desc, examples
def convert_help_message(args: argparse.Namespace):
"""Convert help message."""
path = Path(args.name)
name = path.stem
msg = subprocess.check_output(
f"{path.absolute().as_posix()} --help", shell=True)
sections = parse_help_message(msg.decode(), name)
if args.format == "rst":
data = format_rst(sections)
else:
data = format_groff(sections)
output = args.out if args.out is not None else f"{name}.{args.format}"
with open(output, 'w') as handler:
handler.write(data)
def main():
args = parse_user_arguments()
convert_help_message(args)
if __name__ == "__main__":
main()
|