forked from canonical/checkbox
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
154 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,49 @@ | ||
import yaml | ||
|
||
from plainbox.impl.secure.origin import Origin | ||
|
||
class LoaderWithMarks(yaml.Loader): | ||
def construct_mapping(self, node, deep=False): | ||
mapping = super().construct_mapping(node, deep=deep) | ||
# attach line number for tracking the offset | ||
for key_node, value_node in node.value: | ||
key = self.construct_object(key_node, deep=deep) | ||
if isinstance(key, str): | ||
mapping[key] = (self.construct_object(value_node, deep=deep), | ||
value_node.start_mark.line) | ||
return mapping | ||
|
||
class YamlRecord: | ||
""" | ||
Checkbox unit definitions encoded in YAML. | ||
""" | ||
|
||
def __init__(self, data, origin=None, field_offset_map=None): | ||
self.data = data | ||
self.raw_data = data | ||
self.field_offset_map = field_offset_map | ||
if origin is None: | ||
origin = Origin.get_caller_origin() | ||
self.origin = origin | ||
|
||
def dump(self): | ||
return yaml.dump(self.data) | ||
|
||
def gen_yaml_records(stream, data_cls=dict, source=None): | ||
if not isinstance(stream, str): | ||
stream = open(stream.name).read() | ||
|
||
|
||
records_with_mappings = yaml.load(stream, Loader=LoaderWithMarks) | ||
for record in records_with_mappings: | ||
data = dict() | ||
field_offsets = dict() | ||
for key, (value, offset) in record.items(): | ||
data[key] = value.strip() | ||
field_offsets[key] = offset | ||
origin = Origin(source, None, None) | ||
yield YamlRecord(data, origin, field_offsets) | ||
|
||
def load_yaml_records(stream, data_cls=dict, source=None): | ||
return list(gen_yaml_records(stream, data_cls, source)) | ||
|