| 1 |
# SPDX-License-Identifier: GPL-3.0-or-later |
| 2 |
# Copyright (C) 2025-2026 Benjamin Abendroth <[email protected]> |
| 3 |
|
| 4 |
"""This module contains functions to parse the --help output of a program.""" |
| 5 |
|
| 6 |
import re |
| 7 |
from collections import namedtuple |
| 8 |
|
| 9 |
|
| 10 |
# Characters that should not be considered option chars |
| 11 |
OPTION_BREAK_CHARS = [' ', '\t', '\n', ',', '|', '=', '['] |
| 12 |
|
| 13 |
# Characters that delimit options |
| 14 |
OPTION_DELIMITER_CHARS = [',', '|'] |
| 15 |
|
| 16 |
Unparsed = namedtuple('Unparsed', ['text']) |
| 17 |
OptionWithMetavar = namedtuple('OptionWithMetavar', ['option', 'metavar', 'optional']) |
| 18 |
OptionsWithDescription = namedtuple('OptionsWithDescription', ['options', 'description']) |
| 19 |
|
| 20 |
|
| 21 |
class CharStream: |
| 22 |
"""A utility class for sequentially reading characters from a string.""" |
| 23 |
|
| 24 |
def __init__(self, string, pos = 0): |
| 25 |
self.string = string |
| 26 |
self.len = len(string) |
| 27 |
self.pos = pos |
| 28 |
|
| 29 |
def peek(self, relative_pos = 0): |
| 30 |
""" |
| 31 |
Returns the character at the current position plus an optional relative |
| 32 |
offset without advancing the stream. Returns None if the position is |
| 33 |
out of bounds. |
| 34 |
""" |
| 35 |
try: |
| 36 |
return self.string[self.pos + relative_pos] |
| 37 |
except IndexError: |
| 38 |
return None |
| 39 |
|
| 40 |
def peek_str(self, length): |
| 41 |
""" |
| 42 |
Returns a substring of the specified length starting from the current |
| 43 |
position without advancing the stream. |
| 44 |
""" |
| 45 |
return self.string[self.pos:self.pos + length] |
| 46 |
|
| 47 |
def get(self): |
| 48 |
"""Returns the current character and advances the position by one.""" |
| 49 |
c = self.string[self.pos] |
| 50 |
self.pos += 1 |
| 51 |
return c |
| 52 |
|
| 53 |
def is_space(self): |
| 54 |
"""Checks if the current character is a space or a tab.""" |
| 55 |
return self.peek() in (' ', '\t') |
| 56 |
|
| 57 |
def is_end(self): |
| 58 |
"""Checks if the current position has reached the end of the string.""" |
| 59 |
return self.pos >= self.len |
| 60 |
|
| 61 |
def copy(self): |
| 62 |
"""Creates and returns a new CharStream object at the current position.""" |
| 63 |
return CharStream(self.string, self.pos) |
| 64 |
|
| 65 |
def __repr__(self): |
| 66 |
line = '' |
| 67 |
i = self.pos |
| 68 |
while i < self.len: |
| 69 |
if self.string[i] == '\n': |
| 70 |
break |
| 71 |
line += self.string[i] |
| 72 |
i += 1 |
| 73 |
return f"CharStream({line!r})" |
| 74 |
|
| 75 |
|
| 76 |
def eat_line(stream): |
| 77 |
'''Read the remainling line and return it (including the newline character).''' |
| 78 |
content = '' |
| 79 |
while not stream.is_end(): |
| 80 |
char = stream.get() |
| 81 |
content += char |
| 82 |
if char == '\n': |
| 83 |
break |
| 84 |
return content |
| 85 |
|
| 86 |
|
| 87 |
def eat_space(stream): |
| 88 |
'''Read spaces and tabs and return it.''' |
| 89 |
content = '' |
| 90 |
while stream.is_space(): |
| 91 |
content += stream.get() |
| 92 |
return content |
| 93 |
|
| 94 |
|
| 95 |
def parse_option_string(stream): |
| 96 |
'''Read an option string and return it. |
| 97 |
|
| 98 |
All chars except OPTION_BREAK_CHARS are considered valid option chars. |
| 99 |
|
| 100 |
Example option strings: --help, -h |
| 101 |
|
| 102 |
If the resulting option string is '-' or '--', it is not considered an option. |
| 103 |
''' |
| 104 |
option = '' |
| 105 |
p = stream.copy() |
| 106 |
|
| 107 |
eat_space(p) |
| 108 |
|
| 109 |
if p.peek() != '-': |
| 110 |
return None |
| 111 |
|
| 112 |
while not p.is_end() and p.peek() not in OPTION_BREAK_CHARS: |
| 113 |
option += p.get() |
| 114 |
|
| 115 |
if option in ('-', '--'): |
| 116 |
return None |
| 117 |
|
| 118 |
stream.pos = p.pos |
| 119 |
return option |
| 120 |
|
| 121 |
|
| 122 |
def parse_bracket(stream): |
| 123 |
'''Read and return a bracketed expression. |
| 124 |
|
| 125 |
Bracketed expressions are: |
| 126 |
<foo bar> |
| 127 |
[foo bar] |
| 128 |
(foo bar) |
| 129 |
{foo bar} |
| 130 |
''' |
| 131 |
content = stream.peek() |
| 132 |
try: |
| 133 |
closing = {'<':'>', '[':']', '(':')', '{':'}'}[content] |
| 134 |
except KeyError: |
| 135 |
return None |
| 136 |
|
| 137 |
stream.get() |
| 138 |
while not stream.is_end(): |
| 139 |
char = stream.get() |
| 140 |
content += char |
| 141 |
if char == closing: |
| 142 |
break |
| 143 |
|
| 144 |
return content |
| 145 |
|
| 146 |
|
| 147 |
def parse_quoted_string(stream): |
| 148 |
'''Read and return a string. |
| 149 |
|
| 150 |
Strings are: |
| 151 |
'foo bar' |
| 152 |
"foo bar" |
| 153 |
|
| 154 |
Since it is unlikely that we encounter escape sequences in a description |
| 155 |
string of an option, we don't process any escape sequences. |
| 156 |
''' |
| 157 |
quote = stream.peek() |
| 158 |
if quote not in ('"', "'"): |
| 159 |
return None |
| 160 |
|
| 161 |
stream.get() |
| 162 |
content = quote |
| 163 |
while not stream.is_end(): |
| 164 |
char = stream.get() |
| 165 |
content += char |
| 166 |
if char == quote: |
| 167 |
break |
| 168 |
|
| 169 |
return content |
| 170 |
|
| 171 |
|
| 172 |
def parse_metavar(stream): |
| 173 |
'''Read and return a metavar. |
| 174 |
|
| 175 |
Everything until a tab, space or newline is considered a metavar. |
| 176 |
|
| 177 |
Special cases: |
| 178 |
- Bracketed expressions (e.g., '<foo bar>') and quoted strings (e.g., '"foo bar"') |
| 179 |
are handled, and the spaces within them are preserved. |
| 180 |
- The function supports metavars enclosed by `<`, `[`, `(`, `{`, as well as |
| 181 |
single (`'`) and double (`"`) quotes. |
| 182 |
|
| 183 |
Metavars are: |
| 184 |
foo_bar |
| 185 |
'foo bar' |
| 186 |
"foo bar" |
| 187 |
<foo bar> |
| 188 |
''' |
| 189 |
metavar = '' |
| 190 |
|
| 191 |
while not stream.is_end() and stream.peek() not in (' ', '\t', '\n'): |
| 192 |
if stream.peek() in ('<', '[', '(', '{'): |
| 193 |
metavar += parse_bracket(stream) |
| 194 |
elif stream.peek() in ('"', "'"): |
| 195 |
metavar += parse_quoted_string(stream) |
| 196 |
elif stream.peek() in OPTION_DELIMITER_CHARS: |
| 197 |
break |
| 198 |
else: |
| 199 |
metavar += stream.get() |
| 200 |
|
| 201 |
return metavar |
| 202 |
|
| 203 |
|
| 204 |
def parse_trailing_description_line(stream): |
| 205 |
'''Reads and returns a trailing description line. |
| 206 |
|
| 207 |
A line is considered a trailing description line if it meets the following criteria: |
| 208 |
- It starts with whitespace (indicating continuation from a previous line). |
| 209 |
- It does not begin with a hyphen ('-'), which would indicate the start of a new option. |
| 210 |
''' |
| 211 |
p = stream.copy() |
| 212 |
|
| 213 |
if not p.is_space(): |
| 214 |
return None |
| 215 |
|
| 216 |
space = eat_space(p) |
| 217 |
|
| 218 |
if p.peek() == '-' and len(space) < 10: |
| 219 |
return None |
| 220 |
|
| 221 |
content = eat_line(p) |
| 222 |
stream.pos = p.pos |
| 223 |
return content |
| 224 |
|
| 225 |
|
| 226 |
def parse_description(stream): |
| 227 |
'''Reads and returns the description of an option.''' |
| 228 |
eat_space(stream) |
| 229 |
content = eat_line(stream) |
| 230 |
while True: |
| 231 |
line = parse_trailing_description_line(stream) |
| 232 |
if line: |
| 233 |
content += line |
| 234 |
else: |
| 235 |
break |
| 236 |
|
| 237 |
return content |
| 238 |
|
| 239 |
|
| 240 |
def parse_option_with_metavar(stream): |
| 241 |
'''Read and return an option with its metavar (if any). |
| 242 |
|
| 243 |
Valid inputs are: |
| 244 |
--option=METAVAR |
| 245 |
--option[=METAVAR] (in this case, 'optional' is set to True) |
| 246 |
--option METAVAR |
| 247 |
|
| 248 |
Invalid inputs are: |
| 249 |
--option METAVAR (notice two spaces) |
| 250 |
''' |
| 251 |
opt = parse_option_string(stream) |
| 252 |
metavar = None |
| 253 |
optional = False |
| 254 |
|
| 255 |
if opt: |
| 256 |
if stream.peek_str(2) == '[=': |
| 257 |
optional = True |
| 258 |
metavar = parse_metavar(stream) |
| 259 |
|
| 260 |
elif stream.peek() == '=': |
| 261 |
stream.get() |
| 262 |
metavar = parse_metavar(stream) |
| 263 |
|
| 264 |
# Two spaces after --option means the description follows |
| 265 |
elif stream.peek_str(2).isspace(): |
| 266 |
return OptionWithMetavar(opt, metavar, optional) |
| 267 |
|
| 268 |
# An option delimiter cannot be a metavar |
| 269 |
elif parse_option_delimiter(stream.copy()): |
| 270 |
return OptionWithMetavar(opt, metavar, optional) |
| 271 |
|
| 272 |
elif not stream.is_end() and stream.is_space(): |
| 273 |
stream.get() |
| 274 |
return OptionWithMetavar(opt, parse_metavar(stream), optional) |
| 275 |
|
| 276 |
return OptionWithMetavar(opt, metavar, optional) |
| 277 |
|
| 278 |
return None |
| 279 |
|
| 280 |
|
| 281 |
def parse_option_delimiter(stream): |
| 282 |
'''Parse an option delimiter and return True if it was found, False otherwise.''' |
| 283 |
p = stream.copy() |
| 284 |
eat_space(p) |
| 285 |
if p.get() in (',', '|'): |
| 286 |
stream.pos = p.pos |
| 287 |
return True |
| 288 |
return False |
| 289 |
|
| 290 |
|
| 291 |
def parse_options_with_description(stream): |
| 292 |
'''Parse options with description.''' |
| 293 |
options = [] |
| 294 |
description = None |
| 295 |
|
| 296 |
while not stream.is_end(): |
| 297 |
option = parse_option_with_metavar(stream) |
| 298 |
if option: |
| 299 |
options.append(option) |
| 300 |
else: |
| 301 |
break |
| 302 |
|
| 303 |
if not parse_option_delimiter(stream): |
| 304 |
break |
| 305 |
|
| 306 |
if not options: |
| 307 |
return None |
| 308 |
|
| 309 |
# if s.peek() == '\n' or s.peek_str(2) in (' ', ' \n'): |
| 310 |
if stream.peek() in (' ', '\t', '\n'): |
| 311 |
description = parse_description(stream) |
| 312 |
|
| 313 |
return OptionsWithDescription(options, description) |
| 314 |
|
| 315 |
|
| 316 |
def parse(stream): |
| 317 |
"""Parses the stream and returns a list of options with descriptions or unparsed lines.""" |
| 318 |
r = [] |
| 319 |
|
| 320 |
while not stream.is_end(): |
| 321 |
options = parse_options_with_description(stream) |
| 322 |
if options: |
| 323 |
r.append(options) |
| 324 |
else: |
| 325 |
line = eat_line(stream) |
| 326 |
r.append(Unparsed(line)) |
| 327 |
|
| 328 |
return r |
| 329 |
|
| 330 |
|
| 331 |
def get_program_name_from_help(string): |
| 332 |
"""Extracts the program name from the help string.""" |
| 333 |
m = re.match('usage:[\n\t ]+([^\n\t ]+)', string, re.I) |
| 334 |
if m: |
| 335 |
return m[1] |
| 336 |
return string.split()[0] |