blob: b0365abcedfc278daa1ce103deabfe9145c8ee7b [file] [log] [blame]
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001# Report significant differences in the buildhistory repository since a specific revision
2#
Brad Bishop6e60e8b2018-02-01 10:27:11 -05003# Copyright (C) 2012-2013, 2016-2017 Intel Corporation
Patrick Williamsc124f4f2015-09-15 14:41:29 -05004# Author: Paul Eggleton <paul.eggleton@linux.intel.com>
5#
6# Note: requires GitPython 0.3.1+
7#
8# You can use this from the command line by running scripts/buildhistory-diff
9#
10
11import sys
12import os.path
13import difflib
14import git
15import re
Brad Bishop6e60e8b2018-02-01 10:27:11 -050016import hashlib
17import collections
Patrick Williamsc124f4f2015-09-15 14:41:29 -050018import bb.utils
Brad Bishop6e60e8b2018-02-01 10:27:11 -050019import bb.tinfoil
Patrick Williamsc124f4f2015-09-15 14:41:29 -050020
21
22# How to display fields
23list_fields = ['DEPENDS', 'RPROVIDES', 'RDEPENDS', 'RRECOMMENDS', 'RSUGGESTS', 'RREPLACES', 'RCONFLICTS', 'FILES', 'FILELIST', 'USER_CLASSES', 'IMAGE_CLASSES', 'IMAGE_FEATURES', 'IMAGE_LINGUAS', 'IMAGE_INSTALL', 'BAD_RECOMMENDATIONS', 'PACKAGE_EXCLUDE']
24list_order_fields = ['PACKAGES']
25defaultval_map = {'PKG': 'PKG', 'PKGE': 'PE', 'PKGV': 'PV', 'PKGR': 'PR'}
26numeric_fields = ['PKGSIZE', 'IMAGESIZE']
27# Fields to monitor
28monitor_fields = ['RPROVIDES', 'RDEPENDS', 'RRECOMMENDS', 'RREPLACES', 'RCONFLICTS', 'PACKAGES', 'FILELIST', 'PKGSIZE', 'IMAGESIZE', 'PKG']
29ver_monitor_fields = ['PKGE', 'PKGV', 'PKGR']
30# Percentage change to alert for numeric fields
31monitor_numeric_threshold = 10
32# Image files to monitor (note that image-info.txt is handled separately)
33img_monitor_files = ['installed-package-names.txt', 'files-in-image.txt']
34# Related context fields for reporting (note: PE, PV & PR are always reported for monitored package fields)
35related_fields = {}
36related_fields['RDEPENDS'] = ['DEPENDS']
37related_fields['RRECOMMENDS'] = ['DEPENDS']
38related_fields['FILELIST'] = ['FILES']
Patrick Williamsc124f4f2015-09-15 14:41:29 -050039related_fields['files-in-image.txt'] = ['installed-package-names.txt', 'USER_CLASSES', 'IMAGE_CLASSES', 'ROOTFS_POSTPROCESS_COMMAND', 'IMAGE_POSTPROCESS_COMMAND']
40related_fields['installed-package-names.txt'] = ['IMAGE_FEATURES', 'IMAGE_LINGUAS', 'IMAGE_INSTALL', 'BAD_RECOMMENDATIONS', 'NO_RECOMMENDATIONS', 'PACKAGE_EXCLUDE']
41
Brad Bishop316dfdd2018-06-25 12:45:53 -040042colours = {
43 'colour_default': '',
44 'colour_add': '',
45 'colour_remove': '',
46}
47
48def init_colours(use_colours):
49 global colours
50 if use_colours:
51 colours = {
52 'colour_default': '\033[0m',
53 'colour_add': '\033[1;32m',
54 'colour_remove': '\033[1;31m',
55 }
56 else:
57 colours = {
58 'colour_default': '',
59 'colour_add': '',
60 'colour_remove': '',
61 }
Patrick Williamsc124f4f2015-09-15 14:41:29 -050062
63class ChangeRecord:
64 def __init__(self, path, fieldname, oldvalue, newvalue, monitored):
65 self.path = path
66 self.fieldname = fieldname
67 self.oldvalue = oldvalue
68 self.newvalue = newvalue
69 self.monitored = monitored
70 self.related = []
71 self.filechanges = None
72
73 def __str__(self):
74 return self._str_internal(True)
75
76 def _str_internal(self, outer):
77 if outer:
78 if '/image-files/' in self.path:
79 prefix = '%s: ' % self.path.split('/image-files/')[0]
80 else:
81 prefix = '%s: ' % self.path
82 else:
83 prefix = ''
84
85 def pkglist_combine(depver):
86 pkglist = []
Patrick Williamsc0f7c042017-02-23 20:41:17 -060087 for k,v in depver.items():
Patrick Williamsc124f4f2015-09-15 14:41:29 -050088 if v:
89 pkglist.append("%s (%s)" % (k,v))
90 else:
91 pkglist.append(k)
92 return pkglist
93
Brad Bishop6e60e8b2018-02-01 10:27:11 -050094 def detect_renamed_dirs(aitems, bitems):
95 adirs = set(map(os.path.dirname, aitems))
96 bdirs = set(map(os.path.dirname, bitems))
97 files_ab = [(name, sorted(os.path.basename(item) for item in aitems if os.path.dirname(item) == name)) \
98 for name in adirs - bdirs]
99 files_ba = [(name, sorted(os.path.basename(item) for item in bitems if os.path.dirname(item) == name)) \
100 for name in bdirs - adirs]
Brad Bishop316dfdd2018-06-25 12:45:53 -0400101 renamed_dirs = []
102 for dir1, files1 in files_ab:
103 rename = False
104 for dir2, files2 in files_ba:
105 if files1 == files2 and not rename:
106 renamed_dirs.append((dir1,dir2))
107 # Make sure that we don't use this (dir, files) pair again.
108 files_ba.remove((dir2,files2))
109 # If a dir has already been found to have a rename, stop and go no further.
110 rename = True
111
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500112 # remove files that belong to renamed dirs from aitems and bitems
113 for dir1, dir2 in renamed_dirs:
114 aitems = [item for item in aitems if os.path.dirname(item) not in (dir1, dir2)]
115 bitems = [item for item in bitems if os.path.dirname(item) not in (dir1, dir2)]
116 return renamed_dirs, aitems, bitems
117
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500118 if self.fieldname in list_fields or self.fieldname in list_order_fields:
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500119 renamed_dirs = []
Brad Bishop316dfdd2018-06-25 12:45:53 -0400120 changed_order = False
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500121 if self.fieldname in ['RPROVIDES', 'RDEPENDS', 'RRECOMMENDS', 'RSUGGESTS', 'RREPLACES', 'RCONFLICTS']:
122 (depvera, depverb) = compare_pkg_lists(self.oldvalue, self.newvalue)
123 aitems = pkglist_combine(depvera)
124 bitems = pkglist_combine(depverb)
125 else:
126 aitems = self.oldvalue.split()
127 bitems = self.newvalue.split()
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500128 if self.fieldname == 'FILELIST':
129 renamed_dirs, aitems, bitems = detect_renamed_dirs(aitems, bitems)
130
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500131 removed = list(set(aitems) - set(bitems))
132 added = list(set(bitems) - set(aitems))
133
Brad Bishop316dfdd2018-06-25 12:45:53 -0400134 if not removed and not added:
135 depvera = bb.utils.explode_dep_versions2(self.oldvalue, sort=False)
136 depverb = bb.utils.explode_dep_versions2(self.newvalue, sort=False)
137 for i, j in zip(depvera.items(), depverb.items()):
138 if i[0] != j[0]:
139 changed_order = True
140 break
141
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500142 lines = []
143 if renamed_dirs:
144 for dfrom, dto in renamed_dirs:
Brad Bishop316dfdd2018-06-25 12:45:53 -0400145 lines.append('directory renamed {colour_remove}{}{colour_default} -> {colour_add}{}{colour_default}'.format(dfrom, dto, **colours))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500146 if removed or added:
147 if removed and not bitems:
Brad Bishop316dfdd2018-06-25 12:45:53 -0400148 lines.append('removed all items "{colour_remove}{}{colour_default}"'.format(' '.join(removed), **colours))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500149 else:
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500150 if removed:
Brad Bishop316dfdd2018-06-25 12:45:53 -0400151 lines.append('removed "{colour_remove}{value}{colour_default}"'.format(value=' '.join(removed), **colours))
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500152 if added:
Brad Bishop316dfdd2018-06-25 12:45:53 -0400153 lines.append('added "{colour_add}{value}{colour_default}"'.format(value=' '.join(added), **colours))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500154 else:
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500155 lines.append('changed order')
156
Brad Bishop316dfdd2018-06-25 12:45:53 -0400157 if not (removed or added or changed_order):
158 out = ''
159 else:
160 out = '%s: %s' % (self.fieldname, ', '.join(lines))
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500161
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500162 elif self.fieldname in numeric_fields:
163 aval = int(self.oldvalue or 0)
164 bval = int(self.newvalue or 0)
165 if aval != 0:
166 percentchg = ((bval - aval) / float(aval)) * 100
167 else:
168 percentchg = 100
Brad Bishop316dfdd2018-06-25 12:45:53 -0400169 out = '{} changed from {colour_remove}{}{colour_default} to {colour_add}{}{colour_default} ({}{:.0f}%)'.format(self.fieldname, self.oldvalue or "''", self.newvalue or "''", '+' if percentchg > 0 else '', percentchg, **colours)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500170 elif self.fieldname in defaultval_map:
Brad Bishop316dfdd2018-06-25 12:45:53 -0400171 out = '{} changed from {colour_remove}{}{colour_default} to {colour_add}{}{colour_default}'.format(self.fieldname, self.oldvalue, self.newvalue, **colours)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500172 if self.fieldname == 'PKG' and '[default]' in self.newvalue:
173 out += ' - may indicate debian renaming failure'
174 elif self.fieldname in ['pkg_preinst', 'pkg_postinst', 'pkg_prerm', 'pkg_postrm']:
175 if self.oldvalue and self.newvalue:
176 out = '%s changed:\n ' % self.fieldname
177 elif self.newvalue:
178 out = '%s added:\n ' % self.fieldname
179 elif self.oldvalue:
180 out = '%s cleared:\n ' % self.fieldname
181 alines = self.oldvalue.splitlines()
182 blines = self.newvalue.splitlines()
183 diff = difflib.unified_diff(alines, blines, self.fieldname, self.fieldname, lineterm='')
184 out += '\n '.join(list(diff)[2:])
185 out += '\n --'
186 elif self.fieldname in img_monitor_files or '/image-files/' in self.path:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500187 if self.filechanges or (self.oldvalue and self.newvalue):
188 fieldname = self.fieldname
189 if '/image-files/' in self.path:
190 fieldname = os.path.join('/' + self.path.split('/image-files/')[1], self.fieldname)
191 out = 'Changes to %s:\n ' % fieldname
192 else:
193 if outer:
194 prefix = 'Changes to %s ' % self.path
195 out = '(%s):\n ' % self.fieldname
196 if self.filechanges:
197 out += '\n '.join(['%s' % i for i in self.filechanges])
198 else:
199 alines = self.oldvalue.splitlines()
200 blines = self.newvalue.splitlines()
201 diff = difflib.unified_diff(alines, blines, fieldname, fieldname, lineterm='')
202 out += '\n '.join(list(diff))
203 out += '\n --'
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500204 else:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500205 out = ''
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500206 else:
Brad Bishop316dfdd2018-06-25 12:45:53 -0400207 out = '{} changed from "{colour_remove}{}{colour_default}" to "{colour_add}{}{colour_default}"'.format(self.fieldname, self.oldvalue, self.newvalue, **colours)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500208
209 if self.related:
210 for chg in self.related:
211 if not outer and chg.fieldname in ['PE', 'PV', 'PR']:
212 continue
213 for line in chg._str_internal(False).splitlines():
214 out += '\n * %s' % line
215
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500216 return '%s%s' % (prefix, out) if out else ''
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500217
218class FileChange:
219 changetype_add = 'A'
220 changetype_remove = 'R'
221 changetype_type = 'T'
222 changetype_perms = 'P'
223 changetype_ownergroup = 'O'
224 changetype_link = 'L'
225
226 def __init__(self, path, changetype, oldvalue = None, newvalue = None):
227 self.path = path
228 self.changetype = changetype
229 self.oldvalue = oldvalue
230 self.newvalue = newvalue
231
232 def _ftype_str(self, ftype):
233 if ftype == '-':
234 return 'file'
235 elif ftype == 'd':
236 return 'directory'
237 elif ftype == 'l':
238 return 'symlink'
239 elif ftype == 'c':
240 return 'char device'
241 elif ftype == 'b':
242 return 'block device'
243 elif ftype == 'p':
244 return 'fifo'
245 elif ftype == 's':
246 return 'socket'
247 else:
248 return 'unknown (%s)' % ftype
249
250 def __str__(self):
251 if self.changetype == self.changetype_add:
252 return '%s was added' % self.path
253 elif self.changetype == self.changetype_remove:
254 return '%s was removed' % self.path
255 elif self.changetype == self.changetype_type:
256 return '%s changed type from %s to %s' % (self.path, self._ftype_str(self.oldvalue), self._ftype_str(self.newvalue))
257 elif self.changetype == self.changetype_perms:
258 return '%s changed permissions from %s to %s' % (self.path, self.oldvalue, self.newvalue)
259 elif self.changetype == self.changetype_ownergroup:
260 return '%s changed owner/group from %s to %s' % (self.path, self.oldvalue, self.newvalue)
261 elif self.changetype == self.changetype_link:
262 return '%s changed symlink target from %s to %s' % (self.path, self.oldvalue, self.newvalue)
263 else:
264 return '%s changed (unknown)' % self.path
265
266
267def blob_to_dict(blob):
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600268 alines = [line for line in blob.data_stream.read().decode('utf-8').splitlines()]
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500269 adict = {}
270 for line in alines:
271 splitv = [i.strip() for i in line.split('=',1)]
272 if len(splitv) > 1:
273 adict[splitv[0]] = splitv[1]
274 return adict
275
276
277def file_list_to_dict(lines):
278 adict = {}
279 for line in lines:
280 # Leave the last few fields intact so we handle file names containing spaces
281 splitv = line.split(None,4)
282 # Grab the path and remove the leading .
283 path = splitv[4][1:].strip()
284 # Handle symlinks
285 if(' -> ' in path):
286 target = path.split(' -> ')[1]
287 path = path.split(' -> ')[0]
288 adict[path] = splitv[0:3] + [target]
289 else:
290 adict[path] = splitv[0:3]
291 return adict
292
293
294def compare_file_lists(alines, blines):
295 adict = file_list_to_dict(alines)
296 bdict = file_list_to_dict(blines)
297 filechanges = []
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600298 for path, splitv in adict.items():
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500299 newsplitv = bdict.pop(path, None)
300 if newsplitv:
301 # Check type
302 oldvalue = splitv[0][0]
303 newvalue = newsplitv[0][0]
304 if oldvalue != newvalue:
305 filechanges.append(FileChange(path, FileChange.changetype_type, oldvalue, newvalue))
306 # Check permissions
307 oldvalue = splitv[0][1:]
308 newvalue = newsplitv[0][1:]
309 if oldvalue != newvalue:
310 filechanges.append(FileChange(path, FileChange.changetype_perms, oldvalue, newvalue))
311 # Check owner/group
312 oldvalue = '%s/%s' % (splitv[1], splitv[2])
313 newvalue = '%s/%s' % (newsplitv[1], newsplitv[2])
314 if oldvalue != newvalue:
315 filechanges.append(FileChange(path, FileChange.changetype_ownergroup, oldvalue, newvalue))
316 # Check symlink target
317 if newsplitv[0][0] == 'l':
318 if len(splitv) > 3:
319 oldvalue = splitv[3]
320 else:
321 oldvalue = None
322 newvalue = newsplitv[3]
323 if oldvalue != newvalue:
324 filechanges.append(FileChange(path, FileChange.changetype_link, oldvalue, newvalue))
325 else:
326 filechanges.append(FileChange(path, FileChange.changetype_remove))
327
328 # Whatever is left over has been added
329 for path in bdict:
330 filechanges.append(FileChange(path, FileChange.changetype_add))
331
332 return filechanges
333
334
335def compare_lists(alines, blines):
336 removed = list(set(alines) - set(blines))
337 added = list(set(blines) - set(alines))
338
339 filechanges = []
340 for pkg in removed:
341 filechanges.append(FileChange(pkg, FileChange.changetype_remove))
342 for pkg in added:
343 filechanges.append(FileChange(pkg, FileChange.changetype_add))
344
345 return filechanges
346
347
348def compare_pkg_lists(astr, bstr):
349 depvera = bb.utils.explode_dep_versions2(astr)
350 depverb = bb.utils.explode_dep_versions2(bstr)
351
352 # Strip out changes where the version has increased
353 remove = []
354 for k in depvera:
355 if k in depverb:
356 dva = depvera[k]
357 dvb = depverb[k]
358 if dva and dvb and len(dva) == len(dvb):
359 # Since length is the same, sort so that prefixes (e.g. >=) will line up
360 dva.sort()
361 dvb.sort()
362 removeit = True
363 for dvai, dvbi in zip(dva, dvb):
364 if dvai != dvbi:
365 aiprefix = dvai.split(' ')[0]
366 biprefix = dvbi.split(' ')[0]
367 if aiprefix == biprefix and aiprefix in ['>=', '=']:
368 if bb.utils.vercmp(bb.utils.split_version(dvai), bb.utils.split_version(dvbi)) > 0:
369 removeit = False
370 break
371 else:
372 removeit = False
373 break
374 if removeit:
375 remove.append(k)
376
377 for k in remove:
378 depvera.pop(k)
379 depverb.pop(k)
380
381 return (depvera, depverb)
382
383
384def compare_dict_blobs(path, ablob, bblob, report_all, report_ver):
385 adict = blob_to_dict(ablob)
386 bdict = blob_to_dict(bblob)
387
388 pkgname = os.path.basename(path)
389
390 defaultvals = {}
391 defaultvals['PKG'] = pkgname
392 defaultvals['PKGE'] = '0'
393
394 changes = []
395 keys = list(set(adict.keys()) | set(bdict.keys()) | set(defaultval_map.keys()))
396 for key in keys:
397 astr = adict.get(key, '')
398 bstr = bdict.get(key, '')
399 if key in ver_monitor_fields:
400 monitored = report_ver or astr or bstr
401 else:
402 monitored = key in monitor_fields
403 mapped_key = defaultval_map.get(key, '')
404 if mapped_key:
405 if not astr:
406 astr = '%s [default]' % adict.get(mapped_key, defaultvals.get(key, ''))
407 if not bstr:
408 bstr = '%s [default]' % bdict.get(mapped_key, defaultvals.get(key, ''))
409
410 if astr != bstr:
411 if (not report_all) and key in numeric_fields:
412 aval = int(astr or 0)
413 bval = int(bstr or 0)
414 if aval != 0:
415 percentchg = ((bval - aval) / float(aval)) * 100
416 else:
417 percentchg = 100
418 if abs(percentchg) < monitor_numeric_threshold:
419 continue
420 elif (not report_all) and key in list_fields:
421 if key == "FILELIST" and path.endswith("-dbg") and bstr.strip() != '':
422 continue
423 if key in ['RPROVIDES', 'RDEPENDS', 'RRECOMMENDS', 'RSUGGESTS', 'RREPLACES', 'RCONFLICTS']:
424 (depvera, depverb) = compare_pkg_lists(astr, bstr)
425 if depvera == depverb:
426 continue
427 alist = astr.split()
428 alist.sort()
429 blist = bstr.split()
430 blist.sort()
431 # We don't care about the removal of self-dependencies
432 if pkgname in alist and not pkgname in blist:
433 alist.remove(pkgname)
434 if ' '.join(alist) == ' '.join(blist):
435 continue
436
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600437 if key == 'PKGR' and not report_all:
438 vers = []
439 # strip leading 'r' and dots
440 for ver in (astr.split()[0], bstr.split()[0]):
441 if ver.startswith('r'):
442 ver = ver[1:]
443 vers.append(ver.replace('.', ''))
444 maxlen = max(len(vers[0]), len(vers[1]))
445 try:
446 # pad with '0' and convert to int
447 vers = [int(ver.ljust(maxlen, '0')) for ver in vers]
448 except ValueError:
449 pass
450 else:
451 # skip decrements and increments
452 if abs(vers[0] - vers[1]) == 1:
453 continue
454
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500455 chg = ChangeRecord(path, key, astr, bstr, monitored)
456 changes.append(chg)
457 return changes
458
459
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500460def compare_siglists(a_blob, b_blob, taskdiff=False):
461 # FIXME collapse down a recipe's tasks?
462 alines = a_blob.data_stream.read().decode('utf-8').splitlines()
463 blines = b_blob.data_stream.read().decode('utf-8').splitlines()
464 keys = []
465 pnmap = {}
466 def readsigs(lines):
467 sigs = {}
468 for line in lines:
469 linesplit = line.split()
470 if len(linesplit) > 2:
471 sigs[linesplit[0]] = linesplit[2]
472 if not linesplit[0] in keys:
473 keys.append(linesplit[0])
474 pnmap[linesplit[1]] = linesplit[0].rsplit('.', 1)[0]
475 return sigs
476 adict = readsigs(alines)
477 bdict = readsigs(blines)
478 out = []
479
480 changecount = 0
481 addcount = 0
482 removecount = 0
483 if taskdiff:
484 with bb.tinfoil.Tinfoil() as tinfoil:
485 tinfoil.prepare(config_only=True)
486
487 changes = collections.OrderedDict()
488
489 def compare_hashfiles(pn, taskname, hash1, hash2):
490 hashes = [hash1, hash2]
491 hashfiles = bb.siggen.find_siginfo(pn, taskname, hashes, tinfoil.config_data)
492
493 if not taskname:
494 (pn, taskname) = pn.rsplit('.', 1)
495 pn = pnmap.get(pn, pn)
496 desc = '%s.%s' % (pn, taskname)
497
498 if len(hashfiles) == 0:
499 out.append("Unable to find matching sigdata for %s with hashes %s or %s" % (desc, hash1, hash2))
500 elif not hash1 in hashfiles:
501 out.append("Unable to find matching sigdata for %s with hash %s" % (desc, hash1))
502 elif not hash2 in hashfiles:
503 out.append("Unable to find matching sigdata for %s with hash %s" % (desc, hash2))
504 else:
505 out2 = bb.siggen.compare_sigfiles(hashfiles[hash1], hashfiles[hash2], recursecb, collapsed=True)
506 for line in out2:
507 m = hashlib.sha256()
508 m.update(line.encode('utf-8'))
509 entry = changes.get(m.hexdigest(), (line, []))
510 if desc not in entry[1]:
511 changes[m.hexdigest()] = (line, entry[1] + [desc])
512
513 # Define recursion callback
514 def recursecb(key, hash1, hash2):
515 compare_hashfiles(key, None, hash1, hash2)
516 return []
517
518 for key in keys:
519 siga = adict.get(key, None)
520 sigb = bdict.get(key, None)
521 if siga is not None and sigb is not None and siga != sigb:
522 changecount += 1
523 (pn, taskname) = key.rsplit('.', 1)
524 compare_hashfiles(pn, taskname, siga, sigb)
525 elif siga is None:
526 addcount += 1
527 elif sigb is None:
528 removecount += 1
529 for key, item in changes.items():
530 line, tasks = item
531 if len(tasks) == 1:
532 desc = tasks[0]
533 elif len(tasks) == 2:
534 desc = '%s and %s' % (tasks[0], tasks[1])
535 else:
536 desc = '%s and %d others' % (tasks[-1], len(tasks)-1)
537 out.append('%s: %s' % (desc, line))
538 else:
539 for key in keys:
540 siga = adict.get(key, None)
541 sigb = bdict.get(key, None)
542 if siga is not None and sigb is not None and siga != sigb:
543 out.append('%s changed from %s to %s' % (key, siga, sigb))
544 changecount += 1
545 elif siga is None:
546 out.append('%s was added' % key)
547 addcount += 1
548 elif sigb is None:
549 out.append('%s was removed' % key)
550 removecount += 1
551 out.append('Summary: %d tasks added, %d tasks removed, %d tasks modified (%.1f%%)' % (addcount, removecount, changecount, (changecount / float(len(bdict)) * 100)))
552 return '\n'.join(out)
553
554
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500555def process_changes(repopath, revision1, revision2='HEAD', report_all=False, report_ver=False,
556 sigs=False, sigsdiff=False, exclude_path=None):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500557 repo = git.Repo(repopath)
558 assert repo.bare == False
559 commit = repo.commit(revision1)
560 diff = commit.diff(revision2)
561
562 changes = []
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500563
564 if sigs or sigsdiff:
565 for d in diff.iter_change_type('M'):
566 if d.a_blob.path == 'siglist.txt':
567 changes.append(compare_siglists(d.a_blob, d.b_blob, taskdiff=sigsdiff))
568 return changes
569
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500570 for d in diff.iter_change_type('M'):
571 path = os.path.dirname(d.a_blob.path)
572 if path.startswith('packages/'):
573 filename = os.path.basename(d.a_blob.path)
574 if filename == 'latest':
575 changes.extend(compare_dict_blobs(path, d.a_blob, d.b_blob, report_all, report_ver))
576 elif filename.startswith('latest.'):
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600577 chg = ChangeRecord(path, filename, d.a_blob.data_stream.read().decode('utf-8'), d.b_blob.data_stream.read().decode('utf-8'), True)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500578 changes.append(chg)
579 elif path.startswith('images/'):
580 filename = os.path.basename(d.a_blob.path)
581 if filename in img_monitor_files:
582 if filename == 'files-in-image.txt':
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600583 alines = d.a_blob.data_stream.read().decode('utf-8').splitlines()
584 blines = d.b_blob.data_stream.read().decode('utf-8').splitlines()
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500585 filechanges = compare_file_lists(alines,blines)
586 if filechanges:
587 chg = ChangeRecord(path, filename, None, None, True)
588 chg.filechanges = filechanges
589 changes.append(chg)
590 elif filename == 'installed-package-names.txt':
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600591 alines = d.a_blob.data_stream.read().decode('utf-8').splitlines()
592 blines = d.b_blob.data_stream.read().decode('utf-8').splitlines()
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500593 filechanges = compare_lists(alines,blines)
594 if filechanges:
595 chg = ChangeRecord(path, filename, None, None, True)
596 chg.filechanges = filechanges
597 changes.append(chg)
598 else:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600599 chg = ChangeRecord(path, filename, d.a_blob.data_stream.read().decode('utf-8'), d.b_blob.data_stream.read().decode('utf-8'), True)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500600 changes.append(chg)
601 elif filename == 'image-info.txt':
602 changes.extend(compare_dict_blobs(path, d.a_blob, d.b_blob, report_all, report_ver))
603 elif '/image-files/' in path:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600604 chg = ChangeRecord(path, filename, d.a_blob.data_stream.read().decode('utf-8'), d.b_blob.data_stream.read().decode('utf-8'), True)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500605 changes.append(chg)
606
607 # Look for added preinst/postinst/prerm/postrm
608 # (without reporting newly added recipes)
609 addedpkgs = []
610 addedchanges = []
611 for d in diff.iter_change_type('A'):
612 path = os.path.dirname(d.b_blob.path)
613 if path.startswith('packages/'):
614 filename = os.path.basename(d.b_blob.path)
615 if filename == 'latest':
616 addedpkgs.append(path)
617 elif filename.startswith('latest.'):
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600618 chg = ChangeRecord(path, filename[7:], '', d.b_blob.data_stream.read().decode('utf-8'), True)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500619 addedchanges.append(chg)
620 for chg in addedchanges:
621 found = False
622 for pkg in addedpkgs:
623 if chg.path.startswith(pkg):
624 found = True
625 break
626 if not found:
627 changes.append(chg)
628
629 # Look for cleared preinst/postinst/prerm/postrm
630 for d in diff.iter_change_type('D'):
631 path = os.path.dirname(d.a_blob.path)
632 if path.startswith('packages/'):
633 filename = os.path.basename(d.a_blob.path)
634 if filename != 'latest' and filename.startswith('latest.'):
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600635 chg = ChangeRecord(path, filename[7:], d.a_blob.data_stream.read().decode('utf-8'), '', True)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500636 changes.append(chg)
637
638 # Link related changes
639 for chg in changes:
640 if chg.monitored:
641 for chg2 in changes:
642 # (Check dirname in the case of fields from recipe info files)
643 if chg.path == chg2.path or os.path.dirname(chg.path) == chg2.path:
644 if chg2.fieldname in related_fields.get(chg.fieldname, []):
645 chg.related.append(chg2)
646 elif chg.path == chg2.path and chg.path.startswith('packages/') and chg2.fieldname in ['PE', 'PV', 'PR']:
647 chg.related.append(chg2)
648
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500649 # filter out unwanted paths
650 if exclude_path:
651 for chg in changes:
652 if chg.filechanges:
653 fchgs = []
654 for fchg in chg.filechanges:
655 for epath in exclude_path:
656 if fchg.path.startswith(epath):
657 break
658 else:
659 fchgs.append(fchg)
660 chg.filechanges = fchgs
661
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500662 if report_all:
663 return changes
664 else:
665 return [chg for chg in changes if chg.monitored]