3
This module contains the code to manage the diff window which shows
4
the changes made between two revisions on a branch.
7
__copyright__ = "Copyright 2005 Canonical Ltd."
8
__author__ = "Scott James Remnant <scott@ubuntu.com>"
11
from cStringIO import StringIO
22
from xml.etree.ElementTree import Element, SubElement, tostring
24
from elementtree.ElementTree import Element, SubElement, tostring
28
have_gtksourceview = True
30
have_gtksourceview = False
44
from bzrlib.diff import show_diff_trees, internal_diff
45
from bzrlib.patches import parse_patches
46
from bzrlib.trace import warning
47
from bzrlib.plugins.gtk import _i18n
48
from bzrlib.plugins.gtk.window import Window
49
from dialog import error_dialog, info_dialog, warning_dialog
52
def fallback_guess_language(slm, content_type):
53
for lang_id in slm.get_language_ids():
54
lang = slm.get_language(lang_id)
55
if "text/x-patch" in lang.get_mime_types():
60
class SelectCancelled(Exception):
65
class DiffFileView(gtk.ScrolledWindow):
66
"""Window for displaying diffs from a diff file"""
69
gtk.ScrolledWindow.__init__(self)
74
self.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
75
self.set_shadow_type(gtk.SHADOW_IN)
77
if have_gtksourceview:
78
self.buffer = gtksourceview2.Buffer()
79
slm = gtksourceview2.LanguageManager()
80
guess_language = getattr(gtksourceview2.LanguageManager,
81
"guess_language", fallback_guess_language)
82
gsl = guess_language(slm, content_type="text/x-patch")
84
self.apply_gedit_colors(self.buffer)
85
self.apply_colordiff_colors(self.buffer)
86
self.buffer.set_language(gsl)
87
self.buffer.set_highlight_syntax(True)
89
self.sourceview = gtksourceview2.View(self.buffer)
91
self.buffer = gtk.TextBuffer()
92
self.sourceview = gtk.TextView(self.buffer)
94
self.sourceview.set_editable(False)
95
self.sourceview.modify_font(pango.FontDescription("Monospace"))
96
self.add(self.sourceview)
97
self.sourceview.show()
100
def apply_gedit_colors(buf):
101
"""Set style to that specified in gedit configuration.
103
This method needs the gconf module.
105
:param buf: a gtksourceview2.Buffer object.
107
GEDIT_SCHEME_PATH = '/apps/gedit-2/preferences/editor/colors/scheme'
108
GEDIT_USER_STYLES_PATH = os.path.expanduser('~/.gnome2/gedit/styles')
110
client = gconf.client_get_default()
111
style_scheme_name = client.get_string(GEDIT_SCHEME_PATH)
112
if style_scheme_name is not None:
113
style_scheme_mgr = gtksourceview2.StyleSchemeManager()
114
style_scheme_mgr.append_search_path(GEDIT_USER_STYLES_PATH)
116
style_scheme = style_scheme_mgr.get_scheme(style_scheme_name)
118
if style_scheme is not None:
119
buf.set_style_scheme(style_scheme)
122
def apply_colordiff_colors(klass, buf):
123
"""Set style colors for lang using the colordiff configuration file.
125
Both ~/.colordiffrc and ~/.colordiffrc.bzr-gtk are read.
127
:param buf: a "Diff" gtksourceview2.Buffer object.
129
scheme_manager = gtksourceview2.StyleSchemeManager()
130
style_scheme = scheme_manager.get_scheme('colordiff')
132
# if style scheme not found, we'll generate it from colordiffrc
133
# TODO: reload if colordiffrc has changed.
134
if style_scheme is None:
137
for f in ('~/.colordiffrc', '~/.colordiffrc.bzr-gtk'):
138
f = os.path.expanduser(f)
139
if os.path.exists(f):
143
warning('could not open file %s: %s' % (f, str(e)))
145
colors.update(klass.parse_colordiffrc(f))
149
# ~/.colordiffrc does not exist
153
# map GtkSourceView2 scheme styles to colordiff names
154
# since GSV is richer, accept new names for extra bits,
155
# defaulting to old names if they're not present
156
'diff:added-line': ['newtext'],
157
'diff:removed-line': ['oldtext'],
158
'diff:location': ['location', 'diffstuff'],
159
'diff:file': ['file', 'diffstuff'],
160
'diff:special-case': ['specialcase', 'diffstuff'],
163
converted_colors = {}
164
for name, values in mapping.items():
167
color = colors.get(value, None)
168
if color is not None:
172
converted_colors[name] = color
174
# some xml magic to produce needed style scheme description
175
e_style_scheme = Element('style-scheme')
176
e_style_scheme.set('id', 'colordiff')
177
e_style_scheme.set('_name', 'ColorDiff')
178
e_style_scheme.set('version', '1.0')
179
for name, color in converted_colors.items():
180
style = SubElement(e_style_scheme, 'style')
181
style.set('name', name)
182
style.set('foreground', '#%s' % color)
184
scheme_xml = tostring(e_style_scheme, 'UTF-8')
185
if not os.path.exists(os.path.expanduser('~/.local/share/gtksourceview-2.0/styles')):
186
os.makedirs(os.path.expanduser('~/.local/share/gtksourceview-2.0/styles'))
187
file(os.path.expanduser('~/.local/share/gtksourceview-2.0/styles/colordiff.xml'), 'w').write(scheme_xml)
189
scheme_manager.force_rescan()
190
style_scheme = scheme_manager.get_scheme('colordiff')
192
buf.set_style_scheme(style_scheme)
195
def parse_colordiffrc(fileobj):
196
"""Parse fileobj as a colordiff configuration file.
198
:return: A dict with the key -> value pairs.
202
if re.match(r'^\s*#', line):
206
key, val = line.split('=', 1)
207
colors[key.strip()] = val.strip()
210
def set_trees(self, rev_tree, parent_tree):
211
self.rev_tree = rev_tree
212
self.parent_tree = parent_tree
213
# self._build_delta()
215
# def _build_delta(self):
216
# self.parent_tree.lock_read()
217
# self.rev_tree.lock_read()
219
# self.delta = iter_changes_to_status(self.parent_tree, self.rev_tree)
220
# self.path_to_status = {}
221
# self.path_to_diff = {}
222
# source_inv = self.parent_tree.inventory
223
# target_inv = self.rev_tree.inventory
224
# for (file_id, real_path, change_type, display_path) in self.delta:
225
# self.path_to_status[real_path] = u'=== %s %s' % (change_type, display_path)
226
# if change_type in ('modified', 'renamed and modified'):
227
# source_ie = source_inv[file_id]
228
# target_ie = target_inv[file_id]
230
# source_ie.diff(internal_diff, *old path, *old_tree,
231
# *new_path, target_ie, self.rev_tree,
233
# self.path_to_diff[real_path] =
236
# self.rev_tree.unlock()
237
# self.parent_tree.unlock()
239
def show_diff(self, specific_files):
241
if specific_files is None:
242
self.buffer.set_text(self._diffs[None])
244
for specific_file in specific_files:
245
sections.append(self._diffs[specific_file])
246
self.buffer.set_text(''.join(sections))
249
class DiffView(DiffFileView):
250
"""This is the soft and chewy filling for a DiffWindow."""
253
DiffFileView.__init__(self)
255
self.parent_tree = None
257
def show_diff(self, specific_files):
258
"""Show the diff for the specified files"""
260
show_diff_trees(self.parent_tree, self.rev_tree, s, specific_files,
261
old_label='', new_label='',
262
# path_encoding=sys.getdefaultencoding()
263
# The default is utf-8, but we interpret the file
264
# contents as getdefaultencoding(), so we should
265
# probably try to make the paths in the same encoding.
267
# str.decode(encoding, 'replace') doesn't do anything. Because if a
268
# character is not valid in 'encoding' there is nothing to replace, the
269
# 'replace' is for 'str.encode()'
271
decoded = s.getvalue().decode(sys.getdefaultencoding())
272
except UnicodeDecodeError:
274
decoded = s.getvalue().decode('UTF-8')
275
except UnicodeDecodeError:
276
decoded = s.getvalue().decode('iso-8859-1')
277
# This always works, because every byte has a valid
278
# mapping from iso-8859-1 to Unicode
279
# TextBuffer must contain pure UTF-8 data
280
self.buffer.set_text(decoded.encode('UTF-8'))
283
class DiffWidget(gtk.HPaned):
288
super(DiffWidget, self).__init__()
290
# The file hierarchy: a scrollable treeview
291
scrollwin = gtk.ScrolledWindow()
292
scrollwin.set_policy(gtk.POLICY_NEVER, gtk.POLICY_AUTOMATIC)
293
scrollwin.set_shadow_type(gtk.SHADOW_IN)
294
self.pack1(scrollwin)
297
self.model = gtk.TreeStore(str, str)
298
self.treeview = gtk.TreeView(self.model)
299
self.treeview.set_headers_visible(False)
300
self.treeview.set_search_column(1)
301
self.treeview.connect("cursor-changed", self._treeview_cursor_cb)
302
scrollwin.add(self.treeview)
305
cell = gtk.CellRendererText()
306
cell.set_property("width-chars", 20)
307
column = gtk.TreeViewColumn()
308
column.pack_start(cell, expand=True)
309
column.add_attribute(cell, "text", 0)
310
self.treeview.append_column(column)
312
def set_diff_text(self, lines):
313
"""Set the current diff from a list of lines
315
:param lines: The diff to show, in unified diff format
317
# The diffs of the selected file: a scrollable source or
320
def set_diff_text_sections(self, sections):
321
if getattr(self, 'diff_view', None) is None:
322
self.diff_view = DiffFileView()
323
self.pack2(self.diff_view)
324
self.diff_view.show()
325
for oldname, newname, patch in sections:
326
self.diff_view._diffs[newname] = str(patch)
329
self.model.append(None, [oldname, newname])
330
self.diff_view.show_diff(None)
332
def set_diff(self, rev_tree, parent_tree):
333
"""Set the differences showed by this window.
335
Compares the two trees and populates the window with the
338
if getattr(self, 'diff_view', None) is None:
339
self.diff_view = DiffView()
340
self.pack2(self.diff_view)
341
self.diff_view.show()
342
self.diff_view.set_trees(rev_tree, parent_tree)
343
self.rev_tree = rev_tree
344
self.parent_tree = parent_tree
347
delta = self.rev_tree.changes_from(self.parent_tree)
349
self.model.append(None, [ "Complete Diff", "" ])
352
titer = self.model.append(None, [ "Added", None ])
353
for path, id, kind in delta.added:
354
self.model.append(titer, [ path, path ])
356
if len(delta.removed):
357
titer = self.model.append(None, [ "Removed", None ])
358
for path, id, kind in delta.removed:
359
self.model.append(titer, [ path, path ])
361
if len(delta.renamed):
362
titer = self.model.append(None, [ "Renamed", None ])
363
for oldpath, newpath, id, kind, text_modified, meta_modified \
365
self.model.append(titer, [ oldpath, newpath ])
367
if len(delta.modified):
368
titer = self.model.append(None, [ "Modified", None ])
369
for path, id, kind, text_modified, meta_modified in delta.modified:
370
self.model.append(titer, [ path, path ])
372
self.treeview.expand_all()
373
self.diff_view.show_diff(None)
375
def set_file(self, file_path):
376
"""Select the current file to display"""
378
for data in self.model:
379
for child in data.iterchildren():
380
if child[0] == file_path or child[1] == file_path:
384
raise errors.NoSuchFile(file_path)
385
self.treeview.set_cursor(tv_path)
386
self.treeview.scroll_to_cell(tv_path)
388
def _treeview_cursor_cb(self, *args):
389
"""Callback for when the treeview cursor changes."""
390
(path, col) = self.treeview.get_cursor()
391
specific_files = [ self.model[path][1] ]
392
if specific_files == [ None ]:
394
elif specific_files == [ "" ]:
395
specific_files = None
397
self.diff_view.show_diff(specific_files)
399
def _on_wraplines_toggled(self, widget=None, wrap=False):
400
"""Callback for when the wrap lines checkbutton is toggled"""
401
if wrap or widget.get_active():
402
self.diff_view.sourceview.set_wrap_mode(gtk.WRAP_WORD)
404
self.diff_view.sourceview.set_wrap_mode(gtk.WRAP_NONE)
406
class DiffWindow(Window):
409
This object represents and manages a single window containing the
410
differences between two revisions on a branch.
413
def __init__(self, parent=None, operations=None):
414
Window.__init__(self, parent)
415
self.set_border_width(0)
416
self.set_title("bzrk diff")
418
# Use two thirds of the screen by default
419
screen = self.get_screen()
420
monitor = screen.get_monitor_geometry(0)
421
width = int(monitor.width * 0.66)
422
height = int(monitor.height * 0.66)
423
self.set_default_size(width, height)
424
self.construct(operations)
426
def construct(self, operations):
427
"""Construct the window contents."""
428
self.vbox = gtk.VBox()
431
self.diff = DiffWidget()
432
self.vbox.pack_end(self.diff, True, True, 0)
434
# Build after DiffWidget to connect signals
435
menubar = self._get_menu_bar()
436
self.vbox.pack_start(menubar, False, False, 0)
437
hbox = self._get_button_bar(operations)
439
self.vbox.pack_start(hbox, False, True, 0)
442
def _get_menu_bar(self):
443
menubar = gtk.MenuBar()
445
mb_view = gtk.MenuItem(_i18n("_View"))
446
mb_view_menu = gtk.Menu()
447
mb_view_wrapsource = gtk.CheckMenuItem(_i18n("Wrap _Long Lines"))
448
mb_view_wrapsource.connect('activate', self.diff._on_wraplines_toggled)
449
mb_view_wrapsource.show()
450
mb_view_menu.append(mb_view_wrapsource)
452
mb_view.set_submenu(mb_view_menu)
454
menubar.append(mb_view)
458
def _get_button_bar(self, operations):
459
"""Return a button bar to use.
461
:return: None, meaning that no button bar will be used.
463
if operations is None:
465
hbox = gtk.HButtonBox()
466
hbox.set_layout(gtk.BUTTONBOX_START)
467
for title, method in operations:
468
merge_button = gtk.Button(title)
470
merge_button.set_relief(gtk.RELIEF_NONE)
471
merge_button.connect("clicked", method)
472
hbox.pack_start(merge_button, expand=False, fill=True)
476
def _get_merge_target(self):
477
d = gtk.FileChooserDialog('Merge branch', self,
478
gtk.FILE_CHOOSER_ACTION_SELECT_FOLDER,
479
buttons=(gtk.STOCK_OK, gtk.RESPONSE_OK,
481
gtk.RESPONSE_CANCEL,))
484
if result != gtk.RESPONSE_OK:
485
raise SelectCancelled()
486
return d.get_current_folder_uri()
490
def _merge_successful(self):
491
# No conflicts found.
492
info_dialog(_i18n('Merge successful'),
493
_i18n('All changes applied successfully.'))
495
def _conflicts(self):
496
warning_dialog(_i18n('Conflicts encountered'),
497
_i18n('Please resolve the conflicts manually'
498
' before committing.'))
500
def _handle_error(self, e):
501
error_dialog('Error', str(e))
503
def _get_save_path(self, basename):
504
d = gtk.FileChooserDialog('Save As', self,
505
gtk.FILE_CHOOSER_ACTION_SAVE,
506
buttons=(gtk.STOCK_OK, gtk.RESPONSE_OK,
508
gtk.RESPONSE_CANCEL,))
509
d.set_current_name(basename)
512
if result != gtk.RESPONSE_OK:
513
raise SelectCancelled()
514
return urlutils.local_path_from_url(d.get_uri())
518
def set_diff(self, description, rev_tree, parent_tree):
519
"""Set the differences showed by this window.
521
Compares the two trees and populates the window with the
524
self.diff.set_diff(rev_tree, parent_tree)
525
self.set_title(description + " - bzrk diff")
527
def set_file(self, file_path):
528
self.diff.set_file(file_path)
531
class DiffController(object):
533
def __init__(self, path, patch, window=None, allow_dirty=False):
536
self.allow_dirty = allow_dirty
538
window = DiffWindow(operations=self._provide_operations())
539
self.initialize_window(window)
542
def initialize_window(self, window):
543
window.diff.set_diff_text_sections(self.get_diff_sections())
544
window.set_title(self.path + " - diff")
546
def get_diff_sections(self):
547
yield "Complete Diff", None, ''.join(self.patch)
548
# allow_dirty was added to parse_patches in bzrlib 2.2b1
549
if 'allow_dirty' in inspect.getargspec(parse_patches).args:
550
patches = parse_patches(self.patch, allow_dirty=self.allow_dirty)
552
patches = parse_patches(self.patch)
553
for patch in patches:
554
oldname = patch.oldname.split('\t')[0]
555
newname = patch.newname.split('\t')[0]
556
yield oldname, newname, str(patch)
558
def perform_save(self, window):
560
save_path = self.window._get_save_path(osutils.basename(self.path))
561
except SelectCancelled:
563
source = open(self.path, 'rb')
565
target = open(save_path, 'wb')
567
osutils.pumpfile(source, target)
573
def _provide_operations(self):
574
return [('Save', self.perform_save)]
577
class MergeDirectiveController(DiffController):
579
def __init__(self, path, directive, window=None):
580
DiffController.__init__(self, path, directive.patch.splitlines(True),
582
self.directive = directive
583
self.merge_target = None
585
def _provide_operations(self):
586
return [('Merge', self.perform_merge), ('Save', self.perform_save)]
588
def perform_merge(self, window):
589
if self.merge_target is None:
591
self.merge_target = self.window._get_merge_target()
592
except SelectCancelled:
594
tree = workingtree.WorkingTree.open(self.merge_target)
598
if tree.has_changes():
599
raise errors.UncommittedChanges(tree)
600
merger, verified = _mod_merge.Merger.from_mergeable(
601
tree, self.directive, pb=None)
602
merger.merge_type = _mod_merge.Merge3Merger
603
conflict_count = merger.do_merge()
605
if conflict_count == 0:
606
self.window._merge_successful()
608
self.window._conflicts()
609
# There are conflicts to be resolved.
610
self.window.destroy()
612
self.window._handle_error(e)
617
def iter_changes_to_status(source, target):
618
"""Determine the differences between trees.
620
This is a wrapper around iter_changes which just yields more
621
understandable results.
623
:param source: The source tree (basis tree)
624
:param target: The target tree
625
:return: A list of (file_id, real_path, change_type, display_path)
630
renamed_and_modified = 'renamed and modified'
631
modified = 'modified'
632
kind_changed = 'kind changed'
635
# TODO: Handle metadata changes
642
for (file_id, paths, changed_content, versioned, parent_ids, names,
643
kinds, executables) in target.iter_changes(source):
645
# Skip the root entry if it isn't very interesting
646
if parent_ids == (None, None):
653
source_marker = osutils.kind_marker(kinds[0])
657
# We assume bzr will flag only files in that case,
658
# there may be a bzr bug there as only files seems to
659
# not receive any kind.
660
marker = osutils.kind_marker('file')
662
marker = osutils.kind_marker(kinds[0])
664
marker = osutils.kind_marker(kinds[1])
667
if real_path is None:
669
assert real_path is not None
671
present_source = versioned[0] and kinds[0] is not None
672
present_target = versioned[1] and kinds[1] is not None
674
if kinds[0] is None and kinds[1] is None:
675
change_type = missing
676
display_path = real_path + marker
677
elif present_source != present_target:
681
assert present_source
682
change_type = removed
683
display_path = real_path + marker
684
elif names[0] != names[1] or parent_ids[0] != parent_ids[1]:
686
if changed_content or executables[0] != executables[1]:
688
change_type = renamed_and_modified
690
change_type = renamed
691
display_path = (paths[0] + source_marker
692
+ ' => ' + paths[1] + marker)
693
elif kinds[0] != kinds[1]:
694
change_type = kind_changed
695
display_path = (paths[0] + source_marker
696
+ ' => ' + paths[1] + marker)
697
elif changed_content or executables[0] != executables[1]:
698
change_type = modified
699
display_path = real_path + marker
701
assert False, "How did we get here?"
703
status.append((file_id, real_path, change_type, display_path))