/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: John Arbash Meinel
  • Date: 2009-12-02 23:09:40 UTC
  • mfrom: (4853.1.1 whitespace)
  • mto: This revision was merged to the branch mainline in revision 4856.
  • Revision ID: john@arbash-meinel.com-20091202230940-7n2aydoxngdqxzld
Strip trailing whitespace from doc files by Patrick Regan.

Resolve one small conflict with another doc edit.
Also, revert the changes to all the .pdf and .png files. We shouldn't
be touching them as they are pure-binary files.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2004, 2005, 2006 Canonical Ltd.
 
2
#
 
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.
 
7
#
 
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.
 
12
#
 
13
# You should have received a copy of the GNU General Public License
 
14
# along with this program; if not, write to the Free Software
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
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
 
 
55
 
 
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
 
 
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'):
 
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
 
88
 
 
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
 
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
 
 
110
    for line in ud:
 
111
        to_file.write(line)
 
112
        if not line.endswith('\n'):
 
113
            to_file.write("\n\\ No newline at end of file\n")
 
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,
 
155
                  diff_opts):
 
156
    """Display a diff by calling out to the external diff program."""
 
157
    # make sure our own output is properly ordered before the diff
 
158
    to_file.flush()
 
159
 
 
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')
 
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
 
 
176
        oldtmpf.close()
 
177
        newtmpf.close()
 
178
 
 
179
        if not diff_opts:
 
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')
 
186
        diffcmd = ['diff',
 
187
                   '--label', old_filename,
 
188
                   old_abspath,
 
189
                   '--label', new_filename,
 
190
                   new_abspath,
 
191
                   '--binary',
 
192
                  ]
 
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')
 
214
 
 
215
        if diff_opts:
 
216
            diffcmd.extend(diff_opts)
 
217
 
 
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):
 
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
 
262
 
 
263
            raise errors.BzrError('external diff failed with %s; command: %r'
 
264
                                  % (rc, diffcmd))
 
265
 
 
266
 
 
267
    finally:
 
268
        oldtmpf.close()                 # and delete
 
269
        newtmpf.close()
 
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.
 
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]
 
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()
 
325
 
 
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
 
336
    else:
 
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)
 
405
 
 
406
 
 
407
def show_diff_trees(old_tree, new_tree, to_file, specific_files=None,
 
408
                    external_diff_options=None,
 
409
                    old_label='a/', new_label='b/',
 
410
                    extra_trees=None,
 
411
                    path_encoding='utf8',
 
412
                    using=None):
 
413
    """Show in text form the changes from one tree to another.
 
414
 
 
415
    to_file
 
416
        The output stream.
 
417
 
 
418
    specific_files
 
419
        Include only changes to these files - None for all changes.
 
420
 
 
421
    external_diff_options
 
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
 
430
    """
 
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],)]
 
462
    else:
 
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)