1
# Copyright (C) 2004, 2005, 2006 Canonical Ltd.
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
# GNU General Public License for more details.
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
24
from bzrlib.lazy_import import lazy_import
25
lazy_import(globals(), """
32
branch as _mod_branch,
44
from bzrlib.symbol_versioning import (
47
from bzrlib.trace import mutter, note, warning
50
class AtTemplate(string.Template):
51
"""Templating class that uses @ instead of $."""
56
# TODO: Rather than building a changeset object, we should probably
57
# invoke callbacks on an object. That object can either accumulate a
58
# list, write them out directly, etc etc.
61
class _PrematchedMatcher(difflib.SequenceMatcher):
62
"""Allow SequenceMatcher operations to use predetermined blocks"""
64
def __init__(self, matching_blocks):
65
difflib.SequenceMatcher(self, None, None)
66
self.matching_blocks = matching_blocks
70
def internal_diff(old_filename, oldlines, new_filename, newlines, to_file,
71
allow_binary=False, sequence_matcher=None,
72
path_encoding='utf8'):
73
# FIXME: difflib is wrong if there is no trailing newline.
74
# The syntax used by patch seems to be "\ No newline at
75
# end of file" following the last diff line from that
76
# file. This is not trivial to insert into the
77
# unified_diff output and it might be better to just fix
78
# or replace that function.
80
# In the meantime we at least make sure the patch isn't
84
# Special workaround for Python2.3, where difflib fails if
85
# both sequences are empty.
86
if not oldlines and not newlines:
89
if allow_binary is False:
90
textfile.check_text_lines(oldlines)
91
textfile.check_text_lines(newlines)
93
if sequence_matcher is None:
94
sequence_matcher = patiencediff.PatienceSequenceMatcher
95
ud = patiencediff.unified_diff(oldlines, newlines,
96
fromfile=old_filename.encode(path_encoding),
97
tofile=new_filename.encode(path_encoding),
98
sequencematcher=sequence_matcher)
101
if len(ud) == 0: # Identical contents, nothing to do
103
# work-around for difflib being too smart for its own good
104
# if /dev/null is "1,0", patch won't recognize it as /dev/null
106
ud[2] = ud[2].replace('-1,0', '-0,0')
108
ud[2] = ud[2].replace('+1,0', '+0,0')
112
if not line.endswith('\n'):
113
to_file.write("\n\\ No newline at end of file\n")
117
def _spawn_external_diff(diffcmd, capture_errors=True):
118
"""Spawn the externall diff process, and return the child handle.
120
:param diffcmd: The command list to spawn
121
:param capture_errors: Capture stderr as well as setting LANG=C
122
and LC_ALL=C. This lets us read and understand the output of diff,
123
and respond to any errors.
124
:return: A Popen object.
127
# construct minimal environment
129
path = os.environ.get('PATH')
132
env['LANGUAGE'] = 'C' # on win32 only LANGUAGE has effect
135
stderr = subprocess.PIPE
141
pipe = subprocess.Popen(diffcmd,
142
stdin=subprocess.PIPE,
143
stdout=subprocess.PIPE,
147
if e.errno == errno.ENOENT:
148
raise errors.NoDiff(str(e))
154
def external_diff(old_filename, oldlines, new_filename, newlines, to_file,
156
"""Display a diff by calling out to the external diff program."""
157
# make sure our own output is properly ordered before the diff
160
oldtmp_fd, old_abspath = tempfile.mkstemp(prefix='bzr-diff-old-')
161
newtmp_fd, new_abspath = tempfile.mkstemp(prefix='bzr-diff-new-')
162
oldtmpf = os.fdopen(oldtmp_fd, 'wb')
163
newtmpf = os.fdopen(newtmp_fd, 'wb')
166
# TODO: perhaps a special case for comparing to or from the empty
167
# sequence; can just use /dev/null on Unix
169
# TODO: if either of the files being compared already exists as a
170
# regular named file (e.g. in the working directory) then we can
171
# compare directly to that, rather than copying it.
173
oldtmpf.writelines(oldlines)
174
newtmpf.writelines(newlines)
181
if sys.platform == 'win32':
182
# Popen doesn't do the proper encoding for external commands
183
# Since we are dealing with an ANSI api, use mbcs encoding
184
old_filename = old_filename.encode('mbcs')
185
new_filename = new_filename.encode('mbcs')
187
'--label', old_filename,
189
'--label', new_filename,
194
# diff only allows one style to be specified; they don't override.
195
# note that some of these take optargs, and the optargs can be
196
# directly appended to the options.
197
# this is only an approximate parser; it doesn't properly understand
199
for s in ['-c', '-u', '-C', '-U',
204
'-y', '--side-by-side',
216
diffcmd.extend(diff_opts)
218
pipe = _spawn_external_diff(diffcmd, capture_errors=True)
219
out,err = pipe.communicate()
222
# internal_diff() adds a trailing newline, add one here for consistency
225
# 'diff' gives retcode == 2 for all sorts of errors
226
# one of those is 'Binary files differ'.
227
# Bad options could also be the problem.
228
# 'Binary files' is not a real error, so we suppress that error.
231
# Since we got here, we want to make sure to give an i18n error
232
pipe = _spawn_external_diff(diffcmd, capture_errors=False)
233
out, err = pipe.communicate()
235
# Write out the new i18n diff response
236
to_file.write(out+'\n')
237
if pipe.returncode != 2:
238
raise errors.BzrError(
239
'external diff failed with exit code 2'
240
' when run with LANG=C and LC_ALL=C,'
241
' but not when run natively: %r' % (diffcmd,))
243
first_line = lang_c_out.split('\n', 1)[0]
244
# Starting with diffutils 2.8.4 the word "binary" was dropped.
245
m = re.match('^(binary )?files.*differ$', first_line, re.I)
247
raise errors.BzrError('external diff failed with exit code 2;'
248
' command: %r' % (diffcmd,))
250
# Binary files differ, just return
253
# If we got to here, we haven't written out the output of diff
257
# returns 1 if files differ; that's OK
259
msg = 'signal %d' % (-rc)
261
msg = 'exit code %d' % rc
263
raise errors.BzrError('external diff failed with %s; command: %r'
268
oldtmpf.close() # and delete
270
# Clean up. Warn in case the files couldn't be deleted
271
# (in case windows still holds the file open, but not
272
# if the files have already been deleted)
274
os.remove(old_abspath)
276
if e.errno not in (errno.ENOENT,):
277
warning('Failed to delete temporary file: %s %s',
280
os.remove(new_abspath)
282
if e.errno not in (errno.ENOENT,):
283
warning('Failed to delete temporary file: %s %s',
287
def get_trees_and_branches_to_diff(path_list, revision_specs, old_url, new_url,
289
"""Get the trees and specific files to diff given a list of paths.
291
This method works out the trees to be diff'ed and the files of
292
interest within those trees.
295
the list of arguments passed to the diff command
296
:param revision_specs:
297
Zero, one or two RevisionSpecs from the diff command line,
298
saying what revisions to compare.
300
The url of the old branch or tree. If None, the tree to use is
301
taken from the first path, if any, or the current working tree.
303
The url of the new branch or tree. If None, the tree to use is
304
taken from the first path, if any, or the current working tree.
306
if True and a view is set, apply the view or check that the paths
309
a tuple of (old_tree, new_tree, old_branch, new_branch,
310
specific_files, extra_trees) where extra_trees is a sequence of
311
additional trees to search in for file-ids.
313
# Get the old and new revision specs
314
old_revision_spec = None
315
new_revision_spec = None
316
if revision_specs is not None:
317
if len(revision_specs) > 0:
318
old_revision_spec = revision_specs[0]
320
old_url = old_revision_spec.get_branch()
321
if len(revision_specs) > 1:
322
new_revision_spec = revision_specs[1]
324
new_url = new_revision_spec.get_branch()
327
make_paths_wt_relative = True
328
consider_relpath = True
329
if path_list is None or len(path_list) == 0:
330
# If no path is given, the current working tree is used
331
default_location = u'.'
332
consider_relpath = False
333
elif old_url is not None and new_url is not None:
334
other_paths = path_list
335
make_paths_wt_relative = False
337
default_location = path_list[0]
338
other_paths = path_list[1:]
340
# Get the old location
343
old_url = default_location
344
working_tree, branch, relpath = \
345
bzrdir.BzrDir.open_containing_tree_or_branch(old_url)
346
if consider_relpath and relpath != '':
347
if working_tree is not None and apply_view:
348
views.check_path_in_view(working_tree, relpath)
349
specific_files.append(relpath)
350
old_tree = _get_tree_to_diff(old_revision_spec, working_tree, branch)
353
# Get the new location
355
new_url = default_location
356
if new_url != old_url:
357
working_tree, branch, relpath = \
358
bzrdir.BzrDir.open_containing_tree_or_branch(new_url)
359
if consider_relpath and relpath != '':
360
if working_tree is not None and apply_view:
361
views.check_path_in_view(working_tree, relpath)
362
specific_files.append(relpath)
363
new_tree = _get_tree_to_diff(new_revision_spec, working_tree, branch,
364
basis_is_default=working_tree is None)
367
# Get the specific files (all files is None, no files is [])
368
if make_paths_wt_relative and working_tree is not None:
370
from bzrlib.builtins import safe_relpath_files
371
other_paths = safe_relpath_files(working_tree, other_paths,
372
apply_view=apply_view)
373
except errors.FileInWrongBranch:
374
raise errors.BzrCommandError("Files are in different branches")
375
specific_files.extend(other_paths)
376
if len(specific_files) == 0:
377
specific_files = None
378
if (working_tree is not None and working_tree.supports_views()
380
view_files = working_tree.views.lookup_view()
382
specific_files = view_files
383
view_str = views.view_display_str(view_files)
384
note("*** Ignoring files outside view. View is %s" % view_str)
386
# Get extra trees that ought to be searched for file-ids
388
if working_tree is not None and working_tree not in (old_tree, new_tree):
389
extra_trees = (working_tree,)
390
return old_tree, new_tree, old_branch, new_branch, specific_files, extra_trees
393
def _get_tree_to_diff(spec, tree=None, branch=None, basis_is_default=True):
394
if branch is None and tree is not None:
396
if spec is None or spec.spec is None:
399
return tree.basis_tree()
401
return branch.basis_tree()
404
return spec.as_tree(branch)
407
def show_diff_trees(old_tree, new_tree, to_file, specific_files=None,
408
external_diff_options=None,
409
old_label='a/', new_label='b/',
411
path_encoding='utf8',
413
"""Show in text form the changes from one tree to another.
419
Include only changes to these files - None for all changes.
421
external_diff_options
422
If set, use an external GNU diff and pass these options.
425
If set, more Trees to use for looking up file ids
428
If set, the path will be encoded as specified, otherwise is supposed
433
if extra_trees is not None:
434
for tree in extra_trees:
438
differ = DiffTree.from_trees_options(old_tree, new_tree, to_file,
440
external_diff_options,
441
old_label, new_label, using)
442
return differ.show_diff(specific_files, extra_trees)
445
if extra_trees is not None:
446
for tree in extra_trees:
452
def _patch_header_date(tree, file_id, path):
453
"""Returns a timestamp suitable for use in a patch header."""
454
mtime = tree.get_file_mtime(file_id, path)
455
return timestamp.format_patch_date(mtime)
458
def get_executable_change(old_is_x, new_is_x):
459
descr = { True:"+x", False:"-x", None:"??" }
460
if old_is_x != new_is_x:
461
return ["%s to %s" % (descr[old_is_x], descr[new_is_x],)]
466
class DiffPath(object):
467
"""Base type for command object that compare files"""
469
# The type or contents of the file were unsuitable for diffing
470
CANNOT_DIFF = 'CANNOT_DIFF'
471
# The file has changed in a semantic way
473
# The file content may have changed, but there is no semantic change
474
UNCHANGED = 'UNCHANGED'
476
def __init__(self, old_tree, new_tree, to_file, path_encoding='utf-8'):
479
:param old_tree: The tree to show as the old tree in the comparison
480
:param new_tree: The tree to show as new in the comparison
481
:param to_file: The file to write comparison data to
482
:param path_encoding: The character encoding to write paths in
484
self.old_tree = old_tree
485
self.new_tree = new_tree
486
self.to_file = to_file
487
self.path_encoding = path_encoding
493
def from_diff_tree(klass, diff_tree):
494
return klass(diff_tree.old_tree, diff_tree.new_tree,
495
diff_tree.to_file, diff_tree.path_encoding)
498
def _diff_many(differs, file_id, old_path, new_path, old_kind, new_kind):
499
for file_differ in differs:
500
result = file_differ.diff(file_id, old_path, new_path, old_kind,
502
if result is not DiffPath.CANNOT_DIFF:
505
return DiffPath.CANNOT_DIFF
508
class DiffKindChange(object):
509
"""Special differ for file kind changes.
511
Represents kind change as deletion + creation. Uses the other differs
514
def __init__(self, differs):
515
self.differs = differs
521
def from_diff_tree(klass, diff_tree):
522
return klass(diff_tree.differs)
524
def diff(self, file_id, old_path, new_path, old_kind, new_kind):
525
"""Perform comparison
527
:param file_id: The file_id of the file to compare
528
:param old_path: Path of the file in the old tree
529
:param new_path: Path of the file in the new tree
530
:param old_kind: Old file-kind of the file
531
:param new_kind: New file-kind of the file
533
if None in (old_kind, new_kind):
534
return DiffPath.CANNOT_DIFF
535
result = DiffPath._diff_many(self.differs, file_id, old_path,
536
new_path, old_kind, None)
537
if result is DiffPath.CANNOT_DIFF:
539
return DiffPath._diff_many(self.differs, file_id, old_path, new_path,
543
class DiffDirectory(DiffPath):
545
def diff(self, file_id, old_path, new_path, old_kind, new_kind):
546
"""Perform comparison between two directories. (dummy)
549
if 'directory' not in (old_kind, new_kind):
550
return self.CANNOT_DIFF
551
if old_kind not in ('directory', None):
552
return self.CANNOT_DIFF
553
if new_kind not in ('directory', None):
554
return self.CANNOT_DIFF
558
class DiffSymlink(DiffPath):
560
def diff(self, file_id, old_path, new_path, old_kind, new_kind):
561
"""Perform comparison between two symlinks
563
:param file_id: The file_id of the file to compare
564
:param old_path: Path of the file in the old tree
565
:param new_path: Path of the file in the new tree
566
:param old_kind: Old file-kind of the file
567
:param new_kind: New file-kind of the file
569
if 'symlink' not in (old_kind, new_kind):
570
return self.CANNOT_DIFF
571
if old_kind == 'symlink':
572
old_target = self.old_tree.get_symlink_target(file_id)
573
elif old_kind is None:
576
return self.CANNOT_DIFF
577
if new_kind == 'symlink':
578
new_target = self.new_tree.get_symlink_target(file_id)
579
elif new_kind is None:
582
return self.CANNOT_DIFF
583
return self.diff_symlink(old_target, new_target)
585
def diff_symlink(self, old_target, new_target):
586
if old_target is None:
587
self.to_file.write('=== target is %r\n' % new_target)
588
elif new_target is None:
589
self.to_file.write('=== target was %r\n' % old_target)
591
self.to_file.write('=== target changed %r => %r\n' %
592
(old_target, new_target))
596
class DiffText(DiffPath):
598
# GNU Patch uses the epoch date to detect files that are being added
599
# or removed in a diff.
600
EPOCH_DATE = '1970-01-01 00:00:00 +0000'
602
def __init__(self, old_tree, new_tree, to_file, path_encoding='utf-8',
603
old_label='', new_label='', text_differ=internal_diff):
604
DiffPath.__init__(self, old_tree, new_tree, to_file, path_encoding)
605
self.text_differ = text_differ
606
self.old_label = old_label
607
self.new_label = new_label
608
self.path_encoding = path_encoding
610
def diff(self, file_id, old_path, new_path, old_kind, new_kind):
611
"""Compare two files in unified diff format
613
:param file_id: The file_id of the file to compare
614
:param old_path: Path of the file in the old tree
615
:param new_path: Path of the file in the new tree
616
:param old_kind: Old file-kind of the file
617
:param new_kind: New file-kind of the file
619
if 'file' not in (old_kind, new_kind):
620
return self.CANNOT_DIFF
621
from_file_id = to_file_id = file_id
622
if old_kind == 'file':
623
old_date = _patch_header_date(self.old_tree, file_id, old_path)
624
elif old_kind is None:
625
old_date = self.EPOCH_DATE
628
return self.CANNOT_DIFF
629
if new_kind == 'file':
630
new_date = _patch_header_date(self.new_tree, file_id, new_path)
631
elif new_kind is None:
632
new_date = self.EPOCH_DATE
635
return self.CANNOT_DIFF
636
from_label = '%s%s\t%s' % (self.old_label, old_path, old_date)
637
to_label = '%s%s\t%s' % (self.new_label, new_path, new_date)
638
return self.diff_text(from_file_id, to_file_id, from_label, to_label,
641
def diff_text(self, from_file_id, to_file_id, from_label, to_label,
642
from_path=None, to_path=None):
643
"""Diff the content of given files in two trees
645
:param from_file_id: The id of the file in the from tree. If None,
646
the file is not present in the from tree.
647
:param to_file_id: The id of the file in the to tree. This may refer
648
to a different file from from_file_id. If None,
649
the file is not present in the to tree.
650
:param from_path: The path in the from tree or None if unknown.
651
:param to_path: The path in the to tree or None if unknown.
653
def _get_text(tree, file_id, path):
654
if file_id is not None:
655
return tree.get_file(file_id, path).readlines()
659
from_text = _get_text(self.old_tree, from_file_id, from_path)
660
to_text = _get_text(self.new_tree, to_file_id, to_path)
661
self.text_differ(from_label, from_text, to_label, to_text,
663
except errors.BinaryFile:
665
("Binary files %s and %s differ\n" %
666
(from_label, to_label)).encode(self.path_encoding))
670
class DiffFromTool(DiffPath):
672
def __init__(self, command_template, old_tree, new_tree, to_file,
673
path_encoding='utf-8'):
674
DiffPath.__init__(self, old_tree, new_tree, to_file, path_encoding)
675
self.command_template = command_template
676
self._root = osutils.mkdtemp(prefix='bzr-diff-')
679
def from_string(klass, command_string, old_tree, new_tree, to_file,
680
path_encoding='utf-8'):
681
command_template = commands.shlex_split_unicode(command_string)
682
if '@' not in command_string:
683
command_template.extend(['@old_path', '@new_path'])
684
return klass(command_template, old_tree, new_tree, to_file,
688
def make_from_diff_tree(klass, command_string):
689
def from_diff_tree(diff_tree):
690
return klass.from_string(command_string, diff_tree.old_tree,
691
diff_tree.new_tree, diff_tree.to_file)
692
return from_diff_tree
694
def _get_command(self, old_path, new_path):
695
my_map = {'old_path': old_path, 'new_path': new_path}
696
return [AtTemplate(t).substitute(my_map) for t in
697
self.command_template]
699
def _execute(self, old_path, new_path):
700
command = self._get_command(old_path, new_path)
702
proc = subprocess.Popen(command, stdout=subprocess.PIPE,
705
if e.errno == errno.ENOENT:
706
raise errors.ExecutableMissing(command[0])
709
self.to_file.write(proc.stdout.read())
712
def _try_symlink_root(self, tree, prefix):
713
if (getattr(tree, 'abspath', None) is None
714
or not osutils.host_os_dereferences_symlinks()):
717
os.symlink(tree.abspath(''), osutils.pathjoin(self._root, prefix))
719
if e.errno != errno.EEXIST:
723
def _write_file(self, file_id, tree, prefix, relpath, force_temp=False,
725
full_path = osutils.pathjoin(self._root, prefix, relpath)
726
if not force_temp and self._try_symlink_root(tree, prefix):
728
parent_dir = osutils.dirname(full_path)
730
os.makedirs(parent_dir)
732
if e.errno != errno.EEXIST:
734
source = tree.get_file(file_id, relpath)
736
target = open(full_path, 'wb')
738
osutils.pumpfile(source, target)
744
osutils.make_readonly(full_path)
745
mtime = tree.get_file_mtime(file_id)
746
os.utime(full_path, (mtime, mtime))
749
def _prepare_files(self, file_id, old_path, new_path, force_temp=False,
750
allow_write_new=False):
751
old_disk_path = self._write_file(file_id, self.old_tree, 'old',
752
old_path, force_temp)
753
new_disk_path = self._write_file(file_id, self.new_tree, 'new',
754
new_path, force_temp,
755
allow_write=allow_write_new)
756
return old_disk_path, new_disk_path
760
osutils.rmtree(self._root)
762
if e.errno != errno.ENOENT:
763
mutter("The temporary directory \"%s\" was not "
764
"cleanly removed: %s." % (self._root, e))
766
def diff(self, file_id, old_path, new_path, old_kind, new_kind):
767
if (old_kind, new_kind) != ('file', 'file'):
768
return DiffPath.CANNOT_DIFF
769
self._prepare_files(file_id, old_path, new_path)
770
self._execute(osutils.pathjoin('old', old_path),
771
osutils.pathjoin('new', new_path))
773
def edit_file(self, file_id):
774
"""Use this tool to edit a file.
776
A temporary copy will be edited, and the new contents will be
779
:param file_id: The id of the file to edit.
780
:return: The new contents of the file.
782
old_path = self.old_tree.id2path(file_id)
783
new_path = self.new_tree.id2path(file_id)
784
new_abs_path = self._prepare_files(file_id, old_path, new_path,
785
allow_write_new=True,
787
self._execute(osutils.pathjoin('old', old_path),
788
osutils.pathjoin('new', new_path))
789
new_file = open(new_abs_path, 'r')
791
return new_file.read()
796
class DiffTree(object):
797
"""Provides textual representations of the difference between two trees.
799
A DiffTree examines two trees and where a file-id has altered
800
between them, generates a textual representation of the difference.
801
DiffTree uses a sequence of DiffPath objects which are each
802
given the opportunity to handle a given altered fileid. The list
803
of DiffPath objects can be extended globally by appending to
804
DiffTree.diff_factories, or for a specific diff operation by
805
supplying the extra_factories option to the appropriate method.
808
# list of factories that can provide instances of DiffPath objects
809
# may be extended by plugins.
810
diff_factories = [DiffSymlink.from_diff_tree,
811
DiffDirectory.from_diff_tree]
813
def __init__(self, old_tree, new_tree, to_file, path_encoding='utf-8',
814
diff_text=None, extra_factories=None):
817
:param old_tree: Tree to show as old in the comparison
818
:param new_tree: Tree to show as new in the comparison
819
:param to_file: File to write comparision to
820
:param path_encoding: Character encoding to write paths in
821
:param diff_text: DiffPath-type object to use as a last resort for
823
:param extra_factories: Factories of DiffPaths to try before any other
825
if diff_text is None:
826
diff_text = DiffText(old_tree, new_tree, to_file, path_encoding,
827
'', '', internal_diff)
828
self.old_tree = old_tree
829
self.new_tree = new_tree
830
self.to_file = to_file
831
self.path_encoding = path_encoding
833
if extra_factories is not None:
834
self.differs.extend(f(self) for f in extra_factories)
835
self.differs.extend(f(self) for f in self.diff_factories)
836
self.differs.extend([diff_text, DiffKindChange.from_diff_tree(self)])
839
def from_trees_options(klass, old_tree, new_tree, to_file,
840
path_encoding, external_diff_options, old_label,
842
"""Factory for producing a DiffTree.
844
Designed to accept options used by show_diff_trees.
845
:param old_tree: The tree to show as old in the comparison
846
:param new_tree: The tree to show as new in the comparison
847
:param to_file: File to write comparisons to
848
:param path_encoding: Character encoding to use for writing paths
849
:param external_diff_options: If supplied, use the installed diff
850
binary to perform file comparison, using supplied options.
851
:param old_label: Prefix to use for old file labels
852
:param new_label: Prefix to use for new file labels
853
:param using: Commandline to use to invoke an external diff tool
855
if using is not None:
856
extra_factories = [DiffFromTool.make_from_diff_tree(using)]
859
if external_diff_options:
860
opts = external_diff_options.split()
861
def diff_file(olab, olines, nlab, nlines, to_file):
862
external_diff(olab, olines, nlab, nlines, to_file, opts)
864
diff_file = internal_diff
865
diff_text = DiffText(old_tree, new_tree, to_file, path_encoding,
866
old_label, new_label, diff_file)
867
return klass(old_tree, new_tree, to_file, path_encoding, diff_text,
870
def show_diff(self, specific_files, extra_trees=None):
871
"""Write tree diff to self.to_file
873
:param sepecific_files: the specific files to compare (recursive)
874
:param extra_trees: extra trees to use for mapping paths to file_ids
877
return self._show_diff(specific_files, extra_trees)
879
for differ in self.differs:
882
def _show_diff(self, specific_files, extra_trees):
883
# TODO: Generation of pseudo-diffs for added/deleted files could
884
# be usefully made into a much faster special case.
885
iterator = self.new_tree.iter_changes(self.old_tree,
886
specific_files=specific_files,
887
extra_trees=extra_trees,
888
require_versioned=True)
890
def changes_key(change):
891
old_path, new_path = change[1]
896
def get_encoded_path(path):
898
return path.encode(self.path_encoding, "replace")
899
for (file_id, paths, changed_content, versioned, parent, name, kind,
900
executable) in sorted(iterator, key=changes_key):
901
# The root does not get diffed, and items with no known kind (that
902
# is, missing) in both trees are skipped as well.
903
if parent == (None, None) or kind == (None, None):
905
oldpath, newpath = paths
906
oldpath_encoded = get_encoded_path(paths[0])
907
newpath_encoded = get_encoded_path(paths[1])
908
old_present = (kind[0] is not None and versioned[0])
909
new_present = (kind[1] is not None and versioned[1])
910
renamed = (parent[0], name[0]) != (parent[1], name[1])
912
properties_changed = []
913
properties_changed.extend(get_executable_change(executable[0], executable[1]))
915
if properties_changed:
916
prop_str = " (properties changed: %s)" % (", ".join(properties_changed),)
920
if (old_present, new_present) == (True, False):
921
self.to_file.write("=== removed %s '%s'\n" %
922
(kind[0], oldpath_encoded))
924
elif (old_present, new_present) == (False, True):
925
self.to_file.write("=== added %s '%s'\n" %
926
(kind[1], newpath_encoded))
929
self.to_file.write("=== renamed %s '%s' => '%s'%s\n" %
930
(kind[0], oldpath_encoded, newpath_encoded, prop_str))
932
# if it was produced by iter_changes, it must be
933
# modified *somehow*, either content or execute bit.
934
self.to_file.write("=== modified %s '%s'%s\n" % (kind[0],
935
newpath_encoded, prop_str))
937
self._diff(file_id, oldpath, newpath, kind[0], kind[1])
943
def diff(self, file_id, old_path, new_path):
944
"""Perform a diff of a single file
946
:param file_id: file-id of the file
947
:param old_path: The path of the file in the old tree
948
:param new_path: The path of the file in the new tree
951
old_kind = self.old_tree.kind(file_id)
952
except (errors.NoSuchId, errors.NoSuchFile):
955
new_kind = self.new_tree.kind(file_id)
956
except (errors.NoSuchId, errors.NoSuchFile):
958
self._diff(file_id, old_path, new_path, old_kind, new_kind)
961
def _diff(self, file_id, old_path, new_path, old_kind, new_kind):
962
result = DiffPath._diff_many(self.differs, file_id, old_path,
963
new_path, old_kind, new_kind)
964
if result is DiffPath.CANNOT_DIFF:
965
error_path = new_path
966
if error_path is None:
967
error_path = old_path
968
raise errors.NoDiffFound(error_path)