Debian Codegraph @

strictyaml/utils.py

raw
1 from strictyaml.ruamel.comments import CommentedSeq, CommentedMap
2 from strictyaml import exceptions
3 from re import compile
4 import decimal
5 import sys
6
7 if sys.version_info[:2] > (3, 4):
8 from collections.abc import Iterable
9 else:
10 from collections import Iterable
11
12 if sys.version_info[0] == 3:
13 unicode = str
14
15
16 def flatten(items):
17 """
18 Yield items from any nested iterable.
19
20 >>> list(flatten([[1, 2, 3], [[4, 5], 6, 7]]))
21 [1, 2, 3, 4, 5, 6, 7]
22 """
23 for x in items:
24 if isinstance(x, Iterable) and not isinstance(x, (str, bytes)):
25 for sub_x in flatten(x):
26 yield sub_x
27 else:
28 yield x
29
30
31 def has_number_type(value):
32 """
33 Is a value a number or a non-number?
34
35 >>> has_number_type(3.5)
36 True
37
38 >>> has_number_type(3)
39 True
40
41 >>> has_number_type(decimal.Decimal("3.5"))
42 True
43
44 >>> has_number_type("3.5")
45 False
46
47 >>> has_number_type(True)
48 False
49 """
50 return isinstance(value, (int, float, decimal.Decimal)) and not isinstance(
51 value, bool
52 )
53
54
55 def is_string(value):
56 """
57 Python 2/3 compatible way of checking if a value is a string.
58 """
59 return isinstance(value, unicode) or str(type(value)) in (
60 "<type 'unicode'>",
61 "<type 'str'>",
62 "<class 'str'>",
63 )
64
65
66 def is_integer(value):
67 """
68 Is a string a string of an integer?
69
70 >>> is_integer("4")
71 True
72
73 >>> is_integer("4_000")
74 True
75
76 >>> is_integer("3.4")
77 False
78 """
79 return compile(r"^[-+]?[0-9_]+$").match(value) is not None
80
81
82 def is_hexadecimal(value):
83 """
84 Is a string a string of a hexademcial integer?
85
86 >>> is_hexadecimal("0xa1")
87 True
88
89 >>> is_hexadecimal("0XA1")
90 True
91
92 >>> is_hexadecimal("0xa1x")
93 False
94
95 >>> is_hexadecimal("xa1")
96 False
97
98 >>> is_hexadecimal("a1")
99 False
100
101 >>> is_hexadecimal("1")
102 False
103 """
104 return compile(r"^0[xX]+[a-fA-F0-9]+$").match(value) is not None
105
106
107 def is_decimal(value):
108 """
109 Is a string a decimal?
110
111 >>> is_decimal("4")
112 True
113
114 >>> is_decimal("4_000")
115 True
116
117 >>> is_decimal("3.5")
118 True
119
120 >>> is_decimal("4.")
121 True
122
123 >>> is_decimal("4.000_001")
124 True
125
126 >>> is_decimal("blah")
127 False
128 """
129 return (
130 compile(r"^[-+]?[0-9_]*(\.[0-9_]*)?([eE][-+]?[0-9_]+)?$").match(value)
131 is not None
132 )
133
134
135 def is_infinity(value):
136 """
137 Is string a valid representation for positive or negative infinity?
138
139 Valid formats are:
140 [+/-]inf, [+/-]INF, [+/-]Inf, [+/-].inf, [+/-].INF and [+/-].Inf
141
142 >>> is_infinity(".inf")
143 True
144
145 >>> is_infinity("+.INF")
146 True
147
148 >>> is_infinity("-.Inf")
149 True
150
151 >>> is_infinity("Inf")
152 True
153
154 >>> is_infinity("INF")
155 True
156
157 >>> is_infinity("-INF")
158 True
159
160 >>> is_infinity("infinitesimal")
161 False
162 """
163 return compile(r"^[-+]?\.?(?:inf|Inf|INF)$").match(value) is not None
164
165
166 def is_not_a_number(value):
167 """
168 Is string a valid representation for 'not a number'?
169
170 Valid formats are: nan, NaN, NAN, .nan, .NaN, .NAN.
171
172 >>> is_not_a_number(".nan")
173 True
174
175 >>> is_not_a_number(".NaN")
176 True
177
178 >>> is_not_a_number("NAN")
179 True
180
181 >>> is_not_a_number("nan")
182 True
183
184 >>> is_not_a_number("nanan")
185 False
186
187 >>> is_not_a_number("1e5")
188 False
189 """
190 return compile(r"^\.?(?:nan|NaN|NAN)$").match(value) is not None
191
192
193 def comma_separated_positions(text):
194 """
195 Start and end positions of comma separated text items.
196
197 Commas and trailing spaces should not be included.
198
199 >>> comma_separated_positions("ABC, 2,3")
200 [(0, 3), (5, 6), (7, 8)]
201 """
202 chunks = []
203 start = 0
204 end = 0
205 for item in text.split(","):
206 space_increment = 1 if item[0] == " " else 0
207 start += space_increment # Is there a space after the comma to ignore? ", "
208 end += len(item.lstrip()) + space_increment
209 chunks.append((start, end))
210 start += len(item.lstrip()) + 1 # Plus comma
211 end = start
212 return chunks
213
214
215 def ruamel_structure(data, validator=None):
216 """
217 Take dicts and lists and return a strictyaml.ruamel style
218 structure of CommentedMaps, CommentedSeqs and
219 data.
220
221 If a validator is presented and the type is unknown,
222 it is checked against the validator to see if it will
223 turn it back in to YAML.
224 """
225 if isinstance(data, dict):
226 if len(data) == 0:
227 raise exceptions.CannotBuildDocumentsFromEmptyDictOrList(
228 "Document must be built with non-empty dicts and lists"
229 )
230 return CommentedMap(
231 [
232 (ruamel_structure(key), ruamel_structure(value))
233 for key, value in data.items()
234 ]
235 )
236 elif isinstance(data, list):
237 if len(data) == 0:
238 raise exceptions.CannotBuildDocumentsFromEmptyDictOrList(
239 "Document must be built with non-empty dicts and lists"
240 )
241 return CommentedSeq([ruamel_structure(item) for item in data])
242 elif isinstance(data, bool):
243 return "yes" if data else "no"
244 elif isinstance(data, (int, float)):
245 return str(data)
246 else:
247 if not is_string(data):
248 raise exceptions.CannotBuildDocumentFromInvalidData(
249 (
250 "Document must be built from a combination of:\n"
251 "string, int, float, bool or nonempty list/dict\n\n"
252 "Instead, found variable with type '{}': '{}'"
253 ).format(type(data).__name__, data)
254 )
255 return data