| 1 |
# SPDX-License-Identifier: GPL-3.0-or-later |
| 2 |
# Copyright (C) 2025-2026 Benjamin Abendroth <[email protected]> |
| 3 |
|
| 4 |
'''This module contains the CommandLine, Option and Positional classes.''' |
| 5 |
|
| 6 |
from collections import OrderedDict |
| 7 |
from types import NoneType |
| 8 |
|
| 9 |
from .type_utils import validate_type |
| 10 |
from .errors import CrazyError, CrazyTypeError |
| 11 |
from .str_utils import ( |
| 12 |
contains_space, is_valid_option_string, |
| 13 |
is_valid_variable_name, is_empty_or_whitespace |
| 14 |
) |
| 15 |
|
| 16 |
# pylint: disable=redefined-builtin |
| 17 |
# pylint: disable=too-few-public-methods |
| 18 |
# pylint: disable=too-many-instance-attributes |
| 19 |
# pylint: disable=too-many-arguments |
| 20 |
# pylint: disable=too-many-positional-arguments |
| 21 |
|
| 22 |
|
| 23 |
# Used for inheriting options |
| 24 |
INHERIT = 'INHERIT' |
| 25 |
|
| 26 |
|
| 27 |
def is_extended_bool(obj): |
| 28 |
'''Check if `obj` is a bool or `INHERIT`''' |
| 29 |
|
| 30 |
return obj in (True, False, INHERIT) |
| 31 |
|
| 32 |
|
| 33 |
class CommandLine: |
| 34 |
'''Represents a command line with options, positionals, and subcommands.''' |
| 35 |
|
| 36 |
def __init__(self, |
| 37 |
prog, |
| 38 |
parent=None, |
| 39 |
help=None, |
| 40 |
aliases=None, |
| 41 |
wraps=None, |
| 42 |
abbreviate_commands=INHERIT, |
| 43 |
abbreviate_options=INHERIT, |
| 44 |
inherit_options=INHERIT): |
| 45 |
'''Initializes a CommandLine object with the specified parameters. |
| 46 |
|
| 47 |
Args: |
| 48 |
prog (str): |
| 49 |
The name of the program (or subcommand). |
| 50 |
|
| 51 |
help (str): |
| 52 |
The help message for the program (or subcommand). |
| 53 |
|
| 54 |
parent (CommandLine or None): |
| 55 |
The parent command line object, if any. |
| 56 |
|
| 57 |
aliases (list of str or None): |
| 58 |
Aliases for this command. |
| 59 |
|
| 60 |
wraps (str or None): |
| 61 |
Specify the command to inherit options from. |
| 62 |
|
| 63 |
abbreviate_commands (ExtendedBool): |
| 64 |
Specifies if commands can be abbreviated. |
| 65 |
|
| 66 |
abbreviate_options (ExtendedBool): |
| 67 |
Specifies if options can be abbreviated. |
| 68 |
|
| 69 |
inherit_options (ExtendedBool): |
| 70 |
Specifies if options are visible to subcommands. |
| 71 |
''' |
| 72 |
if aliases is None: |
| 73 |
aliases = [] |
| 74 |
|
| 75 |
validate_type(prog, (str,), 'prog') |
| 76 |
validate_type(parent, (CommandLine, NoneType), 'parent') |
| 77 |
validate_type(help, (str, NoneType), 'help') |
| 78 |
validate_type(aliases, (list,), 'aliases') |
| 79 |
validate_type(wraps, (str, NoneType), 'wraps') |
| 80 |
|
| 81 |
if wraps is not None: |
| 82 |
if is_empty_or_whitespace(wraps): |
| 83 |
raise CrazyError('wraps is empty') |
| 84 |
|
| 85 |
if contains_space(wraps): |
| 86 |
raise CrazyError('wraps: cannot contain space') |
| 87 |
|
| 88 |
for index, alias in enumerate(aliases): |
| 89 |
if not isinstance(alias, str): |
| 90 |
raise CrazyTypeError(f'aliases[{index}]', 'str', alias) |
| 91 |
|
| 92 |
if contains_space(alias): |
| 93 |
raise CrazyError(f'aliases[{index}]: cannot contain space') |
| 94 |
|
| 95 |
if not is_extended_bool(abbreviate_commands): |
| 96 |
raise CrazyTypeError('abbreviate_commands', 'ExtendedBool', abbreviate_commands) |
| 97 |
|
| 98 |
if not is_extended_bool(abbreviate_options): |
| 99 |
raise CrazyTypeError('abbreviate_options', 'ExtendedBool', abbreviate_options) |
| 100 |
|
| 101 |
if not is_extended_bool(inherit_options): |
| 102 |
raise CrazyTypeError('inherit_options', 'ExtendedBool', inherit_options) |
| 103 |
|
| 104 |
self.prog = prog |
| 105 |
self.parent = parent |
| 106 |
self.help = help |
| 107 |
self.aliases = aliases |
| 108 |
self.wraps = wraps |
| 109 |
self.abbreviate_commands = abbreviate_commands |
| 110 |
self.abbreviate_options = abbreviate_options |
| 111 |
self.inherit_options = inherit_options |
| 112 |
self.options = [] |
| 113 |
self.positionals = [] |
| 114 |
self.subcommands = None |
| 115 |
|
| 116 |
def add_option(self, option_strings, **parameters): |
| 117 |
'''Adds a new option to the command line. |
| 118 |
|
| 119 |
For a list of valid parameters, see `class Option`. |
| 120 |
|
| 121 |
Returns: |
| 122 |
Option: The newly added Option object. |
| 123 |
''' |
| 124 |
|
| 125 |
o = Option(self, option_strings, **parameters) |
| 126 |
self.options.append(o) |
| 127 |
return o |
| 128 |
|
| 129 |
def add_positional(self, number, **parameters): |
| 130 |
'''Adds a new positional argument to the command line. |
| 131 |
|
| 132 |
For a list of valid parameters, see `class Positional`. |
| 133 |
|
| 134 |
Returns: |
| 135 |
Positional: The newly added Positional object. |
| 136 |
''' |
| 137 |
|
| 138 |
p = Positional(self, number, **parameters) |
| 139 |
self.positionals.append(p) |
| 140 |
return p |
| 141 |
|
| 142 |
def add_mutually_exclusive_group(self, group): |
| 143 |
'''Adds a new mutually exclusive group. |
| 144 |
|
| 145 |
Returns: |
| 146 |
MutuallyExclusiveGroup: The newly created mutually exclusive group. |
| 147 |
''' |
| 148 |
|
| 149 |
return MutuallyExclusiveGroup(self, group) |
| 150 |
|
| 151 |
def add_subcommands(self): |
| 152 |
'''Adds a subcommands option to the command line. |
| 153 |
|
| 154 |
Returns: |
| 155 |
SubCommandsOption: The newly created subcommands option. |
| 156 |
|
| 157 |
Raises: |
| 158 |
CrazyError: If the command line object already has subcommands. |
| 159 |
''' |
| 160 |
|
| 161 |
if self.subcommands: |
| 162 |
raise CrazyError('CommandLine object already has subcommands') |
| 163 |
|
| 164 |
self.subcommands = SubCommandsOption(self) |
| 165 |
return self.subcommands |
| 166 |
|
| 167 |
class OptionsGetter: |
| 168 |
'''A class for getting options from a CommandLine object.''' |
| 169 |
|
| 170 |
def __init__(self, commandline, with_parent_options=False, only_with_arguments=False): |
| 171 |
self.options = OrderedDict() |
| 172 |
|
| 173 |
if with_parent_options: |
| 174 |
commandlines = commandline.get_parents(include_self=True) |
| 175 |
else: |
| 176 |
commandlines = [commandline] |
| 177 |
|
| 178 |
for cmdline in reversed(commandlines): |
| 179 |
for option in cmdline.options: |
| 180 |
if not only_with_arguments or option.complete: |
| 181 |
self._add(option, cmdline) |
| 182 |
|
| 183 |
def _add(self, option, commandline): |
| 184 |
key = option.get_option_strings_key() |
| 185 |
|
| 186 |
if key not in self.options: |
| 187 |
self.options[key] = (commandline, []) |
| 188 |
|
| 189 |
if self.options[key][0] == commandline: |
| 190 |
self.options[key][1].append(option) |
| 191 |
|
| 192 |
def get(self): |
| 193 |
'''Return the result.''' |
| 194 |
r = [] |
| 195 |
for _, options in self.options.values(): |
| 196 |
for option in options: |
| 197 |
r.append(option) |
| 198 |
return r |
| 199 |
|
| 200 |
def get_options(self, with_parent_options=False, only_with_arguments=False): |
| 201 |
'''Gets a list of options associated with the command line. |
| 202 |
|
| 203 |
Args: |
| 204 |
with_parent_options (bool): |
| 205 |
If True, include options from parent command lines. |
| 206 |
|
| 207 |
only_with_arguments (bool): |
| 208 |
If True, include only options that take arguments. |
| 209 |
|
| 210 |
Returns: |
| 211 |
list: A list of Option objects |
| 212 |
''' |
| 213 |
|
| 214 |
assert isinstance(with_parent_options, bool) |
| 215 |
assert isinstance(only_with_arguments, bool) |
| 216 |
|
| 217 |
getter = CommandLine.OptionsGetter( |
| 218 |
self, |
| 219 |
with_parent_options=with_parent_options, |
| 220 |
only_with_arguments=only_with_arguments) |
| 221 |
|
| 222 |
return getter.get() |
| 223 |
|
| 224 |
def get_option_strings(self, with_parent_options=False, only_with_arguments=False): |
| 225 |
'''Gets a list of option strings associated with the command line. |
| 226 |
|
| 227 |
Args: |
| 228 |
with_parent_options (bool): |
| 229 |
If True, include options from parent command lines. |
| 230 |
|
| 231 |
only_with_arguments (bool): |
| 232 |
If True, include only options that take arguments. |
| 233 |
|
| 234 |
Returns: |
| 235 |
list: A list of option strings |
| 236 |
''' |
| 237 |
|
| 238 |
assert isinstance(with_parent_options, bool) |
| 239 |
assert isinstance(only_with_arguments, bool) |
| 240 |
|
| 241 |
option_strings = [] |
| 242 |
|
| 243 |
options = self.get_options( |
| 244 |
with_parent_options=with_parent_options, |
| 245 |
only_with_arguments=only_with_arguments) |
| 246 |
|
| 247 |
for o in options: |
| 248 |
option_strings.extend(o.option_strings) |
| 249 |
|
| 250 |
return option_strings |
| 251 |
|
| 252 |
def get_final_options(self): |
| 253 |
'''Gets a list of all final options.''' |
| 254 |
|
| 255 |
r = [] |
| 256 |
cmdline = self |
| 257 |
|
| 258 |
while cmdline: |
| 259 |
for option in cmdline.options: |
| 260 |
if option.final: |
| 261 |
r.append(option) |
| 262 |
cmdline = cmdline.parent |
| 263 |
|
| 264 |
return r |
| 265 |
|
| 266 |
def get_final_option_strings(self): |
| 267 |
'''Gets a list of all final option strings.''' |
| 268 |
|
| 269 |
r = [] |
| 270 |
for option in self.get_final_options(): |
| 271 |
r.extend(option.option_strings) |
| 272 |
return r |
| 273 |
|
| 274 |
def get_positionals(self): |
| 275 |
'''Gets a list of positional arguments associated with the command line. |
| 276 |
|
| 277 |
Note: |
| 278 |
SubCommandsOption objects are not considered positional arguments |
| 279 |
and are not included in the list. |
| 280 |
|
| 281 |
Returns: |
| 282 |
list: A list of positional arguments |
| 283 |
''' |
| 284 |
|
| 285 |
return list(self.positionals) |
| 286 |
|
| 287 |
def get_subcommands(self): |
| 288 |
'''Gets the subcommands of the command line. |
| 289 |
|
| 290 |
Returns: |
| 291 |
SubCommandsOption or None: |
| 292 |
The subcommands option if it exists, otherwise None. |
| 293 |
''' |
| 294 |
|
| 295 |
return self.subcommands |
| 296 |
|
| 297 |
def get_parents(self, include_self=False): |
| 298 |
'''Gets a list of parent CommandLine objects. |
| 299 |
|
| 300 |
Args: |
| 301 |
include_self (bool): |
| 302 |
If True, includes the current CommandLine object in the list. |
| 303 |
|
| 304 |
Returns: |
| 305 |
list: A list of parent CommandLine objects. |
| 306 |
''' |
| 307 |
|
| 308 |
assert isinstance(include_self, bool) |
| 309 |
|
| 310 |
parents = [] |
| 311 |
|
| 312 |
parent = self.parent |
| 313 |
while parent: |
| 314 |
parents.insert(0, parent) |
| 315 |
parent = parent.parent |
| 316 |
|
| 317 |
if include_self: |
| 318 |
parents.append(self) |
| 319 |
|
| 320 |
return parents |
| 321 |
|
| 322 |
def get_root_commandline(self): |
| 323 |
'''Return the root commandline.''' |
| 324 |
|
| 325 |
if not self.parent: |
| 326 |
return self |
| 327 |
|
| 328 |
return self.parent.get_root_commandline() |
| 329 |
|
| 330 |
def get_options_by_option_strings(self, option_strings): |
| 331 |
'''Return all options containing one option_strings.''' |
| 332 |
|
| 333 |
result = [] |
| 334 |
|
| 335 |
for option_string in option_strings: |
| 336 |
found = False |
| 337 |
for option in self.options: |
| 338 |
if option_string in option.option_strings: |
| 339 |
if option not in result: |
| 340 |
result.append(option) |
| 341 |
found = True |
| 342 |
break |
| 343 |
if not found: |
| 344 |
raise CrazyError('Option %r not found' % option_string) |
| 345 |
|
| 346 |
return result |
| 347 |
|
| 348 |
def get_highest_positional_num(self): |
| 349 |
'''Get the highest positional number.''' |
| 350 |
|
| 351 |
highest = 0 |
| 352 |
for positional in self.positionals: |
| 353 |
highest = max(highest, positional.number) |
| 354 |
if self.subcommands: |
| 355 |
highest += 1 |
| 356 |
return highest |
| 357 |
|
| 358 |
def get_program_name(self): |
| 359 |
'''Return the program name.''' |
| 360 |
|
| 361 |
commandlines = self.get_parents(include_self=True) |
| 362 |
return commandlines[0].prog |
| 363 |
|
| 364 |
def get_command_path(self, progname=None): |
| 365 |
'''Return the full command path.''' |
| 366 |
prognames = [c.prog for c in self.get_parents(include_self=True)] |
| 367 |
|
| 368 |
if progname is not None: |
| 369 |
prognames[0] = progname |
| 370 |
|
| 371 |
return ' '.join(prognames) |
| 372 |
|
| 373 |
def visit_commandlines(self, callback): |
| 374 |
'''Apply a callback to all CommandLine objects.''' |
| 375 |
|
| 376 |
callback(self) |
| 377 |
if self.get_subcommands(): |
| 378 |
for sub in self.get_subcommands().subcommands: |
| 379 |
sub.visit_commandlines(callback) |
| 380 |
|
| 381 |
def get_all_commandlines(self): |
| 382 |
'''Get a list of all defined commandlines.''' |
| 383 |
|
| 384 |
result = [] |
| 385 |
self.visit_commandlines(result.append) |
| 386 |
return result |
| 387 |
|
| 388 |
def copy(self): |
| 389 |
'''Make a deep copy of the current CommandLine object.''' |
| 390 |
|
| 391 |
copy = CommandLine( |
| 392 |
self.prog, |
| 393 |
parent = None, |
| 394 |
help = self.help, |
| 395 |
aliases = self.aliases, |
| 396 |
wraps = self.wraps, |
| 397 |
abbreviate_commands = self.abbreviate_commands, |
| 398 |
abbreviate_options = self.abbreviate_options, |
| 399 |
inherit_options = self.inherit_options) |
| 400 |
|
| 401 |
for option in self.options: |
| 402 |
copy.add_option( |
| 403 |
option.option_strings, |
| 404 |
metavar = option.metavar, |
| 405 |
help = option.help, |
| 406 |
complete = option.complete, |
| 407 |
nosort = option.nosort, |
| 408 |
optional_arg = option.optional_arg, |
| 409 |
groups = option.groups, |
| 410 |
repeatable = option.repeatable, |
| 411 |
final = option.final, |
| 412 |
hidden = option.hidden, |
| 413 |
when = option.when, |
| 414 |
capture = option.capture, |
| 415 |
long_opt_arg_sep = option.long_opt_arg_sep |
| 416 |
) |
| 417 |
|
| 418 |
for positional in self.positionals: |
| 419 |
copy.add_positional( |
| 420 |
positional.number, |
| 421 |
metavar = positional.metavar, |
| 422 |
help = positional.help, |
| 423 |
repeatable = positional.repeatable, |
| 424 |
nosort = positional.nosort, |
| 425 |
complete = positional.complete, |
| 426 |
when = positional.when, |
| 427 |
capture = positional.capture |
| 428 |
) |
| 429 |
|
| 430 |
if self.subcommands is not None: |
| 431 |
subcommands_option = copy.add_subcommands() |
| 432 |
for subparser in self.subcommands.subcommands: |
| 433 |
subcommands_option.add_commandline_object(subparser.copy()) |
| 434 |
|
| 435 |
return copy |
| 436 |
|
| 437 |
def __eq__(self, other): |
| 438 |
return ( |
| 439 |
isinstance(other, CommandLine) and |
| 440 |
self.prog == other.prog and |
| 441 |
self.aliases == other.aliases and |
| 442 |
self.help == other.help and |
| 443 |
self.wraps == other.wraps and |
| 444 |
self.abbreviate_commands == other.abbreviate_commands and |
| 445 |
self.abbreviate_options == other.abbreviate_options and |
| 446 |
self.inherit_options == other.inherit_options and |
| 447 |
self.options == other.options and |
| 448 |
self.positionals == other.positionals and |
| 449 |
self.subcommands == other.subcommands |
| 450 |
) |
| 451 |
|
| 452 |
def __repr__(self): |
| 453 |
r = '{' |
| 454 |
r += f'\nprog: {self.prog!r},' |
| 455 |
r += f'\naliases: {self.aliases!r},' |
| 456 |
r += f'\nwraps: {self.wraps!r},' |
| 457 |
r += f'\nhelp: {self.help!r},' |
| 458 |
r += f'\nabbreviate_commands: {self.abbreviate_commands!r},' |
| 459 |
r += f'\nabbreviate_options: {self.abbreviate_options!r},' |
| 460 |
r += f'\ninherit_options: {self.inherit_options!r},' |
| 461 |
r += f'\noptions: {self.options!r},' |
| 462 |
r += f'\npositionals: {self.positionals!r},' |
| 463 |
r += f'\nsubcommands: {self.subcommands!r},' |
| 464 |
r += '\n}' |
| 465 |
return r |
| 466 |
|
| 467 |
|
| 468 |
class Positional: |
| 469 |
'''Class representing a command line positional.''' |
| 470 |
|
| 471 |
def __init__( |
| 472 |
self, |
| 473 |
parent, |
| 474 |
number, |
| 475 |
metavar=None, |
| 476 |
help=None, |
| 477 |
complete=None, |
| 478 |
nosort=False, |
| 479 |
repeatable=False, |
| 480 |
when=None, |
| 481 |
capture=None): |
| 482 |
'''Initializes a Positional object with the specified parameters. |
| 483 |
|
| 484 |
Args: |
| 485 |
parent (CommandLine): |
| 486 |
The parent command line object, if any. |
| 487 |
|
| 488 |
number (int): |
| 489 |
The number of the positional argument (starting from 1) |
| 490 |
|
| 491 |
metavar (str): |
| 492 |
The metavar for the positional. |
| 493 |
|
| 494 |
help (str): |
| 495 |
The help message for the positional. |
| 496 |
|
| 497 |
repeatable (bool): |
| 498 |
Specifies if positional can be specified more times |
| 499 |
|
| 500 |
complete (list): |
| 501 |
The completion specification for the positional. |
| 502 |
|
| 503 |
nosort (bool): |
| 504 |
Do not sort the completion suggestions. |
| 505 |
|
| 506 |
when (str): |
| 507 |
Specifies a condition for showing this positional. |
| 508 |
|
| 509 |
capture (str): |
| 510 |
Specifies the variable name for capturing |
| 511 |
''' |
| 512 |
|
| 513 |
validate_type(parent, (CommandLine, NoneType), 'parent') |
| 514 |
validate_type(number, (int,), 'number') |
| 515 |
validate_type(metavar, (str, NoneType), 'metavar') |
| 516 |
validate_type(help, (str, NoneType), 'help') |
| 517 |
validate_type(complete, (list, tuple, NoneType), 'complete') |
| 518 |
validate_type(repeatable, (bool,), 'repeatable') |
| 519 |
validate_type(nosort, (bool,), 'nosort') |
| 520 |
validate_type(when, (str, NoneType), 'when') |
| 521 |
validate_type(capture, (str, NoneType), 'capture') |
| 522 |
|
| 523 |
if capture is not None and not is_valid_variable_name(capture): |
| 524 |
raise CrazyError(f"Invalid variable name: {capture!r}") |
| 525 |
|
| 526 |
if number <= 0: |
| 527 |
raise CrazyError(f'number: value ({number}) is invalid, number has to be >= 1') |
| 528 |
|
| 529 |
self.parent = parent |
| 530 |
self.number = number |
| 531 |
self.metavar = metavar |
| 532 |
self.help = help |
| 533 |
self.repeatable = repeatable |
| 534 |
self.complete = complete if complete else ['none'] |
| 535 |
self.nosort = nosort |
| 536 |
self.when = when |
| 537 |
self.capture = capture |
| 538 |
|
| 539 |
def get_positional_index(self): |
| 540 |
'''Returns the index of the current positional argument within the |
| 541 |
current commandline, including parent commandlines. |
| 542 |
|
| 543 |
Returns: |
| 544 |
int: The index of the positional argument. |
| 545 |
''' |
| 546 |
|
| 547 |
positional_no = self.number - 1 |
| 548 |
|
| 549 |
for commandline in self.parent.get_parents(): |
| 550 |
highest = 0 |
| 551 |
for positional in commandline.get_positionals(): |
| 552 |
highest = max(highest, positional.number) |
| 553 |
positional_no += highest |
| 554 |
|
| 555 |
if commandline.get_subcommands(): |
| 556 |
positional_no += 1 |
| 557 |
|
| 558 |
return positional_no |
| 559 |
|
| 560 |
def get_positional_num(self): |
| 561 |
'''Returns the number of the current positional argument within the |
| 562 |
current commandline, including parent commandlines. |
| 563 |
|
| 564 |
Note: |
| 565 |
This is the same as `CommandLine.get_positional_index() + 1`. |
| 566 |
|
| 567 |
Returns: |
| 568 |
int: The number of the positional argument. |
| 569 |
''' |
| 570 |
|
| 571 |
return self.get_positional_index() + 1 |
| 572 |
|
| 573 |
def __eq__(self, other): |
| 574 |
return ( |
| 575 |
isinstance(other, Positional) and |
| 576 |
self.number == other.number and |
| 577 |
self.metavar == other.metavar and |
| 578 |
self.help == other.help and |
| 579 |
self.repeatable == other.repeatable and |
| 580 |
self.complete == other.complete and |
| 581 |
self.nosort == other.nosort and |
| 582 |
self.when == other.when and |
| 583 |
self.capture == other.capture |
| 584 |
) |
| 585 |
|
| 586 |
|
| 587 |
def is_short_option_string(string): |
| 588 |
'''Return True if string is a short option string.''' |
| 589 |
return len(string) == 2 |
| 590 |
|
| 591 |
|
| 592 |
def is_long_option_string(string): |
| 593 |
'''Return True if string is a long option string.''' |
| 594 |
return string.startswith('--') |
| 595 |
|
| 596 |
|
| 597 |
def is_old_option_string(string): |
| 598 |
'''Return True if string is an old option string.''' |
| 599 |
return not string.startswith('--') and len(string) > 2 |
| 600 |
|
| 601 |
|
| 602 |
class Option: |
| 603 |
'''Class representing a command line option.''' |
| 604 |
|
| 605 |
# pylint: disable=too-many-locals |
| 606 |
|
| 607 |
def __init__( |
| 608 |
self, |
| 609 |
parent, |
| 610 |
option_strings, |
| 611 |
metavar=None, |
| 612 |
help=None, |
| 613 |
complete=None, |
| 614 |
nosort=False, |
| 615 |
groups=None, |
| 616 |
optional_arg=False, |
| 617 |
repeatable=INHERIT, |
| 618 |
final=False, |
| 619 |
hidden=False, |
| 620 |
when=None, |
| 621 |
capture=None, |
| 622 |
long_opt_arg_sep=INHERIT): |
| 623 |
'''Initializes an Option object with the specified parameters. |
| 624 |
|
| 625 |
Args: |
| 626 |
parent (CommandLine): |
| 627 |
The parent command line object, if any. |
| 628 |
|
| 629 |
option_strings (list of str): |
| 630 |
The list of option strings. |
| 631 |
|
| 632 |
metavar (str): |
| 633 |
The metavar for the option. |
| 634 |
|
| 635 |
help (str): |
| 636 |
The help message for the option. |
| 637 |
|
| 638 |
complete (tuple): |
| 639 |
The completion specification for the option. |
| 640 |
|
| 641 |
nosort (bool): |
| 642 |
Do not sort the completion suggestions. |
| 643 |
|
| 644 |
optional_arg (bool): |
| 645 |
Specifies if option's argument is optional. |
| 646 |
|
| 647 |
groups (list of str): |
| 648 |
Specify to which mutually exclusive groups this option |
| 649 |
belongs to. |
| 650 |
|
| 651 |
repeatable (ExtendedBool): |
| 652 |
Specifies if the option can be repeated. |
| 653 |
|
| 654 |
final (bool): |
| 655 |
If True, no more options are suggested after this one. |
| 656 |
|
| 657 |
hidden (bool): |
| 658 |
Specifies if this option is hidden. |
| 659 |
|
| 660 |
when (str): |
| 661 |
Specifies a condition for showing this option. |
| 662 |
|
| 663 |
capture (str): |
| 664 |
Specifies the variable name for capturing |
| 665 |
|
| 666 |
long_opt_arg_sep (str): |
| 667 |
Specifies which separators are used for delimiting a long |
| 668 |
option from its argument. |
| 669 |
|
| 670 |
If `space`, only the form `--option argument` is allowed. |
| 671 |
If `equals`, only the form `--option=argument` is allowed. |
| 672 |
If `both`, both forms are allowed. |
| 673 |
If `INHERIT`, the default setting from the config object is |
| 674 |
used. |
| 675 |
|
| 676 |
Returns: |
| 677 |
Option: The newly added Option object. |
| 678 |
''' |
| 679 |
|
| 680 |
validate_type(parent, (CommandLine, NoneType), 'parent') |
| 681 |
validate_type(option_strings, (list,), 'option_strings') |
| 682 |
validate_type(metavar, (str, NoneType), 'metavar') |
| 683 |
validate_type(help, (str, NoneType), 'help') |
| 684 |
validate_type(complete, (list, tuple, NoneType), 'complete') |
| 685 |
validate_type(groups, (list, NoneType), 'groups') |
| 686 |
|
| 687 |
if groups is not None: |
| 688 |
for index, group in enumerate(groups): |
| 689 |
if not isinstance(group, str): |
| 690 |
raise CrazyTypeError(f'groups[{index}]', 'str', group) |
| 691 |
|
| 692 |
validate_type(optional_arg, (bool,), 'optional_arg') |
| 693 |
|
| 694 |
if not is_extended_bool(repeatable): |
| 695 |
raise CrazyTypeError('repeatable', 'ExtendedBool', repeatable) |
| 696 |
|
| 697 |
validate_type(final, (bool,), 'final') |
| 698 |
validate_type(hidden, (bool,), 'hidden') |
| 699 |
validate_type(nosort, (bool,), 'nosort') |
| 700 |
validate_type(when, (str, NoneType), 'when') |
| 701 |
validate_type(capture, (str, NoneType), 'capture') |
| 702 |
validate_type(long_opt_arg_sep, (str,), 'long_opt_arg_sep') |
| 703 |
|
| 704 |
if not option_strings: |
| 705 |
raise CrazyError('Empty option strings') |
| 706 |
|
| 707 |
for index, option_string in enumerate(option_strings): |
| 708 |
if not isinstance(option_string, str): |
| 709 |
raise CrazyTypeError(f'option_strings[{index}]', 'str', option_string) |
| 710 |
|
| 711 |
if not is_valid_option_string(option_string): |
| 712 |
raise CrazyError(f"Invalid option string: {option_string!r}") |
| 713 |
|
| 714 |
if capture is not None and not is_valid_variable_name(capture): |
| 715 |
raise CrazyError(f"Invalid variable name: {capture!r}") |
| 716 |
|
| 717 |
if metavar and not complete: |
| 718 |
raise CrazyError(f'Option {option_strings} has metavar set, but has no complete') |
| 719 |
|
| 720 |
if optional_arg and not complete: |
| 721 |
raise CrazyError(f'Option {option_strings} has optional_arg=True, but has no complete') |
| 722 |
|
| 723 |
if hidden is True and repeatable is True: |
| 724 |
raise CrazyError(f'Option {option_strings} has both hidden and repeatable set to True') |
| 725 |
|
| 726 |
if long_opt_arg_sep not in (INHERIT, 'space', 'equals', 'both'): |
| 727 |
raise CrazyError('Invalid value for `long_opt_arg_sep`') |
| 728 |
|
| 729 |
self.parent = parent |
| 730 |
self.option_strings = option_strings |
| 731 |
self.metavar = metavar |
| 732 |
self.help = help |
| 733 |
self.complete = complete |
| 734 |
self.nosort = nosort |
| 735 |
self.groups = groups |
| 736 |
self.optional_arg = optional_arg |
| 737 |
self.repeatable = repeatable |
| 738 |
self.final = final |
| 739 |
self.hidden = hidden |
| 740 |
self.when = when |
| 741 |
self.capture = capture |
| 742 |
self.long_opt_arg_sep = long_opt_arg_sep |
| 743 |
|
| 744 |
def get_option_strings(self): |
| 745 |
'''Returns the option strings associated with the Option object. |
| 746 |
|
| 747 |
Returns: |
| 748 |
list: A list of strings representing the option strings. |
| 749 |
''' |
| 750 |
|
| 751 |
return self.option_strings |
| 752 |
|
| 753 |
def get_option_strings_key(self, delimiter=' '): |
| 754 |
'''Returns a key with consisting of all option strings.''' |
| 755 |
|
| 756 |
return delimiter.join(sorted(self.option_strings)) |
| 757 |
|
| 758 |
def get_short_option_strings(self): |
| 759 |
'''Returns the short option strings associated with the object. |
| 760 |
|
| 761 |
Returns: |
| 762 |
list: A list of short option strings ("-o"). |
| 763 |
''' |
| 764 |
|
| 765 |
return list(filter(is_short_option_string, self.option_strings)) |
| 766 |
|
| 767 |
def get_long_option_strings(self): |
| 768 |
'''Returns the long option strings associated with the object. |
| 769 |
|
| 770 |
Returns: |
| 771 |
list: A list of long option strings ("--option"). |
| 772 |
''' |
| 773 |
|
| 774 |
return list(filter(is_long_option_string, self.option_strings)) |
| 775 |
|
| 776 |
def get_old_option_strings(self): |
| 777 |
'''Returns the old-style option strings associated with the object. |
| 778 |
|
| 779 |
Returns: |
| 780 |
list: A list of old-style option strings ("-option"). |
| 781 |
''' |
| 782 |
|
| 783 |
return list(filter(is_old_option_string, self.option_strings)) |
| 784 |
|
| 785 |
def get_conflicting_options(self): |
| 786 |
'''Returns a list of conflicting options within the same mutually |
| 787 |
exclusive groups. |
| 788 |
|
| 789 |
Returns: |
| 790 |
list: A list of Option objects representing conflicting options. |
| 791 |
''' |
| 792 |
|
| 793 |
if not self.groups: |
| 794 |
return [] |
| 795 |
r = [] |
| 796 |
for group in self.groups: |
| 797 |
for option in self.parent.options: |
| 798 |
if option.groups is not None and group in option.groups: |
| 799 |
if option not in r: |
| 800 |
r.append(option) |
| 801 |
r.remove(self) |
| 802 |
return r |
| 803 |
|
| 804 |
def get_conflicting_option_strings(self): |
| 805 |
'''Returns a list of option strings conflicting with the current option |
| 806 |
within the same mutually exclusive groups. |
| 807 |
|
| 808 |
Returns: |
| 809 |
list: A list of option strings representing conflicting options. |
| 810 |
''' |
| 811 |
|
| 812 |
r = [] |
| 813 |
for option in self.get_conflicting_options(): |
| 814 |
r.extend(option.get_option_strings()) |
| 815 |
return r |
| 816 |
|
| 817 |
def has_required_arg(self): |
| 818 |
'''Return True if the option takes a required argument.''' |
| 819 |
|
| 820 |
return self.complete is not None and self.optional_arg is False |
| 821 |
|
| 822 |
def has_optional_arg(self): |
| 823 |
'''Return True if the option takes an optional argument.''' |
| 824 |
|
| 825 |
return self.complete is not None and self.optional_arg is True |
| 826 |
|
| 827 |
def __eq__(self, other): |
| 828 |
return ( |
| 829 |
isinstance(other, Option) and |
| 830 |
self.option_strings == other.option_strings and |
| 831 |
self.metavar == other.metavar and |
| 832 |
self.help == other.help and |
| 833 |
self.optional_arg == other.optional_arg and |
| 834 |
self.repeatable == other.repeatable and |
| 835 |
self.final == other.final and |
| 836 |
self.hidden == other.hidden and |
| 837 |
self.complete == other.complete and |
| 838 |
self.nosort == other.nosort and |
| 839 |
self.groups == other.groups and |
| 840 |
self.when == other.when and |
| 841 |
self.capture == other.capture |
| 842 |
) |
| 843 |
|
| 844 |
def __repr__(self): |
| 845 |
return '{option_strings: %r, metavar: %r, help: %r}' % ( |
| 846 |
self.option_strings, self.metavar, self.help) |
| 847 |
|
| 848 |
|
| 849 |
class SubCommandsOption(Positional): |
| 850 |
'''Class holding subcommands of a commandline.''' |
| 851 |
|
| 852 |
def __init__(self, parent): |
| 853 |
self.subcommands = [] |
| 854 |
|
| 855 |
super().__init__( |
| 856 |
parent, |
| 857 |
parent.get_highest_positional_num() + 1, |
| 858 |
metavar='command') |
| 859 |
|
| 860 |
def add_commandline_object(self, commandline): |
| 861 |
'''Add an existing commandline object as a subcommand.''' |
| 862 |
|
| 863 |
if self.get_subcommand_by_name(commandline.prog): |
| 864 |
raise CrazyError(f'Duplicate subcommand. {commandline.prog} already defined.') |
| 865 |
|
| 866 |
commandline.parent = self.parent |
| 867 |
self.subcommands.append(commandline) |
| 868 |
|
| 869 |
def add_commandline(self, name, help=''): |
| 870 |
'''Create a new commandline object and add it as a subcommand.''' |
| 871 |
|
| 872 |
if self.get_subcommand_by_name(name): |
| 873 |
raise CrazyError(f'Duplicate subcommand. {name} already defined.') |
| 874 |
|
| 875 |
commandline = CommandLine(name, help=help, parent=self.parent) |
| 876 |
self.subcommands.append(commandline) |
| 877 |
return commandline |
| 878 |
|
| 879 |
def get_choices(self, with_aliases=True): |
| 880 |
'''Return a mapping of command and its description.''' |
| 881 |
|
| 882 |
r = OrderedDict() |
| 883 |
for subcommand in self.subcommands: |
| 884 |
r[subcommand.prog] = subcommand.help |
| 885 |
if with_aliases: |
| 886 |
for alias in subcommand.aliases: |
| 887 |
r[alias] = subcommand.help |
| 888 |
return r |
| 889 |
|
| 890 |
def get_subcommand_by_name(self, name): |
| 891 |
'''Return a subcommand by name or None if not found.''' |
| 892 |
|
| 893 |
for subcommand in self.subcommands: |
| 894 |
if subcommand.prog == name: |
| 895 |
return subcommand |
| 896 |
return None |
| 897 |
|
| 898 |
def __eq__(self, other): |
| 899 |
return ( |
| 900 |
isinstance(other, SubCommandsOption) and |
| 901 |
self.subcommands == other.subcommands and |
| 902 |
self.help == other.help and |
| 903 |
self.metavar == other.metavar and |
| 904 |
self.complete == other.complete |
| 905 |
) |
| 906 |
|
| 907 |
def __repr__(self): |
| 908 |
return '{help: %r, subcommands %r}' % (self.help, self.subcommands) |
| 909 |
|
| 910 |
|
| 911 |
class MutuallyExclusiveGroup: |
| 912 |
'''Helper class for adding mutually exclusive options.''' |
| 913 |
|
| 914 |
def __init__(self, parent, group): |
| 915 |
assert isinstance(parent, CommandLine) |
| 916 |
assert isinstance(group, str) |
| 917 |
|
| 918 |
self.parent = parent |
| 919 |
self.group = group |
| 920 |
|
| 921 |
def add(self, option_strings, **parameters): |
| 922 |
'''Creates and adds a new option. |
| 923 |
|
| 924 |
For a list of valid parameters, see `class Option`. |
| 925 |
''' |
| 926 |
|
| 927 |
if 'groups' in parameters: |
| 928 |
raise CrazyError('Paramter `groups` not allowed') |
| 929 |
|
| 930 |
if 'group' in parameters: |
| 931 |
raise CrazyError('Paramter `group` not allowed') |
| 932 |
|
| 933 |
return self.parent.add_option( |
| 934 |
option_strings, |
| 935 |
groups=[self.group], |
| 936 |
**parameters) |
| 937 |
|
| 938 |
def add_option(self, option): |
| 939 |
'''Adds an option object.''' |
| 940 |
|
| 941 |
option.parent = self.parent |
| 942 |
option.groups = [self.group] |