| 1 |
# SPDX-License-Identifier: GPL-3.0-or-later |
| 2 |
# Copyright (C) 2025-2026 Benjamin Abendroth <[email protected]> |
| 3 |
|
| 4 |
'''Code for validating the structure of a command line definition.''' |
| 5 |
|
| 6 |
from types import NoneType |
| 7 |
|
| 8 |
from .cli import INHERIT, is_extended_bool |
| 9 |
from .when import parse_when |
| 10 |
from .errors import CrazyError, CrazySchemaValidationError |
| 11 |
from .pattern import bash_glob_to_regex, bash_glob_to_zsh_glob |
| 12 |
from .value_with_trace import ValueWithTrace |
| 13 |
from .str_utils import ( |
| 14 |
contains_space, is_empty_or_whitespace, |
| 15 |
is_valid_option_string, is_valid_variable_name, |
| 16 |
is_valid_extended_regex, validate_prog) |
| 17 |
from . import messages as m |
| 18 |
|
| 19 |
|
| 20 |
_error = CrazySchemaValidationError |
| 21 |
|
| 22 |
|
| 23 |
# ============================================================================= |
| 24 |
# Helper functions for validating |
| 25 |
# ============================================================================= |
| 26 |
|
| 27 |
|
| 28 |
class Context: |
| 29 |
'''Class for providing context to validation.''' |
| 30 |
|
| 31 |
# pylint: disable=too-few-public-methods |
| 32 |
|
| 33 |
TYPE_OPTION = 0 |
| 34 |
TYPE_POSITIONAL = 1 |
| 35 |
|
| 36 |
def __init__(self): |
| 37 |
self.definition = None |
| 38 |
self.option = None |
| 39 |
self.positional = None |
| 40 |
self.type = None |
| 41 |
self.trace = None |
| 42 |
|
| 43 |
|
| 44 |
class Arguments: |
| 45 |
'''Class for accessing arguments.''' |
| 46 |
|
| 47 |
def __init__(self, args): |
| 48 |
self.args = args |
| 49 |
self.index = 0 |
| 50 |
|
| 51 |
def get_required_arg(self, name): |
| 52 |
'''Return a required argument, else raise an exception.''' |
| 53 |
|
| 54 |
if self.index < len(self.args.value): |
| 55 |
arg = self.args.value[self.index] |
| 56 |
self.index += 1 |
| 57 |
return arg |
| 58 |
|
| 59 |
raise _error('%s: %s' % (m.missing_arg(), name), self.args) |
| 60 |
|
| 61 |
def get_optional_arg(self, default=None): |
| 62 |
'''Return an optional arg, else return a default.''' |
| 63 |
|
| 64 |
if self.index < len(self.args.value): |
| 65 |
arg = self.args.value[self.index] |
| 66 |
self.index += 1 |
| 67 |
return arg |
| 68 |
|
| 69 |
return ValueWithTrace(default, '<default value>', 1, 1) |
| 70 |
|
| 71 |
def require_no_more(self): |
| 72 |
'''Raise an exception if there are any arguments left.''' |
| 73 |
|
| 74 |
if self.index < len(self.args.value): |
| 75 |
raise _error(m.too_many_arguments(), self.args) |
| 76 |
|
| 77 |
|
| 78 |
def _has_set(dictionary, key): |
| 79 |
return (key in dictionary.value and |
| 80 |
dictionary.value[key].value is not None) |
| 81 |
|
| 82 |
|
| 83 |
def _is_true(dictionary, key): |
| 84 |
return (key in dictionary.value and |
| 85 |
dictionary.value[key].value is True) |
| 86 |
|
| 87 |
|
| 88 |
def _check_type(value, types, parameter_name=None): |
| 89 |
if not isinstance(value.value, types): |
| 90 |
types_strings = [] |
| 91 |
for t in types: |
| 92 |
types_strings.append({ |
| 93 |
str: 'string', |
| 94 |
int: 'integer', |
| 95 |
float: 'float', |
| 96 |
list: 'list', |
| 97 |
dict: 'dictionary', |
| 98 |
bool: 'boolean', |
| 99 |
NoneType: 'none'}[t]) |
| 100 |
types_string = '|'.join(types_strings) |
| 101 |
|
| 102 |
msg = m.invalid_type_expected_types(types_string) |
| 103 |
if parameter_name is not None: |
| 104 |
msg = f'{parameter_name}: {msg}' |
| 105 |
raise _error(msg, value) |
| 106 |
|
| 107 |
|
| 108 |
def _check_dictionary(dictionary, rules): |
| 109 |
_check_type(dictionary, (dict,)) |
| 110 |
|
| 111 |
for key, value in dictionary.value.items(): |
| 112 |
if key.value not in rules: |
| 113 |
raise _error('%s: %s' % (m.unknown_parameter(), key.value), key) |
| 114 |
|
| 115 |
_check_type(value, rules[key.value][1], key.value) |
| 116 |
|
| 117 |
if rules[key.value][2]: |
| 118 |
rules[key.value][2](value, key.value) |
| 119 |
|
| 120 |
for key, rule in rules.items(): |
| 121 |
if rule[0] is True and key not in dictionary.value: |
| 122 |
raise _error('%s: %s' % (m.missing_arg(), key), dictionary) |
| 123 |
|
| 124 |
|
| 125 |
def _check_regex(value, parameter): |
| 126 |
if not is_valid_extended_regex(value.value): |
| 127 |
raise _error('%s: %s' % (parameter, m.not_an_extended_regex()), value) |
| 128 |
|
| 129 |
|
| 130 |
def _check_char(value, parameter): |
| 131 |
if len(value.value) != 1: |
| 132 |
msg = '%s: %s' % (parameter, m.single_character_expected()) |
| 133 |
raise _error(msg, value) |
| 134 |
|
| 135 |
|
| 136 |
def _check_variable_name(value, parameter): |
| 137 |
if not is_valid_variable_name(value.value): |
| 138 |
raise _error('%s: %s' % (parameter, m.not_a_variable_name()), value) |
| 139 |
|
| 140 |
|
| 141 |
def _check_non_empty_string(value, parameter): |
| 142 |
if is_empty_or_whitespace(value.value): |
| 143 |
raise _error('%s: %s' % (parameter, m.string_cannot_be_empty()), value) |
| 144 |
|
| 145 |
|
| 146 |
def _check_no_spaces(value, parameter): |
| 147 |
if contains_space(value.value): |
| 148 |
msg = '%s: %s' % (parameter, m.string_cannot_contain_space()) |
| 149 |
raise _error(msg, value) |
| 150 |
|
| 151 |
|
| 152 |
def _check_non_empty_list(value, parameter): |
| 153 |
if len(value.value) == 0: |
| 154 |
raise _error('%s: %s' % (parameter, m.list_cannot_be_empty()), value) |
| 155 |
|
| 156 |
|
| 157 |
def _check_non_empty_dict(value, parameter): |
| 158 |
if len(value.value) == 0: |
| 159 |
raise _error('%s: %s' % (parameter, m.dict_cannot_be_empty()), value) |
| 160 |
|
| 161 |
|
| 162 |
def _check_extended_bool(value, parameter): |
| 163 |
if not is_extended_bool(value.value): |
| 164 |
expected = 'true, false or `%s`' % INHERIT |
| 165 |
msg = '%s: %s' % (parameter, m.invalid_value_expected_values(expected)) |
| 166 |
raise _error(msg, value) |
| 167 |
|
| 168 |
|
| 169 |
# ============================================================================= |
| 170 |
# Actual validation code |
| 171 |
# ============================================================================= |
| 172 |
|
| 173 |
|
| 174 |
def _check_when(value): |
| 175 |
try: |
| 176 |
parse_when(value.value) |
| 177 |
except CrazyError as e: |
| 178 |
raise _error(f'when: {e}', value) from e |
| 179 |
|
| 180 |
|
| 181 |
def _check_void(_ctxt, arguments): |
| 182 |
arguments.require_no_more() |
| 183 |
|
| 184 |
|
| 185 |
def _check_none(ctxt, arguments): |
| 186 |
arguments.require_no_more() |
| 187 |
|
| 188 |
if ctxt.trace and ctxt.trace[-1] in ('combine', 'list', 'prefix'): |
| 189 |
msg = m.completer_not_allowed_in('none', ctxt.trace[-1]) |
| 190 |
raise _error(msg, arguments.args) |
| 191 |
|
| 192 |
|
| 193 |
def _check_choices(_ctxt, arguments): |
| 194 |
choices = arguments.get_required_arg('values') |
| 195 |
_check_type(choices, (list, dict), 'values') |
| 196 |
arguments.require_no_more() |
| 197 |
|
| 198 |
if isinstance(choices.value, dict): |
| 199 |
for i, (value, desc) in enumerate(choices.value.items()): |
| 200 |
_check_type(value, (str, int), f'values[{i}]: item') |
| 201 |
_check_type(desc, (str, int), f'values[{i}]: description') |
| 202 |
|
| 203 |
elif isinstance(choices.value, list): |
| 204 |
for i, value in enumerate(choices.value): |
| 205 |
_check_type(value, (str, int), f'values[{i}]') |
| 206 |
|
| 207 |
|
| 208 |
def _check_command(_ctxt, arguments): |
| 209 |
opts = arguments.get_optional_arg({}) |
| 210 |
_check_type(opts, (dict,), 'options') |
| 211 |
arguments.require_no_more() |
| 212 |
|
| 213 |
_check_dictionary(opts, { |
| 214 |
'path': (False, (str,), _check_non_empty_string), |
| 215 |
'path_append': (False, (str,), _check_non_empty_string), |
| 216 |
'path_prepend': (False, (str,), _check_non_empty_string), |
| 217 |
}) |
| 218 |
|
| 219 |
path = opts.value.get('path', None) |
| 220 |
append = opts.value.get('path_append', None) |
| 221 |
prepend = opts.value.get('path_prepend', None) |
| 222 |
|
| 223 |
if path and append: |
| 224 |
msg = m.mutually_exclusive_parameters('path, path_append') |
| 225 |
raise _error(msg, opts) |
| 226 |
|
| 227 |
if path and prepend: |
| 228 |
msg = m.mutually_exclusive_parameters('path, path_prepend') |
| 229 |
raise _error(msg, opts) |
| 230 |
|
| 231 |
|
| 232 |
def _check_command_arg(ctxt, arguments): |
| 233 |
arguments.require_no_more() |
| 234 |
|
| 235 |
if ctxt.trace and ctxt.trace[-1] in ('combine', 'list', 'key_value_list', 'key_value_pair'): |
| 236 |
msg = m.completer_not_allowed_in('command_arg', ctxt.trace[-1]) |
| 237 |
raise _error(msg, arguments.args) |
| 238 |
|
| 239 |
if ctxt.type != Context.TYPE_POSITIONAL: |
| 240 |
msg = m.completer_not_allowed_in_option('command_arg') |
| 241 |
raise _error(msg, arguments.args) |
| 242 |
|
| 243 |
if (not _has_set(ctxt.positional, 'repeatable') or |
| 244 |
not ctxt.positional.value['repeatable'].value): |
| 245 |
msg = m.completer_requires_repeatable('command_arg') |
| 246 |
raise _error(msg, ctxt.positional) |
| 247 |
|
| 248 |
def command_is_previous_to_command_arg(positional): |
| 249 |
return ( |
| 250 |
_has_set(positional, 'complete') and |
| 251 |
positional.value['complete'].value[0] == 'command' and |
| 252 |
positional.value['number'].value + 1 == ctxt.positional.value['number'].value |
| 253 |
) |
| 254 |
|
| 255 |
positionals = ctxt.definition.value['positionals'].value |
| 256 |
if not any(filter(command_is_previous_to_command_arg, positionals)): |
| 257 |
msg = m.command_arg_without_command() |
| 258 |
raise _error(msg, ctxt.positional) |
| 259 |
|
| 260 |
|
| 261 |
def _check_filedir(_ctxt, arguments, with_file_opts=False, with_list_opts=False): |
| 262 |
options = arguments.get_optional_arg({}) |
| 263 |
_check_type(options, (dict,), 'options') |
| 264 |
arguments.require_no_more() |
| 265 |
|
| 266 |
spec = {'directory': (False, (str,), _check_non_empty_string)} |
| 267 |
|
| 268 |
if with_file_opts: |
| 269 |
spec['extensions'] = (False, (list,), _check_non_empty_list) |
| 270 |
spec['fuzzy'] = (False, (bool,), None) |
| 271 |
spec['ignore_globs'] = (False, (list,), _check_non_empty_list) |
| 272 |
|
| 273 |
if with_list_opts: |
| 274 |
spec['separator'] = (False, (str,), _check_char) |
| 275 |
spec['duplicates'] = (False, (bool,), None) |
| 276 |
|
| 277 |
_check_dictionary(options, spec) |
| 278 |
|
| 279 |
if _has_set(options, 'extensions'): |
| 280 |
for i, extension in enumerate(options.value['extensions'].value): |
| 281 |
_check_type(extension, (str,), f'extensions[{i}]') |
| 282 |
_check_non_empty_string(extension, f'extensions[{i}]') |
| 283 |
_check_no_spaces(extension, f'extensions[{i}]') |
| 284 |
|
| 285 |
if _has_set(options, 'ignore_globs'): |
| 286 |
for pattern in options.value['ignore_globs'].value: |
| 287 |
_check_type(pattern, (str,), 'pattern') |
| 288 |
_check_non_empty_string(pattern, 'pattern') |
| 289 |
try: |
| 290 |
bash_glob_to_regex(pattern.value) |
| 291 |
bash_glob_to_zsh_glob(pattern.value) |
| 292 |
except ValueError as e: |
| 293 |
raise _error('%s: %s' % ('pattern', e), pattern) from e |
| 294 |
|
| 295 |
|
| 296 |
def _check_file(ctxt, arguments): |
| 297 |
_check_filedir(ctxt, arguments, with_file_opts=True) |
| 298 |
|
| 299 |
|
| 300 |
def _check_directory(ctxt, arguments): |
| 301 |
_check_filedir(ctxt, arguments) |
| 302 |
|
| 303 |
|
| 304 |
def _check_file_list(ctxt, arguments): |
| 305 |
_check_filedir(ctxt, arguments, with_file_opts=True, with_list_opts=True) |
| 306 |
|
| 307 |
|
| 308 |
def _check_directory_list(ctxt, arguments): |
| 309 |
_check_filedir(ctxt, arguments, with_list_opts=True) |
| 310 |
|
| 311 |
|
| 312 |
def _check_mime_file(_ctxt, arguments): |
| 313 |
pattern = arguments.get_required_arg("pattern") |
| 314 |
_check_type(pattern, (str,), "pattern") |
| 315 |
arguments.require_no_more() |
| 316 |
_check_regex(pattern, 'pattern') |
| 317 |
|
| 318 |
|
| 319 |
def _check_range(_ctxt, arguments): |
| 320 |
start = arguments.get_required_arg("start") |
| 321 |
stop = arguments.get_required_arg("stop") |
| 322 |
step = arguments.get_optional_arg(1) |
| 323 |
arguments.require_no_more() |
| 324 |
|
| 325 |
_check_type(start, (int,), "start") |
| 326 |
_check_type(stop, (int,), "stop") |
| 327 |
_check_type(step, (int,), "step") |
| 328 |
|
| 329 |
if step.value == 0: |
| 330 |
msg = '%s: %s' % ('step', m.integer_cannot_be_zero()) |
| 331 |
raise _error(msg, step) |
| 332 |
|
| 333 |
if step.value > 0 and start.value > stop.value: |
| 334 |
msg = f"start > stop: {start.value} > {stop.value} (step={step.value})" |
| 335 |
raise _error(msg, step) |
| 336 |
|
| 337 |
if step.value < 0 and stop.value > start.value: |
| 338 |
msg = f"stop > start: {stop.value} > {start.value} (step={step.value})" |
| 339 |
raise _error(msg, step) |
| 340 |
|
| 341 |
|
| 342 |
def _check_exec(_ctxt, arguments): |
| 343 |
command = arguments.get_required_arg("command") |
| 344 |
_check_type(command, (str,), "command") |
| 345 |
arguments.require_no_more() |
| 346 |
|
| 347 |
|
| 348 |
def _check_key_value_list_exec(_ctxt, arguments): |
| 349 |
pair_separator = arguments.get_required_arg('pair_separator') |
| 350 |
value_separator = arguments.get_required_arg('value_separator') |
| 351 |
command = arguments.get_required_arg('command') |
| 352 |
arguments.require_no_more() |
| 353 |
|
| 354 |
_check_type(pair_separator, (str,), 'pair_separator') |
| 355 |
_check_type(value_separator, (str,), 'value_separator') |
| 356 |
_check_char(pair_separator, 'pair_separator') |
| 357 |
_check_char(value_separator, 'value_separator') |
| 358 |
_check_type(command, (str,), 'command') |
| 359 |
_check_non_empty_string(command, 'command') |
| 360 |
|
| 361 |
|
| 362 |
def _check_key_value_pair_exec(_ctxt, arguments): |
| 363 |
value_separator = arguments.get_required_arg('value_separator') |
| 364 |
command = arguments.get_required_arg('command') |
| 365 |
arguments.require_no_more() |
| 366 |
|
| 367 |
_check_type(value_separator, (str,), 'value_separator') |
| 368 |
_check_char(value_separator, 'value_separator') |
| 369 |
_check_type(command, (str,), 'command') |
| 370 |
_check_non_empty_string(command, 'command') |
| 371 |
|
| 372 |
|
| 373 |
def _check_value_list(_ctxt, arguments): |
| 374 |
options = arguments.get_required_arg('options') |
| 375 |
_check_type(options, (dict,), 'options') |
| 376 |
arguments.require_no_more() |
| 377 |
|
| 378 |
_check_dictionary(options, { |
| 379 |
'values': (True, (list, dict), None), |
| 380 |
'separator': (False, (str,), _check_char), |
| 381 |
'duplicates': (False, (bool,), None), |
| 382 |
}) |
| 383 |
|
| 384 |
values = options.value['values'] |
| 385 |
|
| 386 |
if isinstance(values.value, dict): |
| 387 |
_check_non_empty_dict(values, 'values') |
| 388 |
|
| 389 |
for i, (item, desc) in enumerate(values.value.items()): |
| 390 |
_check_type(item, (str,), f'values[{i}]: item') |
| 391 |
_check_type(desc, (str,), f'values[{i}]: description') |
| 392 |
else: |
| 393 |
_check_non_empty_list(values, 'values') |
| 394 |
|
| 395 |
for i, value in enumerate(values.value): |
| 396 |
_check_type(value, (str,), f'values[{i}]: item') |
| 397 |
|
| 398 |
|
| 399 |
def _check_key_value_list(ctxt, arguments): |
| 400 |
pair_separator = arguments.get_required_arg('pair_separator') |
| 401 |
value_separator = arguments.get_required_arg('value_separator') |
| 402 |
values = arguments.get_required_arg('values') |
| 403 |
condition_func = arguments.get_optional_arg(None) |
| 404 |
arguments.require_no_more() |
| 405 |
|
| 406 |
_check_type(pair_separator, (str,), 'pair_separator') |
| 407 |
_check_type(value_separator, (str,), 'value_separator') |
| 408 |
_check_type(values, (list,), 'values') |
| 409 |
_check_type(condition_func, (str, NoneType), 'condition_func') |
| 410 |
|
| 411 |
ctxt.trace.append('key_value_list') |
| 412 |
|
| 413 |
_check_char(pair_separator, 'pair_separator') |
| 414 |
_check_char(value_separator, 'value_separator') |
| 415 |
_check_non_empty_list(values, 'values') |
| 416 |
if condition_func.value is not None: |
| 417 |
_check_non_empty_string(condition_func, 'condition_func') |
| 418 |
|
| 419 |
defined_keys = set() |
| 420 |
|
| 421 |
for i, compldef in enumerate(values.value): |
| 422 |
index = f'definition[{i}]' |
| 423 |
_check_type(compldef, (list,), index) |
| 424 |
|
| 425 |
if len(compldef.value) < 3: |
| 426 |
msg = '%s: %s' % (index, m.list_must_contain_at_least_n_items('3')) |
| 427 |
raise _error(msg, compldef) |
| 428 |
|
| 429 |
if len(compldef.value) > 4: |
| 430 |
msg = '%s: %s' % (index, m.list_must_contain_exact_n_items('3/4')) |
| 431 |
raise _error(msg, compldef) |
| 432 |
|
| 433 |
key = compldef.value[0] |
| 434 |
description = compldef.value[1] |
| 435 |
complete = compldef.value[2] |
| 436 |
|
| 437 |
_check_type(key, (str,), f'{index}: key') |
| 438 |
_check_type(description, (str, NoneType), f'{index}: description') |
| 439 |
_check_type(complete, (list, NoneType), f'{index}: completer') |
| 440 |
_check_non_empty_string(key, f'{index}: key') |
| 441 |
_check_no_spaces(key, f'{index}: key') |
| 442 |
|
| 443 |
if key.value in defined_keys: |
| 444 |
cause = f'{index}: {key.value}' |
| 445 |
msg = '%s: Duplicate key' % cause |
| 446 |
raise _error(msg, key) |
| 447 |
|
| 448 |
defined_keys.add(key.value) |
| 449 |
|
| 450 |
if complete.value is not None: |
| 451 |
_check_complete(ctxt, complete) |
| 452 |
|
| 453 |
if len(compldef.value) == 4: |
| 454 |
excludes = compldef.value[3] |
| 455 |
_check_type(excludes, (list,), f'{index}: excludes') |
| 456 |
for i2, exclude in enumerate(excludes.value): |
| 457 |
_check_type(exclude, (str,), f'{index}: excludes[{i2}]') |
| 458 |
_check_non_empty_string(exclude, f'{index}: excludes[{i2}]') |
| 459 |
|
| 460 |
# Check if keys which are specified in `excludes` actually exist |
| 461 |
for i, compldef in enumerate(values.value): |
| 462 |
if len(compldef.value) != 4: |
| 463 |
continue |
| 464 |
|
| 465 |
index = f'definition[{i}]' |
| 466 |
for i2, exclude in enumerate(compldef.value[3].value): |
| 467 |
if exclude.value not in defined_keys: |
| 468 |
cause = f'definition[{i}]: excludes[{i2}]: {exclude.value}' |
| 469 |
msg = '%s: No such key' % cause |
| 470 |
raise _error(msg, exclude) |
| 471 |
|
| 472 |
|
| 473 |
def _check_key_value_pair(ctxt, arguments): |
| 474 |
value_separator = arguments.get_required_arg('value_separator') |
| 475 |
values = arguments.get_required_arg('values') |
| 476 |
condition_func = arguments.get_optional_arg(None) |
| 477 |
arguments.require_no_more() |
| 478 |
|
| 479 |
_check_type(value_separator, (str,), 'value_separator') |
| 480 |
_check_type(values, (list,), 'values') |
| 481 |
_check_type(condition_func, (str, NoneType), 'condition_func') |
| 482 |
|
| 483 |
ctxt.trace.append('key_value_pair') |
| 484 |
|
| 485 |
_check_char(value_separator, 'value_separator') |
| 486 |
_check_non_empty_list(values, 'values') |
| 487 |
if condition_func.value is not None: |
| 488 |
_check_non_empty_string(condition_func, 'condition_func') |
| 489 |
|
| 490 |
for i, compldef in enumerate(values.value): |
| 491 |
index = f'definition[{i}]' |
| 492 |
_check_type(compldef, (list,), index) |
| 493 |
|
| 494 |
if len(compldef.value) != 3: |
| 495 |
msg = '%s: %s' % (index, m.list_must_contain_exact_n_items('3')) |
| 496 |
raise _error(msg, compldef) |
| 497 |
|
| 498 |
key = compldef.value[0] |
| 499 |
description = compldef.value[1] |
| 500 |
complete = compldef.value[2] |
| 501 |
|
| 502 |
_check_type(key, (str,), f'{index}: key') |
| 503 |
_check_type(description, (str, NoneType), f'{index}: description') |
| 504 |
_check_type(complete, (list, NoneType), f'{index}: completer') |
| 505 |
_check_non_empty_string(key, f'{index}: key') |
| 506 |
_check_no_spaces(key, f'{index}: key') |
| 507 |
|
| 508 |
if complete.value is None: |
| 509 |
continue |
| 510 |
|
| 511 |
_check_complete(ctxt, complete) |
| 512 |
|
| 513 |
|
| 514 |
def _check_combine(ctxt, arguments): |
| 515 |
commands = arguments.get_required_arg('commands') |
| 516 |
arguments.require_no_more() |
| 517 |
|
| 518 |
_check_type(commands, (list,), 'commands') |
| 519 |
_check_non_empty_list(commands, 'commands') |
| 520 |
|
| 521 |
if len(commands.value) == 1: |
| 522 |
msg = '%s: %s' % ('commands', m.list_must_contain_at_least_n_items('2')) |
| 523 |
raise _error(msg, commands) |
| 524 |
|
| 525 |
ctxt.trace.append('combine') |
| 526 |
|
| 527 |
for i, completer in enumerate(commands.value): |
| 528 |
_check_type(completer, (list,), f'command[{i}]') |
| 529 |
_check_complete(ctxt, completer) |
| 530 |
|
| 531 |
|
| 532 |
def _check_list(ctxt, arguments): |
| 533 |
command = arguments.get_required_arg('command') |
| 534 |
options = arguments.get_optional_arg({}) |
| 535 |
arguments.require_no_more() |
| 536 |
|
| 537 |
_check_type(command, (list,), 'command') |
| 538 |
_check_type(options, (dict,), 'options') |
| 539 |
|
| 540 |
_check_dictionary(options, { |
| 541 |
'separator': (False, (str,), _check_char), |
| 542 |
'duplicates': (False, (bool,), None), |
| 543 |
}) |
| 544 |
|
| 545 |
ctxt.trace.append('list') |
| 546 |
_check_complete(ctxt, command) |
| 547 |
|
| 548 |
|
| 549 |
def _check_prefix(ctxt, arguments): |
| 550 |
prefix = arguments.get_required_arg('prefix') |
| 551 |
command = arguments.get_required_arg('command') |
| 552 |
arguments.require_no_more() |
| 553 |
|
| 554 |
_check_type(prefix, (str,), 'prefix') |
| 555 |
_check_type(command, (list,), 'command') |
| 556 |
|
| 557 |
ctxt.trace.append('prefix') |
| 558 |
_check_complete(ctxt, command) |
| 559 |
|
| 560 |
|
| 561 |
def _check_history(_ctxt, arguments): |
| 562 |
pattern = arguments.get_required_arg("pattern") |
| 563 |
_check_type(pattern, (str,), "pattern") |
| 564 |
arguments.require_no_more() |
| 565 |
_check_regex(pattern, 'pattern') |
| 566 |
|
| 567 |
|
| 568 |
def _check_date(_ctxt, arguments): |
| 569 |
format_ = arguments.get_required_arg("format") |
| 570 |
_check_type(format_, (str,), "format") |
| 571 |
arguments.require_no_more() |
| 572 |
_check_non_empty_string(format_, 'format') |
| 573 |
|
| 574 |
|
| 575 |
def _check_ip_address(_ctxt, arguments): |
| 576 |
type_ = arguments.get_optional_arg('all') |
| 577 |
arguments.require_no_more() |
| 578 |
_check_type(type_, (str,), "type") |
| 579 |
|
| 580 |
allowed = ('ipv4', 'ipv6', 'all', 'ipv4+', 'ipv6+', 'all+') |
| 581 |
|
| 582 |
if type_.value not in allowed: |
| 583 |
allowed = ', '.join(allowed) |
| 584 |
msg = '%s: %s' % ('type', m.invalid_value_expected_values(allowed)) |
| 585 |
raise _error(msg, type_) |
| 586 |
|
| 587 |
|
| 588 |
def _check_integer_float(_ctxt, arguments, types): |
| 589 |
options = arguments.get_optional_arg({}) |
| 590 |
arguments.require_no_more() |
| 591 |
_check_type(options, (dict,), "options") |
| 592 |
|
| 593 |
_check_dictionary(options, { |
| 594 |
'min': (False, types, None), |
| 595 |
'max': (False, types, None), |
| 596 |
'help': (False, (str,), _check_non_empty_string), |
| 597 |
'suffixes': (False, (dict,), _check_non_empty_dict), |
| 598 |
}) |
| 599 |
|
| 600 |
if _has_set(options, 'min') and _has_set(options, 'max'): |
| 601 |
min_ = options.value['min'].value |
| 602 |
max_ = options.value['max'].value |
| 603 |
|
| 604 |
if min_ > max_: |
| 605 |
raise _error(f'min > max ({min_} > {max_})', options) |
| 606 |
|
| 607 |
if _has_set(options, 'suffixes'): |
| 608 |
for suffix, description in options.value['suffixes'].value.items(): |
| 609 |
_check_type(suffix, (str,), "suffix") |
| 610 |
_check_type(description, (str,), "description") |
| 611 |
_check_non_empty_string(suffix, "suffix") |
| 612 |
_check_non_empty_string(description, "description") |
| 613 |
|
| 614 |
|
| 615 |
def _check_integer(ctxt, arguments): |
| 616 |
_check_integer_float(ctxt, arguments, (int,)) |
| 617 |
|
| 618 |
|
| 619 |
def _check_float(ctxt, arguments): |
| 620 |
_check_integer_float(ctxt, arguments, (int, float)) |
| 621 |
|
| 622 |
|
| 623 |
_COMMANDS = { |
| 624 |
'alsa_card': _check_void, |
| 625 |
'alsa_device': _check_void, |
| 626 |
'charset': _check_void, |
| 627 |
'choices': _check_choices, |
| 628 |
'combine': _check_combine, |
| 629 |
'command': _check_command, |
| 630 |
'command_arg': _check_command_arg, |
| 631 |
'commandline_string': _check_void, |
| 632 |
'date': _check_date, |
| 633 |
'date_format': _check_void, |
| 634 |
'directory': _check_directory, |
| 635 |
'directory_list': _check_directory_list, |
| 636 |
'environment': _check_void, |
| 637 |
'exec': _check_exec, |
| 638 |
'exec_fast': _check_exec, |
| 639 |
'exec_internal': _check_exec, |
| 640 |
'file': _check_file, |
| 641 |
'file_list': _check_file_list, |
| 642 |
'filesystem_type': _check_void, |
| 643 |
'float': _check_float, |
| 644 |
'gid': _check_void, |
| 645 |
'group': _check_void, |
| 646 |
'history': _check_history, |
| 647 |
'hostname': _check_void, |
| 648 |
'integer': _check_integer, |
| 649 |
'ip_address': _check_ip_address, |
| 650 |
'key_value_list': _check_key_value_list, |
| 651 |
'key_value_list_exec': _check_key_value_list_exec, |
| 652 |
'key_value_pair': _check_key_value_pair, |
| 653 |
'key_value_pair_exec': _check_key_value_pair_exec, |
| 654 |
'list': _check_list, |
| 655 |
'locale': _check_void, |
| 656 |
'login_shell': _check_void, |
| 657 |
'mime_file': _check_mime_file, |
| 658 |
'mountpoint': _check_void, |
| 659 |
'net_interface': _check_void, |
| 660 |
'none': _check_none, |
| 661 |
'pid': _check_void, |
| 662 |
'prefix': _check_prefix, |
| 663 |
'process': _check_void, |
| 664 |
'range': _check_range, |
| 665 |
'service': _check_void, |
| 666 |
'signal': _check_void, |
| 667 |
'timezone': _check_void, |
| 668 |
'uid': _check_void, |
| 669 |
'user': _check_void, |
| 670 |
'value_list': _check_value_list, |
| 671 |
'variable': _check_void, |
| 672 |
} |
| 673 |
|
| 674 |
|
| 675 |
def _check_complete(ctxt, args): |
| 676 |
arguments = Arguments(args) |
| 677 |
cmd = arguments.get_required_arg('command') |
| 678 |
|
| 679 |
_check_type(cmd, (str,), 'command') |
| 680 |
|
| 681 |
if cmd.value not in _COMMANDS: |
| 682 |
msg = '%s: %s' % (m.unknown_completer(), cmd.value) |
| 683 |
raise _error(msg, cmd) |
| 684 |
|
| 685 |
try: |
| 686 |
_COMMANDS[cmd.value](ctxt, arguments) |
| 687 |
except _error as e: |
| 688 |
msg = '%s: %s' % (cmd.value, e.message) |
| 689 |
raise _error(msg, e.value_with_trace) from e |
| 690 |
|
| 691 |
|
| 692 |
def _check_positionals_repeatable0(definition_tree, definition): |
| 693 |
if not _has_set(definition, 'positionals'): |
| 694 |
return |
| 695 |
|
| 696 |
positionals = definition.value['positionals'].value |
| 697 |
repeatable_number = None |
| 698 |
|
| 699 |
for positional in sorted(positionals, key=lambda p: p.value['number'].value): |
| 700 |
repeatable = False |
| 701 |
if _has_set(positional, 'repeatable'): |
| 702 |
repeatable = positional.value['repeatable'].value |
| 703 |
|
| 704 |
positional_number = positional.value['number'].value |
| 705 |
|
| 706 |
if repeatable: |
| 707 |
if repeatable_number is not None and repeatable_number != positional_number: |
| 708 |
msg = m.too_many_repeatable_positionals() |
| 709 |
raise _error(msg, positional) |
| 710 |
|
| 711 |
repeatable_number = positional_number |
| 712 |
elif repeatable_number is not None and positional_number > repeatable_number: |
| 713 |
msg = m.positional_argument_after_repeatable() |
| 714 |
raise _error(msg, positional) |
| 715 |
|
| 716 |
node = definition_tree.get_definition(definition.value['prog'].value) |
| 717 |
if repeatable_number is not None and len(node.subcommands) > 0: |
| 718 |
msg = m.repeatable_with_subcommands() |
| 719 |
raise _error(msg, definition) |
| 720 |
|
| 721 |
|
| 722 |
def _check_positionals_repeatable(definition_tree, definition): |
| 723 |
try: |
| 724 |
_check_positionals_repeatable0(definition_tree, definition) |
| 725 |
except _error as e: |
| 726 |
prog = definition.value['prog'].value |
| 727 |
msg = '%s: %s' % (prog, e.message) |
| 728 |
raise _error(msg, e.value_with_trace) from e |
| 729 |
|
| 730 |
|
| 731 |
def _check_option0(ctxt, option): |
| 732 |
chkbool = _check_extended_bool |
| 733 |
|
| 734 |
_check_dictionary(option, { |
| 735 |
'option_strings': (True, (list,), None), |
| 736 |
'metavar': (False, (str, NoneType), None), |
| 737 |
'help': (False, (str, NoneType), None), |
| 738 |
'optional_arg': (False, (bool, NoneType), None), |
| 739 |
'group': (False, (str, NoneType), None), |
| 740 |
'groups': (False, (list, NoneType), None), |
| 741 |
'repeatable': (False, (bool, str, NoneType), chkbool), |
| 742 |
'final': (False, (bool, NoneType), None), |
| 743 |
'hidden': (False, (bool, NoneType), None), |
| 744 |
'nosort': (False, (bool, NoneType), None), |
| 745 |
'complete': (False, (list, NoneType), None), |
| 746 |
'when': (False, (str, NoneType), None), |
| 747 |
'capture': (False, (str, NoneType), None), |
| 748 |
'long_opt_arg_sep': (False, (str,), None), |
| 749 |
}) |
| 750 |
|
| 751 |
option_strings = option.value['option_strings'] |
| 752 |
|
| 753 |
_check_non_empty_list(option_strings, 'option_strings') |
| 754 |
|
| 755 |
for option_string in option_strings.value: |
| 756 |
_check_type(option_string, (str,), "option_string") |
| 757 |
|
| 758 |
if not is_valid_option_string(option_string.value): |
| 759 |
msg = m.invalid_value() |
| 760 |
raise _error(msg, option_string) |
| 761 |
|
| 762 |
if _has_set(option, 'metavar') and not _has_set(option, 'complete'): |
| 763 |
msg = m.parameter_requires_parameter('metavar', 'complete') |
| 764 |
raise _error(msg, option) |
| 765 |
|
| 766 |
if _is_true(option, 'optional_arg') and not _has_set(option, 'complete'): |
| 767 |
msg = m.parameter_requires_parameter('optional_arg', 'complete') |
| 768 |
raise _error(msg, option) |
| 769 |
|
| 770 |
if _is_true(option, 'repeatable') and _is_true(option, 'hidden'): |
| 771 |
msg = m.mutually_exclusive_parameters('repeatable, hidden') |
| 772 |
raise _error(msg, option) |
| 773 |
|
| 774 |
if _has_set(option, 'group') and _has_set(option, 'groups'): |
| 775 |
msg = m.mutually_exclusive_parameters('groups, group') |
| 776 |
raise _error(msg, option) |
| 777 |
|
| 778 |
if _has_set(option, 'groups'): |
| 779 |
for group in option.value['groups'].value: |
| 780 |
_check_type(group, (str,), "group") |
| 781 |
|
| 782 |
if _has_set(option, 'complete'): |
| 783 |
ctxt.type = Context.TYPE_OPTION |
| 784 |
ctxt.option = option |
| 785 |
ctxt.trace = [] |
| 786 |
_check_complete(ctxt, option.value['complete']) |
| 787 |
|
| 788 |
if _has_set(option, 'when'): |
| 789 |
_check_when(option.value['when']) |
| 790 |
|
| 791 |
if _has_set(option, 'capture'): |
| 792 |
_check_variable_name(option.value['capture'], 'capture') |
| 793 |
|
| 794 |
if _has_set(option, 'long_opt_arg_sep'): |
| 795 |
if option.value['long_opt_arg_sep'] not in ( |
| 796 |
'space', 'equals', 'both', INHERIT): |
| 797 |
expected = f'space, equals, both, {INHERIT}' |
| 798 |
msg = m.invalid_value_expected_values(expected) |
| 799 |
raise _error(msg, option.value['long_opt_arg_sep']) |
| 800 |
|
| 801 |
|
| 802 |
def _check_option(ctxt, option): |
| 803 |
try: |
| 804 |
_check_option0(ctxt, option) |
| 805 |
except _error as e: |
| 806 |
try: |
| 807 |
option_strings = option.value['option_strings'].value |
| 808 |
option_strings = '|'.join([o.value for o in option_strings]) |
| 809 |
except (KeyError, TypeError): |
| 810 |
raise e from None |
| 811 |
|
| 812 |
msg = '%s: %s' % (option_strings, e.message) |
| 813 |
raise _error(msg, e.value_with_trace) from e |
| 814 |
|
| 815 |
|
| 816 |
def _check_positional0(ctxt, positional): |
| 817 |
_check_dictionary(positional, { |
| 818 |
'number': (True, (int,), None), |
| 819 |
'metavar': (False, (str, NoneType), None), |
| 820 |
'help': (False, (str, NoneType), None), |
| 821 |
'repeatable': (False, (bool, NoneType), None), |
| 822 |
'nosort': (False, (bool, NoneType), None), |
| 823 |
'complete': (False, (list, NoneType), None), |
| 824 |
'when': (False, (str, NoneType), None), |
| 825 |
'capture': (False, (str, NoneType), None), |
| 826 |
}) |
| 827 |
|
| 828 |
if positional.value['number'].value < 1: |
| 829 |
msg = m.integer_must_be_greater_than_zero() |
| 830 |
raise _error('%s: %s' % ('number', msg), positional.value['number']) |
| 831 |
|
| 832 |
if _has_set(positional, 'complete'): |
| 833 |
ctxt.type = Context.TYPE_POSITIONAL |
| 834 |
ctxt.positional = positional |
| 835 |
ctxt.trace = [] |
| 836 |
_check_complete(ctxt, positional.value['complete']) |
| 837 |
|
| 838 |
if _has_set(positional, 'when'): |
| 839 |
_check_when(positional.value['when']) |
| 840 |
|
| 841 |
if _has_set(positional, 'capture'): |
| 842 |
_check_variable_name(positional.value['capture'], 'capture') |
| 843 |
|
| 844 |
|
| 845 |
def _check_positional(ctxt, positional): |
| 846 |
try: |
| 847 |
_check_positional0(ctxt, positional) |
| 848 |
except _error as e: |
| 849 |
metavar = 'unknown' |
| 850 |
|
| 851 |
try: |
| 852 |
metavar = 'positional #%d' % positional.value['number'].value |
| 853 |
except (KeyError, TypeError): |
| 854 |
pass |
| 855 |
|
| 856 |
try: |
| 857 |
metavar_ = positional.value['metavar'].value |
| 858 |
assert isinstance(metavar_, str) |
| 859 |
metavar = metavar_ |
| 860 |
except (AssertionError, KeyError): |
| 861 |
pass |
| 862 |
|
| 863 |
msg = '%s: %s' % (metavar, e.message) |
| 864 |
raise _error(msg, e.value_with_trace) from e |
| 865 |
|
| 866 |
|
| 867 |
def _check_commandline_definition0(ctxt, definition): |
| 868 |
chkbool = _check_extended_bool |
| 869 |
|
| 870 |
_check_dictionary(definition, { |
| 871 |
'prog': (True, (str,), None), |
| 872 |
'help': (False, (str, NoneType), None), |
| 873 |
'aliases': (False, (list, NoneType), None), |
| 874 |
'wraps': (False, (str, NoneType), None), |
| 875 |
'abbreviate_commands': (False, (bool, str, NoneType), chkbool), |
| 876 |
'abbreviate_options': (False, (bool, str, NoneType), chkbool), |
| 877 |
'inherit_options': (False, (bool, str, NoneType), chkbool), |
| 878 |
'options': (False, (list, NoneType), None), |
| 879 |
'positionals': (False, (list, NoneType), None), |
| 880 |
}) |
| 881 |
|
| 882 |
try: |
| 883 |
validate_prog(definition.value['prog'].value) |
| 884 |
except CrazyError as e: |
| 885 |
raise _error(f'prog: {e}', definition.value['prog']) from None |
| 886 |
|
| 887 |
if _has_set(definition, 'aliases'): |
| 888 |
for alias in definition.value['aliases'].value: |
| 889 |
_check_type(alias, (str,), 'alias') |
| 890 |
_check_non_empty_string(alias, 'alias') |
| 891 |
_check_no_spaces(alias, 'alias') |
| 892 |
|
| 893 |
if _has_set(definition, 'wraps'): |
| 894 |
wraps = definition.value['wraps'] |
| 895 |
_check_non_empty_string(wraps, 'wraps') |
| 896 |
_check_no_spaces(wraps, 'wraps') |
| 897 |
|
| 898 |
if contains_space(definition.value['prog'].value): |
| 899 |
msg = m.parameter_not_allowed_in_subcommand('wraps') |
| 900 |
raise _error(msg, definition.value['wraps']) |
| 901 |
|
| 902 |
if _has_set(definition, 'options'): |
| 903 |
for option in definition.value['options'].value: |
| 904 |
_check_option(ctxt, option) |
| 905 |
|
| 906 |
if _has_set(definition, 'positionals'): |
| 907 |
for positional in definition.value['positionals'].value: |
| 908 |
_check_positional(ctxt, positional) |
| 909 |
|
| 910 |
|
| 911 |
def _check_commandline_definition(ctxt, definition): |
| 912 |
try: |
| 913 |
_check_commandline_definition0(ctxt, definition) |
| 914 |
except _error as e: |
| 915 |
try: |
| 916 |
prog = definition.value['prog'].value |
| 917 |
except (KeyError, TypeError): |
| 918 |
prog = 'unknown' |
| 919 |
|
| 920 |
msg = '%s: %s' % (prog, e.message) |
| 921 |
raise _error(msg, e.value_with_trace) from e |
| 922 |
|
| 923 |
|
| 924 |
class DefinitionTree: |
| 925 |
'''Holds a command-line definition with subcommands.''' |
| 926 |
|
| 927 |
def __init__(self, definition): |
| 928 |
self.definition = definition |
| 929 |
self.subcommands = {} |
| 930 |
|
| 931 |
def add_definition(self, definition): |
| 932 |
'''Add a definition to subcommands.''' |
| 933 |
|
| 934 |
_check_type(definition, (dict,)) |
| 935 |
|
| 936 |
if not _has_set(definition, 'prog'): |
| 937 |
raise _error('%s: %s' % (m.missing_arg(), 'prog'), definition) |
| 938 |
|
| 939 |
try: |
| 940 |
validate_prog(definition.value['prog'].value) |
| 941 |
except CrazyError as e: |
| 942 |
raise _error(f'prog: {e}', definition.value['prog']) from None |
| 943 |
|
| 944 |
commands = definition.value['prog'].value.split(' ') |
| 945 |
subcommand = commands.pop(-1) |
| 946 |
|
| 947 |
node = self |
| 948 |
|
| 949 |
for i, part in enumerate(commands): |
| 950 |
try: |
| 951 |
node = node.subcommands[part] |
| 952 |
except KeyError: |
| 953 |
prog = ' '.join(commands[0:i+1]) |
| 954 |
msg = m.missing_definition_of_program(prog) |
| 955 |
raise _error(msg, definition) from None |
| 956 |
|
| 957 |
if subcommand in node.subcommands: |
| 958 |
prog = definition.value['prog'].value |
| 959 |
msg = m.multiple_definition_of_program(prog) |
| 960 |
raise _error(msg, definition) |
| 961 |
|
| 962 |
node.subcommands[subcommand] = DefinitionTree(definition) |
| 963 |
|
| 964 |
def get_definition(self, prog): |
| 965 |
'''Get definition by prog.''' |
| 966 |
|
| 967 |
commands = prog.split(' ') |
| 968 |
node = self |
| 969 |
|
| 970 |
for part in commands: |
| 971 |
node = node.subcommands[part] |
| 972 |
|
| 973 |
return node |
| 974 |
|
| 975 |
def visit(self, callback): |
| 976 |
'''Call `callback` on each node in the tree.''' |
| 977 |
callback(self) |
| 978 |
for subcommand in self.subcommands.values(): |
| 979 |
callback(subcommand) |
| 980 |
|
| 981 |
def get_all(self): |
| 982 |
'''Return a list of all nodes.''' |
| 983 |
result = [] |
| 984 |
self.visit(result.append) |
| 985 |
return result |
| 986 |
|
| 987 |
def get_first_commandline(self): |
| 988 |
'''Return the first command line in the tree.''' |
| 989 |
return list(self.subcommands.values())[0] |
| 990 |
|
| 991 |
@staticmethod |
| 992 |
def make_tree(definition_list): |
| 993 |
'''Make a tree out of a list of definitions.''' |
| 994 |
|
| 995 |
root = DefinitionTree(None) |
| 996 |
|
| 997 |
for definition in definition_list: |
| 998 |
root.add_definition(definition) |
| 999 |
|
| 1000 |
return root |
| 1001 |
|
| 1002 |
|
| 1003 |
def validate(definition_list): |
| 1004 |
'''Validate a list of definitions.''' |
| 1005 |
|
| 1006 |
context = Context() |
| 1007 |
commandline_root = DefinitionTree.make_tree(definition_list) |
| 1008 |
|
| 1009 |
if len(commandline_root.subcommands) == 0: |
| 1010 |
msg = m.no_programs_defined() |
| 1011 |
raise _error(msg, ValueWithTrace(None, '', 1, 1)) |
| 1012 |
|
| 1013 |
if len(commandline_root.subcommands) > 1: |
| 1014 |
value = ValueWithTrace(None, '', 1, 1) |
| 1015 |
progs = list(commandline_root.subcommands.keys()) |
| 1016 |
msg = m.too_many_programs_defined() |
| 1017 |
raise _error('%s: %s' % (msg, progs), value) |
| 1018 |
|
| 1019 |
for cmdline in commandline_root.get_first_commandline().get_all(): |
| 1020 |
context.definition = cmdline.definition |
| 1021 |
_check_commandline_definition(context, cmdline.definition) |
| 1022 |
_check_positionals_repeatable(commandline_root, cmdline.definition) |