Skip to content

Commit

Permalink
Fix serializing multi-line yaml strings. Fixes #1
Browse files Browse the repository at this point in the history
  • Loading branch information
bkabrda committed Mar 21, 2017
1 parent efc4b3f commit 200336d
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 0 deletions.
9 changes: 9 additions & 0 deletions anymarkup_core/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -483,6 +483,15 @@ def represent_ordereddict(dumper, data):
values.append(node_item)
return node

def represent_str(dumper, data):
# borrowed from http://stackoverflow.com/a/33300001
if len(data.splitlines()) > 1:
return dumper.represent_scalar('tag:yaml.org,2002:str', data, style='|')
return dumper.represent_scalar('tag:yaml.org,2002:str', data)

if yaml is not None:
yaml.SafeLoader.add_constructor(u'tag:yaml.org,2002:omap', construct_ordereddict)
yaml.SafeDumper.add_representer(collections.OrderedDict, represent_ordereddict)
yaml.SafeDumper.add_representer(str, represent_str)
if six.PY2:
yaml.SafeDumper.add_representer(unicode, represent_str)
5 changes: 5 additions & 0 deletions test/test_serialize.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,3 +75,8 @@ def test_serialize_file_format_overrides_extension(self, tmpdir):
f = os.path.join(str(tmpdir), 'foo.ini')
serialize_file(example_as_dict, f, 'json')
assert parse(self._read_decode(f)) == example_as_dict

def test_parse_and_serialize_yaml_multiline_string(self):
# https://github.com/bkabrda/anymarkup-core/issues/1
inp = b'foo: |-\n line1\n line2\n line3\n'
assert serialize(parse(inp), 'yaml') == inp

0 comments on commit 200336d

Please sign in to comment.