From fe98954018fd511a789d837aa91246504cef0cf7 Mon Sep 17 00:00:00 2001 From: Dan White Date: Fri, 24 Feb 2012 16:14:30 -0600 Subject: [PATCH] fpfixup.py: Properly handle quoted strings --- fpfixup.py | 65 ++++++++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 58 insertions(+), 7 deletions(-) diff --git a/fpfixup.py b/fpfixup.py index b20ca65..9f783da 100755 --- a/fpfixup.py +++ b/fpfixup.py @@ -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)) -- 2.25.1