Debian Codegraph @

lib/ansible/utils/helpers.py

raw
1 # (c) 2016, Ansible by Red Hat <[email protected]>
2 #
3 # This file is part of Ansible
4 #
5 # Ansible is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # Ansible is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with Ansible. If not, see <http://www.gnu.org/licenses/>.
17
18 from __future__ import annotations
19
20 from ansible.module_utils._internal import _no_six
21
22
23 def pct_to_int(value, num_items, min_value=1):
24 """
25 Converts a given value to a percentage if specified as "x%",
26 otherwise converts the given value to an integer.
27 """
28 if isinstance(value, str) and value.endswith('%'):
29 value_pct = int(value.replace("%", ""))
30 return int((value_pct / 100.0) * num_items) or min_value
31 else:
32 return int(value)
33
34
35 def object_to_dict(obj, exclude=None):
36 """
37 Converts an object into a dict making the properties into keys, allows excluding certain keys
38 """
39 if exclude is None or not isinstance(exclude, list):
40 exclude = []
41 return dict((key, getattr(obj, key)) for key in dir(obj) if not (key.startswith('_') or key in exclude))
42
43
44 def deduplicate_list(original_list):
45 """
46 Creates a deduplicated list with the order in which each item is first found.
47 """
48 seen = set()
49 return [x for x in original_list if x not in seen and not seen.add(x)]
50
51
52 def __getattr__(importable_name):
53 return _no_six.deprecate(importable_name, __name__, "string_types")