Skip to content

Instantly share code, notes, and snippets.

@ericholscher
Created November 10, 2009 21:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ericholscher/231300 to your computer and use it in GitHub Desktop.
Save ericholscher/231300 to your computer and use it in GitHub Desktop.
diff_settings.py
import os
import sys
import difflib
from pprint import pformat
settings1 = sys.argv[1]
settings2 = sys.argv[2]
def get_diff_msg(first, second, fromfile='First', tofile='Second'):
"""Return a unified diff between first and second."""
# Force inputs to iterables for diffing.
# use pformat instead of str or repr to output dicts and such
# in a stable order for comparison.
if isinstance(first, (tuple, list)):
first = [pformat(d) for d in first]
elif isinstance(first, dict):
first = ["%s:%s" % (pformat(key), pformat(val)) for key,val in first.iteritems()]
else:
first = [pformat(first)]
if isinstance(second, (tuple, list)):
second = [pformat(d) for d in second]
elif isinstance(second, dict):
second = ["%s:%s" % (pformat(key), pformat(val)) for key,val in second.iteritems()]
else:
second = [pformat(second)]
diff = difflib.ndiff(first, second)
# Add line endings.
return '\n' + ''.join([d + '\n' for d in diff])
KEYNOTFOUND = '<KEYNOTFOUND>' # KeyNotFound for dictDiff
def dict_diff(first, second):
""" Return a dict of keys that differ with another config object. If a value is
not found in one fo the configs, it will be represented by KEYNOTFOUND.
@param first: Fist dictionary to diff.
@param second: Second dicationary to diff.
@return diff: Dict of Key => (first.val, second.val)
"""
diff = {}
# Check all keys in first dict
for key in first.keys():
if (not second.has_key(key)):
diff[key] = (first[key], KEYNOTFOUND)
elif (first[key] != second[key]):
diff[key] = (first[key], second[key])
# Check all keys in second dict to find missing
for key in second.keys():
if (not first.has_key(key)):
diff[key] = (KEYNOTFOUND, second[key])
return diff
def get_settings(conf):
settings_dict = {}
for setting in conf.settings.get_all_members():
if setting.upper() == setting and 'APPS' not in setting:
settings_dict[setting] = getattr(conf.settings, setting)
return settings_dict
os.environ['DJANGO_SETTINGS_MODULE'] = settings1
from django import conf
old_settings = get_settings(conf)
os.environ['DJANGO_SETTINGS_MODULE'] = settings2
reload(conf)
new_settings = get_settings(conf)
d = dict_diff(new_settings, old_settings)
for key, val in d.items():
print key, get_diff_msg(val[0], val[1])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment