Debian Codegraph @

lib/diff.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 #
3 # QBrz - Qt frontend to Breezy commands
4 # Copyright (C) 2008 Gary van der Merwe <[email protected]>
5 #
6 # This program is free software; you can redistribute it and/or
7 # modify it under the terms of the GNU General Public License
8 # as published by the Free Software Foundation; either version 2
9 # of the License, or (at your option) any later version.
10 #
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with this program; if not, write to the Free Software
18 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 import tempfile
20 from contextlib import ExitStack
21 import errno
22 import re
23 import time
24 import sys
25 import os
26 import glob
27
28 from PyQt5 import QtCore, QtGui, QtWidgets
29
30 from breezy import trace, osutils, cmdline
31
32 from breezy.errors import NoSuchId, ExecutableMissing
33 from breezy.tree import FileTimestampUnavailable
34 from breezy.plugins.qbrz.lib.diff_arg import * # import DiffArgProvider classes
35 from breezy.plugins.qbrz.lib.i18n import gettext
36 from breezy.plugins.qbrz.lib.subprocess import SimpleSubProcessDialog
37 from breezy.plugins.qbrz.lib.util import (
38 get_qbrz_config,
39 content_seems_to_be_binary,
40 )
41
42 from breezy.lazy_import import lazy_import
43 lazy_import(globals(), '''
44 from patiencediff import PatienceSequenceMatcher as SequenceMatcher
45 from breezy.plugins.qbrz.lib.i18n import gettext, ngettext, N_
46 from breezy.workingtree import WorkingTree
47 from breezy.trace import mutter
48 ''')
49 from breezy.diff import DiffFromTool, DiffPath
50 subprocess = __import__('subprocess', {}, {}, [])
51
52 qconfig = get_qbrz_config()
53 default_diff = qconfig.get_option("default_diff")
54 if default_diff is None:
55 default_diff = ""
56 ext_diffs = {gettext("Builtin Diff"):""}
57 for name, command in list(qconfig.get_section('EXTDIFF').items()):
58 ext_diffs[name] = command
59
60
61 def show_diff(arg_provider, ext_diff=None, parent_window=None, context=None):
62
63 if ext_diff is None:
64 ext_diff = default_diff
65
66 if ext_diff == "":
67
68 # We can't import this globaly becuse it ties to import us,
69 # which causes and Import Error.
70 from breezy.plugins.qbrz.lib.diffwindow import DiffWindow
71
72 window = DiffWindow(arg_provider, parent=parent_window)
73 window.show()
74 if parent_window:
75 parent_window.windows.append(window)
76 elif context:
77 ext_diff = str(ext_diff) # convert QString to str
78 with ExitStack() as es:
79 args = arg_provider.get_diff_window_args(
80 QtWidgets.QApplication.processEvents, es
81 )
82 old_tree = args["old_tree"]
83 new_tree = args["new_tree"]
84 specific_files = args.get("specific_files")
85 context.setup(ext_diff, old_tree, new_tree)
86 if specific_files:
87 context.diff_paths(specific_files)
88 else:
89 context.diff_tree()
90
91 else:
92 args=["diff", "--using", ext_diff] # NEVER USE --using=xxx, ALWAYS --using xxx
93 # This should be move to after the window has been shown.
94 dir, extra_args = arg_provider.get_ext_diff_args(
95 QtCore.QCoreApplication.processEvents)
96 args.extend(extra_args)
97
98 window = SimpleSubProcessDialog("External Diff",
99 desc=ext_diff,
100 args=args,
101 dir=dir,
102 auto_start_show_on_failed=True,
103 parent=parent_window)
104 window.process_widget.hide_progress()
105 if parent_window:
106 parent_window.windows.append(window)
107
108
109 def has_ext_diff():
110 return len(ext_diffs) > 1
111
112
113 class ExtDiffMenu(QtWidgets.QMenu):
114 _triggered = QtCore.pyqtSignal('QString')
115
116 def __init__(self, parent=None, include_builtin=True, set_default=True):
117 QtWidgets.QMenu.__init__(self, gettext("Show &differences"), parent)
118
119 for name, command in list(ext_diffs.items()):
120 if command == "" and include_builtin or not command == "":
121 action = QtWidgets.QAction(name, self)
122 action.setData(command)
123 if command == default_diff and set_default:
124 self.setDefaultAction(action)
125 self.addAction(action)
126
127 self.triggered[QtWidgets.QAction].connect(self.do_trigger)
128
129 def do_trigger(self, action):
130 ext_diff = str(action.data())
131 self._triggered.emit(ext_diff)
132
133
134 class DiffButtons(QtWidgets.QWidget):
135 _triggered = QtCore.pyqtSignal('QString')
136
137 def __init__(self, parent = None):
138 QtWidgets.QWidget.__init__(self, parent)
139 layout = QtWidgets.QHBoxLayout(self)
140
141 self.default_button = QtWidgets.QPushButton(gettext('Diff'), self)
142 layout.addWidget(self.default_button)
143 layout.setSpacing(0)
144 self.default_button.clicked.connect(self.do_trigger)
145
146 if has_ext_diff():
147 self.menu = ExtDiffMenu(self)
148 self.menu_button = QtWidgets.QPushButton("", self)
149 layout.addWidget(self.menu_button)
150 self.menu_button.setMenu(self.menu)
151 #QStyle.PM_MenuButtonIndicator
152 self.menu_button.setFixedWidth(
153 self.menu_button.style().pixelMetric(
154 QtWidgets.QStyle.PM_MenuButtonIndicator) +
155 self.menu_button.style().pixelMetric(
156 QtWidgets.QStyle.PM_ButtonMargin)
157 )
158 self.menu._triggered.connect(self.do_trigger)
159
160 def do_trigger(self, ext_diff=None):
161 # Note: this is connected to default_button.clicked
162 # as well as the menu events. The button passes it's
163 # checked state (always False here) in arguments.
164 if not ext_diff:
165 ext_diff = default_diff
166 self._triggered.emit(ext_diff)
167
168
169 class DiffItem(object):
170 """
171 Diff data for each file.
172
173 This class has moved from lib/diffwindow.py.
174 You can see annotation of older code by::
175
176 bzr ann lib/diffwindow.py -r 1429
177 """
178
179 @classmethod
180 def iter_items(cls, trees, specific_files=None, filter=None, lock_trees=False):
181 """
182 RJLRJL: updated to call .iter_changes directly
183 """
184 with ExitStack() as es:
185 if lock_trees:
186 for t in trees:
187 es.enter_context(t.lock_read())
188
189 # changes = trees[1].iter_changes(trees[0], specific_files=specific_files, require_versioned=True)
190
191 # def changes_key(change):
192 # return change[1][1] or change[1][0]
193 for change in trees[1].iter_changes(trees[0], specific_files=specific_files, require_versioned=True):
194 # file_id -> ascii string
195 # paths -> 2-tuple (old, new) fullpaths unicode/None
196 # changed_content -> bool
197 # versioned -> 2-tuple (bool, bool)
198 # parent -> 2-tuple
199 # name -> 2-tuple (old_name, new_name) utf-8?/None
200 # kind -> 2-tuple (string/None, string/None)
201 # executable -> 2-tuple (bool/None, bool/None)
202 # NOTE: None value used for non-existing entry in corresponding
203 # tree, e.g. for added/deleted file
204 di = DiffItem.create(trees, change.file_id, change.path, change.changed_content,
205 change.versioned, change.parent_id, change.name, change.kind, change.executable,
206 filter = filter)
207 if not di:
208 continue
209 yield di
210
211 @classmethod
212 def create(cls, trees, file_id, paths, changed_content, versioned,
213 parent, name, kind, executable, filter = None):
214
215 if parent == (None, None): # filter out TREE_ROOT (?)
216 return None
217
218 # check for manually deleted files (w/o using bzr rm commands)
219 if kind[1] is None:
220 if versioned == (False, True):
221 # added and missed
222 return None
223 if versioned == (True, True):
224 versioned = (True, False)
225 paths = (paths[0], None)
226
227 renamed = (parent[0], name[0]) != (parent[1], name[1])
228
229 dates = [None, None]
230 for ix in range(2):
231 if versioned[ix]:
232 try:
233 dates[ix] = trees[ix].get_file_mtime(paths[ix])
234 except OSError as e:
235 if not renamed or e.errno != errno.ENOENT:
236 raise
237 # If we get ENOENT error then probably we trigger
238 # bug #251532 in breezy. Take current time instead
239 dates[ix] = time.time()
240 except FileTimestampUnavailable:
241 # ghosts around us (see Bug #513096)
242 dates[ix] = 0 # using 1970/1/1 instead
243
244 properties_changed = []
245 if bool(executable[0]) != bool(executable[1]):
246 descr = {True: "+x", False: "-x", None: None}
247 properties_changed.append((descr[executable[0]],
248 descr[executable[1]]))
249
250 if versioned == (True, False):
251 status = N_('removed')
252 elif versioned == (False, True):
253 status = N_('added')
254 elif renamed and changed_content:
255 status = N_('renamed and modified')
256 elif renamed:
257 status = N_('renamed')
258 else:
259 status = N_('modified')
260 # check filter options
261 if filter and not filter(status):
262 return None
263
264 return cls(trees, file_id, paths, changed_content, versioned, kind,
265 properties_changed, dates, status)
266
267 def __init__(self, trees, file_id, paths, changed_content, versioned, kind,
268 properties_changed, dates, status):
269 self.trees = trees
270 self.file_id = file_id
271 self.paths = paths
272 self.changed_content = changed_content
273 self.versioned = versioned
274 self.kind = kind
275 self.properties_changed = properties_changed
276 self.dates = dates
277 self.status = status
278
279 self._lines = None
280 self._binary = None
281 self._group_cache = {}
282 self._encodings = [None, None]
283 self._ulines = [None, None]
284
285 def load(self):
286 if self._lines is None:
287 self._load_lines()
288
289 def _load_lines(self):
290 if ((self.versioned[0] != self.versioned[1] or self.changed_content) and (self.kind[0] == 'file' or self.kind[1] == 'file')):
291 lines = []
292 binary = False
293 # print('\n_load_lines', self.file_id)
294 for ix, tree in enumerate(self.trees):
295 content = ()
296 if self.versioned[ix] and self.kind[ix] == 'file':
297 content = tree.get_file_lines(tree.id2path(self.file_id))
298 # print('\n\tcontent loaded for ', tree.id2path(self.file_id), self.file_id)
299 lines.append(content)
300 binary = binary or content_seems_to_be_binary(content)
301 self._lines = lines
302 self._binary = binary
303 else:
304 self._lines = ((),())
305 self._binary = False
306
307 @property
308 def lines(self):
309 if self._lines is None:
310 self._load_lines()
311 return self._lines
312
313 @property
314 def binary(self):
315 if self._binary is None:
316 self._load_lines()
317 return self._binary
318
319 def groups(self, complete, ignore_whitespace):
320 key = (complete, ignore_whitespace)
321 groups = self._group_cache.get(key)
322 if groups is not None:
323 return groups
324
325 lines = self.lines
326
327 if not self.binary:
328 if self.versioned == (True, False):
329 groups = [[('delete', 0, len(lines[0]), 0, 0)]]
330 elif self.versioned == (False, True):
331 groups = [[('insert', 0, 0, 0, len(lines[1]))]]
332 else:
333 groups = self.difference_groups(lines, complete, ignore_whitespace)
334 else:
335 groups = []
336
337 self._group_cache[key] = groups
338 return groups
339
340 def difference_groups(self, lines, complete, ignore_whitespace):
341 # RJL Changed strings to bytes for pattern-matching and coerced
342 # left and right to lists (instead of generators) in 'if...'
343 left, right = lines
344 if ignore_whitespace:
345 re_whitespaces = re.compile(br"\s+")
346 left = list((re_whitespaces.sub(b" ", line) for line in left))
347 right = list((re_whitespaces.sub(b" ", line) for line in right))
348 matcher = SequenceMatcher(None, left, right)
349 if complete:
350 groups = list([matcher.get_opcodes()])
351 else:
352 groups = list(matcher.get_grouped_opcodes())
353
354 return groups
355
356 def get_unicode_lines(self, encodings):
357 """
358 Return pair of unicode lines for each side of diff.
359 Parameter encodings is 2-list or 2-tuple with encoding names (str) for each side of diff.
360 """
361 lines = self.lines
362 ulines = self._ulines
363 for i in range(2):
364 if encodings[i] != self._encodings[i]:
365 self._encodings[i] = encodings[i]
366 if self.binary:
367 ulines[i] = lines[i][:]
368 else:
369 try:
370 ulines[i] = [l.decode(encodings[i]) for l in lines[i]]
371 except UnicodeDecodeError as e:
372 filename = self.paths[i]
373 trace.note("Some characters in file %s "
374 "could not be properly decoded "
375 "using '%s' encoding "
376 "and therefore they replaced with special character.",
377 filename,
378 e.encoding)
379 ulines[i] = [l.decode(encodings[i], 'replace') for l in lines[i]]
380 return ulines
381
382 CACHE_TIMEOUT = 3600
383
384 class _ExtDiffer(DiffFromTool):
385 """
386 Run extdiff async.
387 XXX: This class is strongly depending on DiffFromTool internals now.
388 """
389 def __init__(self, command_string, old_tree, new_tree, to_file=None, path_encoding='utf-8'):
390 DiffPath.__init__(self, old_tree, new_tree, to_file or sys.stdout, path_encoding)
391 self.set_command_string(command_string)
392 # parent = osutils.joinpath([osutils.tempfile.gettempdir(), 'qbrz'])
393 parent = osutils.joinpath([tempfile.gettempdir(), 'qbrz'])
394 if not os.path.isdir(parent):
395 os.mkdir(parent)
396 # self._root = osutils.mkdtemp(prefix='qbrz/brz-diff-')
397 self._root = tempfile.mkdtemp(prefix='qbrz/brz-diff-')
398 self.prefixes = {}
399 self._set_prefix()
400
401 @property
402 def trees(self):
403 return self.old_tree, self.new_tree
404
405 def set_trees(self, old_tree, new_tree):
406 self.old_tree = old_tree
407 self.new_tree = new_tree
408 self._set_prefix()
409
410 def _set_prefix(self):
411 self.old_prefix = self.get_prefix(self.old_tree)
412 self.new_prefix = self.get_prefix(self.new_tree)
413
414 def get_prefix(self, tree):
415
416 def get_key(tree):
417 if hasattr(tree, "get_revision_id"):
418 return tree.__class__.__name__ + ":" + tree.get_revision_id().decode('utf-8')
419 elif hasattr(tree, "abspath"):
420 return tree.__class__.__name__ + ":" + tree.abspath("")
421 else:
422 return tree.__class__.__name__ + ":" + str(hash(tree))
423
424 if tree is None:
425 return None
426 key = get_key(tree)
427 if key in self.prefixes:
428 return self.prefixes[key]
429 prefix = str(len(self.prefixes) + 1)
430 self.prefixes[key] = prefix
431 return prefix
432
433 def set_command_string(self, command_string):
434 command_template = cmdline.split(command_string)
435 if "{old_path}" not in command_string:
436 command_template.extend(["{old_path}", "{new_path}"])
437 self.command_template = command_template
438
439 def finish(self):
440 parent = os.path.dirname(self._root)
441 for path in glob.glob(os.path.join(parent, "*")):
442 if self._is_deletable(path):
443 self._delete_tmpdir(path)
444 self._delete_tmpdir(self._root)
445
446 def finish_lazy(self):
447 parent = os.path.dirname(self._root)
448 for path in glob.glob(os.path.join(parent, "*")):
449 if self._is_deletable(path):
450 self._delete_tmpdir(path)
451 open(os.path.join(self._root, ".delete"), "w").close()
452
453 def _is_deletable(self, root):
454 if os.path.exists(os.path.join(root, ".delete")):
455 return True
456 elif time.time() > os.path.getctime(root) + CACHE_TIMEOUT:
457 return True
458 else:
459 return False
460
461 def _delete_tmpdir(self, path):
462 try:
463 osutils.rmtree(path)
464 except:
465 if os.path.isdir(path):
466 open(os.path.join(path, ".delete"), "w").close()
467
468 def _write_file(self, relpath, tree, prefix, force_temp=False, allow_write=False, file_id=None):
469 if force_temp or not isinstance(tree, WorkingTree):
470 full_path = self._safe_filename(prefix, relpath)
471 if os.path.isfile(full_path):
472 return full_path
473 # return DiffFromTool._write_file(self, relpath, tree, prefix, force_temp, allow_write, file_id)
474 return DiffFromTool._write_file(self, relpath, tree, prefix, force_temp, allow_write)
475
476 # def _prepare_files(self, old_path, new_path, force_temp=False,
477 # file_id=None, allow_write_new=False):
478 # old_disk_path = self._write_file(old_path, self.old_tree,
479 # self.old_prefix, force_temp,
480 # file_id=file_id)
481 # new_disk_path = self._write_file(new_path, self.new_tree,
482 # self.new_prefix, force_temp,
483 # allow_write=allow_write_new,
484 # file_id=file_id)
485 # return old_disk_path, new_disk_path
486
487 def _execute(self, old_path, new_path):
488 command = self._get_command(old_path, new_path)
489 try:
490 subprocess.Popen(command, cwd=self._root)
491 except OSError as e:
492 if e.errno == errno.ENOENT:
493 raise ExecutableMissing(command[0])
494 else:
495 raise
496 return 0
497
498 def diff(self, file_id):
499 try:
500 new_path = self.new_tree.id2path(file_id)
501 # new_kind = self.new_tree.kind(new_path, file_id)
502 new_kind = self.new_tree.kind(new_path)
503 old_path = self.old_tree.id2path(file_id)
504 # old_kind = self.old_tree.kind(old_path, file_id)
505 old_kind = self.old_tree.kind(old_path)
506 except NoSuchId:
507 return DiffPath.CANNOT_DIFF
508 # return DiffFromTool.diff(self, file_id, old_path, new_path, old_kind, new_kind)
509 return DiffFromTool.diff(self, old_path, new_path, old_kind, new_kind)
510
511 class ExtDiffContext(QtCore.QObject):
512 """
513 Environment for external diff execution.
514 This class manages cache of diffed files and when it will be deleted.
515 """
516 def __init__(self, parent, to_file=None, path_encoding='utf-8'):
517 """
518 :parent: parent widget. If specified, cache is deleted automatically
519 when parent is closed.
520 :to_file: stream to write output messages. If not specified,
521 stdout is used.
522 :path_encoding: encoding of path
523 """
524 QtCore.QObject.__init__(self, parent)
525 self.to_file = to_file
526 self.path_encoding = path_encoding
527 self._differ = None
528 if parent is not None:
529 parent.window().installEventFilter(self)
530
531 def finish(self):
532 """
533 Remove temporary directory which contains cached files.
534 """
535 try:
536 if self._differ:
537 self._differ.finish()
538 self._differ = None
539 except:
540 pass
541
542 def finish_lazy(self):
543 """
544 Mark temporary directory as deletable, without delete it actually.
545 XXX: Directory marked as deletable will be deleted next time.
546 """
547 try:
548 if self._differ:
549 self._differ.finish_lazy()
550 self._differ = None
551 except:
552 pass
553
554 @property
555 def rootdir(self):
556 if self._differ:
557 return self._differ._root
558 else:
559 return None
560
561 def setup(self, command_string, old_tree, new_tree):
562 """
563 Set or change diff command and diffed trees.
564 """
565 if self._differ is None:
566 self._differ = _ExtDiffer(command_string, old_tree, new_tree, self.to_file, self.path_encoding)
567 else:
568 self._differ.set_trees(old_tree, new_tree)
569 self._differ.set_command_string(command_string)
570
571 def eventFilter(self, obj, event):
572 if event.type() == QtCore.QEvent.Close:
573 self.finish()
574 return QtCore.QObject.eventFilter(self, obj, event)
575
576 def diff_ids(self, file_ids, interval=50, lock_trees=True):
577 """
578 Show diffs of specified file_ids.
579 NOTE: Directories cannot be specified.
580 Use diff_tree or diff_paths instead when specifing directory.
581 """
582 with ExitStack() as es:
583 if lock_trees:
584 es.enter_context(self._differ.new_tree.lock_read())
585 es.enter_context(self._differ.old_tree.lock_read())
586 for file_id in file_ids:
587 self._differ.diff(file_id)
588 time.sleep(interval * 0.001)
589
590 def diff_paths(self, paths, interval=50, lock_trees=True):
591 """
592 Show diffs of specified file paths.
593 """
594 new_tree = self._differ.new_tree
595 old_tree = self._differ.old_tree
596
597 valid_paths = []
598 ids = []
599 dir_included = False
600 with ExitStack() as es:
601 # Sometimes, we must lock tree before calling tree.kind()
602 if lock_trees:
603 es.enter_context(new_tree.lock_read())
604 es.enter_context(old_tree.lock_read())
605 for p in paths:
606 id = new_tree.path2id(p)
607 if id:
608 valid_paths.append(p)
609 ids.append(id)
610 dir_included = dir_included or (new_tree.kind(p) != 'file')
611 else:
612 mutter('%s does not exist in the new tree' % p)
613 if not ids:
614 return
615 if dir_included:
616 self.diff_tree(valid_paths, interval, False)
617 else:
618 self.diff_ids(ids, interval, False)
619
620 def diff_tree(self, specific_files=None, interval=50, lock_trees=True):
621 """
622 Show diffs between two trees. (trees must be set by setup method)
623 NOTE: Directory path can be specified to specific_files.
624 """
625 for di in DiffItem.iter_items(self._differ.trees,
626 specific_files=specific_files,
627 lock_trees=lock_trees):
628 if di.changed_content:
629 self._differ.diff(di.file_id)
630 time.sleep(interval * 0.001)