diff options
author | Matěj Cepl <mcepl@redhat.com> | 2011-11-29 19:50:16 +0100 |
---|---|---|
committer | Matěj Cepl <mcepl@redhat.com> | 2011-11-29 19:52:39 +0100 |
commit | ccc7c6a3b36a3c7d096b12e62e63334374dd897c (patch) | |
tree | 53374df591efa222586321d040fdac647443a67c /json_diff.py | |
parent | 2f56bd116a0b29aef3d3475ad4d70d6935a41727 (diff) | |
download | json_diff-ccc7c6a3b36a3c7d096b12e62e63334374dd897c.tar.gz |
Make scripts pylint and PEP8 compliant.1.1.0
New version 1.1.0.
Diffstat (limited to 'json_diff.py')
-rwxr-xr-x | json_diff.py | 72 |
1 files changed, 45 insertions, 27 deletions
diff --git a/json_diff.py b/json_diff.py index 4522ceb..8322fd9 100755 --- a/json_diff.py +++ b/json_diff.py @@ -8,19 +8,20 @@ Copyright (c) 2011, Red Hat Corp. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of -the Software, and to permit persons to whom the Software is furnished to do so, -subject to the following conditions: +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS -FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR -COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER -IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. """ try: import json @@ -30,11 +31,12 @@ import logging from optparse import OptionParser __author__ = "Matěj Cepl" -__version__ = "0.9.2" +__version__ = "1.1.0" import locale -logging.basicConfig(format='%(levelname)s:%(funcName)s:%(message)s', level=logging.INFO) +logging.basicConfig(format='%(levelname)s:%(funcName)s:%(message)s', + level=logging.INFO) STYLE_MAP = { u"_append": u"append_class", @@ -69,6 +71,7 @@ td { %s """ + def is_scalar(value): """ Primitive version, relying on the fact that JSON cannot @@ -76,12 +79,17 @@ def is_scalar(value): """ return not isinstance(value, (list, tuple, dict)) + class HTMLFormatter(object): + """Special formatter to generate HTML page from diff dict. + """ def __init__(self, diff_object): self.diff = diff_object def _generate_page(self, in_dict, title="json_diff result"): + """A shell function to start recursive self._format_dict. + """ out_str = out_str_template % (title, title, self._format_dict(in_dict)) out_str += u"""</table> @@ -90,6 +98,7 @@ class HTMLFormatter(object): return out_str def _format_item(self, item, index, typch, level=0): + """Function to unify formatting on the leaf node level.""" level_str = (u"<td>" + LEVEL_INDENT + u"</td>") * level if is_scalar(item): @@ -102,13 +111,15 @@ class HTMLFormatter(object): return out_str.strip() def _format_array(self, diff_array, typch, level=0): + """Recursively generate HTML for two different arrays.""" out_str = [] for index in range(len(diff_array)): - out_str.append(self._format_item(diff_array[index], index, typch, level)) + out_str.append(self._format_item(diff_array[index], index, typch, + level)) return ("".join(out_str)).strip() - # doesn't have level and neither concept of it, much def _format_dict(self, diff_dict, typch="unknown_change", level=0): + """Recursively generate HTML for two different dicts.""" out_str = [] # For all STYLE_MAP keys which are present in diff_dict for typechange in set(diff_dict.keys()) & INTERNAL_KEYS: @@ -125,9 +136,12 @@ class HTMLFormatter(object): def __unicode__(self): return self._generate_page(self.diff) + class BadJSONError(ValueError): + """Module should use its own exceptions.""" pass + class Comparator(object): """ Main workhorse, the object itself @@ -139,7 +153,8 @@ class Comparator(object): try: self.obj1 = json.load(fn1) except (TypeError, OverflowError, ValueError), exc: - raise BadJSONError("Cannot decode object from JSON.\n%s" % unicode(exc)) + raise BadJSONError("Cannot decode object from JSON.\n%s" % + unicode(exc)) if fn2: try: self.obj2 = json.load(fn2) @@ -203,6 +218,7 @@ class Comparator(object): return out_result def _compare_elements(self, old, new): + """Unify decision making on the leaf node level.""" res = None # We want to go through the tree post-order if isinstance(old, dict): @@ -228,15 +244,16 @@ class Comparator(object): return res - def _compare_scalars(self, old, new, name=None): """ - Be careful with the result of this function. Negative answer from this function - is really None, not False, so deciding based on the return value like in + Be careful with the result of this function. Negative answer from this + function is really None, not False, so deciding based on the return + value like in if self._compare_scalars(...): - leads to wrong answer (it should be if self._compare_scalars(...) is not None:) + leads to wrong answer (it should be + if self._compare_scalars(...) is not None:) """ # Explicitly excluded arguments if old != new: @@ -246,12 +263,12 @@ class Comparator(object): def _compare_arrays(self, old_arr, new_arr): """ - simpler version of compare_dicts; just an internal method, becase + simpler version of compare_dicts; just an internal method, because it could never be called from outside. We have it guaranteed that both new_arr and old_arr are of type list. """ - inters = min(len(old_arr), len(new_arr)) # this is the smaller length + inters = min(len(old_arr), len(new_arr)) # this is the smaller length result = { u"_append": {}, @@ -322,8 +339,8 @@ if __name__ == "__main__": description = "Generates diff between two JSON files." parser = OptionParser(usage=usage) parser.add_option("-x", "--exclude", - action="append", dest="exclude", metavar="ATTR", default=[], - help="attributes which should be ignored when comparing") + action="append", dest="exclude", metavar="ATTR", default=[], + help="attributes which should be ignored when comparing") parser.add_option("-i", "--include", action="append", dest="include", metavar="ATTR", default=[], help="attributes which should be exclusively used when comparing") @@ -331,19 +348,20 @@ if __name__ == "__main__": action="store_true", dest="ignore_append", metavar="BOOL", default=False, help="ignore appended keys") parser.add_option("-H", "--HTML", - action="store_true", dest="HTMLoutput", metavar="BOOL", default=False, - help="program should output to HTML report") + action="store_true", dest="HTMLoutput", metavar="BOOL", default=False, + help="program should output to HTML report") (options, args) = parser.parse_args() if len(args) != 2: - parser.error("Script requires two positional arguments, names for old and new JSON file.") + parser.error("Script requires two positional arguments, " + \ + "names for old and new JSON file.") diff = Comparator(open(args[0]), open(args[1]), options) if options.HTMLoutput: diff_res = diff.compare_dicts() - # we want to hardcode UTF-8 here, because that's what's in <meta> element - # of the generated HTML + # we want to hardcode UTF-8 here, because that's what's + # in <meta> element of the generated HTML print(unicode(HTMLFormatter(diff_res)).encode("utf-8")) else: outs = json.dumps(diff.compare_dicts(), indent=4, ensure_ascii=False) - print(outs.encode(locale.getpreferredencoding()))
\ No newline at end of file + print(outs.encode(locale.getpreferredencoding())) |