File: diffr.py

package info (click to toggle)
cylc-flow 8.6.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 14,368 kB
  • sloc: python: 87,751; sh: 17,109; sql: 233; xml: 171; javascript: 78; lisp: 55; makefile: 11
file content (303 lines) | stat: -rw-r--r-- 9,646 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
# THIS FILE IS PART OF THE CYLC WORKFLOW ENGINE.
# Copyright (C) NIWA & British Crown (Met Office) & Contributors.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
"""Quick and simple JSON diff util.

Examples:
    >>> bool(Diff({}, {}))
    True

    >>> diff = Diff({'a': 1, 'b': 2},
    ...             {'b': 3, 'd': 4})
    >>> bool(diff)
    False
    >>> list(diff.added())
    [(['d'], 4)]
    >>> list(diff.removed())
    [(['a'], 1)]
    >>> list(diff.modified())
    [(['b'], 2, 3)]

    >>> diff = Diff({'x': {'y': {'z': 1}}},
    ...             {'x': {'y': {'z': 2}}})
    >>> list(diff.modified())
    [(['x', 'y', 'z'], 1, 2)]

"""
import argparse
import json
import sys
from typing import Callable, Optional, Tuple, Type


class Diff:
    """Representation of a diff between two dictionaries."""

    BRACES = {
        dict: ('{', '}'),
        list: ('[', ']')
    }

    def __init__(self, this, that, this_name='expected', that_name='got'):
        self.typ, self.changed = self.compute_diff(this, that)
        self.this_name = this_name
        self.that_name = that_name

    @classmethod
    def _diff_method(
        cls, this: object, that: object
    ) -> Tuple[Optional[Type], Optional[Callable]]:
        if isinstance(this, list) and isinstance(that, list):
            return list, cls.diff_list
        if isinstance(this, dict) and isinstance(that, dict):
            return dict, cls.diff_dict
        return None, None

    @classmethod
    def compute_diff(cls, this, that):
        """Return a list of differences between this and that.

        Entries take the form::
            (symbol, (key, *value))

        Where:
            symbol:
               * ``+``: for items in that but not in this.
               * ``-``: for items in this but not in that.
               * ``?``: for items common to both but with different values.
            key:
               * ``dict``: The key of a key, value pair.
               * ``list``: The index of an element.
            value:
               A tuple containing information about the change:

               * ``+ (key, value)``
               * ``- (key, value)``
               * ``? (key, this_value, that_value)``

        """
        typ, meth = cls._diff_method(this, that)
        if meth:
            return typ, meth(this, that)
        raise TypeError('%s Cannot compare %s and %s' % (
            cls.__name__, type(this), type(that)))

    @classmethod
    def diff_list(cls, this, that):
        """Return differences between two lists.

        So unsurprisingly differencing nested lists is actually a little
        tricky so this is the simple and crude method, just mark the items as
        modified rather than going through the mess of working out how the
        lists could fit together.

        """
        changed = []
        for index, (this_item, that_item) in enumerate(zip(this, that)):
            if this_item != that_item:
                if cls._diff_method(this_item, that_item):
                    changed.append((index, cls(this_item, that_item)))
                else:
                    changed.append(('?', (index, this_item, that_item)))

        if len(this) > len(that):
            symbol = '-'
            additional = this
        else:
            symbol = '+'
            additional = that

        for index in range(min(len(this), len(that)),
                           max(len(this), len(that))):
            changed.append((symbol, (index, additional[index],)))

        return changed

    @classmethod
    def diff_dict(cls, this, that):
        """Return differences between two dictionaries.

        As this is a JSON comparison tool ignore the order of keys.

        """
        changed = []
        for key, value in that.items():
            if key not in this:
                changed.append(('+', (key, value)))
            elif isinstance(value, (dict, list)):
                if cls._diff_method(this[key], that[key]):
                    this[key] = cls(this[key], that[key])
                    if this[key].changed:
                        changed.append((key, this[key]))
                else:
                    changed.append(('?', (key, this[key], value)))
            elif value != this[key]:
                changed.append(('?', (key, this[key], value)))
        for key, value in this.items():
            if key not in that:
                changed.append(('-', (key, value)))
        return changed

    def __str__(self):
        return self.tostr()

    def tostr(self, indent=0):
        """Return unified(ish) diff."""
        ret = ''

        if indent == 0:
            ret += '--- %s\n' % self.this_name
            ret += '+++ %s\n' % self.that_name
            ret += '============\n'
            ret += ' %s\n' % self.BRACES[self.typ][0]

        pre = '    ' * indent
        for itt, (symbol, item) in enumerate(self.changed):
            post = ''
            if itt != len(self.changed) - 1:
                post = ','

            if isinstance(item, Diff):
                diff = item
                key = symbol
                ret += ' %s %s: %s\n' % (pre, key, self.BRACES[diff.typ][0])
                ret += diff.tostr(indent + 1)
                ret += ' %s %s%s\n' % (pre, self.BRACES[diff.typ][1], post)
            else:
                if symbol == '?':
                    key, before, after = item
                    ret += f'{symbol}{pre} {key}: {before} => {after}{post}\n'
                elif symbol in ['+', '-']:
                    if len(item) == 2:
                        value = '%s: %s' % item
                    else:
                        value = item[0]
                    ret += f'{symbol}{pre} {value}{post}\n'

        if indent == 0:
            ret += ' %s\n' % self.BRACES[self.typ][1]

        return ret

    def added(self):
        """Yield items present in this but not in that as (key, value)."""
        yield from self.filter('+')

    def removed(self):
        """Yield items present in that but not in this as (key, value)."""
        yield from self.filter('-')

    def modified(self):
        """Yield items change as (key, this_value, that_value)."""
        yield from self.filter('?')

    def filter(self, *symbols):
        """Filter items by change status (+,-,?)."""
        for symbol, item in self.changed:
            if symbol in symbols:
                yield ([item[0]], *item[1:])
            elif isinstance(item, Diff):
                yield from (([symbol, *res[0]], *res[1:])
                            for res in item.filter(*symbols))

    def __bool__(self):
        return not bool(self.changed)

    def __len__(self):
        return len(self.changed)


def load_json(file1, file2=None):
    """Read in JSON, return python data structure.

    If file2 is None read from sys.stdin

    """
    try:
        this = json.loads(file1)
    except json.decoder.JSONDecodeError as exc:
        sys.exit(f'Syntax error in file1: {exc}')

    try:
        if file2:
            that = json.loads(file2)
        else:
            that = json.load(sys.stdin)
    except json.decoder.JSONDecodeError as exc:
        sys.exit(f'Syntax error in file2: {exc}')

    return this, that


def parse_args():
    """Return CLI args."""
    parser = argparse.ArgumentParser()
    parser.add_argument('file1')
    parser.add_argument('file2', nargs='?')

    parser.add_argument(
        '-1', action='store', dest='name1', default='expected', help=(
            'name file 1, default=expected'))
    parser.add_argument(
        '-2', action='store', dest='name2', default='got', help=(
            'name file 2, default=got'))

    parser.add_argument(
        '-c1', '--contains1', action='store_const', const=1, default=0,
        dest='contains', help=(
            'test all (key, value) pairs in file1 are in file2'))
    parser.add_argument(
        '-c2', '--contains2', action='store_const', const=2, default=0,
        dest='contains', help=(
            'test all (key, value) pairs in file2 are in file1'))

    parser.add_argument(
        '--color', '--colour', action='store', default='never', help=(
            'Use color? Option in always, never'), dest='color')

    args = parser.parse_args()

    return args


def main(args):
    """Implement dictdiff."""
    this, that = load_json(args.file1, args.file2)

    if this == that:
        # skip all diff logic if possible
        sys.exit(0)

    if args.contains:
        # test if items from one file present in the other
        if args.contains == 2:
            this, that = that, this
            args.name1, args.name2 = args.name2, args.name1
        diff = Diff(this, that, args.name1, args.name2)
        for _ in diff.filter('-', '?'):
            sys.stderr.write(str(diff))
            sys.exit(1)
        sys.exit(0)

    diff = Diff(this, that, args.name1, args.name2)
    if diff:
        sys.exit(0)
    else:
        sys.stderr.write(str(diff))
        sys.exit(len(diff))


if __name__ == '__main__':
    main(parse_args())