#!/usr/bin/env python
-
import sys
from os.path import basename
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)
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))