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)
41 def __cmp__(self, other):
42 return cmp(self.type, other.type)
44 return "<SubscriptionType: %s>" % str(self)
45 def string_tree(self, indent=0):
47 for depth,node in self.thread():
48 lines.append("%s%s" % (" "*(indent+2*depth), node))
49 return "\n".join(lines)
52 BUGDIR_TYPE_NEW = SubscriptionType("new")
53 BUGDIR_TYPE_MOD = SubscriptionType("mod")
54 BUGDIR_TYPE_REM = SubscriptionType("rem")
55 BUGDIR_TYPE_ALL = SubscriptionType("all",
56 [BUGDIR_TYPE_NEW, BUGDIR_TYPE_MOD, BUGDIR_TYPE_REM])
58 # same name as BUGDIR_TYPE_ALL for consistency
59 BUG_TYPE_ALL = SubscriptionType(str(BUGDIR_TYPE_ALL))
61 INVALID_TYPE = SubscriptionType("INVALID")
63 class InvalidType (ValueError):
64 def __init__(self, type_name, type_root):
65 msg = "Invalid type %s for tree:\n%s" \
66 % (type_name, type_root.string_tree(4))
67 ValueError.__init__(self, msg)
68 self.type_name = type_name
69 self.type_root = type_root
71 def type_from_name(name, type_root, default=None, default_ok=False):
72 if name == str(type_root):
74 for t in type_root.traverse():
79 raise InvalidType(name, type_root)
81 class Subscription (object):
83 >>> subscriptions = [Subscription('XYZ', 'all'),
84 ... Subscription('DIR', 'new'),
85 ... Subscription('ABC', BUG_TYPE_ALL),]
86 >>> print sorted(subscriptions)
87 [<Subscription: DIR (new)>, <Subscription: ABC (all)>, <Subscription: XYZ (all)>]
89 def __init__(self, id, subscription_type, **kwargs):
90 if 'type_root' not in kwargs:
92 kwargs['type_root'] = BUGDIR_TYPE_ALL
94 kwargs['type_root'] = BUG_TYPE_ALL
95 if type(subscription_type) in types.StringTypes:
96 subscription_type = type_from_name(subscription_type, **kwargs)
98 self.type = subscription_type
99 def __cmp__(self, other):
100 for attr in 'id', 'type':
101 value = cmp(getattr(self, attr), getattr(other, attr))
103 if self.id == BUGDIR_ID:
105 elif other.id == BUGDIR_ID:
109 return str(self.type)
111 return "<Subscription: %s (%s)>" % (self.id, self.type)
113 def subscriptions_from_string(string=None, subscription_sep=',', id_sep=':'):
115 >>> subscriptions_from_string(None)
116 [<Subscription: DIR (all)>]
117 >>> subscriptions_from_string('DIR:new,DIR:rem,ABC:all,XYZ:all')
118 [<Subscription: DIR (new)>, <Subscription: DIR (rem)>, <Subscription: ABC (all)>, <Subscription: XYZ (all)>]
119 >>> subscriptions_from_string('DIR::new')
120 Traceback (most recent call last):
122 ValueError: Invalid subscription "DIR::new", should be ID:TYPE
125 return [Subscription(BUGDIR_ID, BUGDIR_TYPE_ALL)]
127 for subscription in string.split(','):
128 fields = subscription.split(':')
130 raise ValueError('Invalid subscription "%s", should be ID:TYPE'
133 subscriptions.append(Subscription(id, type))
136 class DiffTree (tree.Tree):
138 A tree holding difference data for easy report generation.
139 >>> bugdir = DiffTree("bugdir")
140 >>> bdsettings = DiffTree("settings", data="target: None -> 1.0")
141 >>> bugdir.append(bdsettings)
142 >>> bugs = DiffTree("bugs", "bug-count: 5 -> 6")
143 >>> bugdir.append(bugs)
144 >>> new = DiffTree("new", "new bugs: ABC, DEF")
146 >>> rem = DiffTree("rem", "removed bugs: RST, UVW")
148 >>> print bugdir.report_string()
152 removed bugs: RST, UVW
153 >>> print "\\n".join(bugdir.paths())
159 >>> bugdir.child_by_path("/") == bugdir
161 >>> bugdir.child_by_path("/bugs") == bugs
163 >>> bugdir.child_by_path("/bugs/rem") == rem
165 >>> bugdir.child_by_path("bugdir") == bugdir
167 >>> bugdir.child_by_path("bugdir/") == bugdir
169 >>> bugdir.child_by_path("bugdir/bugs") == bugs
171 >>> bugdir.child_by_path("/bugs").masked = True
172 >>> print bugdir.report_string()
175 def __init__(self, name, data=None, data_part_fn=str,
176 requires_children=False, masked=False):
177 tree.Tree.__init__(self)
180 self.data_part_fn = data_part_fn
181 self.requires_children = requires_children
183 def paths(self, parent_path=None):
185 if parent_path == None:
188 path = "%s/%s" % (parent_path, self.name)
191 paths.extend(child.paths(path))
193 def child_by_path(self, path):
194 if hasattr(path, "split"): # convert string path to a list of names
195 names = path.split("/")
197 names[0] = self.name # replace root with self
198 if len(names) > 1 and names[-1] == "":
199 names = names[:-1] # strip empty tail
200 else: # it was already an array
202 assert len(names) > 0, path
203 if names[0] == self.name:
207 if names[1] == child.name:
208 return child.child_by_path(names[1:])
210 raise KeyError, "%s doesn't match '%s'" % (names, self.name)
211 raise KeyError, "%s points to child not in %s" % (names, [c.name for c in self])
212 def report_string(self):
213 return "\n".join(self.report())
214 def report(self, root=None, parent=None, depth=0):
216 root = self.make_root()
217 if self.masked == True:
219 data_part = self.data_part(depth)
220 if self.requires_children == True \
221 and len([c for c in self if c.masked == False]) == 0:
224 self.join(root, parent, data_part)
225 if data_part != None:
228 root = child.report(root, self, depth)
232 def join(self, root, parent, data_part):
233 if data_part != None:
234 root.append(data_part)
235 def data_part(self, depth, indent=True):
236 if self.data == None:
238 if hasattr(self, "_cached_data_part"):
239 return self._cached_data_part
240 data_part = self.data_part_fn(self.data)
242 data_part_lines = data_part.splitlines()
244 line_sep = "\n"+indent
245 data_part = indent+line_sep.join(data_part_lines)
246 self._cached_data_part = data_part
251 Difference tree generator for BugDirs.
253 >>> bd = bugdir.SimpleBugDir(sync_with_disk=False)
254 >>> bd.user_id = "John Doe <j@doe.com>"
255 >>> bd_new = copy.deepcopy(bd)
256 >>> bd_new.target = "1.0"
257 >>> a = bd_new.bug_from_uuid("a")
258 >>> rep = a.comment_root.new_reply("I'm closing this bug")
259 >>> rep.uuid = "acom"
260 >>> rep.date = "Thu, 01 Jan 1970 00:00:00 +0000"
261 >>> a.status = "closed"
262 >>> b = bd_new.bug_from_uuid("b")
263 >>> bd_new.remove_bug(b)
264 >>> c = bd_new.new_bug("c", "Bug C")
265 >>> d = Diff(bd, bd_new)
266 >>> r = d.report_tree()
267 >>> print "\\n".join(r.paths())
277 bugdir/bugs/mod/a/settings
278 bugdir/bugs/mod/a/comments
279 bugdir/bugs/mod/a/comments/new
280 bugdir/bugs/mod/a/comments/new/acom
281 bugdir/bugs/mod/a/comments/rem
282 bugdir/bugs/mod/a/comments/mod
283 >>> print r.report_string()
284 Changed bug directory settings:
292 Changed bug settings:
293 status: open -> closed
295 from John Doe <j@doe.com> on Thu, 01 Jan 1970 00:00:00 +0000
296 I'm closing this bug...
298 You can also limit the report generation by providing a list of
301 >>> subscriptions = [Subscription('DIR', BUGDIR_TYPE_NEW),
302 ... Subscription('b', BUG_TYPE_ALL)]
303 >>> r = d.report_tree(subscriptions)
304 >>> print r.report_string()
310 While sending subscriptions to report_tree() makes the report
311 generation more efficient (because you may not need to compare
312 _all_ the bugs, etc.), sometimes you will have several sets of
313 subscriptions. In that case, it's better to run full_report()
314 first, and then use report_tree() to avoid redundant comparisons.
317 >>> print d.report_tree([subscriptions[0]]).report_string()
320 >>> print d.report_tree([subscriptions[1]]).report_string()
326 def __init__(self, old_bugdir, new_bugdir):
327 self.old_bugdir = old_bugdir
328 self.new_bugdir = new_bugdir
330 # data assembly methods
332 def _changed_bugs(self, subscriptions):
334 Search for differences in all bugs between .old_bugdir and
336 (added_bugs, modified_bugs, removed_bugs)
337 where added_bugs and removed_bugs are lists of added and
338 removed bugs respectively. modified_bugs is a list of
339 (old_bug,new_bug) pairs.
341 bugdir_types = [s.type for s in subscriptions if s.id == BUGDIR_ID]
344 for bd_type in [BUGDIR_TYPE_ALL, BUGDIR_TYPE_NEW, BUGDIR_TYPE_MOD]:
345 if bd_type in bugdir_types:
346 new_uuids = list(self.new_bugdir.uuids())
348 for bd_type in [BUGDIR_TYPE_ALL, BUGDIR_TYPE_REM]:
349 if bd_type in bugdir_types:
350 old_uuids = list(self.old_bugdir.uuids())
352 subscribed_bugs = [s.id for s in subscriptions
353 if BUG_TYPE_ALL.has_descendant( \
354 s.type, match_self=True)]
355 new_uuids.extend([s for s in subscribed_bugs
356 if self.new_bugdir.has_bug(s)])
357 new_uuids = sorted(set(new_uuids))
358 old_uuids.extend([s for s in subscribed_bugs
359 if self.old_bugdir.has_bug(s)])
360 old_uuids = sorted(set(old_uuids))
364 for uuid in new_uuids:
365 new_bug = self.new_bugdir.bug_from_uuid(uuid)
367 old_bug = self.old_bugdir.bug_from_uuid(uuid)
369 if BUGDIR_TYPE_ALL in bugdir_types \
370 or BUGDIR_TYPE_NEW in bugdir_types \
371 or uuid in subscribed_bugs:
372 added.append(new_bug)
374 if BUGDIR_TYPE_ALL in bugdir_types \
375 or BUGDIR_TYPE_MOD in bugdir_types \
376 or uuid in subscribed_bugs:
377 if old_bug.sync_with_disk == True:
378 old_bug.load_comments()
379 if new_bug.sync_with_disk == True:
380 new_bug.load_comments()
381 if old_bug != new_bug:
382 modified.append((old_bug, new_bug))
383 for uuid in old_uuids:
384 if not self.new_bugdir.has_bug(uuid):
385 old_bug = self.old_bugdir.bug_from_uuid(uuid)
386 removed.append(old_bug)
389 modified.sort(self._bug_modified_cmp)
390 return (added, modified, removed)
391 def _bug_modified_cmp(self, left, right):
392 return cmp(left[1], right[1])
393 def _changed_comments(self, old, new):
395 Search for differences in all loaded comments between the bugs
397 (added_comments, modified_comments, removed_comments)
398 analogous to ._changed_bugs.
400 if hasattr(self, "__changed_comments"):
401 if new.uuid in self.__changed_comments:
402 return self.__changed_comments[new.uuid]
404 self.__changed_comments = {}
408 old.comment_root.sort(key=lambda comm : comm.time)
409 new.comment_root.sort(key=lambda comm : comm.time)
410 old_comment_ids = [c.uuid for c in old.comments()]
411 new_comment_ids = [c.uuid for c in new.comments()]
412 for uuid in new_comment_ids:
413 new_comment = new.comment_from_uuid(uuid)
415 old_comment = old.comment_from_uuid(uuid)
417 added.append(new_comment)
419 if old_comment != new_comment:
420 modified.append((old_comment, new_comment))
421 for uuid in old_comment_ids:
422 if uuid not in new_comment_ids:
423 old_comment = old.comment_from_uuid(uuid)
424 removed.append(old_comment)
425 self.__changed_comments[new.uuid] = (added, modified, removed)
426 return self.__changed_comments[new.uuid]
427 def _attribute_changes(self, old, new, attributes):
429 Take two objects old and new, and compare the value of *.attr
430 for attr in the list attribute names. Returns a list of
431 (attr_name, old_value, new_value)
435 for attr in attributes:
436 old_value = getattr(old, attr)
437 new_value = getattr(new, attr)
438 if old_value != new_value:
439 change_list.append((attr, old_value, new_value))
440 if len(change_list) >= 0:
443 def _settings_properties_attribute_changes(self, old, new,
444 hidden_properties=[]):
445 properties = sorted(new.settings_properties)
446 for p in hidden_properties:
448 attributes = [settings_object.setting_name_to_attr_name(None, p)
450 return self._attribute_changes(old, new, attributes)
451 def _bugdir_attribute_changes(self):
452 return self._settings_properties_attribute_changes( \
453 self.old_bugdir, self.new_bugdir,
454 ["vcs_name"]) # tweaked by bugdir.duplicate_bugdir
455 def _bug_attribute_changes(self, old, new):
456 return self._settings_properties_attribute_changes(old, new)
457 def _comment_attribute_changes(self, old, new):
458 return self._settings_properties_attribute_changes(old, new)
460 # report generation methods
462 def full_report(self, diff_tree=DiffTree):
464 Generate a full report for efficiency if you'll be using
465 .report_tree() with several sets of subscriptions.
467 self._cached_full_report = self.report_tree(diff_tree=diff_tree,
469 self._cached_full_report_diff_tree = diff_tree
470 def _sub_report(self, subscriptions):
472 Return ._cached_full_report masked for subscriptions.
474 root = self._cached_full_report
475 bugdir_types = [s.type for s in subscriptions if s.id == BUGDIR_ID]
476 subscribed_bugs = [s.id for s in subscriptions
477 if BUG_TYPE_ALL.has_descendant( \
478 s.type, match_self=True)]
479 selected_by_bug = [node.name
480 for node in root.child_by_path('bugdir/bugs')]
481 if BUGDIR_TYPE_ALL in bugdir_types:
482 for node in root.traverse():
487 node = root.child_by_path('bugdir/settings')
491 for name,type in (('new', BUGDIR_TYPE_NEW),
492 ('mod', BUGDIR_TYPE_MOD),
493 ('rem', BUGDIR_TYPE_REM)):
494 if type in bugdir_types:
495 bugs = root.child_by_path('bugdir/bugs/%s' % name)
496 for bug_node in bugs:
497 for node in bug_node.traverse():
499 selected_by_bug.remove(name)
500 for name in selected_by_bug:
501 bugs = root.child_by_path('bugdir/bugs/%s' % name)
502 for bug_node in bugs:
503 if bug_node.name in subscribed_bugs:
504 for node in bug_node.traverse():
507 for node in bug_node.traverse():
510 def report_tree(self, subscriptions=None, diff_tree=DiffTree,
513 Pretty bare to make it easy to adjust to specific cases. You
514 can pass in a DiffTree subclass via diff_tree to override the
515 default report assembly process.
517 if allow_cached == True \
518 and hasattr(self, '_cached_full_report') \
519 and diff_tree == self._cached_full_report_diff_tree:
520 return self._sub_report(subscriptions)
521 if subscriptions == None:
522 subscriptions = [Subscription(BUGDIR_ID, BUGDIR_TYPE_ALL)]
523 bugdir_settings = sorted(self.new_bugdir.settings_properties)
524 bugdir_settings.remove("vcs_name") # tweaked by bugdir.duplicate_bugdir
525 root = diff_tree("bugdir")
526 bugdir_subscriptions = [s.type for s in subscriptions
527 if s.id == BUGDIR_ID]
528 if BUGDIR_TYPE_ALL in bugdir_subscriptions:
529 bugdir_attribute_changes = self._bugdir_attribute_changes()
530 if len(bugdir_attribute_changes) > 0:
531 bugdir = diff_tree("settings", bugdir_attribute_changes,
532 self.bugdir_attribute_change_string)
534 bug_root = diff_tree("bugs")
535 root.append(bug_root)
536 add,mod,rem = self._changed_bugs(subscriptions)
537 bnew = diff_tree("new", "New bugs:", requires_children=True)
538 bug_root.append(bnew)
540 b = diff_tree(bug.uuid, bug, self.bug_add_string)
542 brem = diff_tree("rem", "Removed bugs:", requires_children=True)
543 bug_root.append(brem)
545 b = diff_tree(bug.uuid, bug, self.bug_rem_string)
547 bmod = diff_tree("mod", "Modified bugs:", requires_children=True)
548 bug_root.append(bmod)
550 b = diff_tree(new.uuid, (old,new), self.bug_mod_string)
552 bug_attribute_changes = self._bug_attribute_changes(old, new)
553 if len(bug_attribute_changes) > 0:
554 bset = diff_tree("settings", bug_attribute_changes,
555 self.bug_attribute_change_string)
557 if old.summary != new.summary:
558 data = (old.summary, new.summary)
559 bsum = diff_tree("summary", data, self.bug_summary_change_string)
561 cr = diff_tree("comments")
563 a,m,d = self._changed_comments(old, new)
564 cnew = diff_tree("new", "New comments:", requires_children=True)
566 c = diff_tree(comment.uuid, comment, self.comment_add_string)
568 crem = diff_tree("rem", "Removed comments:",requires_children=True)
570 c = diff_tree(comment.uuid, comment, self.comment_rem_string)
572 cmod = diff_tree("mod","Modified comments:",requires_children=True)
574 c = diff_tree(n.uuid, (o,n), self.comment_mod_string)
576 comm_attribute_changes = self._comment_attribute_changes(o, n)
577 if len(comm_attribute_changes) > 0:
578 cset = diff_tree("settings", comm_attribute_changes,
579 self.comment_attribute_change_string)
581 data = (o.body, n.body)
582 cbody = diff_tree("cbody", data,
583 self.comment_body_change_string)
585 cr.extend([cnew, crem, cmod])
588 # change data -> string methods.
589 # Feel free to play with these in subclasses.
591 def attribute_change_string(self, attribute_changes, indent=0):
592 indent_string = " "*indent
593 change_strings = [u"%s: %s -> %s" % f for f in attribute_changes]
594 for i,change_string in enumerate(change_strings):
595 change_strings[i] = indent_string+change_string
596 return u"\n".join(change_strings)
597 def bugdir_attribute_change_string(self, attribute_changes):
598 return "Changed bug directory settings:\n%s" % \
599 self.attribute_change_string(attribute_changes, indent=1)
600 def bug_attribute_change_string(self, attribute_changes):
601 return "Changed bug settings:\n%s" % \
602 self.attribute_change_string(attribute_changes, indent=1)
603 def comment_attribute_change_string(self, attribute_changes):
604 return "Changed comment settings:\n%s" % \
605 self.attribute_change_string(attribute_changes, indent=1)
606 def bug_add_string(self, bug):
607 return bug.string(shortlist=True)
608 def bug_rem_string(self, bug):
609 return bug.string(shortlist=True)
610 def bug_mod_string(self, bugs):
611 old_bug,new_bug = bugs
612 return new_bug.string(shortlist=True)
613 def bug_summary_change_string(self, summaries):
614 old_summary,new_summary = summaries
615 return "summary changed:\n %s\n %s" % (old_summary, new_summary)
616 def _comment_summary_string(self, comment):
617 return "from %s on %s" % (comment.author, time_to_str(comment.time))
618 def comment_add_string(self, comment):
619 summary = self._comment_summary_string(comment)
620 first_line = comment.body.splitlines()[0]
621 return "%s\n %s..." % (summary, first_line)
622 def comment_rem_string(self, comment):
623 summary = self._comment_summary_string(comment)
624 first_line = comment.body.splitlines()[0]
625 return "%s\n %s..." % (summary, first_line)
626 def comment_mod_string(self, comments):
627 old_comment,new_comment = comments
628 return self._comment_summary_string(new_comment)
629 def comment_body_change_string(self, bodies):
630 old_body,new_body = bodies
631 return difflib.unified_diff(old_body, new_body)
634 if libbe.TESTING == True:
635 suite = doctest.DocTestSuite()