Last active
December 12, 2019 15:06
-
-
Save noonedeadpunk/0d0aa5cec249a011b824762f5d4363b6 to your computer and use it in GitHub Desktop.
Compare config files with configparser
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import configparser | |
import itertools | |
import sys | |
from pprint import pprint | |
def compare_confs(src, dst): | |
src_conf = configparser.RawConfigParser() | |
dst_conf = configparser.RawConfigParser() | |
src_conf.read(src) | |
dst_conf.read(dst) | |
src_sections = set(src_conf.sections()) | |
dest_sections = set(dst_conf.sections()) | |
sections_diff = compare_sections(src_sections, dest_sections) | |
options_diff_list = [ | |
result | |
for section in src_sections & dest_sections | |
for result in compare_options(src_conf[section], dst_conf[section]) | |
] | |
options_diff = set(itertools.chain.from_iterable(options_diff_list)) | |
return sections_diff | options_diff | |
def compare_options(src, dst): | |
src_opts = set([opts for opts in src]) | |
dst_opts = set([opts for opts in dst]) | |
src_opts_diff = src_opts - dst_opts | |
dst_opts_diff = dst_opts - src_opts | |
result = [] | |
for item in src_opts_diff: | |
result.append("Destination config is missing '%s' option" % item) | |
for item in dst_opts_diff: | |
result.append("Source config is missing '%s' option" % item) | |
for item in src_opts & dst_opts: | |
if src.get(item) != dst.get(item): | |
result.append("Option '%s' differs between configs" % item) | |
yield result | |
def compare_sections(src, dst): | |
src_diff = src - dst | |
dst_diff = dst - src | |
result = set() | |
for item in src_diff: | |
result.add("Destination config is missing '%s' section" % item) | |
for item in dst_diff: | |
result.add("Source config is missing '%s' section" % item) | |
return result | |
def main(): | |
if len(sys.argv) < 3: | |
print( | |
"Provide source and destination configs with positionall arguments" | |
) | |
raise SystemExit(1) | |
source = sys.argv[1] | |
dest = sys.argv[2] | |
diff = compare_confs(source, dest) | |
pprint(diff) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment