def __init__(self, value, validator=None): if isinstance(value, YAMLChunk): self._chunk = value self._validator = validator if value.is_scalar(): self._value = validator.validate(value) if isinstance(self._value, YAML): self._value = self._value._value self._text = value.contents else: self._value = ( value.strictparsed()._value if isinstance(value.strictparsed(), YAML) else value.strictparsed() ) self._text = None elif isinstance(value, YAML): self._chunk = value._chunk self._validator = validator if validator is not None else value.validator self._value = value._value self._text = value._text else: self._chunk = YAMLChunk(value) self._validator = validator self._value = value self._text = unicode(value) self._selected_validator = None assert not isinstance(self._value, YAML)
def validate(self, chunk): found_keys = set() items = chunk.expect_mapping() for key, value in items: yaml_key = self._key_validator(key) if yaml_key.scalar not in self._validator_dict.keys(): key.expecting_but_found( u"while parsing a mapping", u"unexpected key not in schema '{0}'".format( unicode(yaml_key.scalar)), ) value.process(self._validator_dict[yaml_key.scalar](value)) key.process(yaml_key) chunk.add_key_association(key.contents, yaml_key.data) found_keys.add(yaml_key.scalar) for default_key, default_data in self._defaults.items(): if default_key not in [key.contents for key, _ in items]: key_chunk = YAMLChunk(default_key) yaml_key = self._key_validator(key_chunk) strictindex = yaml_key.data value_validator = self._validator_dict[default_key] new_value = value_validator( YAMLChunk(value_validator.to_yaml(default_data))) forked_chunk = chunk.fork(strictindex, new_value) forked_chunk.val(strictindex).process(new_value) updated_value = value_validator(forked_chunk.val(strictindex)) updated_value._chunk.make_child_of(chunk.val(strictindex)) # marked_up = new_value.as_marked_up() # chunk.contents[chunk.ruamelindex(strictindex)] = marked_up chunk.add_key_association(default_key, strictindex) sp = chunk.strictparsed() if isinstance(sp, YAML): # Do not trigger __setitem__ validation at this point, as # we just ran the validator, and # representation.py:revalidate() doesn't overwrite the # _validator property until after all values are checked, # which leads to an exception being raised if it is # re-checked. sp._value[yaml_key] = updated_value else: sp[yaml_key] = updated_value if not set(self._required_keys).issubset(found_keys): chunk.while_parsing_found( u"a mapping", u"required key(s) '{0}' not found".format("', '".join( sorted( list(set( self._required_keys).difference(found_keys))))), )
def __setitem__(self, index, value): strictindex = self._strictindex(index) try: value_validator = self._value[strictindex].validator except KeyError: # TODO: What if value isn't a YAML object? value_validator = value.validator new_value = (value_validator(value._chunk) if isinstance(value, YAML) else value_validator( YAMLChunk(value_validator.to_yaml(value)))) # Fork the value forked_chunk = self._chunk.fork(strictindex, new_value) # Validate and attach to current structure if self.is_mapping(): updated_value = value_validator(forked_chunk.val(strictindex)) updated_value._chunk.make_child_of(self._chunk.val(strictindex)) else: updated_value = value_validator(forked_chunk.index(strictindex)) updated_value._chunk.make_child_of(self._chunk.index(strictindex)) marked_up = new_value.as_marked_up() # So that the nicer x: | style of text is used instead of # x: "text\nacross\nlines" if isinstance(marked_up, (str, unicode)): if u"\n" in marked_up: marked_up = PreservedScalarString(marked_up) self._chunk.contents[self._chunk.ruamelindex(strictindex)] = marked_up self._value[YAML(forked_chunk.ruamelindex(strictindex)) if self. is_mapping() else forked_chunk.ruamelindex(strictindex )] = new_value
def generic_load( yaml_string, schema=None, label=u"<unicode string>", allow_flow_style=False ): if not utils.is_string(yaml_string): raise TypeError("StrictYAML can only read a string of valid YAML.") # We manufacture a class that has the label we want DynamicStrictYAMLLoader = type( "DynamicStrictYAMLLoader", (StrictYAMLLoader,), {"label": label, "allow_flow_style": allow_flow_style}, ) try: document = ruamelyaml.load(yaml_string, Loader=DynamicStrictYAMLLoader) except ruamelyaml.YAMLError as parse_error: if parse_error.context_mark is not None: parse_error.context_mark.name = label if parse_error.problem_mark is not None: parse_error.problem_mark.name = label raise parse_error # Document is just a (string, int, etc.) if type(document) not in (CommentedMap, CommentedSeq): document = yaml_string if schema is None: schema = Any() return schema(YAMLChunk(document, label=label))
def load(yaml_string, schema=None, label=u"<unicode string>"): """ Parse the first YAML document in a string and produce corresponding YAML object. """ if str(type(yaml_string)) not in ("<type 'unicode'>", "<type 'str'>", "<class 'str'>"): raise TypeError("StrictYAML can only read a string of valid YAML.") # We manufacture a class that has the label we want DynamicStrictYAMLLoader = type('DynamicStrictYAMLLoader', (StrictYAMLLoader, ), {"label": label}) try: document = ruamelyaml.load(yaml_string, Loader=DynamicStrictYAMLLoader) except ruamelyaml.YAMLError as parse_error: if parse_error.context_mark is not None: parse_error.context_mark.name = label if parse_error.problem_mark is not None: parse_error.problem_mark.name = label raise parse_error # Document is just a (string, int, etc.) if type(document) not in (CommentedMap, CommentedSeq): document = yaml_string if schema is None: schema = Any() return schema(YAMLChunk(document, label=label))
def __setitem__(self, index, value): existing_validator = self._value[index].validator if isinstance(value, YAML): new_value = existing_validator(value._chunk) else: new_value = existing_validator(YAMLChunk(ruamel_structure(value))) # First validate against forked document proposed_chunk = self._chunk.fork() proposed_chunk.contents[index] = new_value.as_marked_up() proposed_chunk.strictparsed()[index] = deepcopy( new_value.as_marked_up()) if self.is_mapping(): updated_value = existing_validator(proposed_chunk.val(index)) updated_value._chunk.make_child_of(self._chunk.val(index)) else: updated_value = existing_validator(proposed_chunk.index(index)) updated_value._chunk.make_child_of(self._chunk.index(index)) # If validation succeeds, update for real marked_up = new_value.as_marked_up() # So that the nicer x: | style of text is used instead of # x: "text\nacross\nlines" if isinstance(marked_up, (str, unicode)): if u"\n" in marked_up: marked_up = PreservedScalarString(marked_up) self._chunk.contents[index] = marked_up self._value[YAML(index) if self.is_mapping() else index] = new_value
def as_document(data, schema=None, label=u"<unicode string>"): """ Translate dicts/lists and scalar (string/bool/float/int/etc.) values into a YAML object which can be dumped out. """ if schema is None: schema = Any() return schema(YAMLChunk(schema.to_yaml(data), label=label))
def validate(self, chunk): found_keys = set() items = chunk.expect_mapping() for key, value in items: yaml_key = self._key_validator(key) if yaml_key.scalar not in self._validator_dict.keys(): key.expecting_but_found( u"while parsing a mapping", u"unexpected key not in schema '{0}'".format( unicode(yaml_key.scalar)), ) value.process(self._validator_dict[yaml_key.scalar](value)) key.process(yaml_key) chunk.add_key_association(key.contents, yaml_key.data) found_keys.add(yaml_key.scalar) for default_key, default_data in self._defaults.items(): if default_key not in [key.contents for key, _ in items]: key_chunk = YAMLChunk(default_key) yaml_key = self._key_validator(key_chunk) strictindex = yaml_key.data value_validator = self._validator_dict[default_key] new_value = value_validator( YAMLChunk(value_validator.to_yaml(default_data))) forked_chunk = chunk.fork(strictindex, new_value) forked_chunk.val(strictindex).process(new_value) updated_value = value_validator(forked_chunk.val(strictindex)) updated_value._chunk.make_child_of(chunk.val(strictindex)) # marked_up = new_value.as_marked_up() # chunk.contents[chunk.ruamelindex(strictindex)] = marked_up chunk.add_key_association(default_key, strictindex) chunk.strictparsed()[yaml_key] = updated_value if not set(self._required_keys).issubset(found_keys): chunk.while_parsing_found( u"a mapping", u"required key(s) '{0}' not found".format("', '".join( sorted( list(set( self._required_keys).difference(found_keys))))), )
def _strictindex(self, index): if isinstance(index, YAML): index = index.data if self.is_mapping(): key_validator = (self._selected_validator.key_validator if self._selected_validator is not None else self._validator.key_validator) return key_validator(YAMLChunk(index)).data else: return index
def _prepostindices(self, index): from strictyaml.compound import MapValidator if isinstance(index, YAML): index = index.data if isinstance(self.validator, MapValidator): strictindex = self.validator.key_validator(YAMLChunk(index)).data preindex = self._chunk.key_association[strictindex] else: preindex = strictindex = index return preindex, strictindex
def __setitem__(self, index, value): strictindex = self._strictindex(index) # Generate nice error messages - first, copy our whole node's data # and use ``to_yaml()`` to determine if the resulting data would # validate our schema. Must replace whole current node to support # complex types, e.g. ``EmptyList() | Seq(Str())``. if isinstance(value, YAML): yaml_value = self._chunk.fork(strictindex, value) new_value = self._validator(yaml_value) else: old_data = self.data if isinstance(old_data, dict): old_data[index] = value elif isinstance(old_data, list): if len(old_data) <= index: raise YAMLSerializationError( "cannot extend list via __setitem__. " "Instead, replace whole list on parent " "node.") old_data[index] = value else: raise NotImplementedError(repr(old_data)) yaml_value = YAMLChunk(self._validator.to_yaml(old_data)) yaml_value_repr = self._validator(yaml_value) # Now that the new content is properly validated, create a valid # chunk with the new information. forked_chunk = self._chunk.fork(strictindex, yaml_value_repr[strictindex]) new_value = self._validator(forked_chunk) # Now, overwrite our chunk and value with the new information. old_chunk = self._chunk # Needed for reference to pre-fork ruamel self._chunk = new_value._chunk self._value = new_value._value self._text = new_value._text self._selected_validator = new_value._selected_validator # Update any parent ruamel links to point to our new chunk. self._chunk.pointer.set(old_chunk, "_ruamelparsed", new_value._chunk.contents) self._chunk.pointer.set(old_chunk, "_strictparsed", self, strictdoc=True) # forked chunk made a deep copy of the original document, but we just # updated pointers in the original document. So, restore our chunk to # pointing at the original document. self._chunk._ruamelparsed = old_chunk._ruamelparsed self._chunk._strictparsed = old_chunk._strictparsed
def __init__(self, value, text=None, chunk=None, validator=None): """ Create a renderable YAML object from data. """ if isinstance(value, YAML): self._value = value._value self._text = value._text self._chunk = value._chunk self._validator = value._validator elif isinstance(value, CommentedMap): self._value = value self._text = None self._validator = validator self._chunk = chunk elif isinstance(value, CommentedSeq): self._value = value self._text = None self._validator = validator self._chunk = chunk else: self._validator = validator self._value = value self._text = unicode(value) if text is None else text self._chunk = YAMLChunk(text) if chunk is None else chunk
def load(yaml_string, schema=None): """ Parse the first YAML document in a string and produce corresponding python object (dict, list, string). """ if str(type(yaml_string)) not in ("<type 'unicode'>", "<type 'str'>", "<class 'str'>"): raise TypeError("StrictYAML can only read a string of valid YAML.") document = ruamelyaml.load(yaml_string, Loader=StrictYAMLLoader) # Document is just a (string, int, etc.) if type(document) not in (CommentedMap, CommentedSeq): document = yaml_string if schema is None: schema = Any() return schema(YAMLChunk(document))
class YAML(object): """ A YAML object represents a block of YAML which can be: * Used to extract parsed data from the YAML (.data). * Used to render to a string of YAML, with comments (.as_yaml()). * Revalidated with a stricter schema (.revalidate(schema)). """ def __init__(self, value, validator=None): if isinstance(value, YAMLChunk): self._chunk = value self._validator = validator if value.is_scalar(): self._value = validator.validate(value) if isinstance(self._value, YAML): self._value = self._value._value self._text = value.contents else: self._value = ( value.strictparsed()._value if isinstance(value.strictparsed(), YAML) else value.strictparsed() ) self._text = None elif isinstance(value, YAML): self._chunk = value._chunk self._validator = validator if validator is not None else value.validator self._value = value._value self._text = value._text else: self._chunk = YAMLChunk(value) self._validator = validator self._value = value self._text = unicode(value) self._selected_validator = None assert not isinstance(self._value, YAML) def __int__(self): # TODO: Raise more sensible exception if not int return int(self._value) def __str__(self): if not self.is_scalar(): raise TypeError( "Cannot cast mapping/sequence '{0}' to string".format(repr(self._value)) ) elif type(self._value) in (unicode, str, int, float, decimal.Decimal): return unicode(self._value) else: raise_type_error( repr(self), "str", "str(yamlobj.data) or str(yamlobj.text)" ) def __unicode__(self): return self.__str__() def revalidate(self, schema): if self.is_scalar(): self._value = schema(self._chunk)._value else: result = schema(self._chunk) self._selected_validator = result._selected_validator self._validator = schema @property def data(self): """ Returns raw data representation of the document or document segment. Mappings are rendered as ordered dicts, sequences as lists and scalar values as whatever the validator returns (int, string, etc.). If no validators are used, scalar values are always returned as strings. """ if isinstance(self._value, CommentedMap): mapping = OrderedDict() for key, value in self._value.items(): mapping[key.data] = value.data return mapping elif isinstance(self._value, CommentedSeq): return [item.data for item in self._value] else: return self._value def as_marked_up(self): """ Returns ruamel.yaml CommentedSeq/CommentedMap objects with comments. This can be fed directly into a ruamel.yaml dumper. """ return self._chunk.contents @property def start_line(self): """ Return line number that the element starts on (including preceding comments). """ return self._chunk.start_line() @property def end_line(self): """ Return line number that the element ends on (including trailing comments). """ return self._chunk.end_line() def lines(self): """ Return a string of the lines which make up the selected line including preceding and trailing comments. """ return self._chunk.lines() def lines_before(self, how_many): return self._chunk.lines_before(how_many) def lines_after(self, how_many): return self._chunk.lines_after(how_many) def __float__(self): return float(self._value) def __repr__(self): return u"YAML({0})".format(self.data) def __bool__(self): if isinstance(self._value, bool): return self._value else: raise_type_error( repr(self), "bool", "bool(yamlobj.data) or bool(yamlobj.text)" ) def _strictindex(self, index): if isinstance(index, YAML): index = index.data if self.is_mapping(): key_validator = ( self._selected_validator.key_validator if self._selected_validator is not None else self._validator.key_validator ) return key_validator(YAMLChunk(index)).data else: return index def __nonzero__(self): return self.__bool__() def __getitem__(self, index): return self._value[self._strictindex(index)] def __setitem__(self, index, value): strictindex = self._strictindex(index) try: value_validator = self._value[strictindex].validator except KeyError: # TODO: What if value isn't a YAML object? value_validator = value.validator new_value = ( value_validator(value._chunk) if isinstance(value, YAML) else value_validator(YAMLChunk(value_validator.to_yaml(value))) ) # Fork the value forked_chunk = self._chunk.fork(strictindex, new_value) # Validate and attach to current structure if self.is_mapping(): updated_value = value_validator(forked_chunk.val(strictindex)) updated_value._chunk.make_child_of(self._chunk.val(strictindex)) else: updated_value = value_validator(forked_chunk.index(strictindex)) updated_value._chunk.make_child_of(self._chunk.index(strictindex)) marked_up = new_value.as_marked_up() # So that the nicer x: | style of text is used instead of # x: "text\nacross\nlines" if isinstance(marked_up, (str, unicode)): if u"\n" in marked_up: marked_up = PreservedScalarString(marked_up) self._chunk.contents[self._chunk.ruamelindex(strictindex)] = marked_up self._value[ YAML(forked_chunk.ruamelindex(strictindex)) if self.is_mapping() else forked_chunk.ruamelindex(strictindex) ] = new_value def __delitem__(self, index): strictindex = self._strictindex(index) del self._value[strictindex] del self._chunk.contents[self._chunk.ruamelindex(strictindex)] def __hash__(self): return hash(self._value) def __len__(self): return len(self._value) def as_yaml(self): """ Render the YAML node and subnodes as string. """ dumped = dump(self.as_marked_up(), Dumper=StrictYAMLDumper, allow_unicode=True) return dumped if sys.version_info[0] == 3 else dumped.decode("utf8") def items(self): if not isinstance(self._value, CommentedMap): raise TypeError("{0} not a mapping, cannot use .items()".format(repr(self))) return [(key, self._value[key]) for key, value in self._value.items()] def keys(self): if not isinstance(self._value, CommentedMap): raise TypeError("{0} not a mapping, cannot use .keys()".format(repr(self))) return [key for key, _ in self._value.items()] def values(self): if not isinstance(self._value, CommentedMap): raise TypeError( "{0} not a mapping, cannot use .values()".format(repr(self)) ) return [self._value[key] for key, value in self._value.items()] def get(self, index, default=None): if not isinstance(self._value, CommentedMap): raise TypeError("{0} not a mapping, cannot use .get()".format(repr(self))) return self._value[index] if index in self._value.keys() else default def __contains__(self, item): if isinstance(self._value, CommentedSeq): return item in self._value elif isinstance(self._value, CommentedMap): return item in self.keys() else: return item in self._value def __iter__(self): if self.is_sequence(): return YAMLIterator(self) elif self.is_mapping(): return YAMLIterator(self.keys()) else: raise TypeError("{0} is a scalar value, cannot iterate.".format(repr(self))) @property def validator(self): return self._validator @property def text(self): """ Return string value of scalar, whatever value it was parsed as. """ if isinstance(self._value, CommentedMap): raise TypeError("{0} is a mapping, has no text value.".format(repr(self))) if isinstance(self._value, CommentedSeq): raise TypeError("{0} is a sequence, has no text value.".format(repr(self))) return self._text def copy(self): return copy(self) def __gt__(self, val): if isinstance(self._value, CommentedMap) or isinstance( self._value, CommentedSeq ): raise TypeError("{0} not an orderable type.".format(repr(self._value))) return self._value > val def __lt__(self, val): if isinstance(self._value, CommentedMap) or isinstance( self._value, CommentedSeq ): raise TypeError("{0} not an orderable type.".format(repr(self._value))) return self._value < val @property def value(self): return self._value def is_mapping(self): return isinstance(self._value, CommentedMap) def is_sequence(self): return isinstance(self._value, CommentedSeq) def is_scalar(self): return not isinstance(self._value, CommentedSeq) and not isinstance( self._value, CommentedMap ) @property def scalar(self): if isinstance(self._value, (CommentedMap, CommentedSeq)): raise TypeError("{0} has no scalar value.".format(repr(self))) return self._value def whole_document(self): return self._chunk.whole_document def __eq__(self, value): return self.data == value def __ne__(self, value): return self.data != value
class YAML(object): """ A YAML object represents a block of YAML which can be: * Used to extract parsed data from the YAML (.data). * Used to render to a string of YAML, with comments (.as_yaml()). * Revalidated with a stricter schema (.revalidate(schema)). """ def __init__(self, value, validator=None): if isinstance(value, YAMLChunk): self._chunk = value self._validator = validator if value.is_scalar(): self._value = validator.validate(value) if isinstance(self._value, YAML): self._value = self._value._value self._text = value.contents else: self._value = ( value.strictparsed()._value if isinstance(value.strictparsed(), YAML) else value.strictparsed() ) self._text = None elif isinstance(value, YAML): self._chunk = value._chunk self._validator = validator if validator is not None else value.validator self._value = value._value self._text = value._text else: self._chunk = YAMLChunk(value) self._validator = validator self._value = value self._text = unicode(value) self._selected_validator = None assert not isinstance(self._value, YAML) def __int__(self): # TODO: Raise more sensible exception if not int return int(self._value) def __str__(self): if not self.is_scalar(): raise TypeError( "Cannot cast mapping/sequence '{0}' to string".format(repr(self._value)) ) elif type(self._value) in (unicode, str, int, float, decimal.Decimal): return unicode(self._value) else: raise_type_error( repr(self), "str", "str(yamlobj.data) or str(yamlobj.text)" ) def __unicode__(self): return self.__str__() def revalidate(self, schema): if self.is_scalar(): self._value = schema(self._chunk)._value else: result = schema(self._chunk) self._selected_validator = result._selected_validator self._validator = schema @property def data(self): """ Returns raw data representation of the document or document segment. Mappings are rendered as ordered dicts, sequences as lists and scalar values as whatever the validator returns (int, string, etc.). If no validators are used, scalar values are always returned as strings. """ if isinstance(self._value, CommentedMap): mapping = OrderedDict() for key, value in self._value.items(): """ #if isinstance(key, YAML): #mapping[key.data] = value.data if isinstance(value, YAML) else value """ mapping[key.data] = value.data return mapping elif isinstance(self._value, CommentedSeq): return [item.data for item in self._value] else: if isinstance(self._value, scalarstring.ScalarString): return str(self._value) return self._value def as_marked_up(self): """ Returns ruamel.yaml CommentedSeq/CommentedMap objects with comments. This can be fed directly into a ruamel.yaml dumper. """ return self._chunk.contents @property def start_line(self): """ Return line number that the element starts on (including preceding comments). """ return self._chunk.start_line() @property def end_line(self): """ Return line number that the element ends on (including trailing comments). """ return self._chunk.end_line() def lines(self): """ Return a string of the lines which make up the selected line including preceding and trailing comments. """ return self._chunk.lines() def lines_before(self, how_many): return self._chunk.lines_before(how_many) def lines_after(self, how_many): return self._chunk.lines_after(how_many) def __float__(self): return float(self._value) def __repr__(self): return u"YAML({0})".format(self.data) def __bool__(self): if isinstance(self._value, bool): return self._value else: raise_type_error( repr(self), "bool", "bool(yamlobj.data) or bool(yamlobj.text)" ) def _strictindex(self, index): if isinstance(index, YAML): index = index.data if self.is_mapping(): key_validator = ( self._selected_validator.key_validator if self._selected_validator is not None else self._validator.key_validator ) return key_validator(YAMLChunk(index)).data else: return index def __nonzero__(self): return self.__bool__() def __getitem__(self, index): return self._value[self._strictindex(index)] def __setitem__(self, index, value): strictindex = self._strictindex(index) # Generate nice error messages - first, copy our whole node's data # and use ``to_yaml()`` to determine if the resulting data would # validate our schema. Must replace whole current node to support # complex types, e.g. ``EmptyList() | Seq(Str())``. if isinstance(value, YAML): yaml_value = self._chunk.fork(strictindex, value) new_value = self._validator(yaml_value) else: old_data = self.data if isinstance(old_data, dict): old_data[index] = value elif isinstance(old_data, list): if len(old_data) <= index: raise YAMLSerializationError( "cannot extend list via __setitem__. " "Instead, replace whole list on parent " "node." ) old_data[index] = value else: raise NotImplementedError(repr(old_data)) yaml_value = YAMLChunk(self._validator.to_yaml(old_data)) yaml_value_repr = self._validator(yaml_value) # Now that the new content is properly validated, create a valid # chunk with the new information. forked_chunk = self._chunk.fork(strictindex, yaml_value_repr[strictindex]) new_value = self._validator(forked_chunk) # Now, overwrite our chunk and value with the new information. old_chunk = self._chunk # Needed for reference to pre-fork ruamel self._chunk = new_value._chunk self._value = new_value._value self._text = new_value._text self._selected_validator = new_value._selected_validator # Update any parent ruamel links to point to our new chunk. self._chunk.pointer.set(old_chunk, "_ruamelparsed", new_value._chunk.contents) self._chunk.pointer.set(old_chunk, "_strictparsed", self, strictdoc=True) # forked chunk made a deep copy of the original document, but we just # updated pointers in the original document. So, restore our chunk to # pointing at the original document. self._chunk._ruamelparsed = old_chunk._ruamelparsed self._chunk._strictparsed = old_chunk._strictparsed def __delitem__(self, index): strictindex = self._strictindex(index) del self._value[strictindex] del self._chunk.contents[self._chunk.ruamelindex(strictindex)] def __hash__(self): return hash(self._value) def __len__(self): return len(self._value) def as_yaml(self): """ Render the YAML node and subnodes as string. """ dumped = dump(self.as_marked_up(), Dumper=StrictYAMLDumper, allow_unicode=True) return dumped if sys.version_info[0] == 3 else dumped.decode("utf8") def items(self): if not isinstance(self._value, CommentedMap): raise TypeError("{0} not a mapping, cannot use .items()".format(repr(self))) return [(key, self._value[key]) for key, value in self._value.items()] def keys(self): if not isinstance(self._value, CommentedMap): raise TypeError("{0} not a mapping, cannot use .keys()".format(repr(self))) return [key for key, _ in self._value.items()] def values(self): if not isinstance(self._value, CommentedMap): raise TypeError( "{0} not a mapping, cannot use .values()".format(repr(self)) ) return [self._value[key] for key, value in self._value.items()] def get(self, index, default=None): if not isinstance(self._value, CommentedMap): raise TypeError("{0} not a mapping, cannot use .get()".format(repr(self))) return self._value[index] if index in self._value.keys() else default def __contains__(self, item): if isinstance(self._value, CommentedSeq): return item in self._value elif isinstance(self._value, CommentedMap): return item in self.keys() else: return item in self._value def __iter__(self): if self.is_sequence(): return YAMLIterator(self) elif self.is_mapping(): return YAMLIterator(self.keys()) else: raise TypeError("{0} is a scalar value, cannot iterate.".format(repr(self))) @property def validator(self): return self._validator @property def text(self): """ Return string value of scalar, whatever value it was parsed as. """ if isinstance(self._value, CommentedMap): raise TypeError("{0} is a mapping, has no text value.".format(repr(self))) if isinstance(self._value, CommentedSeq): raise TypeError("{0} is a sequence, has no text value.".format(repr(self))) return self._text def copy(self): return copy(self) def __gt__(self, val): if isinstance(self._value, CommentedMap) or isinstance( self._value, CommentedSeq ): raise TypeError("{0} not an orderable type.".format(repr(self._value))) return self._value > val def __lt__(self, val): if isinstance(self._value, CommentedMap) or isinstance( self._value, CommentedSeq ): raise TypeError("{0} not an orderable type.".format(repr(self._value))) return self._value < val @property def value(self): return self._value def is_mapping(self): return isinstance(self._value, CommentedMap) def is_sequence(self): return isinstance(self._value, CommentedSeq) def is_scalar(self): return not self.is_mapping() and not self.is_sequence() @property def scalar(self): if isinstance(self._value, (CommentedMap, CommentedSeq)): raise TypeError("{0} has no scalar value.".format(repr(self))) return self._value def whole_document(self): return self._chunk.whole_document def __eq__(self, value): return self.data == value def __ne__(self, value): return self.data != value
class YAML(object): def __init__(self, value, text=None, chunk=None, validator=None): """ Create a renderable YAML object from data. """ if isinstance(value, YAML): self._value = value._value self._text = value._text self._chunk = value._chunk self._validator = value._validator elif isinstance(value, CommentedMap): self._value = value self._text = None self._validator = validator self._chunk = chunk elif isinstance(value, CommentedSeq): self._value = value self._text = None self._validator = validator self._chunk = chunk else: self._validator = validator self._value = value self._text = unicode(value) if text is None else text self._chunk = YAMLChunk(text) if chunk is None else chunk def __int__(self): return int(self._value) def __str__(self): if type(self._value) in (unicode, str, int, float, decimal.Decimal): return unicode(self._value) elif isinstance(self._value, CommentedMap) or isinstance( self._value, CommentedSeq): raise TypeError( "Cannot cast mapping/sequence '{0}' to string".format( repr(self._value))) else: raise_type_error(repr(self), "str", "str(yamlobj.data) or str(yamlobj.text)") def __unicode__(self): return self.__str__() def revalidate(self, schema): if self.is_scalar(): self._value = schema(self._chunk)._value else: schema(self._chunk) @property def data(self): """ Returns raw data representation of the document or document segment. Mappings are rendered as ordered dicts, sequences as lists and scalar values as whatever the validator returns (int, string, etc.). If no validators are used, scalar values are always returned as strings. """ if isinstance(self._value, CommentedMap): mapping = OrderedDict() for key, value in self._value.items(): mapping[key.data] = value.data return mapping elif isinstance(self._value, CommentedSeq): return [item.data for item in self._value] else: return self._value def as_marked_up(self): """ Returns ruamel.yaml CommentedSeq/CommentedMap objects with comments. This can be fed directly into a ruamel.yaml dumper. """ return self._chunk.contents @property def start_line(self): """ Return line number that the element starts on (including preceding comments). """ return self._chunk.start_line() @property def end_line(self): """ Return line number that the element ends on (including trailing comments). """ return self._chunk.end_line() def lines(self): """ Return a string of the lines which make up the selected line including preceding and trailing comments. """ return self._chunk.lines() def lines_before(self, how_many): return self._chunk.lines_before(how_many) def lines_after(self, how_many): return self._chunk.lines_after(how_many) def __float__(self): return float(self._value) def __repr__(self): return u"YAML({0})".format(self.data) def __bool__(self): if isinstance(self._value, bool): return self._value else: raise_type_error(repr(self), "bool", "bool(yamlobj.data) or bool(yamlobj.text)") def __nonzero__(self): return self.__bool__() def __getitem__(self, index): return self._value[index] def __setitem__(self, index, value): existing_validator = self._value[index].validator if isinstance(value, YAML): new_value = existing_validator(value._chunk) else: new_value = existing_validator(YAMLChunk(ruamel_structure(value))) # First validate against forked document proposed_chunk = self._chunk.fork() proposed_chunk.contents[index] = new_value.as_marked_up() proposed_chunk.strictparsed()[index] = deepcopy( new_value.as_marked_up()) if self.is_mapping(): updated_value = existing_validator(proposed_chunk.val(index)) updated_value._chunk.make_child_of(self._chunk.val(index)) else: updated_value = existing_validator(proposed_chunk.index(index)) updated_value._chunk.make_child_of(self._chunk.index(index)) # If validation succeeds, update for real marked_up = new_value.as_marked_up() # So that the nicer x: | style of text is used instead of # x: "text\nacross\nlines" if isinstance(marked_up, (str, unicode)): if u"\n" in marked_up: marked_up = PreservedScalarString(marked_up) self._chunk.contents[index] = marked_up self._value[YAML(index) if self.is_mapping() else index] = new_value def __delitem__(self, index): del self._value[index] def __hash__(self): return hash(self._value) def __len__(self): return len(self._value) def as_yaml(self): """ Render the YAML node and subnodes as string. """ dumped = dump(self.as_marked_up(), Dumper=StrictYAMLDumper, allow_unicode=True) return dumped if sys.version_info[0] == 3 else dumped.decode('utf8') def items(self): if not isinstance(self._value, CommentedMap): raise TypeError("{0} not a mapping, cannot use .items()".format( repr(self))) return [(key, self._value[key]) for key, value in self._value.items()] def keys(self): if not isinstance(self._value, CommentedMap): raise TypeError("{0} not a mapping, cannot use .keys()".format( repr(self))) return [key for key, value in self._value.items()] def values(self): if not isinstance(self._value, CommentedMap): raise TypeError("{0} not a mapping, cannot use .values()".format( repr(self))) return [self._value[key] for key, value in self._value.items()] def get(self, index, default=None): if not isinstance(self._value, CommentedMap): raise TypeError("{0} not a mapping, cannot use .get()".format( repr(self))) return self._value[index] if index in self._value.keys() else default def __contains__(self, item): if isinstance(self._value, CommentedSeq): return item in self._value elif isinstance(self._value, CommentedMap): return item in self.keys() else: return item in self._value @property def validator(self): return self._validator @property def text(self): """ Return string value of scalar, whatever value it was parsed as. """ if isinstance(self._value, CommentedMap): raise TypeError("{0} is a mapping, has no text value.".format( repr(self))) if isinstance(self._value, CommentedSeq): raise TypeError("{0} is a sequence, has no text value.".format( repr(self))) return self._text def copy(self): return copy(self) def __gt__(self, val): if isinstance(self._value, CommentedMap) or isinstance( self._value, CommentedSeq): raise TypeError("{0} not an orderable type.".format( repr(self._value))) return self._value > val def __lt__(self, val): if isinstance(self._value, CommentedMap) or isinstance( self._value, CommentedSeq): raise TypeError("{0} not an orderable type.".format( repr(self._value))) return self._value < val @property def value(self): return self._value def is_mapping(self): return isinstance(self._value, CommentedMap) def is_sequence(self): return isinstance(self._value, CommentedSeq) def is_scalar(self): return not isinstance(self._value, CommentedSeq) \ and not isinstance(self._value, CommentedMap) @property def scalar(self): if isinstance(self._value, (CommentedMap, CommentedSeq)): raise TypeError("{0} has no scalar value.".format(repr(self))) return self._value def document(self): return self._chunk.document def __eq__(self, value): return self.data == value def __ne__(self, value): return self.data != value
class YAML(object): """ A YAML object represents a block of YAML which can be: * Used to extract parsed data from the YAML (.data). * Used to render to a string of YAML, with comments (.as_yaml()). * Revalidated with a stricter schema (.revalidate(schema)). """ def __init__(self, value, validator=None): if isinstance(value, YAMLChunk): self._chunk = value self._validator = validator if value.is_scalar(): self._value = validator.validate(value) if isinstance(self._value, YAML): self._value = self._value._value self._text = value.contents else: self._value = (value.strictparsed()._value if isinstance( value.strictparsed(), YAML) else value.strictparsed()) self._text = None elif isinstance(value, YAML): self._chunk = value._chunk self._validator = validator if validator is not None else value.validator self._value = value._value self._text = value._text else: self._chunk = YAMLChunk(value) self._validator = validator self._value = value self._text = unicode(value) self._selected_validator = None assert not isinstance(self._value, YAML) def __int__(self): # TODO: Raise more sensible exception if not int return int(self._value) def __str__(self): if not self.is_scalar(): raise TypeError( "Cannot cast mapping/sequence '{0}' to string".format( repr(self._value))) elif type(self._value) in (unicode, str, int, float, decimal.Decimal): return unicode(self._value) else: raise_type_error(repr(self), "str", "str(yamlobj.data) or str(yamlobj.text)") def __unicode__(self): return self.__str__() def revalidate(self, schema): if self.is_scalar(): self._value = schema(self._chunk)._value else: result = schema(self._chunk) self._selected_validator = result._selected_validator self._validator = schema @property def data(self): """ Returns raw data representation of the document or document segment. Mappings are rendered as ordered dicts, sequences as lists and scalar values as whatever the validator returns (int, string, etc.). If no validators are used, scalar values are always returned as strings. """ if isinstance(self._value, CommentedMap): mapping = OrderedDict() for key, value in self._value.items(): mapping[key.data] = value.data return mapping elif isinstance(self._value, CommentedSeq): return [item.data for item in self._value] else: return self._value def as_marked_up(self): """ Returns ruamel.yaml CommentedSeq/CommentedMap objects with comments. This can be fed directly into a ruamel.yaml dumper. """ return self._chunk.contents @property def start_line(self): """ Return line number that the element starts on (including preceding comments). """ return self._chunk.start_line() @property def end_line(self): """ Return line number that the element ends on (including trailing comments). """ return self._chunk.end_line() def lines(self): """ Return a string of the lines which make up the selected line including preceding and trailing comments. """ return self._chunk.lines() def lines_before(self, how_many): return self._chunk.lines_before(how_many) def lines_after(self, how_many): return self._chunk.lines_after(how_many) def __float__(self): return float(self._value) def __repr__(self): return u"YAML({0})".format(self.data) def __bool__(self): if isinstance(self._value, bool): return self._value else: raise_type_error(repr(self), "bool", "bool(yamlobj.data) or bool(yamlobj.text)") def _strictindex(self, index): if isinstance(index, YAML): index = index.data if self.is_mapping(): key_validator = (self._selected_validator.key_validator if self._selected_validator is not None else self._validator.key_validator) return key_validator(YAMLChunk(index)).data else: return index def __nonzero__(self): return self.__bool__() def __getitem__(self, index): return self._value[self._strictindex(index)] def __setitem__(self, index, value): strictindex = self._strictindex(index) try: value_validator = self._value[strictindex].validator except KeyError: # TODO: What if value isn't a YAML object? value_validator = value.validator new_value = (value_validator(value._chunk) if isinstance(value, YAML) else value_validator( YAMLChunk(value_validator.to_yaml(value)))) # Fork the value forked_chunk = self._chunk.fork(strictindex, new_value) # Validate and attach to current structure if self.is_mapping(): updated_value = value_validator(forked_chunk.val(strictindex)) updated_value._chunk.make_child_of(self._chunk.val(strictindex)) else: updated_value = value_validator(forked_chunk.index(strictindex)) updated_value._chunk.make_child_of(self._chunk.index(strictindex)) marked_up = new_value.as_marked_up() # So that the nicer x: | style of text is used instead of # x: "text\nacross\nlines" if isinstance(marked_up, (str, unicode)): if u"\n" in marked_up: marked_up = PreservedScalarString(marked_up) self._chunk.contents[self._chunk.ruamelindex(strictindex)] = marked_up self._value[YAML(forked_chunk.ruamelindex(strictindex)) if self. is_mapping() else forked_chunk.ruamelindex(strictindex )] = new_value def __delitem__(self, index): strictindex = self._strictindex(index) del self._value[strictindex] del self._chunk.contents[self._chunk.ruamelindex(strictindex)] def __hash__(self): return hash(self._value) def __len__(self): return len(self._value) def as_yaml(self): """ Render the YAML node and subnodes as string. """ dumped = dump(self.as_marked_up(), Dumper=StrictYAMLDumper, allow_unicode=True) return dumped if sys.version_info[0] == 3 else dumped.decode("utf8") def items(self): if not isinstance(self._value, CommentedMap): raise TypeError("{0} not a mapping, cannot use .items()".format( repr(self))) return [(key, self._value[key]) for key, value in self._value.items()] def keys(self): if not isinstance(self._value, CommentedMap): raise TypeError("{0} not a mapping, cannot use .keys()".format( repr(self))) return [key for key, _ in self._value.items()] def values(self): if not isinstance(self._value, CommentedMap): raise TypeError("{0} not a mapping, cannot use .values()".format( repr(self))) return [self._value[key] for key, value in self._value.items()] def get(self, index, default=None): if not isinstance(self._value, CommentedMap): raise TypeError("{0} not a mapping, cannot use .get()".format( repr(self))) return self._value[index] if index in self._value.keys() else default def __contains__(self, item): if isinstance(self._value, CommentedSeq): return item in self._value elif isinstance(self._value, CommentedMap): return item in self.keys() else: return item in self._value def __iter__(self): if self.is_sequence(): return YAMLIterator(self) elif self.is_mapping(): return YAMLIterator(self.keys()) else: raise TypeError("{0} is a scalar value, cannot iterate.".format( repr(self))) @property def validator(self): return self._validator @property def text(self): """ Return string value of scalar, whatever value it was parsed as. """ if isinstance(self._value, CommentedMap): raise TypeError("{0} is a mapping, has no text value.".format( repr(self))) if isinstance(self._value, CommentedSeq): raise TypeError("{0} is a sequence, has no text value.".format( repr(self))) return self._text def copy(self): return copy(self) def __gt__(self, val): if isinstance(self._value, CommentedMap) or isinstance( self._value, CommentedSeq): raise TypeError("{0} not an orderable type.".format( repr(self._value))) return self._value > val def __lt__(self, val): if isinstance(self._value, CommentedMap) or isinstance( self._value, CommentedSeq): raise TypeError("{0} not an orderable type.".format( repr(self._value))) return self._value < val @property def value(self): return self._value def is_mapping(self): return isinstance(self._value, CommentedMap) def is_sequence(self): return isinstance(self._value, CommentedSeq) def is_scalar(self): return not isinstance(self._value, CommentedSeq) and not isinstance( self._value, CommentedMap) @property def scalar(self): if isinstance(self._value, (CommentedMap, CommentedSeq)): raise TypeError("{0} has no scalar value.".format(repr(self))) return self._value def whole_document(self): return self._chunk.whole_document def __eq__(self, value): return self.data == value def __ne__(self, value): return self.data != value