osc-lib 3.2.0__py3-none-any.whl → 4.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -16,9 +16,12 @@
16
16
  """argparse Custom Actions"""
17
17
 
18
18
  import argparse
19
+ import typing as ty
19
20
 
20
21
  from osc_lib.i18n import _
21
22
 
23
+ _T = ty.TypeVar('_T')
24
+
22
25
 
23
26
  class KeyValueAction(argparse.Action):
24
27
  """A custom action to parse arguments as key=value pairs
@@ -26,7 +29,16 @@ class KeyValueAction(argparse.Action):
26
29
  Ensures that ``dest`` is a dict and values are strings.
27
30
  """
28
31
 
29
- def __call__(self, parser, namespace, values, option_string=None):
32
+ def __call__(
33
+ self,
34
+ parser: argparse.ArgumentParser,
35
+ namespace: argparse.Namespace,
36
+ values: ty.Union[str, ty.Sequence[ty.Any], None],
37
+ option_string: ty.Optional[str] = None,
38
+ ) -> None:
39
+ if not isinstance(values, str):
40
+ raise TypeError('expected str')
41
+
30
42
  # Make sure we have an empty dict rather than None
31
43
  if getattr(namespace, self.dest, None) is None:
32
44
  setattr(namespace, self.dest, {})
@@ -39,7 +51,7 @@ class KeyValueAction(argparse.Action):
39
51
  msg = _("Property key must be specified: %s")
40
52
  raise argparse.ArgumentError(self, msg % str(values))
41
53
  else:
42
- getattr(namespace, self.dest, {}).update([values_list])
54
+ getattr(namespace, self.dest, {}).update(dict([values_list]))
43
55
  else:
44
56
  msg = _("Expected 'key=value' type, but got: %s")
45
57
  raise argparse.ArgumentError(self, msg % str(values))
@@ -51,7 +63,16 @@ class KeyValueAppendAction(argparse.Action):
51
63
  Ensures that ``dest`` is a dict and values are lists of strings.
52
64
  """
53
65
 
54
- def __call__(self, parser, namespace, values, option_string=None):
66
+ def __call__(
67
+ self,
68
+ parser: argparse.ArgumentParser,
69
+ namespace: argparse.Namespace,
70
+ values: ty.Union[str, ty.Sequence[ty.Any], None],
71
+ option_string: ty.Optional[str] = None,
72
+ ) -> None:
73
+ if not isinstance(values, str):
74
+ raise TypeError('expected str')
75
+
55
76
  # Make sure we have an empty dict rather than None
56
77
  if getattr(namespace, self.dest, None) is None:
57
78
  setattr(namespace, self.dest, {})
@@ -86,13 +107,19 @@ class MultiKeyValueAction(argparse.Action):
86
107
 
87
108
  def __init__(
88
109
  self,
89
- option_strings,
90
- dest,
91
- nargs=None,
92
- required_keys=None,
93
- optional_keys=None,
94
- **kwargs,
95
- ):
110
+ option_strings: ty.Sequence[str],
111
+ dest: str,
112
+ nargs: ty.Union[int, str, None] = None,
113
+ required_keys: ty.Optional[ty.Sequence[str]] = None,
114
+ optional_keys: ty.Optional[ty.Sequence[str]] = None,
115
+ const: ty.Optional[_T] = None,
116
+ default: ty.Union[_T, str, None] = None,
117
+ type: ty.Optional[ty.Callable[[str], _T]] = None,
118
+ choices: ty.Optional[ty.Iterable[_T]] = None,
119
+ required: bool = False,
120
+ help: ty.Optional[str] = None,
121
+ metavar: ty.Union[str, ty.Tuple[str, ...], None] = None,
122
+ ) -> None:
96
123
  """Initialize the action object, and parse customized options
97
124
 
98
125
  Required keys and optional keys can be specified when initializing
@@ -106,12 +133,24 @@ class MultiKeyValueAction(argparse.Action):
106
133
  msg = _("Parameter 'nargs' is not allowed, but got %s")
107
134
  raise ValueError(msg % nargs)
108
135
 
109
- super().__init__(option_strings, dest, **kwargs)
136
+ super().__init__(
137
+ option_strings,
138
+ dest,
139
+ nargs=nargs,
140
+ const=const,
141
+ default=default,
142
+ type=type,
143
+ choices=choices,
144
+ required=required,
145
+ help=help,
146
+ metavar=metavar,
147
+ )
110
148
 
111
149
  # required_keys: A list of keys that is required. None by default.
112
150
  if required_keys and not isinstance(required_keys, list):
113
151
  msg = _("'required_keys' must be a list")
114
152
  raise TypeError(msg)
153
+
115
154
  self.required_keys = set(required_keys or [])
116
155
 
117
156
  # optional_keys: A list of keys that is optional. None by default.
@@ -120,7 +159,7 @@ class MultiKeyValueAction(argparse.Action):
120
159
  raise TypeError(msg)
121
160
  self.optional_keys = set(optional_keys or [])
122
161
 
123
- def validate_keys(self, keys):
162
+ def validate_keys(self, keys: ty.Sequence[str]) -> None:
124
163
  """Validate the provided keys.
125
164
 
126
165
  :param keys: A list of keys to validate.
@@ -159,12 +198,21 @@ class MultiKeyValueAction(argparse.Action):
159
198
  },
160
199
  )
161
200
 
162
- def __call__(self, parser, namespace, values, metavar=None):
201
+ def __call__(
202
+ self,
203
+ parser: argparse.ArgumentParser,
204
+ namespace: argparse.Namespace,
205
+ values: ty.Union[str, ty.Sequence[ty.Any], None],
206
+ option_string: ty.Optional[str] = None,
207
+ ) -> None:
208
+ if not isinstance(values, str):
209
+ raise TypeError('expected str')
210
+
163
211
  # Make sure we have an empty list rather than None
164
212
  if getattr(namespace, self.dest, None) is None:
165
213
  setattr(namespace, self.dest, [])
166
214
 
167
- params = {}
215
+ params: ty.Dict[str, str] = {}
168
216
  for kv in values.split(','):
169
217
  # Add value if an assignment else raise ArgumentError
170
218
  if '=' in kv:
@@ -174,7 +222,7 @@ class MultiKeyValueAction(argparse.Action):
174
222
  msg = _("Each property key must be specified: %s")
175
223
  raise argparse.ArgumentError(self, msg % str(kv))
176
224
  else:
177
- params.update([kv_list])
225
+ params.update(dict([kv_list]))
178
226
  else:
179
227
  msg = _(
180
228
  "Expected comma separated 'key=value' pairs, but got: %s"
@@ -196,17 +244,27 @@ class MultiKeyValueCommaAction(MultiKeyValueAction):
196
244
  Ex. key1=val1,val2,key2=val3 => {"key1": "val1,val2", "key2": "val3"}
197
245
  """
198
246
 
199
- def __call__(self, parser, namespace, values, option_string=None):
247
+ def __call__(
248
+ self,
249
+ parser: argparse.ArgumentParser,
250
+ namespace: argparse.Namespace,
251
+ values: ty.Union[str, ty.Sequence[ty.Any], None],
252
+ option_string: ty.Optional[str] = None,
253
+ ) -> None:
200
254
  """Overwrite the __call__ function of MultiKeyValueAction
201
255
 
202
256
  This is done to handle scenarios where we may have comma seperated
203
257
  data as a single value.
204
258
  """
259
+ if not isinstance(values, str):
260
+ msg = _("Invalid key=value pair, non-string value provided: %s")
261
+ raise argparse.ArgumentError(self, msg % str(values))
262
+
205
263
  # Make sure we have an empty list rather than None
206
264
  if getattr(namespace, self.dest, None) is None:
207
265
  setattr(namespace, self.dest, [])
208
266
 
209
- params = {}
267
+ params: ty.Dict[str, str] = {}
210
268
  key = ''
211
269
  for kv in values.split(','):
212
270
  # Add value if an assignment else raise ArgumentError
@@ -217,7 +275,7 @@ class MultiKeyValueCommaAction(MultiKeyValueAction):
217
275
  msg = _("A key must be specified before '=': %s")
218
276
  raise argparse.ArgumentError(self, msg % str(kv))
219
277
  else:
220
- params.update([kv_list])
278
+ params.update(dict([kv_list]))
221
279
  key = kv_list[0]
222
280
  else:
223
281
  # If the ',' split does not have key=value pair, then it
@@ -245,7 +303,17 @@ class RangeAction(argparse.Action):
245
303
  '6:9' sets ``dest`` to (6, 9)
246
304
  """
247
305
 
248
- def __call__(self, parser, namespace, values, option_string=None):
306
+ def __call__(
307
+ self,
308
+ parser: argparse.ArgumentParser,
309
+ namespace: argparse.Namespace,
310
+ values: ty.Union[str, ty.Sequence[ty.Any], None],
311
+ option_string: ty.Optional[str] = None,
312
+ ) -> None:
313
+ if not isinstance(values, str):
314
+ msg = _("Invalid range, non-string value provided")
315
+ raise argparse.ArgumentError(self, msg)
316
+
249
317
  range = values.split(':')
250
318
  if len(range) == 0:
251
319
  # Nothing passed, return a zero default
@@ -279,7 +347,17 @@ class NonNegativeAction(argparse.Action):
279
347
  Ensures the value is >= 0.
280
348
  """
281
349
 
282
- def __call__(self, parser, namespace, values, option_string=None):
350
+ def __call__(
351
+ self,
352
+ parser: argparse.ArgumentParser,
353
+ namespace: argparse.Namespace,
354
+ values: ty.Union[str, ty.Sequence[ty.Any], None],
355
+ option_string: ty.Optional[str] = None,
356
+ ) -> None:
357
+ if not isinstance(values, (str, int, float)):
358
+ msg = _("%s expected a non-negative integer")
359
+ raise argparse.ArgumentError(self, msg % str(option_string))
360
+
283
361
  if int(values) >= 0:
284
362
  setattr(namespace, self.dest, values)
285
363
  else:
osc_lib/clientmanager.py CHANGED
@@ -17,7 +17,12 @@
17
17
 
18
18
  import copy
19
19
  import logging
20
+ import typing as ty
21
+ import warnings
20
22
 
23
+ from keystoneauth1 import access as ksa_access
24
+ from keystoneauth1 import session as ksa_session
25
+ from openstack.config import cloud_region
21
26
  from openstack.config import loader as config # noqa
22
27
  from openstack import connection
23
28
  from oslo_utils import strutils
@@ -25,20 +30,23 @@ from oslo_utils import strutils
25
30
  from osc_lib.api import auth
26
31
  from osc_lib import exceptions
27
32
 
28
-
29
33
  LOG = logging.getLogger(__name__)
30
34
 
31
- PLUGIN_MODULES = []
32
-
33
35
 
34
36
  class ClientCache:
35
37
  """Descriptor class for caching created client handles."""
36
38
 
37
- def __init__(self, factory):
39
+ def __init__(self, factory: ty.Any) -> None:
40
+ warnings.warn(
41
+ "The ClientCache class is deprecated for removal as it has no "
42
+ "users.",
43
+ category=DeprecationWarning,
44
+ )
45
+
38
46
  self.factory = factory
39
47
  self._handle = None
40
48
 
41
- def __get__(self, instance, owner):
49
+ def __get__(self, instance: ty.Any, owner: ty.Any) -> ty.Any:
42
50
  # Tell the ClientManager to login to keystone
43
51
  if self._handle is None:
44
52
  try:
@@ -50,9 +58,15 @@ class ClientCache:
50
58
  return self._handle
51
59
 
52
60
 
61
+ class _PasswordHelper(ty.Protocol):
62
+ def __call__(self, prompt: ty.Optional[str] = None) -> str: ...
63
+
64
+
53
65
  class ClientManager:
54
66
  """Manages access to API clients, including authentication."""
55
67
 
68
+ session: ksa_session.Session
69
+
56
70
  # NOTE(dtroyer): Keep around the auth required state of the _current_
57
71
  # command since ClientManager has no visibility to the
58
72
  # command itself; assume auth is not required.
@@ -60,12 +74,12 @@ class ClientManager:
60
74
 
61
75
  def __init__(
62
76
  self,
63
- cli_options=None,
64
- api_version=None,
65
- pw_func=None,
66
- app_name=None,
67
- app_version=None,
68
- ):
77
+ cli_options: cloud_region.CloudRegion,
78
+ api_version: ty.Optional[ty.Dict[str, str]],
79
+ pw_func: ty.Optional[_PasswordHelper] = None,
80
+ app_name: ty.Optional[str] = None,
81
+ app_version: ty.Optional[str] = None,
82
+ ) -> None:
69
83
  """Set up a ClientManager
70
84
 
71
85
  :param cli_options:
@@ -93,7 +107,6 @@ class ClientManager:
93
107
  self.timing = self._cli_options.timing
94
108
 
95
109
  self._auth_ref = None
96
- self.session = None
97
110
 
98
111
  # self.verify is the Requests-compatible form
99
112
  # self.cacert is the form used by the legacy client libs
@@ -124,7 +137,7 @@ class ClientManager:
124
137
  # prior to dereferrencing auth_ref.
125
138
  self._auth_setup_completed = False
126
139
 
127
- def setup_auth(self):
140
+ def setup_auth(self) -> None:
128
141
  """Set up authentication
129
142
 
130
143
  This is deferred until authentication is actually attempted because
@@ -145,9 +158,11 @@ class ClientManager:
145
158
 
146
159
  # Horrible hack alert...must handle prompt for null password if
147
160
  # password auth is requested.
148
- if self.auth_plugin_name.endswith(
149
- 'password'
150
- ) and not self._cli_options.auth.get('password'):
161
+ if (
162
+ self.auth_plugin_name.endswith('password')
163
+ and not self._cli_options.auth.get('password')
164
+ and self._pw_callback is not None
165
+ ):
151
166
  self._cli_options.auth['password'] = self._pw_callback()
152
167
 
153
168
  LOG.debug('Using auth plugin: %s', self.auth_plugin_name)
@@ -177,7 +192,10 @@ class ClientManager:
177
192
 
178
193
  self._auth_setup_completed = True
179
194
 
180
- def validate_scope(self):
195
+ def validate_scope(self) -> None:
196
+ if not self._auth_ref:
197
+ raise Exception('no authentication information')
198
+
181
199
  if self._auth_ref.project_id is not None:
182
200
  # We already have a project scope.
183
201
  return
@@ -194,7 +212,7 @@ class ClientManager:
194
212
  )
195
213
 
196
214
  @property
197
- def auth_ref(self):
215
+ def auth_ref(self) -> ty.Optional[ksa_access.AccessInfo]:
198
216
  """Dereference will trigger an auth if it hasn't already"""
199
217
  if (
200
218
  not self._auth_required
@@ -208,11 +226,11 @@ class ClientManager:
208
226
  self._auth_ref = self.auth.get_auth_ref(self.session)
209
227
  return self._auth_ref
210
228
 
211
- def _override_for(self, service_type):
229
+ def _override_for(self, service_type: str) -> ty.Optional[str]:
212
230
  key = '{}_endpoint_override'.format(service_type.replace('-', '_'))
213
- return self._cli_options.config.get(key)
231
+ return ty.cast(ty.Optional[str], self._cli_options.config.get(key))
214
232
 
215
- def is_service_available(self, service_type):
233
+ def is_service_available(self, service_type: str) -> ty.Optional[bool]:
216
234
  """Check if a service type is in the current Service Catalog"""
217
235
  # If there is an override, assume the service is available
218
236
  if self._override_for(service_type):
@@ -236,8 +254,11 @@ class ClientManager:
236
254
  return service_available
237
255
 
238
256
  def get_endpoint_for_service_type(
239
- self, service_type, region_name=None, interface='public'
240
- ):
257
+ self,
258
+ service_type: str,
259
+ region_name: ty.Optional[str] = None,
260
+ interface: str = 'public',
261
+ ) -> ty.Optional[str]:
241
262
  """Return the endpoint URL for the service type."""
242
263
  # Overrides take priority unconditionally
243
264
  override = self._override_for(service_type)
@@ -262,5 +283,5 @@ class ClientManager:
262
283
  )
263
284
  return endpoint
264
285
 
265
- def get_configuration(self):
286
+ def get_configuration(self) -> ty.Dict[str, ty.Any]:
266
287
  return copy.deepcopy(self._cli_options.config)
@@ -13,7 +13,9 @@
13
13
  # under the License.
14
14
 
15
15
  import abc
16
+ import argparse
16
17
  import logging
18
+ import typing as ty
17
19
 
18
20
  from cliff import command
19
21
  from cliff import lister
@@ -24,20 +26,27 @@ from osc_lib.i18n import _
24
26
 
25
27
 
26
28
  class CommandMeta(abc.ABCMeta):
27
- def __new__(mcs, name, bases, cls_dict):
28
- if 'log' not in cls_dict:
29
- cls_dict['log'] = logging.getLogger(
30
- cls_dict['__module__'] + '.' + name
29
+ def __new__(
30
+ mcs: ty.Type['CommandMeta'],
31
+ name: str,
32
+ bases: ty.Tuple[ty.Type[ty.Any], ...],
33
+ namespace: ty.Dict[str, ty.Any],
34
+ ) -> 'CommandMeta':
35
+ if 'log' not in namespace:
36
+ namespace['log'] = logging.getLogger(
37
+ namespace['__module__'] + '.' + name
31
38
  )
32
- return super().__new__(mcs, name, bases, cls_dict)
39
+ return super().__new__(mcs, name, bases, namespace)
33
40
 
34
41
 
35
42
  class Command(command.Command, metaclass=CommandMeta):
36
- def run(self, parsed_args):
43
+ log: logging.Logger
44
+
45
+ def run(self, parsed_args: argparse.Namespace) -> int:
37
46
  self.log.debug('run(%s)', parsed_args)
38
47
  return super().run(parsed_args)
39
48
 
40
- def validate_os_beta_command_enabled(self):
49
+ def validate_os_beta_command_enabled(self) -> None:
41
50
  if not self.app.options.os_beta_command:
42
51
  msg = _(
43
52
  'Caution: This is a beta command and subject to '
@@ -46,7 +55,9 @@ class Command(command.Command, metaclass=CommandMeta):
46
55
  )
47
56
  raise exceptions.CommandError(msg)
48
57
 
49
- def deprecated_option_warning(self, old_option, new_option):
58
+ def deprecated_option_warning(
59
+ self, old_option: str, new_option: str
60
+ ) -> None:
50
61
  """Emit a warning for use of a deprecated option"""
51
62
  self.log.warning(
52
63
  _("The %(old)s option is deprecated, please use %(new)s instead.")
osc_lib/command/timing.py CHANGED
@@ -13,13 +13,23 @@
13
13
 
14
14
  """Timing Implementation"""
15
15
 
16
+ import argparse
17
+ import typing as ty
18
+
16
19
  from osc_lib.command import command
17
20
 
21
+ if ty.TYPE_CHECKING:
22
+ from osc_lib import shell
23
+
18
24
 
19
25
  class Timing(command.Lister):
20
26
  """Show timing data"""
21
27
 
22
- def take_action(self, parsed_args):
28
+ app: 'shell.OpenStackShell'
29
+
30
+ def take_action(
31
+ self, parsed_args: argparse.Namespace
32
+ ) -> ty.Tuple[ty.Tuple[str, ...], ty.List[ty.Any]]:
23
33
  column_headers = (
24
34
  'URL',
25
35
  'Seconds',
osc_lib/exceptions.py CHANGED
@@ -15,6 +15,8 @@
15
15
 
16
16
  """Exception definitions."""
17
17
 
18
+ import typing as ty
19
+
18
20
 
19
21
  class CommandError(Exception):
20
22
  pass
@@ -59,7 +61,15 @@ class InvalidValue(Exception):
59
61
  class ClientException(Exception):
60
62
  """The base exception class for all exceptions this library raises."""
61
63
 
62
- def __init__(self, code, message=None, details=None):
64
+ http_status: int
65
+ message: str
66
+
67
+ def __init__(
68
+ self,
69
+ code: ty.Union[int, str],
70
+ message: ty.Optional[str] = None,
71
+ details: ty.Optional[str] = None,
72
+ ):
63
73
  if not isinstance(code, int) and message is None:
64
74
  message = code
65
75
  code = self.http_status
@@ -67,7 +77,7 @@ class ClientException(Exception):
67
77
  self.message = message or self.__class__.message
68
78
  self.details = details
69
79
 
70
- def __str__(self):
80
+ def __str__(self) -> str:
71
81
  return f"{self.message} (HTTP {self.code})"
72
82
 
73
83
 
osc_lib/logs.py CHANGED
@@ -13,19 +13,23 @@
13
13
 
14
14
  """Application logging"""
15
15
 
16
+ import argparse
16
17
  import logging
17
18
  import sys
19
+ import typing as ty
18
20
  import warnings
19
21
 
22
+ from openstack.config import cloud_config
20
23
 
21
- def get_loggers():
24
+
25
+ def get_loggers() -> ty.Dict[str, str]:
22
26
  loggers = {}
23
27
  for logkey in logging.Logger.manager.loggerDict.keys():
24
28
  loggers[logkey] = logging.getLevelName(logging.getLogger(logkey).level)
25
29
  return loggers
26
30
 
27
31
 
28
- def log_level_from_options(options):
32
+ def log_level_from_options(options: argparse.Namespace) -> int:
29
33
  # if --debug, --quiet or --verbose is not specified,
30
34
  # the default logging level is warning
31
35
  log_level = logging.WARNING
@@ -41,7 +45,7 @@ def log_level_from_options(options):
41
45
  return log_level
42
46
 
43
47
 
44
- def log_level_from_string(level_string):
48
+ def log_level_from_string(level_string: str) -> int:
45
49
  log_level = {
46
50
  'critical': logging.CRITICAL,
47
51
  'error': logging.ERROR,
@@ -52,7 +56,7 @@ def log_level_from_string(level_string):
52
56
  return log_level
53
57
 
54
58
 
55
- def log_level_from_config(config):
59
+ def log_level_from_config(config: ty.Mapping[str, ty.Any]) -> int:
56
60
  # Check the command line option
57
61
  verbose_level = config.get('verbose_level')
58
62
  if config.get('debug', False):
@@ -70,7 +74,7 @@ def log_level_from_config(config):
70
74
  return log_level_from_string(verbose_level)
71
75
 
72
76
 
73
- def set_warning_filter(log_level):
77
+ def set_warning_filter(log_level: int) -> None:
74
78
  if log_level == logging.ERROR:
75
79
  warnings.simplefilter("ignore")
76
80
  elif log_level == logging.WARNING:
@@ -89,7 +93,12 @@ class _FileFormatter(logging.Formatter):
89
93
  _LOG_MESSAGE_END = '%(message)s'
90
94
  _LOG_DATE_FORMAT = '%Y-%m-%d %H:%M:%S'
91
95
 
92
- def __init__(self, options=None, config=None, **kwargs):
96
+ def __init__(
97
+ self,
98
+ options: ty.Optional[argparse.Namespace] = None,
99
+ config: ty.Optional[cloud_config.CloudConfig] = None,
100
+ **kwargs: ty.Any,
101
+ ) -> None:
93
102
  context = {}
94
103
  if options:
95
104
  context = {
@@ -117,7 +126,7 @@ class _FileFormatter(logging.Formatter):
117
126
  class LogConfigurator:
118
127
  _CONSOLE_MESSAGE_FORMAT = '%(message)s'
119
128
 
120
- def __init__(self, options):
129
+ def __init__(self, options: argparse.Namespace) -> None:
121
130
  self.root_logger = logging.getLogger('')
122
131
  self.root_logger.setLevel(logging.DEBUG)
123
132
 
@@ -166,7 +175,7 @@ class LogConfigurator:
166
175
  stevedore_log.setLevel(logging.ERROR)
167
176
  iso8601_log.setLevel(logging.ERROR)
168
177
 
169
- def configure(self, cloud_config):
178
+ def configure(self, cloud_config: cloud_config.CloudConfig) -> None:
170
179
  log_level = log_level_from_config(cloud_config.config)
171
180
  set_warning_filter(log_level)
172
181
  self.dump_trace = cloud_config.config.get('debug', self.dump_trace)
osc_lib/py.typed ADDED
File without changes