fpfixup.py: Properly handle quoted strings
authorDan White <dan@whiteaudio.com>
Fri, 24 Feb 2012 22:14:30 +0000 (16:14 -0600)
committerDan White <dan@whiteaudio.com>
Sat, 25 Feb 2012 13:55:24 +0000 (07:55 -0600)
fpfixup.py

index b20ca65c221b6bad4bcda22c6551a680cbba8947..9f783da3dd6bd356e49c9fe23001bf955bba4db4 100755 (executable)
@@ -1,6 +1,5 @@
 #!/usr/bin/env python
 
-
 import sys
 from os.path import basename
 
@@ -8,6 +7,54 @@ if len(sys.argv) < 2:
     print 'usage: %s file0 [file1 [file2...]]' % sys.argv[0]
     sys.exit(1)
 
+
+class QuotedFields(list):
+    def __init__(self, s, sep=' ', qchar='"'):
+        self.sep = sep
+        self.qchar = qchar
+
+        fields = []
+        inquote = ''
+        quoted = ''
+        f = []
+        for c in s:
+            if c == qchar:
+                if inquote:
+                    inquote = ''
+                else:
+                    inquote = qchar
+                    quoted = qchar
+            elif c == sep and not inquote:
+                fields.append(QuotedString(''.join(f), quoted))
+                inquote = ''
+                quoted = ''
+                f = []
+            else:
+                f.append(c)
+        if inquote:
+            raise Exception('Malformed quoted-string: %s' % s)
+        #last field
+        fields.append(QuotedString(''.join(f), quoted))
+        self.fields = fields
+
+    def __getitem__(self, key):
+        return self.fields[key]
+
+    def __str__(self):
+        return self.sep.join(map(str, self.fields))
+
+
+class QuotedString():
+    def __init__(self, s, qchar=''):
+        self.s = s
+        self.qchar = qchar
+
+    def __str__(self):
+        return self.qchar + self.s + self.qchar
+
+
+
+
 for fpath in sys.argv[1:]:
     fname = basename(fpath)
 
@@ -16,15 +63,19 @@ for fpath in sys.argv[1:]:
     fp.close()
     first = lines[0]
     if first[0:7] == 'Element':
-        istart = first.find('[')
-        iend = first.find(']')
-        fields = first[istart:iend+1].split()
-        if fields[1] == fname or fields[1] == '"'+fname+'"':
+        for cs,ce in [['[', ']'], ['(', ')']]:
+            istart = first.find(cs)
+            iend = first.find(ce)
+            if istart > 0 and iend > 0:
+                break
+
+        fields = QuotedFields(first[istart+1:iend])
+        if fields.fields[1].s == fname:
             print 'Not touching:', fpath
         else:
-            fields[1] = '"%s"' % fname
+            fields.fields[1] = QuotedString(fname, '"')
             #put back the split() trailing newline
-            newfirst = 'Element' + ' '.join(fields) + ']\n'
+            newfirst = 'Element' + cs + str(fields) + ce + '\n'
             lines[0] = newfirst
             print 'Rewriting:', fpath
             open(fpath, 'w').write(''.join(lines))