Debian Codegraph @

cloup/constraints/common.py

raw
1 """
2 Useful functions used to implement constraints and predicates.
3 """
4 from typing import Any, Dict, Iterable, List, Sequence
5
6 from click import Argument, Context, Option, Parameter
7
8
9 def param_value_is_set(param: Parameter, value: Any) -> bool:
10 """Define what it means for a parameter of a specific kind to be "set".
11
12 All cases are obvious besides that of boolean options:
13 - (common rule) if the value is ``None``, the parameter is unset;
14 - a parameter that takes multiple values is set if at least one argument is provided;
15 - a boolean **flag** is set only if True;
16 - a boolean option is set if not None, even if it's False.
17 """
18 if value is None:
19 return False
20 # checking for param.is_flag is redundant but necessary to work around
21 # Click 8.0.1 issue: https://github.com/pallets/click/issues/1925
22 elif isinstance(param, Option) and param.is_flag and param.is_bool_flag:
23 return bool(value)
24 elif param.nargs != 1 or param.multiple:
25 return len(value) > 0
26 return True
27
28
29 def get_param_name(param: Parameter) -> str:
30 """Return the name of a parameter casted to ``str``.
31 Use this function to avoid typing errors in places where you expect a parameter
32 having a name.
33 """
34 if param.name is None:
35 raise TypeError(
36 '`param.name` is required to be a string in this context.\n'
37 'Hint: `param.name` is None only when `parameter.expose_value` is False, '
38 'so you are probably using this option incorrectly.'
39 )
40 return param.name
41
42
43 def get_params_whose_value_is_set(
44 params: Iterable[Parameter], values: Dict[str, Any]
45 ) -> List[Parameter]:
46 """Filter ``params``, returning only the parameters that have a value.
47 Boolean flags are considered "set" if their value is ``True``."""
48 return [p for p in params
49 if param_value_is_set(p, values[get_param_name(p)])]
50
51
52 def get_required_params(params: Iterable[Parameter]) -> List[Parameter]:
53 return [p for p in params if p.required]
54
55
56 def get_param_label(param: Parameter) -> str:
57 if param.param_type_name == 'argument':
58 return param.human_readable_name
59 return sorted(param.opts, key=len)[-1]
60
61
62 def join_param_labels(params: Iterable[Parameter], sep: str = ', ') -> str:
63 return sep.join(get_param_label(p) for p in params)
64
65
66 def join_with_and(strings: Sequence[str], sep: str = ', ') -> str:
67 if not strings:
68 return ''
69 if len(strings) == 1:
70 return strings[0]
71 return sep.join(strings[:-1]) + ' and ' + strings[-1]
72
73
74 def format_param(param: Parameter) -> str:
75 if isinstance(param, Argument):
76 return param.human_readable_name
77
78 opts = param.opts
79 if len(opts) == 1:
80 return opts[0]
81
82 # Use the first long opt as the main/canonical one, put all others
83 # opts between parenthesis as aliases, long opts first, then short ones
84 long_opts = [opt for opt in opts if opt.startswith("--")]
85 short_opts = [opt for opt in opts if not opt.startswith("--")]
86 main_opt = long_opts[0]
87 aliases = ", ".join(long_opts[1:] + short_opts)
88 return f'{main_opt} ({aliases})'
89
90
91 def format_param_list(param_list: Iterable[Parameter], indent: int = 2) -> str:
92 lines = map(format_param, param_list)
93 indentation = ' ' * indent
94 return ''.join(indentation + line + '\n'
95 for line in lines)
96
97
98 def param_label_by_name(ctx: Any, name: str) -> str:
99 return get_param_label(ctx.command.get_param_by_name(name))
100
101
102 def get_param_labels(ctx: Any, param_names: Iterable[str]) -> List[str]:
103 params = ctx.command.get_params_by_name(param_names)
104 return [get_param_label(param) for param in params]
105
106
107 def param_value_by_name(ctx: Context, name: str) -> Any:
108 try:
109 return ctx.params[name]
110 except KeyError:
111 raise KeyError(f'"{name}" is not the name of a CLI parameter')