| 1 |
# THIS FILE IS PART OF THE CYLC WORKFLOW ENGINE. |
| 2 |
# Copyright (C) NIWA & British Crown (Met Office) & Contributors. |
| 3 |
# |
| 4 |
# This program is free software: you can redistribute it and/or modify |
| 5 |
# it under the terms of the GNU General Public License as published by |
| 6 |
# the Free Software Foundation, either version 3 of the License, or |
| 7 |
# (at your option) any later version. |
| 8 |
# |
| 9 |
# This program is distributed in the hope that it will be useful, |
| 10 |
# but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 11 |
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 12 |
# GNU General Public License for more details. |
| 13 |
# |
| 14 |
# You should have received a copy of the GNU General Public License |
| 15 |
# along with this program. If not, see <http://www.gnu.org/licenses/>. |
| 16 |
"""Quick and simple JSON diff util. |
| 17 |
|
| 18 |
Examples: |
| 19 |
>>> bool(Diff({}, {})) |
| 20 |
True |
| 21 |
|
| 22 |
>>> diff = Diff({'a': 1, 'b': 2}, |
| 23 |
... {'b': 3, 'd': 4}) |
| 24 |
>>> bool(diff) |
| 25 |
False |
| 26 |
>>> list(diff.added()) |
| 27 |
[(['d'], 4)] |
| 28 |
>>> list(diff.removed()) |
| 29 |
[(['a'], 1)] |
| 30 |
>>> list(diff.modified()) |
| 31 |
[(['b'], 2, 3)] |
| 32 |
|
| 33 |
>>> diff = Diff({'x': {'y': {'z': 1}}}, |
| 34 |
... {'x': {'y': {'z': 2}}}) |
| 35 |
>>> list(diff.modified()) |
| 36 |
[(['x', 'y', 'z'], 1, 2)] |
| 37 |
|
| 38 |
""" |
| 39 |
import argparse |
| 40 |
import json |
| 41 |
import sys |
| 42 |
from typing import Callable, Optional, Tuple, Type |
| 43 |
|
| 44 |
|
| 45 |
class Diff: |
| 46 |
"""Representation of a diff between two dictionaries.""" |
| 47 |
|
| 48 |
BRACES = { |
| 49 |
dict: ('{', '}'), |
| 50 |
list: ('[', ']') |
| 51 |
} |
| 52 |
|
| 53 |
def __init__(self, this, that, this_name='expected', that_name='got'): |
| 54 |
self.typ, self.changed = self.compute_diff(this, that) |
| 55 |
self.this_name = this_name |
| 56 |
self.that_name = that_name |
| 57 |
|
| 58 |
@classmethod |
| 59 |
def _diff_method( |
| 60 |
cls, this: object, that: object |
| 61 |
) -> Tuple[Optional[Type], Optional[Callable]]: |
| 62 |
if isinstance(this, list) and isinstance(that, list): |
| 63 |
return list, cls.diff_list |
| 64 |
if isinstance(this, dict) and isinstance(that, dict): |
| 65 |
return dict, cls.diff_dict |
| 66 |
return None, None |
| 67 |
|
| 68 |
@classmethod |
| 69 |
def compute_diff(cls, this, that): |
| 70 |
"""Return a list of differences between this and that. |
| 71 |
|
| 72 |
Entries take the form:: |
| 73 |
(symbol, (key, *value)) |
| 74 |
|
| 75 |
Where: |
| 76 |
symbol: |
| 77 |
* ``+``: for items in that but not in this. |
| 78 |
* ``-``: for items in this but not in that. |
| 79 |
* ``?``: for items common to both but with different values. |
| 80 |
key: |
| 81 |
* ``dict``: The key of a key, value pair. |
| 82 |
* ``list``: The index of an element. |
| 83 |
value: |
| 84 |
A tuple containing information about the change: |
| 85 |
|
| 86 |
* ``+ (key, value)`` |
| 87 |
* ``- (key, value)`` |
| 88 |
* ``? (key, this_value, that_value)`` |
| 89 |
|
| 90 |
""" |
| 91 |
typ, meth = cls._diff_method(this, that) |
| 92 |
if meth: |
| 93 |
return typ, meth(this, that) |
| 94 |
raise TypeError('%s Cannot compare %s and %s' % ( |
| 95 |
cls.__name__, type(this), type(that))) |
| 96 |
|
| 97 |
@classmethod |
| 98 |
def diff_list(cls, this, that): |
| 99 |
"""Return differences between two lists. |
| 100 |
|
| 101 |
So unsurprisingly differencing nested lists is actually a little |
| 102 |
tricky so this is the simple and crude method, just mark the items as |
| 103 |
modified rather than going through the mess of working out how the |
| 104 |
lists could fit together. |
| 105 |
|
| 106 |
""" |
| 107 |
changed = [] |
| 108 |
for index, (this_item, that_item) in enumerate(zip(this, that)): |
| 109 |
if this_item != that_item: |
| 110 |
if cls._diff_method(this_item, that_item): |
| 111 |
changed.append((index, cls(this_item, that_item))) |
| 112 |
else: |
| 113 |
changed.append(('?', (index, this_item, that_item))) |
| 114 |
|
| 115 |
if len(this) > len(that): |
| 116 |
symbol = '-' |
| 117 |
additional = this |
| 118 |
else: |
| 119 |
symbol = '+' |
| 120 |
additional = that |
| 121 |
|
| 122 |
for index in range(min(len(this), len(that)), |
| 123 |
max(len(this), len(that))): |
| 124 |
changed.append((symbol, (index, additional[index],))) |
| 125 |
|
| 126 |
return changed |
| 127 |
|
| 128 |
@classmethod |
| 129 |
def diff_dict(cls, this, that): |
| 130 |
"""Return differences between two dictionaries. |
| 131 |
|
| 132 |
As this is a JSON comparison tool ignore the order of keys. |
| 133 |
|
| 134 |
""" |
| 135 |
changed = [] |
| 136 |
for key, value in that.items(): |
| 137 |
if key not in this: |
| 138 |
changed.append(('+', (key, value))) |
| 139 |
elif isinstance(value, (dict, list)): |
| 140 |
if cls._diff_method(this[key], that[key]): |
| 141 |
this[key] = cls(this[key], that[key]) |
| 142 |
if this[key].changed: |
| 143 |
changed.append((key, this[key])) |
| 144 |
else: |
| 145 |
changed.append(('?', (key, this[key], value))) |
| 146 |
elif value != this[key]: |
| 147 |
changed.append(('?', (key, this[key], value))) |
| 148 |
for key, value in this.items(): |
| 149 |
if key not in that: |
| 150 |
changed.append(('-', (key, value))) |
| 151 |
return changed |
| 152 |
|
| 153 |
def __str__(self): |
| 154 |
return self.tostr() |
| 155 |
|
| 156 |
def tostr(self, indent=0): |
| 157 |
"""Return unified(ish) diff.""" |
| 158 |
ret = '' |
| 159 |
|
| 160 |
if indent == 0: |
| 161 |
ret += '--- %s\n' % self.this_name |
| 162 |
ret += '+++ %s\n' % self.that_name |
| 163 |
ret += '============\n' |
| 164 |
ret += ' %s\n' % self.BRACES[self.typ][0] |
| 165 |
|
| 166 |
pre = ' ' * indent |
| 167 |
for itt, (symbol, item) in enumerate(self.changed): |
| 168 |
post = '' |
| 169 |
if itt != len(self.changed) - 1: |
| 170 |
post = ',' |
| 171 |
|
| 172 |
if isinstance(item, Diff): |
| 173 |
diff = item |
| 174 |
key = symbol |
| 175 |
ret += ' %s %s: %s\n' % (pre, key, self.BRACES[diff.typ][0]) |
| 176 |
ret += diff.tostr(indent + 1) |
| 177 |
ret += ' %s %s%s\n' % (pre, self.BRACES[diff.typ][1], post) |
| 178 |
else: |
| 179 |
if symbol == '?': |
| 180 |
key, before, after = item |
| 181 |
ret += f'{symbol}{pre} {key}: {before} => {after}{post}\n' |
| 182 |
elif symbol in ['+', '-']: |
| 183 |
if len(item) == 2: |
| 184 |
value = '%s: %s' % item |
| 185 |
else: |
| 186 |
value = item[0] |
| 187 |
ret += f'{symbol}{pre} {value}{post}\n' |
| 188 |
|
| 189 |
if indent == 0: |
| 190 |
ret += ' %s\n' % self.BRACES[self.typ][1] |
| 191 |
|
| 192 |
return ret |
| 193 |
|
| 194 |
def added(self): |
| 195 |
"""Yield items present in this but not in that as (key, value).""" |
| 196 |
yield from self.filter('+') |
| 197 |
|
| 198 |
def removed(self): |
| 199 |
"""Yield items present in that but not in this as (key, value).""" |
| 200 |
yield from self.filter('-') |
| 201 |
|
| 202 |
def modified(self): |
| 203 |
"""Yield items change as (key, this_value, that_value).""" |
| 204 |
yield from self.filter('?') |
| 205 |
|
| 206 |
def filter(self, *symbols): |
| 207 |
"""Filter items by change status (+,-,?).""" |
| 208 |
for symbol, item in self.changed: |
| 209 |
if symbol in symbols: |
| 210 |
yield ([item[0]], *item[1:]) |
| 211 |
elif isinstance(item, Diff): |
| 212 |
yield from (([symbol, *res[0]], *res[1:]) |
| 213 |
for res in item.filter(*symbols)) |
| 214 |
|
| 215 |
def __bool__(self): |
| 216 |
return not bool(self.changed) |
| 217 |
|
| 218 |
def __len__(self): |
| 219 |
return len(self.changed) |
| 220 |
|
| 221 |
|
| 222 |
def load_json(file1, file2=None): |
| 223 |
"""Read in JSON, return python data structure. |
| 224 |
|
| 225 |
If file2 is None read from sys.stdin |
| 226 |
|
| 227 |
""" |
| 228 |
try: |
| 229 |
this = json.loads(file1) |
| 230 |
except json.decoder.JSONDecodeError as exc: |
| 231 |
sys.exit(f'Syntax error in file1: {exc}') |
| 232 |
|
| 233 |
try: |
| 234 |
if file2: |
| 235 |
that = json.loads(file2) |
| 236 |
else: |
| 237 |
that = json.load(sys.stdin) |
| 238 |
except json.decoder.JSONDecodeError as exc: |
| 239 |
sys.exit(f'Syntax error in file2: {exc}') |
| 240 |
|
| 241 |
return this, that |
| 242 |
|
| 243 |
|
| 244 |
def parse_args(): |
| 245 |
"""Return CLI args.""" |
| 246 |
parser = argparse.ArgumentParser() |
| 247 |
parser.add_argument('file1') |
| 248 |
parser.add_argument('file2', nargs='?') |
| 249 |
|
| 250 |
parser.add_argument( |
| 251 |
'-1', action='store', dest='name1', default='expected', help=( |
| 252 |
'name file 1, default=expected')) |
| 253 |
parser.add_argument( |
| 254 |
'-2', action='store', dest='name2', default='got', help=( |
| 255 |
'name file 2, default=got')) |
| 256 |
|
| 257 |
parser.add_argument( |
| 258 |
'-c1', '--contains1', action='store_const', const=1, default=0, |
| 259 |
dest='contains', help=( |
| 260 |
'test all (key, value) pairs in file1 are in file2')) |
| 261 |
parser.add_argument( |
| 262 |
'-c2', '--contains2', action='store_const', const=2, default=0, |
| 263 |
dest='contains', help=( |
| 264 |
'test all (key, value) pairs in file2 are in file1')) |
| 265 |
|
| 266 |
parser.add_argument( |
| 267 |
'--color', '--colour', action='store', default='never', help=( |
| 268 |
'Use color? Option in always, never'), dest='color') |
| 269 |
|
| 270 |
args = parser.parse_args() |
| 271 |
|
| 272 |
return args |
| 273 |
|
| 274 |
|
| 275 |
def main(args): |
| 276 |
"""Implement dictdiff.""" |
| 277 |
this, that = load_json(args.file1, args.file2) |
| 278 |
|
| 279 |
if this == that: |
| 280 |
# skip all diff logic if possible |
| 281 |
sys.exit(0) |
| 282 |
|
| 283 |
if args.contains: |
| 284 |
# test if items from one file present in the other |
| 285 |
if args.contains == 2: |
| 286 |
this, that = that, this |
| 287 |
args.name1, args.name2 = args.name2, args.name1 |
| 288 |
diff = Diff(this, that, args.name1, args.name2) |
| 289 |
for _ in diff.filter('-', '?'): |
| 290 |
sys.stderr.write(str(diff)) |
| 291 |
sys.exit(1) |
| 292 |
sys.exit(0) |
| 293 |
|
| 294 |
diff = Diff(this, that, args.name1, args.name2) |
| 295 |
if diff: |
| 296 |
sys.exit(0) |
| 297 |
else: |
| 298 |
sys.stderr.write(str(diff)) |
| 299 |
sys.exit(len(diff)) |
| 300 |
|
| 301 |
|
| 302 |
if __name__ == '__main__': |
| 303 |
main(parse_args()) |