File: bom_diff.py

package info (click to toggle)
libvpl 1%3A2.16.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 21,580 kB
  • sloc: cpp: 92,604; ansic: 6,176; python: 4,312; sh: 323; makefile: 7
file content (390 lines) | stat: -rw-r--r-- 13,601 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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
#!/usr/bin/env python3
############################################################################
# Copyright (C) Intel Corporation
#
# SPDX-License-Identifier: MIT
############################################################################
"""Generate BOM diffrence report"""
import argparse
import os
import sys
import datetime
import contextlib
import filecmp


# pylint: disable=too-many-instance-attributes
# pylint: disable=consider-using-dict-items
class DiffInfo:
    """Diff information for a single tree node"""
    def log(self, msg):
        """Print a log message for this node"""
        print("  " * self.depth, end='')
        print(msg)

    # pylint: disable=too-many-arguments,too-many-positional-arguments
    def __init__(self, left, right, path='', name='', depth=0):
        self._cmp = None
        self._has_diff = False
        self._has_orphan = False
        self.depth = depth
        self.name = name
        self._root = {'left': left, 'right': right}
        self.rel_path = os.path.join(path, name)
        self._path = {
            'left': os.path.join(left, self.rel_path),
            'right': os.path.join(right, self.rel_path)
        }
        self.children = {}
        for side in self._path:
            self._extend(self._path[side])

    def flags(self, side):
        """Get the flag info for one side of the node"""
        if side not in self._path:
            raise IndexError()
        if self.exists(side):
            return oct(os.stat(self._path[side]).st_mode)[2:]
        return ''

    def path(self, side):
        """Get the filesystem path for one side of the node"""
        if side not in self._path:
            raise IndexError()
        return self._path[side]

    def file_size(self, side):
        """Get the size of one side of the node"""
        if side not in self._path:
            raise IndexError()
        if self.exists(side):
            return os.stat(self._path[side]).st_size
        return ''

    def hasorphan(self):
        """Check if node is an orphan or has orphan children"""
        self.cmp()
        return self._has_orphan

    def hasdiff(self):
        """Check if node is a diffs or has diffs children"""
        self.cmp()
        return self._has_diff

    def exists(self, side):
        """Check if one side of the node exists in the filesystem"""
        if side not in self._path:
            raise IndexError()
        return os.path.exists(self._path[side])

    def isfile(self, side):
        """Check if one side of the node is a file"""
        if side not in self._path:
            raise IndexError()
        return os.path.isfile(self._path[side])

    def isdir(self, side):
        """Check if one side of the node is a folder"""
        if side not in self._path:
            raise IndexError()
        return os.path.isdir(self._path[side])

    def invalidate(self):
        """Invalidate chached comparison info"""
        self._cmp = None
        for child in self.children:
            self.children[child].invalidate()

    # pylint: disable=too-many-branches, too-many-statements
    def cmp(self, check_flags=False):
        """Get comparison info for this node implies child nodes
        are checked as well.

        This information is cached, so multiple calls do
        not incure incresed cost"""
        if self._cmp:
            return self._cmp
        has_left = os.path.exists(self._path['left'])
        has_right = os.path.exists(self._path['right'])
        self._has_diff = False
        self._has_orphan = False

        if has_left and has_right:
            if self.isfile('left') and self.isfile('right'):
                if filecmp.cmp(self._path['left'], self._path['right'], False):
                    if check_flags:
                        if self.flags('left') == self.flags('right'):
                            self._cmp = 'match'
                        else:
                            self._has_diff = True
                            self._cmp = 'mismatch'
                    else:
                        self._cmp = 'match'
                else:
                    self._has_diff = True
                    self._cmp = 'mismatch'
            elif self.isdir('left') and self.isdir('right'):
                self._cmp = 'match'
                for child in self.children:
                    child_cmp = self.children[child].cmp()
                    if child_cmp != 'match':
                        self._has_diff = True
                        self._cmp = 'mismatch'
                    if self.children[child].hasorphan():
                        self._has_orphan = True
                    if self.children[child].hasdiff():
                        self._has_diff = True

                if check_flags and self._cmp == 'match':
                    if self.flags('left') == self.flags('right'):
                        self._cmp = 'match'
                    else:
                        self._has_diff = True
                        self._cmp = 'mismatch'
            else:
                self._cmp = 'mismatch'
                self._has_diff = True
                for child in self.children:
                    child_cmp = self.children[child].cmp()
                    if self.children[child].hasorphan():
                        self._has_orphan = True
                    if self.children[child].hasdiff():
                        self._has_diff = True
        elif has_left:
            self._has_diff = True
            self._has_orphan = True
            self._cmp = 'orphan-left'
        elif has_right:
            self._has_diff = True
            self._has_orphan = True
            self._cmp = 'orphan-right'
        else:
            self._cmp = 'missing'
        return self._cmp

    def _extend(self, child_path):
        """Add any items in the given path as children"""
        if os.path.isdir(child_path):
            for child in os.scandir(child_path):
                if child.name in self.children:
                    continue
                self.children[child.name] = DiffInfo(self._root['left'],
                                                     self._root['right'],
                                                     self.rel_path, child.name,
                                                     self.depth + 1)


@contextlib.contextmanager
def open_output(filename=None):
    """Open the main output stream, which may be stdout"""
    if filename is None or filename == '-':
        output = sys.stdout
        yield output
    else:
        with open(filename, 'w', encoding="utf-8") as output:
            yield output


# pylint: disable=too-many-branches, too-many-statements
def print_row(root, mode, indent=0):
    """Print one row of the diff report"""
    relation = root.cmp()
    result = ''

    if mode == 'All':
        pass
    elif mode == 'Diff' and root.hasdiff():
        pass
    elif mode == 'Orphan' and root.hasorphan():
        pass
    else:
        return ''

    result += '<tr class="SectionAll">'
    if relation == 'match':
        result += '<td class="DirItemSame">\n'
    elif relation == 'mismatch':
        result += '<td class="DirItemDiff">'
    elif relation == 'orphan-left':
        result += '<td class="DirItemOrphan">'
    elif relation == 'orphan-right':
        result += '<td>'
    elif relation == 'missing':
        result += '<td>'
    else:
        result += '<td>'
    if root.exists('left'):
        if root.isdir('left'):
            sym = '&#x1F4C2;'
        else:
            sym = '&#x1F5CE;'
        result += f'<span class="tree">{"&nbsp;&nbsp;" * indent}{sym}</span> {root.name}'
    result += '</td>'
    result += f'<td>{root.file_size("left")}</td>'
    result += f'<td>{root.flags("left")}</td>'

    if relation == 'match':
        sym = '='
        result += f'<td class="DirItemHeader AlignLeft">{sym}</td>'
    elif relation == 'mismatch':
        sym = '&#x2260;'
        result += f'<td class="DirItemHeader AlignLeft">{sym}</td>'
    elif relation == 'orphan-left':
        sym = ''
        result += f'<td class="DirItemHeader AlignLeft">{sym}</td>'
    elif relation == 'orphan-right':
        sym = ''
        result += f'<td class="DirItemHeader AlignLeft">{sym}</td>'
    elif relation == 'missing':
        sym = '&#x1F9A8;'
        result += f'<td class="DirItemHeader AlignLeft">{sym}</td>'
    else:
        sym = relation
        result += f'<td class="DirItemHeader AlignLeft">{sym}</td>'

    if relation == 'match':
        result += '<td class="DirItemSame">'
    elif relation == 'mismatch':
        result += '<td class="DirItemDiff">'
    elif relation == 'orphan-left':
        result += '<td>'
    elif relation == 'orphan-right':
        result += '<td class="DirItemOrphan">'
    elif relation == 'missing':
        result += '<td>'
    else:
        result += '<td>'
    if root.exists('right'):
        if root.isdir('right'):
            sym = '&#x1F4C2;'
        else:
            sym = '&#x1F5CE;'
        result += f'<span class="tree">{"&nbsp;&nbsp;" * indent}{sym}</span> {root.name}'
    result += '</td>'
    result += f'<td>{root.file_size("right")}</td>'
    result += f'<td>{root.flags("right")}</td>'
    result += '</tr>'
    return result


def print_tree(root, mode, indent=0):
    """Print root item and all children for the report"""
    result = ''
    if indent:
        result += print_row(root, mode, indent)
    for child in sorted(root.children):
        result += print_tree(root.children[child], mode, indent + 1)
    return result


def write_report(root, title, mode):
    """Print report

    Supported modes are:

    All: Include all nodes

    Diff: Include only nodes with diffrences

    Orphan: Include only orphan nodes
    """
    now = datetime.datetime.now()
    result = ''
    if mode == 'All':
        mode_name = 'All'
    elif mode == 'Diff':
        mode_name = 'Differences'
    elif mode == 'Orphan':
        mode_name = 'Orphans'
    else:
        mode_name = mode

    result += """<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<style>
.AlignLeft { text-align: left; }
.AlignCenter { text-align: center; }
.AlignRight { text-align: right; }
body { font-family: sans-serif; font-size: 11pt; }
td { vertical-align: top; padding-left: 4px; padding-right: 4px; }

tr.SectionGap td { font-size: 4px; border-left: none; border-top: none; border-bottom: 1px solid Black; border-right: 1px solid Black; }
tr.SectionAll td { border-left: none; border-top: none; border-bottom: 1px solid Black; border-right: 1px solid Black; }
tr.SectionBegin td { border-left: none; border-top: none; border-right: 1px solid Black; }
tr.SectionEnd td { border-left: none; border-top: none; border-bottom: 1px solid Black; border-right: 1px solid Black; }
tr.SectionMiddle td { border-left: none; border-top: none; border-right: 1px solid Black; }
tr.SubsectionAll td { border-left: none; border-top: none; border-bottom: 1px solid Gray; border-right: 1px solid Black; }
tr.SubsectionEnd td { border-left: none; border-top: none; border-bottom: 1px solid Gray; border-right: 1px solid Black; }
table.dc { border-top: 1px solid Black; border-left: 1px solid Black; width: 100%; font-family: sans-serif; font-size: 10pt; }
table.dc tr.SectionBegin td { border-bottom: 1px solid Silver; }
table.dc tr.SectionMiddle td { border-bottom: 1px solid Silver; }
td.DirItemHeader { color: #000000; background-color: #FFFFFF; background-color: #E7E7E7; padding-top: 8px; }
td.DirItemDiff { color: #FF0000; background-color: #FFFFFF; }
td.DirItemNewer { color: #FF0000; background-color: #FFFFFF; }
td.DirItemOlder { color: #808080; background-color: #FFFFFF; }
td.DirItemOrphan { color: #0000FF; background-color: #FFFFFF; }
td.DirItemSame { color: #000000; background-color: #FFFFFF; }
.DirSegInfo { color: #C0C0C0; }
.tree {
    font-family: monospace;
    font-size: 16pt;
}
</style>"""
    result += f"""<title>{title}</title>
</head>
<body>
{title}<br/>
Produced: {now.strftime("%Y-%m-%d %H:%M:%S")}<br/>
&nbsp; &nbsp;
<br/>
Mode:&nbsp; {mode_name} &nbsp;
<br/>
Left base folder:  {os.path.abspath(root.path('left'))}&nbsp;
<br/>
Right base folder:  {os.path.abspath(root.path('right'))}&nbsp;
<br/>
<table class="dc" cellspacing="0" cellpadding="0">
<tr class="SectionAll">
<td class="DirItemHeader">Name</td>
<td class="DirItemHeader">Size</td>
<td class="DirItemHeader">Flags</td>
<td class="DirItemHeader AlignLeft">&nbsp;</td>
<td class="DirItemHeader">Name</td>
<td class="DirItemHeader">Size</td>
<td class="DirItemHeader">Flags</td>
</tr>"""
    result += print_tree(root, mode, 0)
    result += """</tr>
</table>
<br/>
</body>
</html>"""
    return result


def main():
    """Main entrypoint"""
    parser = argparse.ArgumentParser(
        description=globals()['__doc__'],
        formatter_class=argparse.RawTextHelpFormatter)
    parser.add_argument('left', action='store')
    parser.add_argument('right', action='store')
    parser.add_argument('--mode',
                        '-m',
                        default="All",
                        action='store',
                        choices=['All', 'Diff', 'Orphan'])
    parser.add_argument('--output', '-o', default=None, action='store')
    parser.add_argument('--title', '-t', default="BOM Diff", action='store')

    args = parser.parse_args()
    root = DiffInfo(args.left, args.right)
    root.cmp()
    report = write_report(root, args.title, args.mode)
    with open_output(args.output) as output:
        output.write(report)


if __name__ == "__main__":
    main()