Debian Codegraph @

strictyaml/yamlpointer.py

raw
1 from strictyaml.ruamel.comments import CommentedSeq, CommentedMap
2 from strictyaml.ruamel import dump, RoundTripDumper
3 from copy import deepcopy
4 import sys
5
6
7 if sys.version_info[0] == 3:
8 unicode = str
9
10
11 class YAMLPointer(object):
12 """
13 A sequence of indexes/keys that look up a specific chunk of a YAML document.
14
15 A YAML pointer can point to a key, value, item in a sequence or part of a string
16 in a value or item.
17 """
18
19 def __init__(self):
20 self._indices = []
21
22 @property
23 def last_index(self):
24 assert self.is_index()
25 return self._indices[-1][1]
26
27 @property
28 def last_val(self):
29 assert self.is_val()
30 return self._indices[-1][1]
31
32 @property
33 def last_strictkey(self):
34 assert self.is_key() or self.is_val()
35 return self._indices[-1][1][1]
36
37 @property
38 def last_regularkey(self):
39 assert self.is_key() or self.is_val()
40 return self._indices[-1][1][0]
41
42 def val(self, regularkey, strictkey):
43 assert isinstance(regularkey, (str, unicode)), type(regularkey)
44 assert isinstance(strictkey, (str, unicode)), type(strictkey)
45 new_location = deepcopy(self)
46 new_location._indices.append(("val", (regularkey, strictkey)))
47 return new_location
48
49 def is_val(self):
50 return self._indices[-1][0] == "val"
51
52 def key(self, regularkey, strictkey):
53 assert isinstance(regularkey, (str, unicode)), type(regularkey)
54 assert isinstance(strictkey, (str, unicode)), type(strictkey)
55 new_location = deepcopy(self)
56 new_location._indices.append(("key", (regularkey, strictkey)))
57 return new_location
58
59 def is_key(self):
60 return self._indices[-1][0] == "key"
61
62 def index(self, index):
63 new_location = deepcopy(self)
64 new_location._indices.append(("index", index))
65 return new_location
66
67 def is_index(self):
68 return self._indices[-1][0] == "index"
69
70 def textslice(self, start, end):
71 new_location = deepcopy(self)
72 new_location._indices.append(("textslice", (start, end)))
73 return new_location
74
75 def is_textslice(self):
76 return self._indices[-1][0] == "textslice"
77
78 def parent(self):
79 new_location = deepcopy(self)
80 new_location._indices = new_location._indices[:-1]
81 return new_location
82
83 def make_child_of(self, pointer):
84 new_indices = deepcopy(pointer._indices)
85 new_indices.extend(self._indices)
86
87 def _slice_segment(self, indices, segment, include_selected):
88 slicedpart = deepcopy(segment)
89
90 if len(indices) == 0 and not include_selected:
91 slicedpart = None
92 else:
93 if len(indices) > 0:
94 if indices[0][0] in ("val", "key"):
95 index = indices[0][1][0]
96 else:
97 index = indices[0][1]
98 start_popping = False
99
100 if isinstance(segment, CommentedMap):
101 for key in segment.keys():
102 if start_popping:
103 slicedpart.pop(key)
104
105 if index == key:
106 start_popping = True
107
108 if isinstance(segment[index], (CommentedSeq, CommentedMap)):
109 slicedpart[index] = self._slice_segment(
110 indices[1:],
111 segment[index],
112 include_selected=include_selected,
113 )
114
115 if not include_selected and len(indices) == 1:
116 slicedpart.pop(key)
117
118 if isinstance(segment, CommentedSeq):
119 for i, value in enumerate(segment):
120 if start_popping:
121 del slicedpart[-1]
122
123 if i == index:
124 start_popping = True
125
126 if isinstance(segment[index], (CommentedSeq, CommentedMap)):
127 slicedpart[index] = self._slice_segment(
128 indices[1:],
129 segment[index],
130 include_selected=include_selected,
131 )
132
133 if not include_selected and len(indices) == 1:
134 slicedpart.pop(index)
135
136 return slicedpart
137
138 def start_line(self, document):
139 slicedpart = self._slice_segment(
140 self._indices, document, include_selected=False
141 )
142
143 if slicedpart is None or slicedpart == {} or slicedpart == []:
144 return 1
145 else:
146 return (
147 len(dump(slicedpart, Dumper=RoundTripDumper).rstrip().split("\n")) + 1
148 )
149
150 def end_line(self, document):
151 slicedpart = self._slice_segment(self._indices, document, include_selected=True)
152 return len(dump(slicedpart, Dumper=RoundTripDumper).rstrip().split("\n"))
153
154 def lines(self, document):
155 return "\n".join(
156 dump(document, Dumper=RoundTripDumper).split("\n")[
157 self.start_line(document) - 1 : self.end_line(document)
158 ]
159 )
160
161 def lines_before(self, document, how_many):
162 return "\n".join(
163 dump(document, Dumper=RoundTripDumper).split("\n")[
164 self.start_line(document) - 1 - how_many : self.start_line(document) - 1
165 ]
166 )
167
168 def lines_after(self, document, how_many):
169 return "\n".join(
170 dump(document, Dumper=RoundTripDumper).split("\n")[
171 self.end_line(document) : self.end_line(document) + how_many
172 ]
173 )
174
175 def _individual_get(self, segment, index_type, index, strictdoc):
176 if index_type == "val":
177 for key, value in segment.items():
178 if key == index[0]:
179 return value
180 if hasattr(key, "text"):
181 if key.text == index[0]:
182 return value
183 raise Exception("Invalid state")
184 elif index_type == "index":
185 return segment[index]
186 elif index_type == "textslice":
187 return segment[index[0] : index[1]]
188 elif index_type == "key":
189 return index[1] if strictdoc else index[0]
190 else:
191 raise Exception("Invalid state")
192
193 def get(self, document, strictdoc=False):
194 segment = document
195 for index_type, index in self._indices:
196 segment = self._individual_get(segment, index_type, index, strictdoc)
197 return segment
198
199 def set(self, src_obj, src_attr, new_ruamel, strictdoc=False):
200 """Since set() needs to overwrite what this pointer points to, it
201 affects the parent object. Therefore, rather than taking "document"
202 as get(), it takes the object which holds the document and the name
203 of the property which is the document.
204 """
205 obj_last = src_obj
206 key_last = src_attr
207 r = getattr(src_obj, src_attr)
208 for index_type, index in self._indices:
209 obj_last = r
210 if index_type == "val":
211 key_last = index[1] if strictdoc else index[0]
212 r = r[key_last]
213 elif index_type == "index":
214 key_last = index
215 r = r[key_last]
216 elif index_type == "textslice":
217 key_last = None
218 r = r[index[0] : index[1]]
219 elif index_type == "key":
220 key_last = None
221 r = index[1] if strictdoc else index[0]
222 else:
223 raise RuntimeError("Invalid state")
224 if obj_last is src_obj:
225 # Starts with an attribute set
226 setattr(src_obj, src_attr, new_ruamel)
227 elif key_last is not None:
228 # Others are item set
229 if hasattr(obj_last, "_value"):
230 # Only want to overwrite value, do NOT re-validate schema...
231 obj_last._value[key_last] = new_ruamel
232 else:
233 obj_last[key_last] = new_ruamel
234 else:
235 raise NotImplementedError("invalid key, cannot set")
236
237 def __repr__(self):
238 return "<YAMLPointer: {0}>".format(self._indices)