1 # Copyright (C) 2005-2009 Aaron Bentley and Panometrics, Inc.
2 # Gianluca Montecchi <gian@grys.it>
3 # W. Trevor King <wking@drexel.edu>
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 2 of the License, or
8 # (at your option) any later version.
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
15 # You should have received a copy of the GNU General Public License along
16 # with this program; if not, write to the Free Software Foundation, Inc.,
17 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19 """Compare two bug trees."""
25 from libbe import bugdir, bug, settings_object, tree
26 from libbe.utility import time_to_str
27 if libbe.TESTING == True:
31 class SubscriptionType (tree.Tree):
33 Trees of subscription types to allow users to select exactly what
34 notifications they want to subscribe to.
36 def __init__(self, type_name, *args, **kwargs):
37 tree.Tree.__init__(self, *args, **kwargs)
42 return "<SubscriptionType: %s>" % str(self)
43 def string_tree(self, indent=0):
45 for depth,node in self.thread():
46 lines.append("%s%s" % (" "*(indent+2*depth), node))
47 return "\n".join(lines)
50 BUGDIR_TYPE_NEW = SubscriptionType("new")
51 BUGDIR_TYPE_MOD = SubscriptionType("mod")
52 BUGDIR_TYPE_REM = SubscriptionType("rem")
53 BUGDIR_TYPE_ALL = SubscriptionType("all",
54 [BUGDIR_TYPE_NEW, BUGDIR_TYPE_MOD, BUGDIR_TYPE_REM])
56 # same name as BUGDIR_TYPE_ALL for consistency
57 BUG_TYPE_ALL = SubscriptionType(str(BUGDIR_TYPE_ALL))
59 INVALID_TYPE = SubscriptionType("INVALID")
61 class InvalidType (ValueError):
62 def __init__(self, type_name, type_root):
63 msg = "Invalid type %s for tree:\n%s" \
64 % (type_name, type_root.string_tree(4))
65 ValueError.__init__(self, msg)
66 self.type_name = type_name
67 self.type_root = type_root
69 def type_from_name(name, type_root, default=None, default_ok=False):
70 if name == str(type_root):
72 for t in type_root.traverse():
77 raise InvalidType(name, type_root)
79 class Subscription (object):
81 >>> subscriptions = [Subscription('XYZ', 'all'),
82 ... Subscription('DIR', 'new'),
83 ... Subscription('ABC', BUG_TYPE_ALL),]
84 >>> print sorted(subscriptions)
85 [<Subscription: DIR (new)>, <Subscription: ABC (all)>, <Subscription: XYZ (all)>]
87 def __init__(self, id, subscription_type, **kwargs):
88 if 'type_root' not in kwargs:
90 kwargs['type_root'] = BUGDIR_TYPE_ALL
92 kwargs['type_root'] = BUG_TYPE_ALL
93 if type(subscription_type) in types.StringTypes:
94 subscription_type = type_from_name(subscription_type, **kwargs)
96 self.type = subscription_type
97 def __cmp__(self, other):
98 for attr in 'id', 'type':
99 value = cmp(getattr(self, attr), getattr(other, attr))
101 if self.id == BUGDIR_ID:
103 elif other.id == BUGDIR_ID:
107 return str(self.type)
109 return "<Subscription: %s (%s)>" % (self.id, self.type)
111 def subscriptions_from_string(string=None, subscription_sep=',', id_sep=':'):
113 >>> subscriptions_from_string(None)
114 [<Subscription: DIR (all)>]
115 >>> subscriptions_from_string('DIR:new,DIR:rem,ABC:all,XYZ:all')
116 [<Subscription: DIR (new)>, <Subscription: DIR (rem)>, <Subscription: ABC (all)>, <Subscription: XYZ (all)>]
117 >>> subscriptions_from_string('DIR::new')
118 Traceback (most recent call last):
120 ValueError: Invalid subscription "DIR::new", should be ID:TYPE
123 return [Subscription(BUGDIR_ID, BUGDIR_TYPE_ALL)]
125 for subscription in string.split(','):
126 fields = subscription.split(':')
128 raise ValueError('Invalid subscription "%s", should be ID:TYPE'
131 subscriptions.append(Subscription(id, type))
134 class DiffTree (tree.Tree):
136 A tree holding difference data for easy report generation.
137 >>> bugdir = DiffTree("bugdir")
138 >>> bdsettings = DiffTree("settings", data="target: None -> 1.0")
139 >>> bugdir.append(bdsettings)
140 >>> bugs = DiffTree("bugs", "bug-count: 5 -> 6")
141 >>> bugdir.append(bugs)
142 >>> new = DiffTree("new", "new bugs: ABC, DEF")
144 >>> rem = DiffTree("rem", "removed bugs: RST, UVW")
146 >>> print bugdir.report_string()
150 removed bugs: RST, UVW
151 >>> print "\\n".join(bugdir.paths())
157 >>> bugdir.child_by_path("/") == bugdir
159 >>> bugdir.child_by_path("/bugs") == bugs
161 >>> bugdir.child_by_path("/bugs/rem") == rem
163 >>> bugdir.child_by_path("bugdir") == bugdir
165 >>> bugdir.child_by_path("bugdir/") == bugdir
167 >>> bugdir.child_by_path("bugdir/bugs") == bugs
169 >>> bugdir.child_by_path("/bugs").masked = True
170 >>> print bugdir.report_string()
173 def __init__(self, name, data=None, data_part_fn=str,
174 requires_children=False, masked=False):
175 tree.Tree.__init__(self)
178 self.data_part_fn = data_part_fn
179 self.requires_children = requires_children
181 def paths(self, parent_path=None):
183 if parent_path == None:
186 path = "%s/%s" % (parent_path, self.name)
189 paths.extend(child.paths(path))
191 def child_by_path(self, path):
192 if hasattr(path, "split"): # convert string path to a list of names
193 names = path.split("/")
195 names[0] = self.name # replace root with self
196 if len(names) > 1 and names[-1] == "":
197 names = names[:-1] # strip empty tail
198 else: # it was already an array
200 assert len(names) > 0, path
201 if names[0] == self.name:
205 if names[1] == child.name:
206 return child.child_by_path(names[1:])
208 raise KeyError, "%s doesn't match '%s'" % (names, self.name)
209 raise KeyError, "%s points to child not in %s" % (names, [c.name for c in self])
210 def report_string(self):
211 return "\n".join(self.report())
212 def report(self, root=None, parent=None, depth=0):
214 root = self.make_root()
215 if self.masked == True:
217 data_part = self.data_part(depth)
218 if self.requires_children == True \
219 and len([c for c in self if c.masked == False]) == 0:
222 self.join(root, parent, data_part)
223 if data_part != None:
226 child.report(root, self, depth)
230 def join(self, root, parent, data_part):
231 if data_part != None:
232 root.append(data_part)
233 def data_part(self, depth, indent=True):
234 if self.data == None:
236 if hasattr(self, "_cached_data_part"):
237 return self._cached_data_part
238 data_part = self.data_part_fn(self.data)
240 data_part_lines = data_part.splitlines()
242 line_sep = "\n"+indent
243 data_part = indent+line_sep.join(data_part_lines)
244 self._cached_data_part = data_part
249 Difference tree generator for BugDirs.
251 >>> bd = bugdir.SimpleBugDir(sync_with_disk=False)
252 >>> bd.user_id = "John Doe <j@doe.com>"
253 >>> bd_new = copy.deepcopy(bd)
254 >>> bd_new.target = "1.0"
255 >>> a = bd_new.bug_from_uuid("a")
256 >>> rep = a.comment_root.new_reply("I'm closing this bug")
257 >>> rep.uuid = "acom"
258 >>> rep.date = "Thu, 01 Jan 1970 00:00:00 +0000"
259 >>> a.status = "closed"
260 >>> b = bd_new.bug_from_uuid("b")
261 >>> bd_new.remove_bug(b)
262 >>> c = bd_new.new_bug("c", "Bug C")
263 >>> d = Diff(bd, bd_new)
264 >>> r = d.report_tree()
265 >>> print "\\n".join(r.paths())
275 bugdir/bugs/mod/a/settings
276 bugdir/bugs/mod/a/comments
277 bugdir/bugs/mod/a/comments/new
278 bugdir/bugs/mod/a/comments/new/acom
279 bugdir/bugs/mod/a/comments/rem
280 bugdir/bugs/mod/a/comments/mod
281 >>> print r.report_string()
282 Changed bug directory settings:
290 Changed bug settings:
291 status: open -> closed
293 from John Doe <j@doe.com> on Thu, 01 Jan 1970 00:00:00 +0000
294 I'm closing this bug...
296 You can also limit the report generation by providing a list of
299 >>> subscriptions = [Subscription('DIR', BUGDIR_TYPE_NEW),
300 ... Subscription('b', BUG_TYPE_ALL)]
301 >>> r = d.report_tree(subscriptions)
302 >>> print r.report_string()
308 While sending subscriptions to report_tree() makes the report
309 generation more efficient (because you may not need to compare
310 _all_ the bugs, etc.), sometimes you will have several sets of
311 subscriptions. In that case, it's better to run full_report()
312 first, and then use report_tree() to avoid redundant comparisons.
315 >>> print d.report_tree([subscriptions[0]]).report_string()
318 >>> print d.report_tree([subscriptions[1]]).report_string()
324 def __init__(self, old_bugdir, new_bugdir):
325 self.old_bugdir = old_bugdir
326 self.new_bugdir = new_bugdir
328 # data assembly methods
330 def _changed_bugs(self, subscriptions):
332 Search for differences in all bugs between .old_bugdir and
334 (added_bugs, modified_bugs, removed_bugs)
335 where added_bugs and removed_bugs are lists of added and
336 removed bugs respectively. modified_bugs is a list of
337 (old_bug,new_bug) pairs.
339 bugdir_types = [s.type for s in subscriptions if s.id == BUGDIR_ID]
342 for bd_type in [BUGDIR_TYPE_ALL, BUGDIR_TYPE_NEW, BUGDIR_TYPE_MOD]:
343 if bd_type in bugdir_types:
344 new_uuids = list(self.new_bugdir.uuids())
346 for bd_type in [BUGDIR_TYPE_ALL, BUGDIR_TYPE_REM]:
347 if bd_type in bugdir_types:
348 old_uuids = list(self.old_bugdir.uuids())
350 subscribed_bugs = [s.id for s in subscriptions
351 if BUG_TYPE_ALL.has_descendant( \
352 s.type, match_self=True)]
353 new_uuids.extend([s for s in subscribed_bugs
354 if self.new_bugdir.has_bug(s)])
355 new_uuids = sorted(set(new_uuids))
356 old_uuids.extend([s for s in subscribed_bugs
357 if self.old_bugdir.has_bug(s)])
358 old_uuids = sorted(set(old_uuids))
362 for uuid in new_uuids:
363 new_bug = self.new_bugdir.bug_from_uuid(uuid)
365 old_bug = self.old_bugdir.bug_from_uuid(uuid)
367 if BUGDIR_TYPE_ALL in bugdir_types \
368 or BUGDIR_TYPE_NEW in bugdir_types \
369 or uuid in subscribed_bugs:
370 added.append(new_bug)
372 if BUGDIR_TYPE_ALL in bugdir_types \
373 or BUGDIR_TYPE_MOD in bugdir_types \
374 or uuid in subscribed_bugs:
375 if old_bug.sync_with_disk == True:
376 old_bug.load_comments()
377 if new_bug.sync_with_disk == True:
378 new_bug.load_comments()
379 if old_bug != new_bug:
380 modified.append((old_bug, new_bug))
381 for uuid in old_uuids:
382 if not self.new_bugdir.has_bug(uuid):
383 old_bug = self.old_bugdir.bug_from_uuid(uuid)
384 removed.append(old_bug)
387 modified.sort(self._bug_modified_cmp)
388 return (added, modified, removed)
389 def _bug_modified_cmp(self, left, right):
390 return cmp(left[1], right[1])
391 def _changed_comments(self, old, new):
393 Search for differences in all loaded comments between the bugs
395 (added_comments, modified_comments, removed_comments)
396 analogous to ._changed_bugs.
398 if hasattr(self, "__changed_comments"):
399 if new.uuid in self.__changed_comments:
400 return self.__changed_comments[new.uuid]
402 self.__changed_comments = {}
406 old.comment_root.sort(key=lambda comm : comm.time)
407 new.comment_root.sort(key=lambda comm : comm.time)
408 old_comment_ids = [c.uuid for c in old.comments()]
409 new_comment_ids = [c.uuid for c in new.comments()]
410 for uuid in new_comment_ids:
411 new_comment = new.comment_from_uuid(uuid)
413 old_comment = old.comment_from_uuid(uuid)
415 added.append(new_comment)
417 if old_comment != new_comment:
418 modified.append((old_comment, new_comment))
419 for uuid in old_comment_ids:
420 if uuid not in new_comment_ids:
421 old_comment = old.comment_from_uuid(uuid)
422 removed.append(old_comment)
423 self.__changed_comments[new.uuid] = (added, modified, removed)
424 return self.__changed_comments[new.uuid]
425 def _attribute_changes(self, old, new, attributes):
427 Take two objects old and new, and compare the value of *.attr
428 for attr in the list attribute names. Returns a list of
429 (attr_name, old_value, new_value)
433 for attr in attributes:
434 old_value = getattr(old, attr)
435 new_value = getattr(new, attr)
436 if old_value != new_value:
437 change_list.append((attr, old_value, new_value))
438 if len(change_list) >= 0:
441 def _settings_properties_attribute_changes(self, old, new,
442 hidden_properties=[]):
443 properties = sorted(new.settings_properties)
444 for p in hidden_properties:
446 attributes = [settings_object.setting_name_to_attr_name(None, p)
448 return self._attribute_changes(old, new, attributes)
449 def _bugdir_attribute_changes(self):
450 return self._settings_properties_attribute_changes( \
451 self.old_bugdir, self.new_bugdir,
452 ["vcs_name"]) # tweaked by bugdir.duplicate_bugdir
453 def _bug_attribute_changes(self, old, new):
454 return self._settings_properties_attribute_changes(old, new)
455 def _comment_attribute_changes(self, old, new):
456 return self._settings_properties_attribute_changes(old, new)
458 # report generation methods
460 def full_report(self, diff_tree=DiffTree):
462 Generate a full report for efficiency if you'll be using
463 .report_tree() with several sets of subscriptions.
465 self._cached_full_report = self.report_tree(diff_tree=diff_tree,
467 self._cached_full_report_diff_tree = diff_tree
468 def _sub_report(self, subscriptions):
470 Return ._cached_full_report masked for subscriptions.
472 root = self._cached_full_report
473 bugdir_types = [s.type for s in subscriptions if s.id == BUGDIR_ID]
474 subscribed_bugs = [s.id for s in subscriptions
475 if BUG_TYPE_ALL.has_descendant( \
476 s.type, match_self=True)]
477 selected_by_bug = [node.name
478 for node in root.child_by_path('bugdir/bugs')]
479 if BUGDIR_TYPE_ALL in bugdir_types:
480 for node in root.traverse():
484 node = root.child_by_path('bugdir/settings')
486 for name,type in (('new', BUGDIR_TYPE_NEW),
487 ('mod', BUGDIR_TYPE_MOD),
488 ('rem', BUGDIR_TYPE_REM)):
489 if type in bugdir_types:
490 bugs = root.child_by_path('bugdir/bugs/%s' % name)
491 for bug_node in bugs:
492 for node in bug_node.traverse():
494 selected_by_bug.remove(name)
495 for name in selected_by_bug:
496 bugs = root.child_by_path('bugdir/bugs/%s' % name)
497 for bug_node in bugs:
498 if bug_node.name in subscribed_bugs:
499 for node in bug_node.traverse():
502 for node in bug_node.traverse():
505 def report_tree(self, subscriptions=None, diff_tree=DiffTree,
508 Pretty bare to make it easy to adjust to specific cases. You
509 can pass in a DiffTree subclass via diff_tree to override the
510 default report assembly process.
512 if allow_cached == True \
513 and hasattr(self, '_cached_full_report') \
514 and diff_tree == self._cached_full_report_diff_tree:
515 return self._sub_report(subscriptions)
516 if subscriptions == None:
517 subscriptions = [Subscription(BUGDIR_ID, BUGDIR_TYPE_ALL)]
518 bugdir_settings = sorted(self.new_bugdir.settings_properties)
519 bugdir_settings.remove("vcs_name") # tweaked by bugdir.duplicate_bugdir
520 root = diff_tree("bugdir")
521 bugdir_subscriptions = [s.type for s in subscriptions
522 if s.id == BUGDIR_ID]
523 if BUGDIR_TYPE_ALL in bugdir_subscriptions:
524 bugdir_attribute_changes = self._bugdir_attribute_changes()
525 if len(bugdir_attribute_changes) > 0:
526 bugdir = diff_tree("settings", bugdir_attribute_changes,
527 self.bugdir_attribute_change_string)
529 bug_root = diff_tree("bugs")
530 root.append(bug_root)
531 add,mod,rem = self._changed_bugs(subscriptions)
532 bnew = diff_tree("new", "New bugs:", requires_children=True)
533 bug_root.append(bnew)
535 b = diff_tree(bug.uuid, bug, self.bug_add_string)
537 brem = diff_tree("rem", "Removed bugs:", requires_children=True)
538 bug_root.append(brem)
540 b = diff_tree(bug.uuid, bug, self.bug_rem_string)
542 bmod = diff_tree("mod", "Modified bugs:", requires_children=True)
543 bug_root.append(bmod)
545 b = diff_tree(new.uuid, (old,new), self.bug_mod_string)
547 bug_attribute_changes = self._bug_attribute_changes(old, new)
548 if len(bug_attribute_changes) > 0:
549 bset = diff_tree("settings", bug_attribute_changes,
550 self.bug_attribute_change_string)
552 if old.summary != new.summary:
553 data = (old.summary, new.summary)
554 bsum = diff_tree("summary", data, self.bug_summary_change_string)
556 cr = diff_tree("comments")
558 a,m,d = self._changed_comments(old, new)
559 cnew = diff_tree("new", "New comments:", requires_children=True)
561 c = diff_tree(comment.uuid, comment, self.comment_add_string)
563 crem = diff_tree("rem", "Removed comments:",requires_children=True)
565 c = diff_tree(comment.uuid, comment, self.comment_rem_string)
567 cmod = diff_tree("mod","Modified comments:",requires_children=True)
569 c = diff_tree(n.uuid, (o,n), self.comment_mod_string)
571 comm_attribute_changes = self._comment_attribute_changes(o, n)
572 if len(comm_attribute_changes) > 0:
573 cset = diff_tree("settings", comm_attribute_changes,
574 self.comment_attribute_change_string)
576 data = (o.body, n.body)
577 cbody = diff_tree("cbody", data,
578 self.comment_body_change_string)
580 cr.extend([cnew, crem, cmod])
583 # change data -> string methods.
584 # Feel free to play with these in subclasses.
586 def attribute_change_string(self, attribute_changes, indent=0):
587 indent_string = " "*indent
588 change_strings = [u"%s: %s -> %s" % f for f in attribute_changes]
589 for i,change_string in enumerate(change_strings):
590 change_strings[i] = indent_string+change_string
591 return u"\n".join(change_strings)
592 def bugdir_attribute_change_string(self, attribute_changes):
593 return "Changed bug directory settings:\n%s" % \
594 self.attribute_change_string(attribute_changes, indent=1)
595 def bug_attribute_change_string(self, attribute_changes):
596 return "Changed bug settings:\n%s" % \
597 self.attribute_change_string(attribute_changes, indent=1)
598 def comment_attribute_change_string(self, attribute_changes):
599 return "Changed comment settings:\n%s" % \
600 self.attribute_change_string(attribute_changes, indent=1)
601 def bug_add_string(self, bug):
602 return bug.string(shortlist=True)
603 def bug_rem_string(self, bug):
604 return bug.string(shortlist=True)
605 def bug_mod_string(self, bugs):
606 old_bug,new_bug = bugs
607 return new_bug.string(shortlist=True)
608 def bug_summary_change_string(self, summaries):
609 old_summary,new_summary = summaries
610 return "summary changed:\n %s\n %s" % (old_summary, new_summary)
611 def _comment_summary_string(self, comment):
612 return "from %s on %s" % (comment.author, time_to_str(comment.time))
613 def comment_add_string(self, comment):
614 summary = self._comment_summary_string(comment)
615 first_line = comment.body.splitlines()[0]
616 return "%s\n %s..." % (summary, first_line)
617 def comment_rem_string(self, comment):
618 summary = self._comment_summary_string(comment)
619 first_line = comment.body.splitlines()[0]
620 return "%s\n %s..." % (summary, first_line)
621 def comment_mod_string(self, comments):
622 old_comment,new_comment = comments
623 return self._comment_summary_string(new_comment)
624 def comment_body_change_string(self, bodies):
625 old_body,new_body = bodies
626 return difflib.unified_diff(old_body, new_body)
629 if libbe.TESTING == True:
630 suite = doctest.DocTestSuite()