From 897bd5e601f9a602b2e0aef592780c63d3730048 Mon Sep 17 00:00:00 2001 From: Elena ``of Valhalla'' Grandi Date: Fri, 19 Mar 2021 09:34:22 +0100 Subject: Fix converting multiline and long strings to yaml --- lesana/templating.py | 12 ++++++++++-- tests/test_templating.py | 18 +++++++++++++++++- 2 files changed, 27 insertions(+), 3 deletions(-) diff --git a/lesana/templating.py b/lesana/templating.py index 375a6f0..8ff9fcb 100644 --- a/lesana/templating.py +++ b/lesana/templating.py @@ -2,6 +2,7 @@ Custom jinja2 filters and other templating helpers """ import decimal +import io import jinja2 import ruamel.yaml @@ -22,6 +23,13 @@ def to_yaml(data): """ Return the yaml representation of data. """ - if isinstance(data, decimal.Decimal): + if isinstance(data, str): + if len(data) > 75 or "\n" in data: + data = ruamel.yaml.scalarstring.LiteralScalarString(data + "\n") + elif isinstance(data, decimal.Decimal): data = str(data) - return ruamel.yaml.dump(data).strip('...\n').strip() + yaml = ruamel.yaml.YAML() + s_io = io.StringIO() + yaml.dump(data, s_io) + res = s_io.getvalue().strip('...\n').strip() + return res diff --git a/tests/test_templating.py b/tests/test_templating.py index 33889ae..aadcf66 100644 --- a/tests/test_templating.py +++ b/tests/test_templating.py @@ -28,7 +28,16 @@ class testFilters(unittest.TestCase): """ res = templating.to_yaml(s) self.assertIsInstance(res, str) - self.assertIn('"', res) + self.assertTrue(res.startswith('|')) + self.assertIn('\n', res) + + s = """ + short + multiline + """ + res = templating.to_yaml(s) + self.assertIsInstance(res, str) + self.assertTrue(res.startswith('|')) self.assertIn('\n', res) res = templating.to_yaml(10) @@ -37,6 +46,13 @@ class testFilters(unittest.TestCase): res = templating.to_yaml(decimal.Decimal('10.1')) self.assertEqual(res, "'10.1'") + s = "A very long line, but one that has no new lines " \ + + "even if it is definitely longer than a standard " \ + + "80 columns line" + res = templating.to_yaml(s) + self.assertTrue(res.startswith("|\n")) + self.assertNotIn('\n', res.lstrip("|\n")) + if __name__ == '__main__': unittest.main() -- cgit v1.2.3