| 1 |
# SPDX-License-Identifier: GPL-3.0-or-later |
| 2 |
# Copyright (C) 2025-2026 Benjamin Abendroth <[email protected]> |
| 3 |
|
| 4 |
'''This module contains utility functions.''' |
| 5 |
|
| 6 |
import sys |
| 7 |
from collections import namedtuple |
| 8 |
from .type_utils import is_list_type |
| 9 |
|
| 10 |
|
| 11 |
def warn(*a): |
| 12 |
'''Print a warning.''' |
| 13 |
|
| 14 |
print('WARNING:', *a, file=sys.stderr) |
| 15 |
|
| 16 |
|
| 17 |
def print_err(*a): |
| 18 |
'''Print to STDERR.''' |
| 19 |
|
| 20 |
print(*a, file=sys.stderr) |
| 21 |
|
| 22 |
|
| 23 |
class GeneralAbbreviationGenerator: |
| 24 |
'''A class for generating abbreviations from a list of words. |
| 25 |
|
| 26 |
Attributes: |
| 27 |
min_abbreviated_length (int): |
| 28 |
The minimum length of an abbreviation. |
| 29 |
|
| 30 |
abbreviations (dict): |
| 31 |
A dictionary mapping each word to its list of abbreviations. |
| 32 |
|
| 33 |
min_lengths (dict): |
| 34 |
A dictionary mapping each word to its minimum abbreviation length. |
| 35 |
''' |
| 36 |
|
| 37 |
def __init__(self, min_abbreviated_length, words): |
| 38 |
'''Initialize the GeneralAbbreviationGenerator instance. |
| 39 |
|
| 40 |
Args: |
| 41 |
min_abbreviated_length (int): |
| 42 |
The minimum length of an abbreviation. |
| 43 |
|
| 44 |
words (iterable of str): |
| 45 |
The list of words from which to generate abbreviations. |
| 46 |
''' |
| 47 |
|
| 48 |
assert isinstance(min_abbreviated_length, int) |
| 49 |
assert is_list_type(words) |
| 50 |
|
| 51 |
# pylint: disable=cell-var-from-loop |
| 52 |
|
| 53 |
self.min_abbreviated_length = min_abbreviated_length |
| 54 |
self.abbreviations = {} |
| 55 |
self.min_lengths = {} |
| 56 |
|
| 57 |
for word in words: |
| 58 |
self.abbreviations[word] = [] |
| 59 |
self.min_lengths[word] = len(word) |
| 60 |
|
| 61 |
for length in range(len(word), self.min_abbreviated_length - 1, -1): |
| 62 |
abbrev = word[0:length] |
| 63 |
|
| 64 |
can_abbreviate = True |
| 65 |
for other_word in filter(lambda w: w != word, words): |
| 66 |
if other_word.startswith(abbrev): |
| 67 |
can_abbreviate = False |
| 68 |
break |
| 69 |
|
| 70 |
if can_abbreviate or abbrev == word: |
| 71 |
self.abbreviations[word].append(abbrev) |
| 72 |
self.min_lengths[word] = length |
| 73 |
|
| 74 |
def get_abbreviations(self, word): |
| 75 |
'''Get the list of abbreviations for a given word. |
| 76 |
|
| 77 |
Args: |
| 78 |
word (str): The word for which to retrieve abbreviations. |
| 79 |
|
| 80 |
Returns: |
| 81 |
list: A list of abbreviations for the given word. |
| 82 |
''' |
| 83 |
|
| 84 |
assert isinstance(word, str) |
| 85 |
|
| 86 |
return self.abbreviations[word] |
| 87 |
|
| 88 |
def get_many_abbreviations(self, words): |
| 89 |
'''Get the list of abbreviations for multiple words. |
| 90 |
|
| 91 |
Args: |
| 92 |
words (iterable of str): |
| 93 |
The words for which to retrieve abbreviations. |
| 94 |
|
| 95 |
Returns: |
| 96 |
list: A list of abbreviations for the given words. |
| 97 |
''' |
| 98 |
|
| 99 |
assert is_list_type(words) |
| 100 |
|
| 101 |
r = [] |
| 102 |
for word in words: |
| 103 |
r.extend(self.get_abbreviations(word)) |
| 104 |
return r |
| 105 |
|
| 106 |
|
| 107 |
class OptionAbbreviationGenerator(GeneralAbbreviationGenerator): |
| 108 |
'''AbbreviationGenerator for abbreviating long and old-style options.''' |
| 109 |
|
| 110 |
def __init__(self, words): |
| 111 |
assert is_list_type(words) |
| 112 |
|
| 113 |
words = list(words) |
| 114 |
|
| 115 |
for word in words: |
| 116 |
if word.startswith('--') and len(word) > 3: |
| 117 |
pass |
| 118 |
elif word.startswith('-') and len(word) > 2: |
| 119 |
pass |
| 120 |
else: |
| 121 |
raise ValueError('Not a long or old-style option: %r' % word) |
| 122 |
|
| 123 |
super().__init__(3, words) |
| 124 |
|
| 125 |
|
| 126 |
class CommandAbbreviationGenerator(GeneralAbbreviationGenerator): |
| 127 |
'''AbbreviationGenerator for abbreviating commands.''' |
| 128 |
|
| 129 |
def __init__(self, words): |
| 130 |
super().__init__(1, words) |
| 131 |
|
| 132 |
|
| 133 |
class DummyAbbreviationGenerator: |
| 134 |
'''A dummy abbreviation generator that returns the original word as the abbreviation. |
| 135 |
|
| 136 |
This class is used as a placeholder when abbreviation generation is not required. |
| 137 |
''' |
| 138 |
|
| 139 |
def __init__(self): |
| 140 |
pass |
| 141 |
|
| 142 |
def get_abbreviations(self, word): |
| 143 |
'''Don't abbreviate, just return the input.''' |
| 144 |
|
| 145 |
assert isinstance(word, str) |
| 146 |
|
| 147 |
return [word] |
| 148 |
|
| 149 |
def get_many_abbreviations(self, words): |
| 150 |
'''Don't abbreviate, just return the input.''' |
| 151 |
|
| 152 |
assert is_list_type(words) |
| 153 |
|
| 154 |
return words |
| 155 |
|
| 156 |
|
| 157 |
def get_option_abbreviator(commandline): |
| 158 |
'''Return an OptionAbbreviationGenerator for options in `commandline`.''' |
| 159 |
|
| 160 |
if not commandline.abbreviate_options: |
| 161 |
return DummyAbbreviationGenerator() |
| 162 |
|
| 163 |
options = commandline.get_options(with_parent_options=commandline.inherit_options) |
| 164 |
option_strings = [] |
| 165 |
|
| 166 |
for option in options: |
| 167 |
option_strings.extend(option.get_long_option_strings()) |
| 168 |
option_strings.extend(option.get_old_option_strings()) |
| 169 |
|
| 170 |
return OptionAbbreviationGenerator(option_strings) |
| 171 |
|
| 172 |
|
| 173 |
def get_all_command_variations(commandline): |
| 174 |
'''Return all possible names for this command. |
| 175 |
|
| 176 |
If `commandline.abbreviate_commands` is True, also return abbreviated forms. |
| 177 |
''' |
| 178 |
|
| 179 |
if commandline.parent is None: |
| 180 |
return [commandline.prog] + commandline.aliases |
| 181 |
|
| 182 |
if commandline.abbreviate_commands: |
| 183 |
all_commands = [] |
| 184 |
for subcommand in commandline.parent.subcommands.subcommands: |
| 185 |
all_commands.append(subcommand.prog) |
| 186 |
abbrevs = CommandAbbreviationGenerator(all_commands) |
| 187 |
else: |
| 188 |
abbrevs = DummyAbbreviationGenerator() |
| 189 |
|
| 190 |
return abbrevs.get_abbreviations(commandline.prog) + commandline.aliases |
| 191 |
|
| 192 |
|
| 193 |
def get_defined_option_types(commandline): |
| 194 |
'''Return a tuple of defined option types.''' |
| 195 |
|
| 196 |
# pylint: disable=too-many-branches |
| 197 |
|
| 198 |
short_required = False |
| 199 |
short_optional = False |
| 200 |
short_flag = False |
| 201 |
long_required = False |
| 202 |
long_optional = False |
| 203 |
long_flag = False |
| 204 |
old_required = False |
| 205 |
old_optional = False |
| 206 |
old_flag = False |
| 207 |
positionals = False |
| 208 |
subcommands = False |
| 209 |
|
| 210 |
for cmdline in commandline.get_all_commandlines(): |
| 211 |
if len(cmdline.get_positionals()) > 0: |
| 212 |
positionals = True |
| 213 |
|
| 214 |
if cmdline.get_subcommands() and len(cmdline.get_subcommands().subcommands) > 0: |
| 215 |
positionals = True |
| 216 |
subcommands = True |
| 217 |
|
| 218 |
for option in cmdline.options: |
| 219 |
if option.get_long_option_strings(): |
| 220 |
if option.has_required_arg(): |
| 221 |
long_required = True |
| 222 |
elif option.has_optional_arg(): |
| 223 |
long_optional = True |
| 224 |
else: |
| 225 |
long_flag = True |
| 226 |
|
| 227 |
if option.get_old_option_strings(): |
| 228 |
if option.has_required_arg(): |
| 229 |
old_required = True |
| 230 |
elif option.has_optional_arg(): |
| 231 |
old_optional = True |
| 232 |
else: |
| 233 |
old_flag = True |
| 234 |
|
| 235 |
if option.get_short_option_strings(): |
| 236 |
if option.has_required_arg(): |
| 237 |
short_required = True |
| 238 |
elif option.has_optional_arg(): |
| 239 |
short_optional = True |
| 240 |
else: |
| 241 |
short_flag = True |
| 242 |
|
| 243 |
return namedtuple('Types', ( |
| 244 |
'positionals', 'subcommands', |
| 245 |
'short_required', 'short_optional', 'short_flag', 'short', |
| 246 |
'long_required', 'long_optional', 'long_flag', 'long', |
| 247 |
'old_required', 'old_optional', 'old_flag', 'old'))( |
| 248 |
positionals, subcommands, |
| 249 |
short_required, short_optional, short_flag, |
| 250 |
short_required or short_optional or short_flag, |
| 251 |
long_required, long_optional, long_flag, |
| 252 |
long_required or long_optional or long_flag, |
| 253 |
old_required, old_optional, old_flag, |
| 254 |
old_required or old_optional or old_flag) |
| 255 |
|
| 256 |
|
| 257 |
def get_query_option_strings(commandline, with_parent_options=True): |
| 258 |
'''Return a string that can be used by {fish,zsh}_query functions. |
| 259 |
|
| 260 |
Returns something like: |
| 261 |
"-f --flag -a= --argument= -o=? --optional=?" |
| 262 |
''' |
| 263 |
|
| 264 |
r = [] |
| 265 |
|
| 266 |
for option in commandline.get_options(with_parent_options=with_parent_options): |
| 267 |
if option.has_required_arg(): |
| 268 |
r.extend('%s=' % s for s in option.option_strings) |
| 269 |
elif option.has_optional_arg(): |
| 270 |
r.extend('%s=?' % s for s in option.option_strings) |
| 271 |
else: |
| 272 |
r.extend(option.option_strings) |
| 273 |
|
| 274 |
return ' '.join(r) |
| 275 |
|
| 276 |
|
| 277 |
def is_worth_a_function(commandline): |
| 278 |
'''Check if a commandline "is worth a function". |
| 279 |
|
| 280 |
This means that a commandline has one of: |
| 281 |
- Subcommands |
| 282 |
- Positionals (that have meaningful completion) |
| 283 |
- Options (that aren't --help or --version) |
| 284 |
''' |
| 285 |
|
| 286 |
if commandline.get_subcommands(): |
| 287 |
return True |
| 288 |
|
| 289 |
for positional in commandline.get_positionals(): |
| 290 |
if positional.complete[0] == 'none': |
| 291 |
pass |
| 292 |
elif positional.complete[0] in ('integer', 'float'): |
| 293 |
# integer/float without options have no real completion |
| 294 |
if len(positional.complete) > 1: |
| 295 |
return True |
| 296 |
else: |
| 297 |
return True |
| 298 |
|
| 299 |
options = commandline.get_options() |
| 300 |
options = list(filter(lambda o: '--help' not in o.option_strings and |
| 301 |
'--version' not in o.option_strings, options)) |
| 302 |
if len(options) > 0: |
| 303 |
return True |
| 304 |
|
| 305 |
return False |
| 306 |
|
| 307 |
|
| 308 |
_KEY_VALUE_LIST_DEFINITION = namedtuple('KeyValueListDefinition', ( |
| 309 |
'key', 'repeatable', 'description', 'completer', 'excludes')) |
| 310 |
|
| 311 |
|
| 312 |
def get_key_value_list_definitions(definitions): |
| 313 |
'''Normalize a list of key-value definitions. |
| 314 |
|
| 315 |
Each definition is represented as a list containing either three or four |
| 316 |
elements. This function converts the various supported forms into a |
| 317 |
consistent representation, making them easier to process. |
| 318 |
|
| 319 |
If the key name starts with '*', the returned definition is marked as |
| 320 |
repeatable and the leading '*' is removed from the key name. |
| 321 |
''' |
| 322 |
|
| 323 |
r = [] |
| 324 |
|
| 325 |
for definition in definitions: |
| 326 |
key = definition[0] |
| 327 |
repeatable = False |
| 328 |
excludes = [] |
| 329 |
|
| 330 |
if key.startswith('*'): |
| 331 |
key = key[1:] |
| 332 |
repeatable = True |
| 333 |
|
| 334 |
if len(definition) == 4: |
| 335 |
excludes = definition[3] |
| 336 |
|
| 337 |
r.append(_KEY_VALUE_LIST_DEFINITION( |
| 338 |
key, repeatable, definition[1], definition[2], excludes |
| 339 |
)) |
| 340 |
|
| 341 |
return r |