Make updateini.py sexy

This commit is contained in:
Keith Mitchell
2012-03-12 13:01:12 -07:00
parent 4070cf7390
commit 8d7e6a4a81

View File

@@ -1,35 +1,31 @@
#!/usr/bin/env python
import re, sys
line_rx = re.compile('\A([-_a-zA-Z0-9 ]*[-_a-zA-Z0-9]+)\s*=\s*(.*)')
def parse_line(line):
m = line_rx.match(line)
if m:
return m.groups()
from ConfigParser import RawConfigParser as Parser
from ConfigParser import MissingSectionHeaderError
from StringIO import StringIO
import sys
def main(source_ini, update_ini):
#read in update file
update_parts = {}
for line in open(update_ini):
m = parse_line(line)
if m:
update_parts[m[0]] = m[1]
#pass through main file
m = None
for line in open(source_ini):
line = line.strip()
m = parse_line(line)
if m and update_parts.has_key(m[0]):
line = '%s = %s' % (m[0], update_parts[m[0]])
print line
parser = Parser()
# parser.read() will "fail" silently if the file is
# not found; use open() and parser.readfp() to fail
# on missing (or unreadable, etc.) file
parser.readfp(open(source_ini))
with open(update_ini) as f:
updates = f.read()
try:
# Existing *.update files don't include section
# headers; inject a [DEFAULT] header if the parsing
# fails
parser.readfp(StringIO(updates))
except MissingSectionHeaderError:
updates = "[DEFAULT]\n" + updates
parser.readfp(StringIO(updates))
parser.write(sys.stdout)
if __name__ == '__main__':
args = sys.argv
if len(args) != 3:
print 'usage: iniupdate.py [source] [update]'
print 'usage: %s [source] [update]' % sys.argv[0]
sys.exit(1)
else:
main(sys.argv[1], sys.argv[2])