-
Karl-Hermann Wieners authoredKarl-Hermann Wieners authored
compconfig 2.38 KiB
#! /usr/bin/env python3
'''\
Compare the given config files, return information shared by all files
$Id$
'''
from __future__ import print_function
import sys
import io
import argparse
import package_info
import re
from feedback import die
from configobj import Section
from expconfig import ConfigObj
# Extract overlap of two config objects to new config object
def removeNotShared(c1, c2):
for k in c1:
if k not in c2:
del c1[k]
else:
if type(c1[k]) is Section:
removeNotShared(c1[k],c2[k])
if not c1[k].keys():
del c1[k]
else:
for comm in c1.comments[k]:
if comm not in c2.comments[k]:
c1.comments[k].remove(comm)
#
# Main routine
#
# Check command line
command_line = argparse.ArgumentParser(description=__doc__.split('\n', 1)[0])
command_line.add_argument('--indent-string', default=' ', help='set indent string [%(default)s]')
command_line.add_argument('--inline-comments' , '-c', action='store_true',
help='compact white space before inline comments'
' (BETA)')
command_line.add_argument('--trailing-space' , '-t', action='store_true',
help='remove white space at end of lines')
command_line.add_argument('config1')
command_line.add_argument('config2')
command_line.add_argument('configs', nargs='*', metavar='config',
help='original configuration file names')
command_line.add_argument('-V', '--version', action='version',
version=package_info.version)
args = command_line.parse_args()
# File handling
try:
config_files = [args.config1, args.config2] + args.configs
config_data = list()
for i, config_file in enumerate(config_files):
config_data.append(ConfigObj(config_file,
file_error=True, write_empty_values=True))
except IOError as error:
die(error.message)
# Compare configs
for i in range(1,len(config_files)):
removeNotShared(config_data[0],config_data[i])
# Ready to roll out
lines = io.BytesIO()
config_data[0].write(lines)
lines.seek(0)
for line in io.TextIOWrapper(lines):
if args.inline_comments: line = re.sub(r' = (.*?) #', r' = \1 #', line)
if args.trailing_space:
print(line.rstrip())
else:
print(line, end='')