changeset 130:67f18e72024d

Handle corner cases around quotes in strings
author Stefano Rivera <stefano@rivera.za.net>
date Mon, 02 Sep 2013 17:03:25 +0200
parents 423266f0b9e4
children 568476db7115
files nagslang/tests/test_yamlish.py nagslang/yamlish.py
diffstat 2 files changed, 10 insertions(+), 3 deletions(-) [+]
line wrap: on
line diff
--- a/nagslang/tests/test_yamlish.py	Mon Sep 02 16:57:59 2013 +0200
+++ b/nagslang/tests/test_yamlish.py	Mon Sep 02 17:03:25 2013 +0200
@@ -101,6 +101,9 @@
     def test_numeric(self):
         self.roundtrip({'foo': [1, 2.0, -1, -2.5]})
 
+    def test_inline(self):
+        self.roundtrip([[1, 2, "hi, there' joe", '', "'"], [3, 4]])
+
 
 class TestFromPyYAML(TestRoundTrip):
     def dump_s(self, data):
--- a/nagslang/yamlish.py	Mon Sep 02 16:57:59 2013 +0200
+++ b/nagslang/yamlish.py	Mon Sep 02 17:03:25 2013 +0200
@@ -66,6 +66,10 @@
     def _dump_basestring(self, data, indent):
         if data in ('true', 'false', 'null'):
             data = "'%s'" % data
+        elif "'" in data:
+            data = "'%s'" % data.replace("'", "''")
+        elif data == '':
+            data = "''"
         return [' ' * indent + data]
 
     def _dump_int(self, data, indent):
@@ -87,7 +91,7 @@
     _spaces_re = re.compile(r'^(\s*)(.*)')
     _list_re = re.compile(r'^(-\s+)(.*)')
     _dict_re = re.compile(r'^((?![{[])[^-:]+):\s?(.*)')
-    _inline_list_re = re.compile(r"^([^',]+|''|'.+?[^'](?:'')*')(?:, (.*))?$")
+    _inline_list_re = re.compile(r"^([^',]+|(?:'')+|'.+?[^'](?:'')*')(?:, (.*))?$")
 
     def __init__(self):
         # Stack of (indent level, container object)
@@ -188,13 +192,13 @@
 
     def _parse_value(self, value):
         if value.startswith("'") and value.endswith("'"):
-            return value[1:-1]
+            return value[1:-1].replace("''", "'")
         if value.startswith('[') and value.endswith(']'):
             value = value[1:-1]
             output = []
             while value:
                 m = self._inline_list_re.match(value)
-                assert m
+                assert m, value
                 output.append(self._parse_value(m.group(1)))
                 value = m.group(2)
             return output