Debian Codegraph @

strictyaml/yamllocation.py

raw
1 from strictyaml.ruamel.comments import CommentedSeq, CommentedMap
2 from strictyaml.exceptions import YAMLValidationError
3 from strictyaml.yamlpointer import YAMLPointer
4 from strictyaml import utils
5 from copy import deepcopy, copy
6 import sys
7
8 if sys.version_info[0] == 3:
9 unicode = str
10
11
12 class YAMLChunk(object):
13 """
14 Represents a section of the document with references to the ruamel
15 parsed document and the strictparsed document.
16
17 Most operations done by validators on the document are done using this object.
18
19 Before validation the strictparsed document will be identical to the
20 ruamelparsed document. After it will contain CommentedMaps, CommentedSeqs
21 and YAML objects.
22 """
23
24 def __init__(
25 self,
26 ruamelparsed,
27 pointer=None,
28 label=None,
29 strictparsed=None,
30 key_association=None,
31 ):
32 self._ruamelparsed = ruamelparsed
33 self._strictparsed = (
34 deepcopy(ruamelparsed) if strictparsed is None else strictparsed
35 )
36 self._pointer = pointer if pointer is not None else YAMLPointer()
37 self._label = label
38
39 # Associates strictparsed key names with ruamelparsed key names
40 # E.g. "my-key-name" -> "My Key name"
41 self._key_association = {} if key_association is None else key_association
42
43 def expecting_but_found(self, expecting, found=None):
44 raise YAMLValidationError(
45 expecting,
46 found if found is not None else "found {0}".format(self.found()),
47 self,
48 )
49
50 def while_parsing_found(self, what, found=None):
51 self.expecting_but_found("while parsing {0}".format(what), found=found)
52
53 def process(self, new_item):
54 strictparsed = self.pointer.parent().get(self._strictparsed, strictdoc=True)
55 current_parsed = (
56 strictparsed._value if hasattr(strictparsed, "_value") else strictparsed
57 )
58
59 def actual_key_from_string_key(string_key):
60 if string_key in current_parsed.keys():
61 return string_key
62 else:
63 for key in current_parsed.keys():
64 if hasattr(key, "_value"):
65 if key.text == string_key:
66 return key
67
68 if self.pointer.is_index():
69 current_parsed[self.pointer.last_index] = new_item
70 elif self.pointer.is_val():
71 current_parsed[
72 actual_key_from_string_key(self.pointer.last_regularkey)
73 ] = new_item
74 elif self.pointer.is_key():
75 key = actual_key_from_string_key(self.pointer.last_regularkey)
76 existing_val = current_parsed[key]
77 del current_parsed[key]
78 current_parsed[new_item] = existing_val
79
80 def is_sequence(self):
81 return isinstance(self.contents, CommentedSeq)
82
83 def is_mapping(self):
84 return isinstance(self.contents, CommentedMap)
85
86 def is_scalar(self):
87 return not isinstance(self.contents, (CommentedMap, CommentedSeq))
88
89 def found(self):
90 if self.is_sequence():
91 return "a sequence"
92 elif self.is_mapping():
93 return "a mapping"
94 elif self.contents == "":
95 return "a blank string"
96 elif utils.is_integer(self.contents):
97 return "an arbitrary integer"
98 elif utils.is_decimal(self.contents):
99 return "an arbitrary number"
100 else:
101 return "arbitrary text"
102
103 def expect_sequence(self, expecting="when expecting a sequence"):
104 if not self.is_sequence():
105 self.expecting_but_found(expecting, "found {0}".format(self.found()))
106 return [self.index(i) for i in range(len(self.contents))]
107
108 def expect_mapping(self):
109 if not self.is_mapping():
110 self.expecting_but_found(
111 "when expecting a mapping", "found {0}".format(self.found())
112 )
113 return [
114 (
115 self.key(regular_key, unicode(validated_key)),
116 self.val(unicode(validated_key)),
117 )
118 for (regular_key, validated_key) in zip(
119 self.contents.keys(), self.strictparsed().keys()
120 )
121 ]
122
123 def expect_scalar(self, what):
124 if not self.is_scalar():
125 self.expecting_but_found(
126 "when expecting {0}".format(what), "found {0}".format(self.found())
127 )
128
129 @property
130 def label(self):
131 return self._label
132
133 @property
134 def whole_document(self):
135 return self._ruamelparsed
136
137 @property
138 def pointer(self):
139 return self._pointer
140
141 def fork(self, strictindex, new_value):
142 """
143 Return a chunk referring to the same location in a duplicated document.
144
145 Used when modifying a YAML chunk so that the modification can be validated
146 before changing it.
147 """
148 forked_chunk = YAMLChunk(
149 deepcopy(self._ruamelparsed),
150 pointer=self.pointer,
151 label=self.label,
152 key_association=copy(self._key_association),
153 )
154 if self.is_scalar():
155 # Necessary for e.g. EmptyDict, which reports as a scalar.
156 forked_chunk.pointer.set(forked_chunk, "_ruamelparsed", CommentedMap())
157 forked_chunk.pointer.set(
158 forked_chunk, "_strictparsed", CommentedMap(), strictdoc=True
159 )
160 forked_chunk.contents[self.ruamelindex(strictindex)] = new_value.as_marked_up()
161 forked_chunk.strictparsed()[strictindex] = deepcopy(new_value.as_marked_up())
162 return forked_chunk
163
164 def add_key_association(self, unprocessed_key, processed_key):
165 self._key_association[processed_key] = unprocessed_key
166
167 @property
168 def key_association(self):
169 return self._key_association
170
171 def make_child_of(self, chunk):
172 """
173 Link one YAML chunk to another.
174
175 Used when inserting a chunk of YAML into another chunk.
176 """
177 if self.is_mapping():
178 for key, value in self.contents.items():
179 self.key(key, key).pointer.make_child_of(chunk.pointer)
180 self.val(key).make_child_of(chunk)
181 elif self.is_sequence():
182 for index, item in enumerate(self.contents):
183 self.index(index).make_child_of(chunk)
184 else:
185 self.pointer.make_child_of(chunk.pointer)
186
187 def _select(self, pointer):
188 """
189 Get a YAMLChunk referenced by a pointer.
190 """
191 return YAMLChunk(
192 self._ruamelparsed,
193 pointer=pointer,
194 label=self._label,
195 strictparsed=self._strictparsed,
196 key_association=copy(self._key_association),
197 )
198
199 def index(self, strictindex):
200 """
201 Return a chunk in a sequence referenced by index.
202 """
203 return self._select(self._pointer.index(self.ruamelindex(strictindex)))
204
205 def ruamelindex(self, strictindex):
206 """
207 Get the ruamel equivalent of a strict parsed index.
208
209 E.g. 0 -> 0, 1 -> 2, parsed-via-slugify -> Parsed via slugify
210 """
211 return (
212 self.key_association.get(strictindex, strictindex)
213 if self.is_mapping()
214 else strictindex
215 )
216
217 def val(self, strictkey):
218 """
219 Return a chunk referencing a value in a mapping with the key 'key'.
220 """
221 ruamelkey = self.ruamelindex(strictkey)
222 return self._select(self._pointer.val(ruamelkey, strictkey))
223
224 def key(self, key, strictkey=None):
225 """
226 Return a chunk referencing a key in a mapping with the name 'key'.
227 """
228 return self._select(self._pointer.key(key, strictkey))
229
230 def textslice(self, start, end):
231 """
232 Return a chunk referencing a slice of a scalar text value.
233 """
234 return self._select(self._pointer.textslice(start, end))
235
236 def start_line(self):
237 return self._pointer.start_line(self._ruamelparsed)
238
239 def end_line(self):
240 return self._pointer.end_line(self._ruamelparsed)
241
242 def lines(self):
243 return self._pointer.lines(self._ruamelparsed)
244
245 def lines_before(self, how_many):
246 return self._pointer.lines_before(self._ruamelparsed, how_many)
247
248 def lines_after(self, how_many):
249 return self._pointer.lines_after(self._ruamelparsed, how_many)
250
251 @property
252 def contents(self):
253 return self._pointer.get(self._ruamelparsed)
254
255 def strictparsed(self):
256 return self._pointer.get(self._strictparsed, strictdoc=True)