Debian Codegraph @

lib/ansible/module_utils/common/text/formatters.py

raw
1 # -*- coding: utf-8 -*-
2 # Copyright (c) 2019 Ansible Project
3 # Simplified BSD License (see licenses/simplified_bsd.txt or https://opensource.org/licenses/BSD-2-Clause)
4
5 from __future__ import annotations
6
7 import re
8
9 from ansible.module_utils._internal import _no_six
10
11 SIZE_RANGES = {
12 'Y': 1 << 80,
13 'Z': 1 << 70,
14 'E': 1 << 60,
15 'P': 1 << 50,
16 'T': 1 << 40,
17 'G': 1 << 30,
18 'M': 1 << 20,
19 'K': 1 << 10,
20 'B': 1,
21 }
22
23 VALID_UNITS = {
24 'B': (('byte', 'B'), ('bit', 'b')),
25 'K': (('kilobyte', 'KB'), ('kilobit', 'Kb')),
26 'M': (('megabyte', 'MB'), ('megabit', 'Mb')),
27 'G': (('gigabyte', 'GB'), ('gigabit', 'Gb')),
28 'T': (('terabyte', 'TB'), ('terabit', 'Tb')),
29 'P': (('petabyte', 'PB'), ('petabit', 'Pb')),
30 'E': (('exabyte', 'EB'), ('exabit', 'Eb')),
31 'Z': (('zetabyte', 'ZB'), ('zetabit', 'Zb')),
32 'Y': (('yottabyte', 'YB'), ('yottabit', 'Yb')),
33 }
34
35
36 def lenient_lowercase(lst):
37 """Lowercase elements of a list.
38
39 If an element is not a string, pass it through untouched.
40 """
41 lowered = []
42 for value in lst:
43 try:
44 lowered.append(value.lower())
45 except AttributeError:
46 lowered.append(value)
47 return lowered
48
49
50 def human_to_bytes(number, default_unit=None, isbits=False):
51 """Convert number in string format into bytes (ex: '2K' => 2048) or using unit argument.
52
53 example: human_to_bytes('10M') <=> human_to_bytes(10, 'M').
54
55 When isbits is False (default), converts bytes from a human-readable format to integer.
56 example: human_to_bytes('1MB') returns 1048576 (int).
57 The function expects 'B' (uppercase) as a byte identifier passed
58 as a part of 'name' param string or 'unit', e.g. 'MB'/'KB'/etc.
59 (except when the identifier is single 'b', it is perceived as a byte identifier too).
60 if 'Mb'/'Kb'/... is passed, the ValueError will be rased.
61
62 When isbits is True, converts bits from a human-readable format to integer.
63 example: human_to_bytes('1Mb', isbits=True) returns 1048576 (int) -
64 string bits representation was passed and return as a number or bits.
65 The function expects 'b' (lowercase) as a bit identifier, e.g. 'Mb'/'Kb'/etc.
66 if 'MB'/'KB'/... is passed, the ValueError will be rased.
67 """
68 m = re.search(r'^([0-9]*\.?[0-9]+)(?:\s*([A-Za-z]+))?\s*$', str(number))
69
70 if m is None:
71 raise ValueError("human_to_bytes() can't interpret following string: %s" % str(number))
72 try:
73 num = float(m.group(1))
74 except Exception:
75 raise ValueError("human_to_bytes() can't interpret following number: %s (original input string: %s)" % (m.group(1), number))
76
77 unit = m.group(2)
78 if unit is None:
79 unit = default_unit
80
81 if unit is None:
82 # No unit given, returning raw number
83 return int(round(num))
84 range_key = unit[0].upper()
85 try:
86 limit = SIZE_RANGES[range_key]
87 except Exception:
88 raise ValueError("human_to_bytes() failed to convert %s (unit = %s). The suffix must be one of %s" % (number, unit, ", ".join(SIZE_RANGES.keys())))
89
90 # default value
91 unit_class = 'B'
92 unit_class_name = 'byte'
93 # handling bits case
94 if isbits:
95 unit_class = 'b'
96 unit_class_name = 'bit'
97 # check unit value if more than one character (KB, MB)
98 if len(unit) > 1:
99 expect_message = 'expect %s%s or %s' % (range_key, unit_class, range_key)
100 if range_key == 'B':
101 expect_message = 'expect %s or %s' % (unit_class, unit_class_name)
102 unit_group = VALID_UNITS.get(range_key, None)
103 if unit_group is None:
104 raise ValueError(f"human_to_bytes() can't interpret a valid unit for {range_key}")
105 isbits_flag = 1 if isbits else 0
106 if unit.lower() == unit_group[isbits_flag][0]:
107 pass
108 elif unit != unit_group[isbits_flag][1]:
109 raise ValueError("human_to_bytes() failed to convert %s. Value is not a valid string (%s)" % (number, expect_message))
110
111 return int(round(num * limit))
112
113
114 def bytes_to_human(size, isbits=False, unit=None):
115 base = 'Bytes'
116 if isbits:
117 base = 'bits'
118 suffix = ''
119
120 for suffix, limit in sorted(SIZE_RANGES.items(), key=lambda item: -item[1]):
121 if (unit is None and size >= limit) or unit is not None and unit.upper() == suffix[0]:
122 break
123
124 if limit != 1:
125 suffix += base[0]
126 else:
127 suffix = base
128
129 return '%.2f %s' % (size / limit, suffix)
130
131
132 def __getattr__(importable_name):
133 return _no_six.deprecate(importable_name, __name__, "iteritems")