~bzr-pqm/bzr/bzr.dev

1658.1.9 by Martin Pool
Give an error for bzr diff on an nonexistent file (Malone #3619)
1
# Copyright (C) 2004, 2005, 2006 Canonical Ltd.
1711.2.54 by John Arbash Meinel
Use mkstemp instead of NamedTemporary file for external diff.
2
#
1 by mbp at sourcefrog
import from baz patch-364
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.
1711.2.54 by John Arbash Meinel
Use mkstemp instead of NamedTemporary file for external diff.
7
#
1 by mbp at sourcefrog
import from baz patch-364
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.
1711.2.54 by John Arbash Meinel
Use mkstemp instead of NamedTemporary file for external diff.
12
#
1 by mbp at sourcefrog
import from baz patch-364
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
4183.7.1 by Sabin Iacob
update FSF mailing address
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
1 by mbp at sourcefrog
import from baz patch-364
16
2520.4.140 by Aaron Bentley
Use matching blocks from mpdiff for knit delta creation
17
import difflib
1711.2.54 by John Arbash Meinel
Use mkstemp instead of NamedTemporary file for external diff.
18
import os
1899.1.5 by John Arbash Meinel
Always buffer the output of diff, so we can check if retcode==2 is because of Binary files
19
import re
3123.6.2 by Aaron Bentley
Implement diff --using natively
20
import shutil
4603.1.20 by Aaron Bentley
Use string.Template substitution with @ as delimiter.
21
import string
1996.3.9 by John Arbash Meinel
lazy_import diff.py
22
import sys
23
24
from bzrlib.lazy_import import lazy_import
25
lazy_import(globals(), """
26
import errno
1692.8.7 by James Henstridge
changes suggested by John Meinel
27
import subprocess
1711.2.54 by John Arbash Meinel
Use mkstemp instead of NamedTemporary file for external diff.
28
import tempfile
1740.2.5 by Aaron Bentley
Merge from bzr.dev
29
import time
30
1955.2.10 by John Arbash Meinel
Unset a few other LANG type variables when spawning diff
31
from bzrlib import (
1551.19.33 by Aaron Bentley
Use as_revision_id for diff
32
    branch as _mod_branch,
3072.1.1 by Ian Clatworthy
Improved diff based on feedback from abentley
33
    bzrdir,
3123.6.2 by Aaron Bentley
Implement diff --using natively
34
    commands,
1955.2.10 by John Arbash Meinel
Unset a few other LANG type variables when spawning diff
35
    errors,
36
    osutils,
1996.3.9 by John Arbash Meinel
lazy_import diff.py
37
    patiencediff,
38
    textfile,
1551.12.29 by Aaron Bentley
Copy and extend patch date formatting code, add patch-date parsing
39
    timestamp,
3586.1.21 by Ian Clatworthy
enhance diff to support views
40
    views,
1955.2.10 by John Arbash Meinel
Unset a few other LANG type variables when spawning diff
41
    )
1996.3.9 by John Arbash Meinel
lazy_import diff.py
42
""")
43
44
from bzrlib.symbol_versioning import (
3948.3.2 by Martin Pool
Remove APIs deprecated up to and including 1.6
45
    deprecated_function,
46
    )
3586.1.21 by Ian Clatworthy
enhance diff to support views
47
from bzrlib.trace import mutter, note, warning
1 by mbp at sourcefrog
import from baz patch-364
48
1711.2.24 by John Arbash Meinel
Late bind to PatienceSequenceMatcher to allow plugin to override.
49
4603.1.20 by Aaron Bentley
Use string.Template substitution with @ as delimiter.
50
class AtTemplate(string.Template):
51
    """Templating class that uses @ instead of $."""
52
53
    delimiter = '@'
54
55
767 by Martin Pool
- files are only reported as modified if their name or parent has changed,
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.
59
2520.4.140 by Aaron Bentley
Use matching blocks from mpdiff for knit delta creation
60
61
class _PrematchedMatcher(difflib.SequenceMatcher):
62
    """Allow SequenceMatcher operations to use predetermined blocks"""
63
64
    def __init__(self, matching_blocks):
65
        difflib.SequenceMatcher(self, None, None)
66
        self.matching_blocks = matching_blocks
67
        self.opcodes = None
68
69
1558.15.11 by Aaron Bentley
Apply merge review suggestions
70
def internal_diff(old_filename, oldlines, new_filename, newlines, to_file,
1711.2.30 by John Arbash Meinel
Fix bug in internal_diff handling of unicode paths
71
                  allow_binary=False, sequence_matcher=None,
72
                  path_encoding='utf8'):
475 by Martin Pool
- rewrite diff using compare_trees()
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.
79
80
    # In the meantime we at least make sure the patch isn't
81
    # mangled.
82
83
84
    # Special workaround for Python2.3, where difflib fails if
85
    # both sequences are empty.
86
    if not oldlines and not newlines:
87
        return
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
88
1558.15.11 by Aaron Bentley
Apply merge review suggestions
89
    if allow_binary is False:
1996.3.9 by John Arbash Meinel
lazy_import diff.py
90
        textfile.check_text_lines(oldlines)
91
        textfile.check_text_lines(newlines)
475 by Martin Pool
- rewrite diff using compare_trees()
92
1185.81.8 by John Arbash Meinel
Updating unified_diff to take a factory, using the new diff algorithm in the code.
93
    if sequence_matcher is None:
1996.3.9 by John Arbash Meinel
lazy_import diff.py
94
        sequence_matcher = patiencediff.PatienceSequenceMatcher
95
    ud = patiencediff.unified_diff(oldlines, newlines,
1740.2.5 by Aaron Bentley
Merge from bzr.dev
96
                      fromfile=old_filename.encode(path_encoding),
97
                      tofile=new_filename.encode(path_encoding),
1185.81.8 by John Arbash Meinel
Updating unified_diff to take a factory, using the new diff algorithm in the code.
98
                      sequencematcher=sequence_matcher)
475 by Martin Pool
- rewrite diff using compare_trees()
99
1092.1.50 by Robert Collins
make diff lsdiff/filterdiff friendly
100
    ud = list(ud)
3085.1.1 by John Arbash Meinel
Fix internal_diff to not fail when the texts are identical.
101
    if len(ud) == 0: # Identical contents, nothing to do
102
        return
475 by Martin Pool
- rewrite diff using compare_trees()
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
105
    if not oldlines:
106
        ud[2] = ud[2].replace('-1,0', '-0,0')
107
    elif not newlines:
108
        ud[2] = ud[2].replace('+1,0', '+0,0')
109
804 by Martin Pool
Patch from John:
110
    for line in ud:
111
        to_file.write(line)
974.1.5 by Aaron Bentley
Fixed handling of missing newlines in udiffs
112
        if not line.endswith('\n'):
113
            to_file.write("\n\\ No newline at end of file\n")
2911.6.1 by Blake Winton
Change 'print >> f,'s to 'f.write('s.
114
    to_file.write('\n')
475 by Martin Pool
- rewrite diff using compare_trees()
115
116
1920.1.1 by John Arbash Meinel
fix bug #56307, handle binary files even when LANG is not english
117
def _spawn_external_diff(diffcmd, capture_errors=True):
118
    """Spawn the externall diff process, and return the child handle.
119
120
    :param diffcmd: The command list to spawn
2138.1.1 by Wouter van Heyst
Robuster external diff output handling.
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.
1920.1.1 by John Arbash Meinel
fix bug #56307, handle binary files even when LANG is not english
124
    :return: A Popen object.
125
    """
126
    if capture_errors:
2321.2.2 by Alexander Belchenko
win32 fixes for test_external_diff_binary (gettext on win32 rely on $LANGUAGE)
127
        # construct minimal environment
128
        env = {}
129
        path = os.environ.get('PATH')
130
        if path is not None:
131
            env['PATH'] = path
2321.2.5 by Alexander Belchenko
external diff: no need for special code path for win32 (suggested by John Meinel)
132
        env['LANGUAGE'] = 'C'   # on win32 only LANGUAGE has effect
133
        env['LANG'] = 'C'
134
        env['LC_ALL'] = 'C'
1920.1.1 by John Arbash Meinel
fix bug #56307, handle binary files even when LANG is not english
135
        stderr = subprocess.PIPE
136
    else:
2321.2.2 by Alexander Belchenko
win32 fixes for test_external_diff_binary (gettext on win32 rely on $LANGUAGE)
137
        env = None
1920.1.1 by John Arbash Meinel
fix bug #56307, handle binary files even when LANG is not english
138
        stderr = None
139
140
    try:
141
        pipe = subprocess.Popen(diffcmd,
142
                                stdin=subprocess.PIPE,
143
                                stdout=subprocess.PIPE,
144
                                stderr=stderr,
2321.2.2 by Alexander Belchenko
win32 fixes for test_external_diff_binary (gettext on win32 rely on $LANGUAGE)
145
                                env=env)
1920.1.1 by John Arbash Meinel
fix bug #56307, handle binary files even when LANG is not english
146
    except OSError, e:
147
        if e.errno == errno.ENOENT:
148
            raise errors.NoDiff(str(e))
149
        raise
150
151
    return pipe
152
153
1185.35.29 by Aaron Bentley
Support whitespace in diff filenames
154
def external_diff(old_filename, oldlines, new_filename, newlines, to_file,
571 by Martin Pool
- new --diff-options to pass options through to external
155
                  diff_opts):
568 by Martin Pool
- start adding support for showing diffs by calling out to
156
    """Display a diff by calling out to the external diff program."""
581 by Martin Pool
- make sure any bzr output is flushed before
157
    # make sure our own output is properly ordered before the diff
158
    to_file.flush()
159
1711.2.54 by John Arbash Meinel
Use mkstemp instead of NamedTemporary file for external 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')
568 by Martin Pool
- start adding support for showing diffs by calling out to
164
165
    try:
166
        # TODO: perhaps a special case for comparing to or from the empty
167
        # sequence; can just use /dev/null on Unix
168
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.
172
173
        oldtmpf.writelines(oldlines)
174
        newtmpf.writelines(newlines)
175
1711.2.54 by John Arbash Meinel
Use mkstemp instead of NamedTemporary file for external diff.
176
        oldtmpf.close()
177
        newtmpf.close()
568 by Martin Pool
- start adding support for showing diffs by calling out to
178
571 by Martin Pool
- new --diff-options to pass options through to external
179
        if not diff_opts:
180
            diff_opts = []
4422.1.1 by John Arbash Meinel
Possibly fix for bug #382709 handling non-ascii external filenames.
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')
4422.1.2 by Martin
Fix copy-and-paste error in previous change
185
            new_filename = new_filename.encode('mbcs')
571 by Martin Pool
- new --diff-options to pass options through to external
186
        diffcmd = ['diff',
1740.2.5 by Aaron Bentley
Merge from bzr.dev
187
                   '--label', old_filename,
1711.2.54 by John Arbash Meinel
Use mkstemp instead of NamedTemporary file for external diff.
188
                   old_abspath,
1740.2.5 by Aaron Bentley
Merge from bzr.dev
189
                   '--label', new_filename,
1711.2.56 by John Arbash Meinel
Raise NoDiff if 'diff' not present.
190
                   new_abspath,
191
                   '--binary',
192
                  ]
571 by Martin Pool
- new --diff-options to pass options through to external
193
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
198
        # the grammar.
199
        for s in ['-c', '-u', '-C', '-U',
200
                  '-e', '--ed',
201
                  '-q', '--brief',
202
                  '--normal',
203
                  '-n', '--rcs',
204
                  '-y', '--side-by-side',
205
                  '-D', '--ifdef']:
206
            for j in diff_opts:
207
                if j.startswith(s):
208
                    break
209
            else:
210
                continue
211
            break
212
        else:
213
            diffcmd.append('-u')
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
214
571 by Martin Pool
- new --diff-options to pass options through to external
215
        if diff_opts:
216
            diffcmd.extend(diff_opts)
217
1920.1.1 by John Arbash Meinel
fix bug #56307, handle binary files even when LANG is not english
218
        pipe = _spawn_external_diff(diffcmd, capture_errors=True)
219
        out,err = pipe.communicate()
220
        rc = pipe.returncode
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
221
1920.1.1 by John Arbash Meinel
fix bug #56307, handle binary files even when LANG is not english
222
        # internal_diff() adds a trailing newline, add one here for consistency
223
        out += '\n'
1899.1.5 by John Arbash Meinel
Always buffer the output of diff, so we can check if retcode==2 is because of Binary files
224
        if rc == 2:
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.
1904.1.4 by Marien Zwart
Make external diff in binary mode work with recent versions of diffutils.
228
            # 'Binary files' is not a real error, so we suppress that error.
1920.1.1 by John Arbash Meinel
fix bug #56307, handle binary files even when LANG is not english
229
            lang_c_out = out
230
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()
234
235
            # Write out the new i18n diff response
236
            to_file.write(out+'\n')
237
            if pipe.returncode != 2:
1996.3.9 by John Arbash Meinel
lazy_import diff.py
238
                raise errors.BzrError(
239
                               'external diff failed with exit code 2'
2138.1.1 by Wouter van Heyst
Robuster external diff output handling.
240
                               ' when run with LANG=C and LC_ALL=C,'
241
                               ' but not when run natively: %r' % (diffcmd,))
1920.1.1 by John Arbash Meinel
fix bug #56307, handle binary files even when LANG is not english
242
243
            first_line = lang_c_out.split('\n', 1)[0]
1904.1.4 by Marien Zwart
Make external diff in binary mode work with recent versions of diffutils.
244
            # Starting with diffutils 2.8.4 the word "binary" was dropped.
245
            m = re.match('^(binary )?files.*differ$', first_line, re.I)
1920.1.1 by John Arbash Meinel
fix bug #56307, handle binary files even when LANG is not english
246
            if m is None:
1996.3.9 by John Arbash Meinel
lazy_import diff.py
247
                raise errors.BzrError('external diff failed with exit code 2;'
248
                                      ' command: %r' % (diffcmd,))
1920.1.1 by John Arbash Meinel
fix bug #56307, handle binary files even when LANG is not english
249
            else:
250
                # Binary files differ, just return
251
                return
252
253
        # If we got to here, we haven't written out the output of diff
254
        # do so now
255
        to_file.write(out)
256
        if rc not in (0, 1):
571 by Martin Pool
- new --diff-options to pass options through to external
257
            # returns 1 if files differ; that's OK
258
            if rc < 0:
259
                msg = 'signal %d' % (-rc)
260
            else:
261
                msg = 'exit code %d' % rc
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
262
263
            raise errors.BzrError('external diff failed with %s; command: %r'
1996.3.9 by John Arbash Meinel
lazy_import diff.py
264
                                  % (rc, diffcmd))
1899.1.6 by John Arbash Meinel
internal_diff always adds a trailing \n, make sure external_diff does too
265
266
568 by Martin Pool
- start adding support for showing diffs by calling out to
267
    finally:
268
        oldtmpf.close()                 # and delete
269
        newtmpf.close()
1711.2.54 by John Arbash Meinel
Use mkstemp instead of NamedTemporary file for external diff.
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)
273
        try:
274
            os.remove(old_abspath)
275
        except OSError, e:
276
            if e.errno not in (errno.ENOENT,):
277
                warning('Failed to delete temporary file: %s %s',
278
                        old_abspath, e)
279
        try:
280
            os.remove(new_abspath)
281
        except OSError:
282
            if e.errno not in (errno.ENOENT,):
283
                warning('Failed to delete temporary file: %s %s',
284
                        new_abspath, e)
568 by Martin Pool
- start adding support for showing diffs by calling out to
285
1551.2.13 by Aaron Bentley
Got diff working properly with checkouts
286
4705.1.1 by Gary van der Merwe
Change _get_trees_to_diff to get_trees_and_branches_to_diff.
287
def get_trees_and_branches_to_diff(path_list, revision_specs, old_url, new_url,
4732.1.2 by Vincent Ladeuil
(trivial) Fix some PEP8 issues
288
                                   apply_view=True):
3072.1.1 by Ian Clatworthy
Improved diff based on feedback from abentley
289
    """Get the trees and specific files to diff given a list of paths.
290
291
    This method works out the trees to be diff'ed and the files of
292
    interest within those trees.
293
294
    :param path_list:
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.
299
    :param old_url:
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.
302
    :param new_url:
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.
3586.1.21 by Ian Clatworthy
enhance diff to support views
305
    :param apply_view:
306
        if True and a view is set, apply the view or check that the paths
307
        are within it
3072.1.1 by Ian Clatworthy
Improved diff based on feedback from abentley
308
    :returns:
4739.3.1 by Jonathan Lange
Fix the docstring for get_trees_and_branches_to_diff.
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.
3072.1.1 by Ian Clatworthy
Improved diff based on feedback from abentley
312
    """
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]
3072.1.5 by Ian Clatworthy
more good ideas from abentley
319
            if old_url is None:
320
                old_url = old_revision_spec.get_branch()
3072.1.1 by Ian Clatworthy
Improved diff based on feedback from abentley
321
        if len(revision_specs) > 1:
322
            new_revision_spec = revision_specs[1]
3072.1.5 by Ian Clatworthy
more good ideas from abentley
323
            if new_url is None:
324
                new_url = new_revision_spec.get_branch()
3072.1.1 by Ian Clatworthy
Improved diff based on feedback from abentley
325
3072.1.5 by Ian Clatworthy
more good ideas from abentley
326
    other_paths = []
327
    make_paths_wt_relative = True
3164.1.1 by Ian Clatworthy
diff without arguments means the current tree, not the current directory
328
    consider_relpath = True
3072.1.1 by Ian Clatworthy
Improved diff based on feedback from abentley
329
    if path_list is None or len(path_list) == 0:
3164.1.1 by Ian Clatworthy
diff without arguments means the current tree, not the current directory
330
        # If no path is given, the current working tree is used
3072.1.1 by Ian Clatworthy
Improved diff based on feedback from abentley
331
        default_location = u'.'
3164.1.1 by Ian Clatworthy
diff without arguments means the current tree, not the current directory
332
        consider_relpath = False
3072.1.1 by Ian Clatworthy
Improved diff based on feedback from abentley
333
    elif old_url is not None and new_url is not None:
334
        other_paths = path_list
3072.1.5 by Ian Clatworthy
more good ideas from abentley
335
        make_paths_wt_relative = False
3072.1.1 by Ian Clatworthy
Improved diff based on feedback from abentley
336
    else:
337
        default_location = path_list[0]
338
        other_paths = path_list[1:]
339
340
    # Get the old location
3072.1.2 by Ian Clatworthy
Test various --old and --new combinations
341
    specific_files = []
3072.1.1 by Ian Clatworthy
Improved diff based on feedback from abentley
342
    if old_url is None:
343
        old_url = default_location
344
    working_tree, branch, relpath = \
345
        bzrdir.BzrDir.open_containing_tree_or_branch(old_url)
3164.1.1 by Ian Clatworthy
diff without arguments means the current tree, not the current directory
346
    if consider_relpath and relpath != '':
3586.1.21 by Ian Clatworthy
enhance diff to support views
347
        if working_tree is not None and apply_view:
4032.4.1 by Eduardo Padoan
Moved diff._check_path_in_view() to views.check_path_in_view()
348
            views.check_path_in_view(working_tree, relpath)
3072.1.2 by Ian Clatworthy
Test various --old and --new combinations
349
        specific_files.append(relpath)
3072.1.1 by Ian Clatworthy
Improved diff based on feedback from abentley
350
    old_tree = _get_tree_to_diff(old_revision_spec, working_tree, branch)
4705.1.1 by Gary van der Merwe
Change _get_trees_to_diff to get_trees_and_branches_to_diff.
351
    old_branch = branch
3072.1.1 by Ian Clatworthy
Improved diff based on feedback from abentley
352
353
    # Get the new location
354
    if new_url is None:
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)
3164.1.1 by Ian Clatworthy
diff without arguments means the current tree, not the current directory
359
        if consider_relpath and relpath != '':
3586.1.21 by Ian Clatworthy
enhance diff to support views
360
            if working_tree is not None and apply_view:
4032.4.1 by Eduardo Padoan
Moved diff._check_path_in_view() to views.check_path_in_view()
361
                views.check_path_in_view(working_tree, relpath)
3072.1.2 by Ian Clatworthy
Test various --old and --new combinations
362
            specific_files.append(relpath)
3072.1.1 by Ian Clatworthy
Improved diff based on feedback from abentley
363
    new_tree = _get_tree_to_diff(new_revision_spec, working_tree, branch,
364
        basis_is_default=working_tree is None)
4705.1.1 by Gary van der Merwe
Change _get_trees_to_diff to get_trees_and_branches_to_diff.
365
    new_branch = branch
3072.1.1 by Ian Clatworthy
Improved diff based on feedback from abentley
366
3072.1.2 by Ian Clatworthy
Test various --old and --new combinations
367
    # Get the specific files (all files is None, no files is [])
3072.1.5 by Ian Clatworthy
more good ideas from abentley
368
    if make_paths_wt_relative and working_tree is not None:
3586.1.21 by Ian Clatworthy
enhance diff to support views
369
        try:
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")
3072.1.2 by Ian Clatworthy
Test various --old and --new combinations
375
    specific_files.extend(other_paths)
376
    if len(specific_files) == 0:
377
        specific_files = None
3586.1.21 by Ian Clatworthy
enhance diff to support views
378
        if (working_tree is not None and working_tree.supports_views()
379
            and apply_view):
380
            view_files = working_tree.views.lookup_view()
381
            if view_files:
382
                specific_files = view_files
383
                view_str = views.view_display_str(view_files)
4210.1.1 by Ian Clatworthy
reword 'ignoring files outside view' message
384
                note("*** Ignoring files outside view. View is %s" % view_str)
3072.1.2 by Ian Clatworthy
Test various --old and --new combinations
385
386
    # Get extra trees that ought to be searched for file-ids
3072.1.1 by Ian Clatworthy
Improved diff based on feedback from abentley
387
    extra_trees = None
3072.1.5 by Ian Clatworthy
more good ideas from abentley
388
    if working_tree is not None and working_tree not in (old_tree, new_tree):
3072.1.1 by Ian Clatworthy
Improved diff based on feedback from abentley
389
        extra_trees = (working_tree,)
4705.1.1 by Gary van der Merwe
Change _get_trees_to_diff to get_trees_and_branches_to_diff.
390
    return old_tree, new_tree, old_branch, new_branch, specific_files, extra_trees
3072.1.1 by Ian Clatworthy
Improved diff based on feedback from abentley
391
4739.3.1 by Jonathan Lange
Fix the docstring for get_trees_and_branches_to_diff.
392
3072.1.1 by Ian Clatworthy
Improved diff based on feedback from abentley
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:
395
        branch = tree.branch
396
    if spec is None or spec.spec is None:
397
        if basis_is_default:
3072.1.5 by Ian Clatworthy
more good ideas from abentley
398
            if tree is not None:
399
                return tree.basis_tree()
400
            else:
401
                return branch.basis_tree()
3072.1.1 by Ian Clatworthy
Improved diff based on feedback from abentley
402
        else:
403
            return tree
3655.3.1 by Lukáš Lalinský
Fix `bzr st -rbranch:PATH_TO_BRANCH`
404
    return spec.as_tree(branch)
3072.1.1 by Ian Clatworthy
Improved diff based on feedback from abentley
405
406
571 by Martin Pool
- new --diff-options to pass options through to external
407
def show_diff_trees(old_tree, new_tree, to_file, specific_files=None,
1684.1.6 by Martin Pool
(patch) --diff-prefix option (goffredo, alexander)
408
                    external_diff_options=None,
1551.7.17 by Aaron Bentley
Switch to PathsNotVersioned, accept extra_trees
409
                    old_label='a/', new_label='b/',
2598.6.12 by ghigo
Move the encoding of the commit message at the command line level
410
                    extra_trees=None,
3123.6.2 by Aaron Bentley
Implement diff --using natively
411
                    path_encoding='utf8',
412
                    using=None):
550 by Martin Pool
- Refactor diff code into one that works purely on
413
    """Show in text form the changes from one tree to another.
414
3072.1.1 by Ian Clatworthy
Improved diff based on feedback from abentley
415
    to_file
416
        The output stream.
417
418
    specific_files
419
        Include only changes to these files - None for all changes.
571 by Martin Pool
- new --diff-options to pass options through to external
420
421
    external_diff_options
422
        If set, use an external GNU diff and pass these options.
1551.7.18 by Aaron Bentley
Indentation and documentation fixes
423
424
    extra_trees
425
        If set, more Trees to use for looking up file ids
2598.6.12 by ghigo
Move the encoding of the commit message at the command line level
426
427
    path_encoding
2598.6.24 by ghigo
update on the basis of Aaron suggestions
428
        If set, the path will be encoded as specified, otherwise is supposed
429
        to be utf8
550 by Martin Pool
- Refactor diff code into one that works purely on
430
    """
1543.1.1 by Denys Duchier
lock operations for trees - use them for diff
431
    old_tree.lock_read()
432
    try:
2255.7.38 by John Arbash Meinel
show_diff_trees() should lock any extra trees it is passed.
433
        if extra_trees is not None:
434
            for tree in extra_trees:
435
                tree.lock_read()
1543.1.1 by Denys Duchier
lock operations for trees - use them for diff
436
        new_tree.lock_read()
437
        try:
3009.2.22 by Aaron Bentley
Update names & docstring
438
            differ = DiffTree.from_trees_options(old_tree, new_tree, to_file,
3123.6.2 by Aaron Bentley
Implement diff --using natively
439
                                                 path_encoding,
440
                                                 external_diff_options,
441
                                                 old_label, new_label, using)
3009.2.12 by Aaron Bentley
Associate labels with text diffing only
442
            return differ.show_diff(specific_files, extra_trees)
1543.1.1 by Denys Duchier
lock operations for trees - use them for diff
443
        finally:
444
            new_tree.unlock()
2255.7.38 by John Arbash Meinel
show_diff_trees() should lock any extra trees it is passed.
445
            if extra_trees is not None:
446
                for tree in extra_trees:
447
                    tree.unlock()
1543.1.1 by Denys Duchier
lock operations for trees - use them for diff
448
    finally:
449
        old_tree.unlock()
450
451
1740.2.5 by Aaron Bentley
Merge from bzr.dev
452
def _patch_header_date(tree, file_id, path):
453
    """Returns a timestamp suitable for use in a patch header."""
2405.1.2 by John Arbash Meinel
Fix bug #103870 by passing None instead of a (sometimes wrong) path
454
    mtime = tree.get_file_mtime(file_id, path)
455
    return timestamp.format_patch_date(mtime)
1740.2.5 by Aaron Bentley
Merge from bzr.dev
456
457
3268.1.1 by C Miller
Describe the property changes in diffs. Currently, this is the executable-bit
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],)]
462
    else:
463
        return []
464
1398 by Robert Collins
integrate in Gustavos x-bit patch
465
3009.2.22 by Aaron Bentley
Update names & docstring
466
class DiffPath(object):
3009.2.14 by Aaron Bentley
Update return type handling
467
    """Base type for command object that compare files"""
3009.2.17 by Aaron Bentley
Update docs
468
3009.2.14 by Aaron Bentley
Update return type handling
469
    # The type or contents of the file were unsuitable for diffing
3009.2.29 by Aaron Bentley
Change constants to strings
470
    CANNOT_DIFF = 'CANNOT_DIFF'
3009.2.14 by Aaron Bentley
Update return type handling
471
    # The file has changed in a semantic way
3009.2.29 by Aaron Bentley
Change constants to strings
472
    CHANGED = 'CHANGED'
473
    # The file content may have changed, but there is no semantic change
474
    UNCHANGED = 'UNCHANGED'
3009.2.11 by Aaron Bentley
Refactor diff to be more pluggable
475
3009.2.13 by Aaron Bentley
Refactor differ to support registering differ factories
476
    def __init__(self, old_tree, new_tree, to_file, path_encoding='utf-8'):
3009.2.17 by Aaron Bentley
Update docs
477
        """Constructor.
478
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
483
        """
3009.2.11 by Aaron Bentley
Refactor diff to be more pluggable
484
        self.old_tree = old_tree
485
        self.new_tree = new_tree
486
        self.to_file = to_file
3009.2.13 by Aaron Bentley
Refactor differ to support registering differ factories
487
        self.path_encoding = path_encoding
3009.2.11 by Aaron Bentley
Refactor diff to be more pluggable
488
3123.6.2 by Aaron Bentley
Implement diff --using natively
489
    def finish(self):
490
        pass
491
3009.2.28 by Aaron Bentley
Add from_diff_tree factories
492
    @classmethod
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)
496
3009.2.11 by Aaron Bentley
Refactor diff to be more pluggable
497
    @staticmethod
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,
501
                                      new_kind)
3009.2.22 by Aaron Bentley
Update names & docstring
502
            if result is not DiffPath.CANNOT_DIFF:
3009.2.11 by Aaron Bentley
Refactor diff to be more pluggable
503
                return result
504
        else:
3009.2.22 by Aaron Bentley
Update names & docstring
505
            return DiffPath.CANNOT_DIFF
506
507
508
class DiffKindChange(object):
3009.2.17 by Aaron Bentley
Update docs
509
    """Special differ for file kind changes.
3009.2.11 by Aaron Bentley
Refactor diff to be more pluggable
510
3009.2.17 by Aaron Bentley
Update docs
511
    Represents kind change as deletion + creation.  Uses the other differs
512
    to do this.
513
    """
3009.2.11 by Aaron Bentley
Refactor diff to be more pluggable
514
    def __init__(self, differs):
515
        self.differs = differs
516
3123.6.2 by Aaron Bentley
Implement diff --using natively
517
    def finish(self):
518
        pass
519
3009.2.28 by Aaron Bentley
Add from_diff_tree factories
520
    @classmethod
521
    def from_diff_tree(klass, diff_tree):
522
        return klass(diff_tree.differs)
523
3009.2.11 by Aaron Bentley
Refactor diff to be more pluggable
524
    def diff(self, file_id, old_path, new_path, old_kind, new_kind):
3009.2.17 by Aaron Bentley
Update docs
525
        """Perform comparison
526
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
532
        """
3009.2.18 by Aaron Bentley
Change KindChangeDiffer's anti-recursion to avoid kind pairs with None
533
        if None in (old_kind, new_kind):
3009.2.22 by Aaron Bentley
Update names & docstring
534
            return DiffPath.CANNOT_DIFF
535
        result = DiffPath._diff_many(self.differs, file_id, old_path,
3009.2.18 by Aaron Bentley
Change KindChangeDiffer's anti-recursion to avoid kind pairs with None
536
                                       new_path, old_kind, None)
3009.2.22 by Aaron Bentley
Update names & docstring
537
        if result is DiffPath.CANNOT_DIFF:
3009.2.11 by Aaron Bentley
Refactor diff to be more pluggable
538
            return result
3009.2.22 by Aaron Bentley
Update names & docstring
539
        return DiffPath._diff_many(self.differs, file_id, old_path, new_path,
3009.2.11 by Aaron Bentley
Refactor diff to be more pluggable
540
                                     None, new_kind)
541
542
3009.2.22 by Aaron Bentley
Update names & docstring
543
class DiffDirectory(DiffPath):
3009.2.19 by Aaron Bentley
Implement directory diffing
544
545
    def diff(self, file_id, old_path, new_path, old_kind, new_kind):
546
        """Perform comparison between two directories.  (dummy)
547
548
        """
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
555
        return self.CHANGED
556
3009.2.20 by Aaron Bentley
PEP8
557
3009.2.22 by Aaron Bentley
Update names & docstring
558
class DiffSymlink(DiffPath):
3009.2.11 by Aaron Bentley
Refactor diff to be more pluggable
559
560
    def diff(self, file_id, old_path, new_path, old_kind, new_kind):
3009.2.17 by Aaron Bentley
Update docs
561
        """Perform comparison between two symlinks
562
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
568
        """
3009.2.11 by Aaron Bentley
Refactor diff to be more pluggable
569
        if 'symlink' not in (old_kind, new_kind):
3009.2.14 by Aaron Bentley
Update return type handling
570
            return self.CANNOT_DIFF
3009.2.11 by Aaron Bentley
Refactor diff to be more pluggable
571
        if old_kind == 'symlink':
572
            old_target = self.old_tree.get_symlink_target(file_id)
573
        elif old_kind is None:
574
            old_target = None
575
        else:
3009.2.14 by Aaron Bentley
Update return type handling
576
            return self.CANNOT_DIFF
3009.2.11 by Aaron Bentley
Refactor diff to be more pluggable
577
        if new_kind == 'symlink':
578
            new_target = self.new_tree.get_symlink_target(file_id)
579
        elif new_kind is None:
580
            new_target = None
581
        else:
3009.2.14 by Aaron Bentley
Update return type handling
582
            return self.CANNOT_DIFF
3009.2.11 by Aaron Bentley
Refactor diff to be more pluggable
583
        return self.diff_symlink(old_target, new_target)
584
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)
590
        else:
591
            self.to_file.write('=== target changed %r => %r\n' %
592
                              (old_target, new_target))
3009.2.14 by Aaron Bentley
Update return type handling
593
        return self.CHANGED
3009.2.11 by Aaron Bentley
Refactor diff to be more pluggable
594
595
3009.2.22 by Aaron Bentley
Update names & docstring
596
class DiffText(DiffPath):
3009.2.2 by Aaron Bentley
Implement Differ object for abstracting diffing
597
3009.2.7 by Aaron Bentley
Move responsibility for generating diff labels into Differ.diff
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'
601
3009.2.13 by Aaron Bentley
Refactor differ to support registering differ factories
602
    def __init__(self, old_tree, new_tree, to_file, path_encoding='utf-8',
603
                 old_label='', new_label='', text_differ=internal_diff):
3009.2.22 by Aaron Bentley
Update names & docstring
604
        DiffPath.__init__(self, old_tree, new_tree, to_file, path_encoding)
3009.2.11 by Aaron Bentley
Refactor diff to be more pluggable
605
        self.text_differ = text_differ
606
        self.old_label = old_label
607
        self.new_label = new_label
3009.2.12 by Aaron Bentley
Associate labels with text diffing only
608
        self.path_encoding = path_encoding
3009.2.11 by Aaron Bentley
Refactor diff to be more pluggable
609
610
    def diff(self, file_id, old_path, new_path, old_kind, new_kind):
3009.2.17 by Aaron Bentley
Update docs
611
        """Compare two files in unified diff format
612
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
618
        """
3009.2.11 by Aaron Bentley
Refactor diff to be more pluggable
619
        if 'file' not in (old_kind, new_kind):
3009.2.14 by Aaron Bentley
Update return type handling
620
            return self.CANNOT_DIFF
3009.2.11 by Aaron Bentley
Refactor diff to be more pluggable
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
3009.2.12 by Aaron Bentley
Associate labels with text diffing only
626
            from_file_id = None
3009.2.11 by Aaron Bentley
Refactor diff to be more pluggable
627
        else:
3009.2.14 by Aaron Bentley
Update return type handling
628
            return self.CANNOT_DIFF
3009.2.11 by Aaron Bentley
Refactor diff to be more pluggable
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
633
            to_file_id = None
634
        else:
3009.2.14 by Aaron Bentley
Update return type handling
635
            return self.CANNOT_DIFF
3009.2.11 by Aaron Bentley
Refactor diff to be more pluggable
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)
4377.3.3 by Ian Clatworthy
avoid unnecessary id2path calculation when diffing
638
        return self.diff_text(from_file_id, to_file_id, from_label, to_label,
639
            old_path, new_path)
3009.2.11 by Aaron Bentley
Refactor diff to be more pluggable
640
4377.3.3 by Ian Clatworthy
avoid unnecessary id2path calculation when diffing
641
    def diff_text(self, from_file_id, to_file_id, from_label, to_label,
642
        from_path=None, to_path=None):
3009.2.11 by Aaron Bentley
Refactor diff to be more pluggable
643
        """Diff the content of given files in two trees
644
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.
4377.3.3 by Ian Clatworthy
avoid unnecessary id2path calculation when diffing
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.
3009.2.11 by Aaron Bentley
Refactor diff to be more pluggable
652
        """
4377.3.3 by Ian Clatworthy
avoid unnecessary id2path calculation when diffing
653
        def _get_text(tree, file_id, path):
3009.2.11 by Aaron Bentley
Refactor diff to be more pluggable
654
            if file_id is not None:
4377.3.3 by Ian Clatworthy
avoid unnecessary id2path calculation when diffing
655
                return tree.get_file(file_id, path).readlines()
3009.2.11 by Aaron Bentley
Refactor diff to be more pluggable
656
            else:
657
                return []
658
        try:
4377.3.3 by Ian Clatworthy
avoid unnecessary id2path calculation when diffing
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)
3009.2.11 by Aaron Bentley
Refactor diff to be more pluggable
661
            self.text_differ(from_label, from_text, to_label, to_text,
662
                             self.to_file)
663
        except errors.BinaryFile:
664
            self.to_file.write(
665
                  ("Binary files %s and %s differ\n" %
666
                  (from_label, to_label)).encode(self.path_encoding))
3009.2.14 by Aaron Bentley
Update return type handling
667
        return self.CHANGED
3009.2.11 by Aaron Bentley
Refactor diff to be more pluggable
668
669
3123.6.2 by Aaron Bentley
Implement diff --using natively
670
class DiffFromTool(DiffPath):
671
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
3638.3.2 by Vincent Ladeuil
Fix all calls to tempfile.mkdtemp to osutils.mkdtemp.
676
        self._root = osutils.mkdtemp(prefix='bzr-diff-')
3123.6.2 by Aaron Bentley
Implement diff --using natively
677
678
    @classmethod
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)
4603.1.20 by Aaron Bentley
Use string.Template substitution with @ as delimiter.
682
        if '@' not in command_string:
683
            command_template.extend(['@old_path', '@new_path'])
3123.6.2 by Aaron Bentley
Implement diff --using natively
684
        return klass(command_template, old_tree, new_tree, to_file,
685
                     path_encoding)
686
687
    @classmethod
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
693
694
    def _get_command(self, old_path, new_path):
695
        my_map = {'old_path': old_path, 'new_path': new_path}
4603.1.20 by Aaron Bentley
Use string.Template substitution with @ as delimiter.
696
        return [AtTemplate(t).substitute(my_map) for t in
697
                self.command_template]
3123.6.2 by Aaron Bentley
Implement diff --using natively
698
699
    def _execute(self, old_path, new_path):
3145.1.1 by Aaron Bentley
Handle missing tools gracefully in diff --using
700
        command = self._get_command(old_path, new_path)
701
        try:
702
            proc = subprocess.Popen(command, stdout=subprocess.PIPE,
703
                                    cwd=self._root)
704
        except OSError, e:
705
            if e.errno == errno.ENOENT:
706
                raise errors.ExecutableMissing(command[0])
3145.1.2 by Aaron Bentley
Don't swallow other OSErrors
707
            else:
708
                raise
3123.6.2 by Aaron Bentley
Implement diff --using natively
709
        self.to_file.write(proc.stdout.read())
710
        return proc.wait()
711
3123.6.5 by Aaron Bentley
Symlink to real files if possible
712
    def _try_symlink_root(self, tree, prefix):
3287.18.3 by Matt McClure
Toward a more acceptable patch for bug 209281.
713
        if (getattr(tree, 'abspath', None) is None
3287.18.14 by Matt McClure
Extracted a host_os_dereferences_symlinks method.
714
            or not osutils.host_os_dereferences_symlinks()):
3123.6.5 by Aaron Bentley
Symlink to real files if possible
715
            return False
716
        try:
717
            os.symlink(tree.abspath(''), osutils.pathjoin(self._root, prefix))
718
        except OSError, e:
719
            if e.errno != errno.EEXIST:
720
                raise
721
        return True
722
4603.1.4 by Aaron Bentley
Implement DiffFromTool.edit_file
723
    def _write_file(self, file_id, tree, prefix, relpath, force_temp=False,
724
                    allow_write=False):
3123.6.4 by Aaron Bentley
Set mtime (and atime) on files for --using
725
        full_path = osutils.pathjoin(self._root, prefix, relpath)
4603.1.4 by Aaron Bentley
Implement DiffFromTool.edit_file
726
        if not force_temp and self._try_symlink_root(tree, prefix):
3123.6.5 by Aaron Bentley
Symlink to real files if possible
727
            return full_path
3123.6.4 by Aaron Bentley
Set mtime (and atime) on files for --using
728
        parent_dir = osutils.dirname(full_path)
3123.6.2 by Aaron Bentley
Implement diff --using natively
729
        try:
730
            os.makedirs(parent_dir)
731
        except OSError, e:
732
            if e.errno != errno.EEXIST:
733
                raise
3123.6.6 by Aaron Bentley
Use relpath for get_file
734
        source = tree.get_file(file_id, relpath)
3123.6.2 by Aaron Bentley
Implement diff --using natively
735
        try:
3123.6.4 by Aaron Bentley
Set mtime (and atime) on files for --using
736
            target = open(full_path, 'wb')
3123.6.2 by Aaron Bentley
Implement diff --using natively
737
            try:
738
                osutils.pumpfile(source, target)
739
            finally:
740
                target.close()
741
        finally:
742
            source.close()
4603.1.4 by Aaron Bentley
Implement DiffFromTool.edit_file
743
        if not allow_write:
4603.1.1 by Aaron Bentley
Initial pass at shelve-via-editor.
744
            osutils.make_readonly(full_path)
3123.6.4 by Aaron Bentley
Set mtime (and atime) on files for --using
745
        mtime = tree.get_file_mtime(file_id)
746
        os.utime(full_path, (mtime, mtime))
747
        return full_path
3123.6.2 by Aaron Bentley
Implement diff --using natively
748
4603.1.4 by Aaron Bentley
Implement DiffFromTool.edit_file
749
    def _prepare_files(self, file_id, old_path, new_path, force_temp=False,
750
                       allow_write_new=False):
3123.6.2 by Aaron Bentley
Implement diff --using natively
751
        old_disk_path = self._write_file(file_id, self.old_tree, 'old',
4603.1.4 by Aaron Bentley
Implement DiffFromTool.edit_file
752
                                         old_path, force_temp)
3123.6.2 by Aaron Bentley
Implement diff --using natively
753
        new_disk_path = self._write_file(file_id, self.new_tree, 'new',
4603.1.4 by Aaron Bentley
Implement DiffFromTool.edit_file
754
                                         new_path, force_temp,
755
                                         allow_write=allow_write_new)
3123.6.2 by Aaron Bentley
Implement diff --using natively
756
        return old_disk_path, new_disk_path
757
758
    def finish(self):
4354.6.1 by Martitza Mendez
Fix 363837 : catch OSError from osutils.rmtree and mutter to trace file.
759
        try:
760
            osutils.rmtree(self._root)
761
        except OSError, e:
762
            if e.errno != errno.ENOENT:
4399.1.1 by Ian Clatworthy
(igc) address temp file issue with diff --using on Windows (Martitza Mendez)
763
                mutter("The temporary directory \"%s\" was not "
764
                        "cleanly removed: %s." % (self._root, e))
3123.6.2 by Aaron Bentley
Implement diff --using natively
765
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)
3287.18.2 by Matt McClure
Reverts to 3290.
770
        self._execute(osutils.pathjoin('old', old_path),
4603.1.9 by Aaron Bentley
Misc cleanup.
771
                      osutils.pathjoin('new', new_path))
4603.1.1 by Aaron Bentley
Initial pass at shelve-via-editor.
772
4603.1.4 by Aaron Bentley
Implement DiffFromTool.edit_file
773
    def edit_file(self, file_id):
774
        """Use this tool to edit a file.
775
776
        A temporary copy will be edited, and the new contents will be
777
        returned.
778
779
        :param file_id: The id of the file to edit.
780
        :return: The new contents of the file.
781
        """
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,
786
                                           force_temp=True)[1]
4603.3.1 by Benoît Pierre
Fix edit_diff when using a console command.
787
        command = self._get_command(osutils.pathjoin('old', old_path),
788
                                    osutils.pathjoin('new', new_path))
4603.1.24 by Aaron Bentley
Fix call import/invocation.
789
        subprocess.call(command, cwd=self._root)
4603.1.4 by Aaron Bentley
Implement DiffFromTool.edit_file
790
        new_file = open(new_abs_path, 'r')
791
        try:
792
            return new_file.read()
793
        finally:
794
            new_file.close()
795
3123.6.2 by Aaron Bentley
Implement diff --using natively
796
3009.2.22 by Aaron Bentley
Update names & docstring
797
class DiffTree(object):
798
    """Provides textual representations of the difference between two trees.
799
800
    A DiffTree examines two trees and where a file-id has altered
801
    between them, generates a textual representation of the difference.
802
    DiffTree uses a sequence of DiffPath objects which are each
803
    given the opportunity to handle a given altered fileid. The list
804
    of DiffPath objects can be extended globally by appending to
805
    DiffTree.diff_factories, or for a specific diff operation by
3009.2.27 by Aaron Bentley
Use extra_factories instead of extra_diffs
806
    supplying the extra_factories option to the appropriate method.
3009.2.22 by Aaron Bentley
Update names & docstring
807
    """
808
809
    # list of factories that can provide instances of DiffPath objects
3009.2.17 by Aaron Bentley
Update docs
810
    # may be extended by plugins.
3009.2.28 by Aaron Bentley
Add from_diff_tree factories
811
    diff_factories = [DiffSymlink.from_diff_tree,
812
                      DiffDirectory.from_diff_tree]
3009.2.13 by Aaron Bentley
Refactor differ to support registering differ factories
813
3009.2.12 by Aaron Bentley
Associate labels with text diffing only
814
    def __init__(self, old_tree, new_tree, to_file, path_encoding='utf-8',
3009.2.28 by Aaron Bentley
Add from_diff_tree factories
815
                 diff_text=None, extra_factories=None):
3009.2.17 by Aaron Bentley
Update docs
816
        """Constructor
817
818
        :param old_tree: Tree to show as old in the comparison
819
        :param new_tree: Tree to show as new in the comparison
820
        :param to_file: File to write comparision to
821
        :param path_encoding: Character encoding to write paths in
3009.2.28 by Aaron Bentley
Add from_diff_tree factories
822
        :param diff_text: DiffPath-type object to use as a last resort for
3009.2.17 by Aaron Bentley
Update docs
823
            diffing text files.
3009.2.27 by Aaron Bentley
Use extra_factories instead of extra_diffs
824
        :param extra_factories: Factories of DiffPaths to try before any other
825
            DiffPaths"""
3009.2.28 by Aaron Bentley
Add from_diff_tree factories
826
        if diff_text is None:
827
            diff_text = DiffText(old_tree, new_tree, to_file, path_encoding,
828
                                 '', '',  internal_diff)
3009.2.4 by Aaron Bentley
Make old_tree/new_tree construction parameters of Differ
829
        self.old_tree = old_tree
830
        self.new_tree = new_tree
3009.2.2 by Aaron Bentley
Implement Differ object for abstracting diffing
831
        self.to_file = to_file
3009.2.28 by Aaron Bentley
Add from_diff_tree factories
832
        self.path_encoding = path_encoding
3009.2.13 by Aaron Bentley
Refactor differ to support registering differ factories
833
        self.differs = []
3009.2.27 by Aaron Bentley
Use extra_factories instead of extra_diffs
834
        if extra_factories is not None:
3009.2.28 by Aaron Bentley
Add from_diff_tree factories
835
            self.differs.extend(f(self) for f in extra_factories)
836
        self.differs.extend(f(self) for f in self.diff_factories)
837
        self.differs.extend([diff_text, DiffKindChange.from_diff_tree(self)])
3009.2.6 by Aaron Bentley
Convert show_diff_trees into a Differ method
838
839
    @classmethod
840
    def from_trees_options(klass, old_tree, new_tree, to_file,
3009.2.17 by Aaron Bentley
Update docs
841
                           path_encoding, external_diff_options, old_label,
3123.6.2 by Aaron Bentley
Implement diff --using natively
842
                           new_label, using):
3009.2.22 by Aaron Bentley
Update names & docstring
843
        """Factory for producing a DiffTree.
3009.2.17 by Aaron Bentley
Update docs
844
845
        Designed to accept options used by show_diff_trees.
846
        :param old_tree: The tree to show as old in the comparison
847
        :param new_tree: The tree to show as new in the comparison
848
        :param to_file: File to write comparisons to
849
        :param path_encoding: Character encoding to use for writing paths
850
        :param external_diff_options: If supplied, use the installed diff
851
            binary to perform file comparison, using supplied options.
852
        :param old_label: Prefix to use for old file labels
853
        :param new_label: Prefix to use for new file labels
3123.6.2 by Aaron Bentley
Implement diff --using natively
854
        :param using: Commandline to use to invoke an external diff tool
3009.2.17 by Aaron Bentley
Update docs
855
        """
3123.6.2 by Aaron Bentley
Implement diff --using natively
856
        if using is not None:
857
            extra_factories = [DiffFromTool.make_from_diff_tree(using)]
858
        else:
859
            extra_factories = []
3009.2.6 by Aaron Bentley
Convert show_diff_trees into a Differ method
860
        if external_diff_options:
861
            opts = external_diff_options.split()
862
            def diff_file(olab, olines, nlab, nlines, to_file):
863
                external_diff(olab, olines, nlab, nlines, to_file, opts)
864
        else:
865
            diff_file = internal_diff
3009.2.28 by Aaron Bentley
Add from_diff_tree factories
866
        diff_text = DiffText(old_tree, new_tree, to_file, path_encoding,
867
                             old_label, new_label, diff_file)
3123.6.2 by Aaron Bentley
Implement diff --using natively
868
        return klass(old_tree, new_tree, to_file, path_encoding, diff_text,
869
                     extra_factories)
3009.2.6 by Aaron Bentley
Convert show_diff_trees into a Differ method
870
3009.2.12 by Aaron Bentley
Associate labels with text diffing only
871
    def show_diff(self, specific_files, extra_trees=None):
3009.2.17 by Aaron Bentley
Update docs
872
        """Write tree diff to self.to_file
873
874
        :param sepecific_files: the specific files to compare (recursive)
875
        :param extra_trees: extra trees to use for mapping paths to file_ids
876
        """
3123.6.2 by Aaron Bentley
Implement diff --using natively
877
        try:
878
            return self._show_diff(specific_files, extra_trees)
879
        finally:
880
            for differ in self.differs:
881
                differ.finish()
882
883
    def _show_diff(self, specific_files, extra_trees):
3009.2.6 by Aaron Bentley
Convert show_diff_trees into a Differ method
884
        # TODO: Generation of pseudo-diffs for added/deleted files could
885
        # be usefully made into a much faster special case.
3254.1.1 by Aaron Bentley
Make Tree.iter_changes a public method
886
        iterator = self.new_tree.iter_changes(self.old_tree,
3123.4.1 by Aaron Bentley
Diff sorts files in alphabetical order
887
                                               specific_files=specific_files,
888
                                               extra_trees=extra_trees,
889
                                               require_versioned=True)
3009.2.6 by Aaron Bentley
Convert show_diff_trees into a Differ method
890
        has_changes = 0
3123.4.1 by Aaron Bentley
Diff sorts files in alphabetical order
891
        def changes_key(change):
892
            old_path, new_path = change[1]
893
            path = new_path
894
            if path is None:
895
                path = old_path
896
            return path
897
        def get_encoded_path(path):
898
            if path is not None:
899
                return path.encode(self.path_encoding, "replace")
900
        for (file_id, paths, changed_content, versioned, parent, name, kind,
901
             executable) in sorted(iterator, key=changes_key):
3619.4.2 by Robert Collins
Change bzrlib.diff.DiffTree.show_diff to skip entries missing in both trees.
902
            # The root does not get diffed, and items with no known kind (that
903
            # is, missing) in both trees are skipped as well.
904
            if parent == (None, None) or kind == (None, None):
3123.4.3 by Aaron Bentley
Tweak path handling
905
                continue
906
            oldpath, newpath = paths
3123.4.1 by Aaron Bentley
Diff sorts files in alphabetical order
907
            oldpath_encoded = get_encoded_path(paths[0])
908
            newpath_encoded = get_encoded_path(paths[1])
909
            old_present = (kind[0] is not None and versioned[0])
910
            new_present = (kind[1] is not None and versioned[1])
911
            renamed = (parent[0], name[0]) != (parent[1], name[1])
3268.1.1 by C Miller
Describe the property changes in diffs. Currently, this is the executable-bit
912
913
            properties_changed = []
914
            properties_changed.extend(get_executable_change(executable[0], executable[1]))
915
916
            if properties_changed:
917
                prop_str = " (properties changed: %s)" % (", ".join(properties_changed),)
918
            else:
919
                prop_str = ""
920
3123.4.1 by Aaron Bentley
Diff sorts files in alphabetical order
921
            if (old_present, new_present) == (True, False):
922
                self.to_file.write("=== removed %s '%s'\n" %
923
                                   (kind[0], oldpath_encoded))
3123.4.3 by Aaron Bentley
Tweak path handling
924
                newpath = oldpath
3123.4.1 by Aaron Bentley
Diff sorts files in alphabetical order
925
            elif (old_present, new_present) == (False, True):
926
                self.to_file.write("=== added %s '%s'\n" %
927
                                   (kind[1], newpath_encoded))
3123.4.3 by Aaron Bentley
Tweak path handling
928
                oldpath = newpath
3123.4.1 by Aaron Bentley
Diff sorts files in alphabetical order
929
            elif renamed:
930
                self.to_file.write("=== renamed %s '%s' => '%s'%s\n" %
931
                    (kind[0], oldpath_encoded, newpath_encoded, prop_str))
3123.4.2 by Aaron Bentley
Handle diff with property change correctly
932
            else:
3254.1.1 by Aaron Bentley
Make Tree.iter_changes a public method
933
                # if it was produced by iter_changes, it must be
3123.4.2 by Aaron Bentley
Handle diff with property change correctly
934
                # modified *somehow*, either content or execute bit.
3123.4.1 by Aaron Bentley
Diff sorts files in alphabetical order
935
                self.to_file.write("=== modified %s '%s'%s\n" % (kind[0],
936
                                   newpath_encoded, prop_str))
937
            if changed_content:
4377.3.1 by Ian Clatworthy
faster diff on large trees
938
                self._diff(file_id, oldpath, newpath, kind[0], kind[1])
3123.4.1 by Aaron Bentley
Diff sorts files in alphabetical order
939
                has_changes = 1
940
            if renamed:
941
                has_changes = 1
3009.2.6 by Aaron Bentley
Convert show_diff_trees into a Differ method
942
        return has_changes
3009.2.2 by Aaron Bentley
Implement Differ object for abstracting diffing
943
3009.2.12 by Aaron Bentley
Associate labels with text diffing only
944
    def diff(self, file_id, old_path, new_path):
3009.2.17 by Aaron Bentley
Update docs
945
        """Perform a diff of a single file
946
947
        :param file_id: file-id of the file
948
        :param old_path: The path of the file in the old tree
949
        :param new_path: The path of the file in the new tree
950
        """
3009.2.2 by Aaron Bentley
Implement Differ object for abstracting diffing
951
        try:
3009.2.8 by Aaron Bentley
Support diffing without indirecting through inventory entries
952
            old_kind = self.old_tree.kind(file_id)
3087.1.1 by Aaron Bentley
Diff handles missing files correctly, with no tracebacks
953
        except (errors.NoSuchId, errors.NoSuchFile):
3009.2.8 by Aaron Bentley
Support diffing without indirecting through inventory entries
954
            old_kind = None
3009.2.3 by Aaron Bentley
Detect missing files from inv operation
955
        try:
3009.2.8 by Aaron Bentley
Support diffing without indirecting through inventory entries
956
            new_kind = self.new_tree.kind(file_id)
3087.1.1 by Aaron Bentley
Diff handles missing files correctly, with no tracebacks
957
        except (errors.NoSuchId, errors.NoSuchFile):
3009.2.8 by Aaron Bentley
Support diffing without indirecting through inventory entries
958
            new_kind = None
4377.3.1 by Ian Clatworthy
faster diff on large trees
959
        self._diff(file_id, old_path, new_path, old_kind, new_kind)
960
961
962
    def _diff(self, file_id, old_path, new_path, old_kind, new_kind):
3009.2.22 by Aaron Bentley
Update names & docstring
963
        result = DiffPath._diff_many(self.differs, file_id, old_path,
3009.2.11 by Aaron Bentley
Refactor diff to be more pluggable
964
                                       new_path, old_kind, new_kind)
3009.2.22 by Aaron Bentley
Update names & docstring
965
        if result is DiffPath.CANNOT_DIFF:
3009.2.11 by Aaron Bentley
Refactor diff to be more pluggable
966
            error_path = new_path
967
            if error_path is None:
968
                error_path = old_path
3009.2.22 by Aaron Bentley
Update names & docstring
969
            raise errors.NoDiffFound(error_path)