/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/diff.py

  • Committer: Canonical.com Patch Queue Manager
  • Date: 2009-11-18 06:18:14 UTC
  • mfrom: (4634.97.5 doc-2.0)
  • Revision ID: pqm@pqm.ubuntu.com-20091118061814-695imx80olc79o7l
(mbp, trivial) additional doc building fix

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
#! /usr/bin/env python
2
 
# -*- coding: UTF-8 -*-
3
 
 
 
1
# Copyright (C) 2004, 2005, 2006 Canonical Ltd.
 
2
#
4
3
# This program is free software; you can redistribute it and/or modify
5
4
# it under the terms of the GNU General Public License as published by
6
5
# the Free Software Foundation; either version 2 of the License, or
7
6
# (at your option) any later version.
8
 
 
 
7
#
9
8
# This program is distributed in the hope that it will be useful,
10
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
11
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
11
# GNU General Public License for more details.
13
 
 
 
12
#
14
13
# You should have received a copy of the GNU General Public License
15
14
# along with this program; if not, write to the Free Software
16
 
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
17
 
 
18
 
from bzrlib.trace import mutter
19
 
from bzrlib.errors import BzrError
20
 
from bzrlib.delta import compare_trees
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
16
 
 
17
import difflib
 
18
import os
 
19
import re
 
20
import shutil
 
21
import string
 
22
import sys
 
23
 
 
24
from bzrlib.lazy_import import lazy_import
 
25
lazy_import(globals(), """
 
26
import errno
 
27
import subprocess
 
28
import tempfile
 
29
import time
 
30
 
 
31
from bzrlib import (
 
32
    branch as _mod_branch,
 
33
    bzrdir,
 
34
    commands,
 
35
    errors,
 
36
    osutils,
 
37
    patiencediff,
 
38
    textfile,
 
39
    timestamp,
 
40
    views,
 
41
    )
 
42
""")
 
43
 
 
44
from bzrlib.symbol_versioning import (
 
45
    deprecated_function,
 
46
    )
 
47
from bzrlib.trace import mutter, note, warning
 
48
 
 
49
 
 
50
class AtTemplate(string.Template):
 
51
    """Templating class that uses @ instead of $."""
 
52
 
 
53
    delimiter = '@'
 
54
 
21
55
 
22
56
# TODO: Rather than building a changeset object, we should probably
23
57
# invoke callbacks on an object.  That object can either accumulate a
24
58
# list, write them out directly, etc etc.
25
59
 
26
 
def internal_diff(old_label, oldlines, new_label, newlines, to_file):
27
 
    import difflib
28
 
    
 
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
 
 
70
def internal_diff(old_filename, oldlines, new_filename, newlines, to_file,
 
71
                  allow_binary=False, sequence_matcher=None,
 
72
                  path_encoding='utf8'):
29
73
    # FIXME: difflib is wrong if there is no trailing newline.
30
74
    # The syntax used by patch seems to be "\ No newline at
31
75
    # end of file" following the last diff line from that
42
86
    if not oldlines and not newlines:
43
87
        return
44
88
 
45
 
    ud = difflib.unified_diff(oldlines, newlines,
46
 
                              fromfile=old_label, tofile=new_label)
47
 
 
 
89
    if allow_binary is False:
 
90
        textfile.check_text_lines(oldlines)
 
91
        textfile.check_text_lines(newlines)
 
92
 
 
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)
 
99
 
 
100
    ud = list(ud)
 
101
    if len(ud) == 0: # Identical contents, nothing to do
 
102
        return
48
103
    # work-around for difflib being too smart for its own good
49
104
    # if /dev/null is "1,0", patch won't recognize it as /dev/null
50
105
    if not oldlines:
51
 
        ud = list(ud)
52
106
        ud[2] = ud[2].replace('-1,0', '-0,0')
53
107
    elif not newlines:
54
 
        ud = list(ud)
55
108
        ud[2] = ud[2].replace('+1,0', '+0,0')
56
109
 
57
110
    for line in ud:
58
111
        to_file.write(line)
59
112
        if not line.endswith('\n'):
60
113
            to_file.write("\n\\ No newline at end of file\n")
61
 
    print >>to_file
62
 
 
63
 
 
64
 
 
65
 
 
66
 
def external_diff(old_label, oldlines, new_label, newlines, to_file,
 
114
    to_file.write('\n')
 
115
 
 
116
 
 
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
 
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.
 
125
    """
 
126
    if capture_errors:
 
127
        # construct minimal environment
 
128
        env = {}
 
129
        path = os.environ.get('PATH')
 
130
        if path is not None:
 
131
            env['PATH'] = path
 
132
        env['LANGUAGE'] = 'C'   # on win32 only LANGUAGE has effect
 
133
        env['LANG'] = 'C'
 
134
        env['LC_ALL'] = 'C'
 
135
        stderr = subprocess.PIPE
 
136
    else:
 
137
        env = None
 
138
        stderr = None
 
139
 
 
140
    try:
 
141
        pipe = subprocess.Popen(diffcmd,
 
142
                                stdin=subprocess.PIPE,
 
143
                                stdout=subprocess.PIPE,
 
144
                                stderr=stderr,
 
145
                                env=env)
 
146
    except OSError, e:
 
147
        if e.errno == errno.ENOENT:
 
148
            raise errors.NoDiff(str(e))
 
149
        raise
 
150
 
 
151
    return pipe
 
152
 
 
153
 
 
154
def external_diff(old_filename, oldlines, new_filename, newlines, to_file,
67
155
                  diff_opts):
68
156
    """Display a diff by calling out to the external diff program."""
69
 
    import sys
70
 
    
71
 
    if to_file != sys.stdout:
72
 
        raise NotImplementedError("sorry, can't send external diff other than to stdout yet",
73
 
                                  to_file)
74
 
 
75
157
    # make sure our own output is properly ordered before the diff
76
158
    to_file.flush()
77
159
 
78
 
    from tempfile import NamedTemporaryFile
79
 
    import os
80
 
 
81
 
    oldtmpf = NamedTemporaryFile()
82
 
    newtmpf = NamedTemporaryFile()
 
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')
83
164
 
84
165
    try:
85
166
        # TODO: perhaps a special case for comparing to or from the empty
92
173
        oldtmpf.writelines(oldlines)
93
174
        newtmpf.writelines(newlines)
94
175
 
95
 
        oldtmpf.flush()
96
 
        newtmpf.flush()
 
176
        oldtmpf.close()
 
177
        newtmpf.close()
97
178
 
98
179
        if not diff_opts:
99
180
            diff_opts = []
 
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')
100
186
        diffcmd = ['diff',
101
 
                   '--label', old_label,
102
 
                   oldtmpf.name,
103
 
                   '--label', new_label,
104
 
                   newtmpf.name]
 
187
                   '--label', old_filename,
 
188
                   old_abspath,
 
189
                   '--label', new_filename,
 
190
                   new_abspath,
 
191
                   '--binary',
 
192
                  ]
105
193
 
106
194
        # diff only allows one style to be specified; they don't override.
107
195
        # note that some of these take optargs, and the optargs can be
123
211
            break
124
212
        else:
125
213
            diffcmd.append('-u')
126
 
                  
 
214
 
127
215
        if diff_opts:
128
216
            diffcmd.extend(diff_opts)
129
217
 
130
 
        rc = os.spawnvp(os.P_WAIT, 'diff', diffcmd)
131
 
        
132
 
        if rc != 0 and rc != 1:
 
218
        pipe = _spawn_external_diff(diffcmd, capture_errors=True)
 
219
        out,err = pipe.communicate()
 
220
        rc = pipe.returncode
 
221
 
 
222
        # internal_diff() adds a trailing newline, add one here for consistency
 
223
        out += '\n'
 
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.
 
228
            # 'Binary files' is not a real error, so we suppress that error.
 
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:
 
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,))
 
242
 
 
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)
 
246
            if m is None:
 
247
                raise errors.BzrError('external diff failed with exit code 2;'
 
248
                                      ' command: %r' % (diffcmd,))
 
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):
133
257
            # returns 1 if files differ; that's OK
134
258
            if rc < 0:
135
259
                msg = 'signal %d' % (-rc)
136
260
            else:
137
261
                msg = 'exit code %d' % rc
138
 
                
139
 
            raise BzrError('external diff failed with %s; command: %r' % (rc, diffcmd))
 
262
 
 
263
            raise errors.BzrError('external diff failed with %s; command: %r'
 
264
                                  % (rc, diffcmd))
 
265
 
 
266
 
140
267
    finally:
141
268
        oldtmpf.close()                 # and delete
142
269
        newtmpf.close()
143
 
    
144
 
 
145
 
 
146
 
def show_diff(b, revision, specific_files, external_diff_options=None):
147
 
    """Shortcut for showing the diff to the working tree.
148
 
 
149
 
    b
150
 
        Branch.
151
 
 
152
 
    revision
153
 
        None for each, or otherwise the old revision to compare against.
154
 
    
155
 
    The more general form is show_diff_trees(), where the caller
156
 
    supplies any two trees.
 
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)
 
285
 
 
286
 
 
287
def get_trees_and_branches_to_diff(path_list, revision_specs, old_url, new_url,
 
288
                                   apply_view=True):
 
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.
 
305
    :param apply_view:
 
306
        if True and a view is set, apply the view or check that the paths
 
307
        are within it
 
308
    :returns:
 
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.
157
312
    """
158
 
    import sys
 
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]
 
319
            if old_url is None:
 
320
                old_url = old_revision_spec.get_branch()
 
321
        if len(revision_specs) > 1:
 
322
            new_revision_spec = revision_specs[1]
 
323
            if new_url is None:
 
324
                new_url = new_revision_spec.get_branch()
159
325
 
160
 
    if revision == None:
161
 
        old_tree = b.basis_tree()
 
326
    other_paths = []
 
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
162
336
    else:
163
 
        old_tree = b.revision_tree(b.lookup_revision(revision))
164
 
        
165
 
    new_tree = b.working_tree()
166
 
 
167
 
    show_diff_trees(old_tree, new_tree, sys.stdout, specific_files,
168
 
                    external_diff_options)
169
 
 
 
337
        default_location = path_list[0]
 
338
        other_paths = path_list[1:]
 
339
 
 
340
    # Get the old location
 
341
    specific_files = []
 
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)
 
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)
 
351
    old_branch = branch
 
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)
 
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)
 
365
    new_branch = branch
 
366
 
 
367
    # Get the specific files (all files is None, no files is [])
 
368
    if make_paths_wt_relative and working_tree is not None:
 
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")
 
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()
 
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)
 
384
                note("*** Ignoring files outside view. View is %s" % view_str)
 
385
 
 
386
    # Get extra trees that ought to be searched for file-ids
 
387
    extra_trees = None
 
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
 
391
 
 
392
 
 
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:
 
398
            if tree is not None:
 
399
                return tree.basis_tree()
 
400
            else:
 
401
                return branch.basis_tree()
 
402
        else:
 
403
            return tree
 
404
    return spec.as_tree(branch)
170
405
 
171
406
 
172
407
def show_diff_trees(old_tree, new_tree, to_file, specific_files=None,
173
 
                    external_diff_options=None):
 
408
                    external_diff_options=None,
 
409
                    old_label='a/', new_label='b/',
 
410
                    extra_trees=None,
 
411
                    path_encoding='utf8',
 
412
                    using=None):
174
413
    """Show in text form the changes from one tree to another.
175
414
 
176
 
    to_files
177
 
        If set, include only changes to these files.
 
415
    to_file
 
416
        The output stream.
 
417
 
 
418
    specific_files
 
419
        Include only changes to these files - None for all changes.
178
420
 
179
421
    external_diff_options
180
422
        If set, use an external GNU diff and pass these options.
 
423
 
 
424
    extra_trees
 
425
        If set, more Trees to use for looking up file ids
 
426
 
 
427
    path_encoding
 
428
        If set, the path will be encoded as specified, otherwise is supposed
 
429
        to be utf8
181
430
    """
182
 
 
183
 
    # TODO: Options to control putting on a prefix or suffix, perhaps as a format string
184
 
    old_label = ''
185
 
    new_label = ''
186
 
 
187
 
    DEVNULL = '/dev/null'
188
 
    # Windows users, don't panic about this filename -- it is a
189
 
    # special signal to GNU patch that the file should be created or
190
 
    # deleted respectively.
191
 
 
192
 
    # TODO: Generation of pseudo-diffs for added/deleted files could
193
 
    # be usefully made into a much faster special case.
194
 
 
195
 
    if external_diff_options:
196
 
        assert isinstance(external_diff_options, basestring)
197
 
        opts = external_diff_options.split()
198
 
        def diff_file(olab, olines, nlab, nlines, to_file):
199
 
            external_diff(olab, olines, nlab, nlines, to_file, opts)
 
431
    old_tree.lock_read()
 
432
    try:
 
433
        if extra_trees is not None:
 
434
            for tree in extra_trees:
 
435
                tree.lock_read()
 
436
        new_tree.lock_read()
 
437
        try:
 
438
            differ = DiffTree.from_trees_options(old_tree, new_tree, to_file,
 
439
                                                 path_encoding,
 
440
                                                 external_diff_options,
 
441
                                                 old_label, new_label, using)
 
442
            return differ.show_diff(specific_files, extra_trees)
 
443
        finally:
 
444
            new_tree.unlock()
 
445
            if extra_trees is not None:
 
446
                for tree in extra_trees:
 
447
                    tree.unlock()
 
448
    finally:
 
449
        old_tree.unlock()
 
450
 
 
451
 
 
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)
 
456
 
 
457
 
 
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],)]
200
462
    else:
201
 
        diff_file = internal_diff
202
 
    
203
 
 
204
 
    delta = compare_trees(old_tree, new_tree, want_unchanged=False,
205
 
                          specific_files=specific_files)
206
 
 
207
 
    for path, file_id, kind in delta.removed:
208
 
        print >>to_file, '*** removed %s %r' % (kind, path)
209
 
        if kind == 'file':
210
 
            diff_file(old_label + path,
211
 
                      old_tree.get_file(file_id).readlines(),
212
 
                      DEVNULL, 
213
 
                      [],
214
 
                      to_file)
215
 
 
216
 
    for path, file_id, kind in delta.added:
217
 
        print >>to_file, '*** added %s %r' % (kind, path)
218
 
        if kind == 'file':
219
 
            diff_file(DEVNULL,
220
 
                      [],
221
 
                      new_label + path,
222
 
                      new_tree.get_file(file_id).readlines(),
223
 
                      to_file)
224
 
 
225
 
    for old_path, new_path, file_id, kind, text_modified in delta.renamed:
226
 
        print >>to_file, '*** renamed %s %r => %r' % (kind, old_path, new_path)
227
 
        if text_modified:
228
 
            diff_file(old_label + old_path,
229
 
                      old_tree.get_file(file_id).readlines(),
230
 
                      new_label + new_path,
231
 
                      new_tree.get_file(file_id).readlines(),
232
 
                      to_file)
233
 
 
234
 
    for path, file_id, kind in delta.modified:
235
 
        print >>to_file, '*** modified %s %r' % (kind, path)
236
 
        if kind == 'file':
237
 
            diff_file(old_label + path,
238
 
                      old_tree.get_file(file_id).readlines(),
239
 
                      new_label + path,
240
 
                      new_tree.get_file(file_id).readlines(),
241
 
                      to_file)
242
 
 
243
 
 
244
 
 
245
 
 
246
 
 
 
463
        return []
 
464
 
 
465
 
 
466
class DiffPath(object):
 
467
    """Base type for command object that compare files"""
 
468
 
 
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
 
472
    CHANGED = 'CHANGED'
 
473
    # The file content may have changed, but there is no semantic change
 
474
    UNCHANGED = 'UNCHANGED'
 
475
 
 
476
    def __init__(self, old_tree, new_tree, to_file, path_encoding='utf-8'):
 
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
        """
 
484
        self.old_tree = old_tree
 
485
        self.new_tree = new_tree
 
486
        self.to_file = to_file
 
487
        self.path_encoding = path_encoding
 
488
 
 
489
    def finish(self):
 
490
        pass
 
491
 
 
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
 
 
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)
 
502
            if result is not DiffPath.CANNOT_DIFF:
 
503
                return result
 
504
        else:
 
505
            return DiffPath.CANNOT_DIFF
 
506
 
 
507
 
 
508
class DiffKindChange(object):
 
509
    """Special differ for file kind changes.
 
510
 
 
511
    Represents kind change as deletion + creation.  Uses the other differs
 
512
    to do this.
 
513
    """
 
514
    def __init__(self, differs):
 
515
        self.differs = differs
 
516
 
 
517
    def finish(self):
 
518
        pass
 
519
 
 
520
    @classmethod
 
521
    def from_diff_tree(klass, diff_tree):
 
522
        return klass(diff_tree.differs)
 
523
 
 
524
    def diff(self, file_id, old_path, new_path, old_kind, new_kind):
 
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
        """
 
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:
 
538
            return result
 
539
        return DiffPath._diff_many(self.differs, file_id, old_path, new_path,
 
540
                                     None, new_kind)
 
541
 
 
542
 
 
543
class DiffDirectory(DiffPath):
 
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
 
 
557
 
 
558
class DiffSymlink(DiffPath):
 
559
 
 
560
    def diff(self, file_id, old_path, new_path, old_kind, new_kind):
 
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
        """
 
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:
 
574
            old_target = None
 
575
        else:
 
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:
 
580
            new_target = None
 
581
        else:
 
582
            return self.CANNOT_DIFF
 
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))
 
593
        return self.CHANGED
 
594
 
 
595
 
 
596
class DiffText(DiffPath):
 
597
 
 
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
 
 
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
 
609
 
 
610
    def diff(self, file_id, old_path, new_path, old_kind, new_kind):
 
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
        """
 
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
 
626
            from_file_id = None
 
627
        else:
 
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
 
633
            to_file_id = None
 
634
        else:
 
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,
 
639
            old_path, new_path)
 
640
 
 
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
 
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.
 
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.
 
652
        """
 
653
        def _get_text(tree, file_id, path):
 
654
            if file_id is not None:
 
655
                return tree.get_file(file_id, path).readlines()
 
656
            else:
 
657
                return []
 
658
        try:
 
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,
 
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))
 
667
        return self.CHANGED
 
668
 
 
669
 
 
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
 
676
        self._root = osutils.mkdtemp(prefix='bzr-diff-')
 
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)
 
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,
 
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}
 
696
        return [AtTemplate(t).substitute(my_map) for t in
 
697
                self.command_template]
 
698
 
 
699
    def _execute(self, old_path, new_path):
 
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])
 
707
            else:
 
708
                raise
 
709
        self.to_file.write(proc.stdout.read())
 
710
        return proc.wait()
 
711
 
 
712
    def _try_symlink_root(self, tree, prefix):
 
713
        if (getattr(tree, 'abspath', None) is None
 
714
            or not osutils.host_os_dereferences_symlinks()):
 
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
 
 
723
    def _write_file(self, file_id, tree, prefix, relpath, force_temp=False,
 
724
                    allow_write=False):
 
725
        full_path = osutils.pathjoin(self._root, prefix, relpath)
 
726
        if not force_temp and self._try_symlink_root(tree, prefix):
 
727
            return full_path
 
728
        parent_dir = osutils.dirname(full_path)
 
729
        try:
 
730
            os.makedirs(parent_dir)
 
731
        except OSError, e:
 
732
            if e.errno != errno.EEXIST:
 
733
                raise
 
734
        source = tree.get_file(file_id, relpath)
 
735
        try:
 
736
            target = open(full_path, 'wb')
 
737
            try:
 
738
                osutils.pumpfile(source, target)
 
739
            finally:
 
740
                target.close()
 
741
        finally:
 
742
            source.close()
 
743
        if not allow_write:
 
744
            osutils.make_readonly(full_path)
 
745
        mtime = tree.get_file_mtime(file_id)
 
746
        os.utime(full_path, (mtime, mtime))
 
747
        return full_path
 
748
 
 
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
 
757
 
 
758
    def finish(self):
 
759
        try:
 
760
            osutils.rmtree(self._root)
 
761
        except OSError, e:
 
762
            if e.errno != errno.ENOENT:
 
763
                mutter("The temporary directory \"%s\" was not "
 
764
                        "cleanly removed: %s." % (self._root, e))
 
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)
 
770
        self._execute(osutils.pathjoin('old', old_path),
 
771
                      osutils.pathjoin('new', new_path))
 
772
 
 
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]
 
787
        command = self._get_command(osutils.pathjoin('old', old_path),
 
788
                                    osutils.pathjoin('new', new_path))
 
789
        subprocess.call(command, cwd=self._root)
 
790
        new_file = open(new_abs_path, 'r')
 
791
        try:
 
792
            return new_file.read()
 
793
        finally:
 
794
            new_file.close()
 
795
 
 
796
 
 
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
 
806
    supplying the extra_factories option to the appropriate method.
 
807
    """
 
808
 
 
809
    # list of factories that can provide instances of DiffPath objects
 
810
    # may be extended by plugins.
 
811
    diff_factories = [DiffSymlink.from_diff_tree,
 
812
                      DiffDirectory.from_diff_tree]
 
813
 
 
814
    def __init__(self, old_tree, new_tree, to_file, path_encoding='utf-8',
 
815
                 diff_text=None, extra_factories=None):
 
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
 
822
        :param diff_text: DiffPath-type object to use as a last resort for
 
823
            diffing text files.
 
824
        :param extra_factories: Factories of DiffPaths to try before any other
 
825
            DiffPaths"""
 
826
        if diff_text is None:
 
827
            diff_text = DiffText(old_tree, new_tree, to_file, path_encoding,
 
828
                                 '', '',  internal_diff)
 
829
        self.old_tree = old_tree
 
830
        self.new_tree = new_tree
 
831
        self.to_file = to_file
 
832
        self.path_encoding = path_encoding
 
833
        self.differs = []
 
834
        if extra_factories is not None:
 
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)])
 
838
 
 
839
    @classmethod
 
840
    def from_trees_options(klass, old_tree, new_tree, to_file,
 
841
                           path_encoding, external_diff_options, old_label,
 
842
                           new_label, using):
 
843
        """Factory for producing a DiffTree.
 
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
 
854
        :param using: Commandline to use to invoke an external diff tool
 
855
        """
 
856
        if using is not None:
 
857
            extra_factories = [DiffFromTool.make_from_diff_tree(using)]
 
858
        else:
 
859
            extra_factories = []
 
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
 
866
        diff_text = DiffText(old_tree, new_tree, to_file, path_encoding,
 
867
                             old_label, new_label, diff_file)
 
868
        return klass(old_tree, new_tree, to_file, path_encoding, diff_text,
 
869
                     extra_factories)
 
870
 
 
871
    def show_diff(self, specific_files, extra_trees=None):
 
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
        """
 
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):
 
884
        # TODO: Generation of pseudo-diffs for added/deleted files could
 
885
        # be usefully made into a much faster special case.
 
886
        iterator = self.new_tree.iter_changes(self.old_tree,
 
887
                                               specific_files=specific_files,
 
888
                                               extra_trees=extra_trees,
 
889
                                               require_versioned=True)
 
890
        has_changes = 0
 
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):
 
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):
 
905
                continue
 
906
            oldpath, newpath = paths
 
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])
 
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
 
 
921
            if (old_present, new_present) == (True, False):
 
922
                self.to_file.write("=== removed %s '%s'\n" %
 
923
                                   (kind[0], oldpath_encoded))
 
924
                newpath = oldpath
 
925
            elif (old_present, new_present) == (False, True):
 
926
                self.to_file.write("=== added %s '%s'\n" %
 
927
                                   (kind[1], newpath_encoded))
 
928
                oldpath = newpath
 
929
            elif renamed:
 
930
                self.to_file.write("=== renamed %s '%s' => '%s'%s\n" %
 
931
                    (kind[0], oldpath_encoded, newpath_encoded, prop_str))
 
932
            else:
 
933
                # if it was produced by iter_changes, it must be
 
934
                # modified *somehow*, either content or execute bit.
 
935
                self.to_file.write("=== modified %s '%s'%s\n" % (kind[0],
 
936
                                   newpath_encoded, prop_str))
 
937
            if changed_content:
 
938
                self._diff(file_id, oldpath, newpath, kind[0], kind[1])
 
939
                has_changes = 1
 
940
            if renamed:
 
941
                has_changes = 1
 
942
        return has_changes
 
943
 
 
944
    def diff(self, file_id, old_path, new_path):
 
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
        """
 
951
        try:
 
952
            old_kind = self.old_tree.kind(file_id)
 
953
        except (errors.NoSuchId, errors.NoSuchFile):
 
954
            old_kind = None
 
955
        try:
 
956
            new_kind = self.new_tree.kind(file_id)
 
957
        except (errors.NoSuchId, errors.NoSuchFile):
 
958
            new_kind = None
 
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):
 
963
        result = DiffPath._diff_many(self.differs, file_id, old_path,
 
964
                                       new_path, old_kind, new_kind)
 
965
        if result is DiffPath.CANNOT_DIFF:
 
966
            error_path = new_path
 
967
            if error_path is None:
 
968
                error_path = old_path
 
969
            raise errors.NoDiffFound(error_path)