Don't try to re-wrap things that already have newlines

When a string is found (and about to be output) that
already has newlines in it (say it was read in previously)
we shouldn't be trying to reformat that string when
writing it back out; so avoid doing this by searching for
existing newlines and not re-wrapping things when they
already exist.

Change-Id: Ic310677314172f46b360c90197539993eb5bcc99
This commit is contained in:
Joshua Harlow 2016-06-13 11:40:31 -07:00
parent bd888c1f4f
commit 167e228d27
1 changed files with 11 additions and 2 deletions

View File

@ -20,6 +20,12 @@ import yaml
import yamlordereddictloader
def _has_newline(data):
if "\n" in data or "\r" in data:
return True
return False
class PrettySafeDumper(yaml.dumper.SafeDumper):
"""Yaml dumper that tries to not alter original formats (to much)."""
@ -49,10 +55,13 @@ class PrettySafeDumper(yaml.dumper.SafeDumper):
def represent_string(self, data):
if isinstance(data, six.binary_type):
data = data.decode(self.BINARY_ENCODING)
if len(data) > self.MAX_LINE_LENGTH:
# NOTE(harlowja): Try to nicely format it unless its already been
# formatted by someone else, which we check by seeing if newlines
# already exist and assume the person knew what they were doing...
if len(data) > self.MAX_LINE_LENGTH and not _has_newline(data):
data = textwrap.fill(data)
style = "plain"
if "\n" in data:
if _has_newline(data):
style = "|"
return yaml.representer.ScalarNode('tag:yaml.org,2002:str',
data, style=style)