~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/diff.py

  • Committer: Canonical.com Patch Queue Manager
  • Date: 2008-03-16 16:58:03 UTC
  • mfrom: (3224.3.1 news-typo)
  • Revision ID: pqm@pqm.ubuntu.com-20080316165803-tisoc9mpob9z544o
(Matt Nordhoff) Trivial NEWS typo fix

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2011 Canonical Ltd.
 
1
# Copyright (C) 2004, 2005, 2006 Canonical Ltd.
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
12
12
#
13
13
# You should have received a copy of the GNU General Public License
14
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
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
16
 
17
17
import difflib
18
18
import os
19
19
import re
20
 
import string
 
20
import shutil
21
21
import sys
22
22
 
23
23
from bzrlib.lazy_import import lazy_import
25
25
import errno
26
26
import subprocess
27
27
import tempfile
 
28
import time
28
29
 
29
30
from bzrlib import (
30
 
    cleanup,
31
 
    cmdline,
32
 
    controldir,
 
31
    bzrdir,
 
32
    commands,
33
33
    errors,
34
34
    osutils,
35
35
    patiencediff,
36
36
    textfile,
37
37
    timestamp,
38
 
    views,
39
38
    )
40
 
 
41
 
from bzrlib.workingtree import WorkingTree
42
 
from bzrlib.i18n import gettext
43
39
""")
44
40
 
45
 
from bzrlib.registry import (
46
 
    Registry,
47
 
    )
48
 
from bzrlib.trace import mutter, note, warning
49
 
 
50
 
 
51
 
class AtTemplate(string.Template):
52
 
    """Templating class that uses @ instead of $."""
53
 
 
54
 
    delimiter = '@'
 
41
from bzrlib.symbol_versioning import (
 
42
        deprecated_function,
 
43
        one_zero,
 
44
        )
 
45
from bzrlib.trace import mutter, warning
55
46
 
56
47
 
57
48
# TODO: Rather than building a changeset object, we should probably
86
77
    # both sequences are empty.
87
78
    if not oldlines and not newlines:
88
79
        return
89
 
 
 
80
    
90
81
    if allow_binary is False:
91
82
        textfile.check_text_lines(oldlines)
92
83
        textfile.check_text_lines(newlines)
94
85
    if sequence_matcher is None:
95
86
        sequence_matcher = patiencediff.PatienceSequenceMatcher
96
87
    ud = patiencediff.unified_diff(oldlines, newlines,
97
 
                      fromfile=old_filename.encode(path_encoding, 'replace'),
98
 
                      tofile=new_filename.encode(path_encoding, 'replace'),
 
88
                      fromfile=old_filename.encode(path_encoding),
 
89
                      tofile=new_filename.encode(path_encoding),
99
90
                      sequencematcher=sequence_matcher)
100
91
 
101
92
    ud = list(ud)
107
98
        ud[2] = ud[2].replace('-1,0', '-0,0')
108
99
    elif not newlines:
109
100
        ud[2] = ud[2].replace('+1,0', '+0,0')
 
101
    # work around for difflib emitting random spaces after the label
 
102
    ud[0] = ud[0][:-2] + '\n'
 
103
    ud[1] = ud[1][:-2] + '\n'
110
104
 
111
105
    for line in ud:
112
106
        to_file.write(line)
179
173
 
180
174
        if not diff_opts:
181
175
            diff_opts = []
182
 
        if sys.platform == 'win32':
183
 
            # Popen doesn't do the proper encoding for external commands
184
 
            # Since we are dealing with an ANSI api, use mbcs encoding
185
 
            old_filename = old_filename.encode('mbcs')
186
 
            new_filename = new_filename.encode('mbcs')
187
176
        diffcmd = ['diff',
188
177
                   '--label', old_filename,
189
178
                   old_abspath,
212
201
            break
213
202
        else:
214
203
            diffcmd.append('-u')
215
 
 
 
204
                  
216
205
        if diff_opts:
217
206
            diffcmd.extend(diff_opts)
218
207
 
219
208
        pipe = _spawn_external_diff(diffcmd, capture_errors=True)
220
209
        out,err = pipe.communicate()
221
210
        rc = pipe.returncode
222
 
 
 
211
        
223
212
        # internal_diff() adds a trailing newline, add one here for consistency
224
213
        out += '\n'
225
214
        if rc == 2:
260
249
                msg = 'signal %d' % (-rc)
261
250
            else:
262
251
                msg = 'exit code %d' % rc
263
 
 
264
 
            raise errors.BzrError('external diff failed with %s; command: %r'
 
252
                
 
253
            raise errors.BzrError('external diff failed with %s; command: %r' 
265
254
                                  % (rc, diffcmd))
266
255
 
267
256
 
285
274
                        new_abspath, e)
286
275
 
287
276
 
288
 
def get_trees_and_branches_to_diff_locked(
289
 
    path_list, revision_specs, old_url, new_url, add_cleanup, apply_view=True):
 
277
@deprecated_function(one_zero)
 
278
def diff_cmd_helper(tree, specific_files, external_diff_options, 
 
279
                    old_revision_spec=None, new_revision_spec=None,
 
280
                    revision_specs=None,
 
281
                    old_label='a/', new_label='b/'):
 
282
    """Helper for cmd_diff.
 
283
 
 
284
    :param tree:
 
285
        A WorkingTree
 
286
 
 
287
    :param specific_files:
 
288
        The specific files to compare, or None
 
289
 
 
290
    :param external_diff_options:
 
291
        If non-None, run an external diff, and pass it these options
 
292
 
 
293
    :param old_revision_spec:
 
294
        If None, use basis tree as old revision, otherwise use the tree for
 
295
        the specified revision. 
 
296
 
 
297
    :param new_revision_spec:
 
298
        If None, use working tree as new revision, otherwise use the tree for
 
299
        the specified revision.
 
300
    
 
301
    :param revision_specs: 
 
302
        Zero, one or two RevisionSpecs from the command line, saying what revisions 
 
303
        to compare.  This can be passed as an alternative to the old_revision_spec 
 
304
        and new_revision_spec parameters.
 
305
 
 
306
    The more general form is show_diff_trees(), where the caller
 
307
    supplies any two trees.
 
308
    """
 
309
 
 
310
    # TODO: perhaps remove the old parameters old_revision_spec and
 
311
    # new_revision_spec, since this is only really for use from cmd_diff and
 
312
    # it now always passes through a sequence of revision_specs -- mbp
 
313
    # 20061221
 
314
 
 
315
    def spec_tree(spec):
 
316
        if tree:
 
317
            revision = spec.in_store(tree.branch)
 
318
        else:
 
319
            revision = spec.in_store(None)
 
320
        revision_id = revision.rev_id
 
321
        branch = revision.branch
 
322
        return branch.repository.revision_tree(revision_id)
 
323
 
 
324
    if revision_specs is not None:
 
325
        assert (old_revision_spec is None
 
326
                and new_revision_spec is None)
 
327
        if len(revision_specs) > 0:
 
328
            old_revision_spec = revision_specs[0]
 
329
        if len(revision_specs) > 1:
 
330
            new_revision_spec = revision_specs[1]
 
331
 
 
332
    if old_revision_spec is None:
 
333
        old_tree = tree.basis_tree()
 
334
    else:
 
335
        old_tree = spec_tree(old_revision_spec)
 
336
 
 
337
    if (new_revision_spec is None
 
338
        or new_revision_spec.spec is None):
 
339
        new_tree = tree
 
340
    else:
 
341
        new_tree = spec_tree(new_revision_spec)
 
342
 
 
343
    if new_tree is not tree:
 
344
        extra_trees = (tree,)
 
345
    else:
 
346
        extra_trees = None
 
347
 
 
348
    return show_diff_trees(old_tree, new_tree, sys.stdout, specific_files,
 
349
                           external_diff_options,
 
350
                           old_label=old_label, new_label=new_label,
 
351
                           extra_trees=extra_trees)
 
352
 
 
353
 
 
354
def _get_trees_to_diff(path_list, revision_specs, old_url, new_url):
290
355
    """Get the trees and specific files to diff given a list of paths.
291
356
 
292
357
    This method works out the trees to be diff'ed and the files of
303
368
    :param new_url:
304
369
        The url of the new branch or tree. If None, the tree to use is
305
370
        taken from the first path, if any, or the current working tree.
306
 
    :param add_cleanup:
307
 
        a callable like Command.add_cleanup.  get_trees_and_branches_to_diff
308
 
        will register cleanups that must be run to unlock the trees, etc.
309
 
    :param apply_view:
310
 
        if True and a view is set, apply the view or check that the paths
311
 
        are within it
312
371
    :returns:
313
 
        a tuple of (old_tree, new_tree, old_branch, new_branch,
314
 
        specific_files, extra_trees) where extra_trees is a sequence of
315
 
        additional trees to search in for file-ids.  The trees and branches
316
 
        will be read-locked until the cleanups registered via the add_cleanup
317
 
        param are run.
 
372
        a tuple of (old_tree, new_tree, specific_files, extra_trees) where
 
373
        extra_trees is a sequence of additional trees to search in for
 
374
        file-ids.
318
375
    """
319
376
    # Get the old and new revision specs
320
377
    old_revision_spec = None
343
400
        default_location = path_list[0]
344
401
        other_paths = path_list[1:]
345
402
 
346
 
    def lock_tree_or_branch(wt, br):
347
 
        if wt is not None:
348
 
            wt.lock_read()
349
 
            add_cleanup(wt.unlock)
350
 
        elif br is not None:
351
 
            br.lock_read()
352
 
            add_cleanup(br.unlock)
353
 
 
354
403
    # Get the old location
355
404
    specific_files = []
356
405
    if old_url is None:
357
406
        old_url = default_location
358
407
    working_tree, branch, relpath = \
359
 
        controldir.ControlDir.open_containing_tree_or_branch(old_url)
360
 
    lock_tree_or_branch(working_tree, branch)
 
408
        bzrdir.BzrDir.open_containing_tree_or_branch(old_url)
361
409
    if consider_relpath and relpath != '':
362
 
        if working_tree is not None and apply_view:
363
 
            views.check_path_in_view(working_tree, relpath)
364
410
        specific_files.append(relpath)
365
411
    old_tree = _get_tree_to_diff(old_revision_spec, working_tree, branch)
366
 
    old_branch = branch
367
412
 
368
413
    # Get the new location
369
414
    if new_url is None:
370
415
        new_url = default_location
371
416
    if new_url != old_url:
372
417
        working_tree, branch, relpath = \
373
 
            controldir.ControlDir.open_containing_tree_or_branch(new_url)
374
 
        lock_tree_or_branch(working_tree, branch)
 
418
            bzrdir.BzrDir.open_containing_tree_or_branch(new_url)
375
419
        if consider_relpath and relpath != '':
376
 
            if working_tree is not None and apply_view:
377
 
                views.check_path_in_view(working_tree, relpath)
378
420
            specific_files.append(relpath)
379
421
    new_tree = _get_tree_to_diff(new_revision_spec, working_tree, branch,
380
422
        basis_is_default=working_tree is None)
381
 
    new_branch = branch
382
423
 
383
424
    # Get the specific files (all files is None, no files is [])
384
425
    if make_paths_wt_relative and working_tree is not None:
385
 
        other_paths = working_tree.safe_relpath_files(
386
 
            other_paths,
387
 
            apply_view=apply_view)
 
426
        other_paths = _relative_paths_in_tree(working_tree, other_paths)
388
427
    specific_files.extend(other_paths)
389
428
    if len(specific_files) == 0:
390
429
        specific_files = None
391
 
        if (working_tree is not None and working_tree.supports_views()
392
 
            and apply_view):
393
 
            view_files = working_tree.views.lookup_view()
394
 
            if view_files:
395
 
                specific_files = view_files
396
 
                view_str = views.view_display_str(view_files)
397
 
                note(gettext("*** Ignoring files outside view. View is %s") % view_str)
398
430
 
399
431
    # Get extra trees that ought to be searched for file-ids
400
432
    extra_trees = None
401
433
    if working_tree is not None and working_tree not in (old_tree, new_tree):
402
434
        extra_trees = (working_tree,)
403
 
    return (old_tree, new_tree, old_branch, new_branch,
404
 
            specific_files, extra_trees)
 
435
    return old_tree, new_tree, specific_files, extra_trees
405
436
 
406
437
 
407
438
def _get_tree_to_diff(spec, tree=None, branch=None, basis_is_default=True):
415
446
                return branch.basis_tree()
416
447
        else:
417
448
            return tree
418
 
    return spec.as_tree(branch)
 
449
    revision = spec.in_store(branch)
 
450
    revision_id = revision.rev_id
 
451
    rev_branch = revision.branch
 
452
    return rev_branch.repository.revision_tree(revision_id)
 
453
 
 
454
 
 
455
def _relative_paths_in_tree(tree, paths):
 
456
    """Get the relative paths within a working tree.
 
457
 
 
458
    Each path may be either an absolute path or a path relative to the
 
459
    current working directory.
 
460
    """
 
461
    result = []
 
462
    for filename in paths:
 
463
        try:
 
464
            result.append(tree.relpath(osutils.dereference_path(filename)))
 
465
        except errors.PathNotChild:
 
466
            raise errors.BzrCommandError("Files are in different branches")
 
467
    return result
419
468
 
420
469
 
421
470
def show_diff_trees(old_tree, new_tree, to_file, specific_files=None,
423
472
                    old_label='a/', new_label='b/',
424
473
                    extra_trees=None,
425
474
                    path_encoding='utf8',
426
 
                    using=None,
427
 
                    format_cls=None):
 
475
                    using=None):
428
476
    """Show in text form the changes from one tree to another.
429
477
 
430
 
    :param to_file: The output stream.
431
 
    :param specific_files: Include only changes to these files - None for all
432
 
        changes.
433
 
    :param external_diff_options: If set, use an external GNU diff and pass 
434
 
        these options.
435
 
    :param extra_trees: If set, more Trees to use for looking up file ids
436
 
    :param path_encoding: If set, the path will be encoded as specified, 
437
 
        otherwise is supposed to be utf8
438
 
    :param format_cls: Formatter class (DiffTree subclass)
 
478
    to_file
 
479
        The output stream.
 
480
 
 
481
    specific_files
 
482
        Include only changes to these files - None for all changes.
 
483
 
 
484
    external_diff_options
 
485
        If set, use an external GNU diff and pass these options.
 
486
 
 
487
    extra_trees
 
488
        If set, more Trees to use for looking up file ids
 
489
 
 
490
    path_encoding
 
491
        If set, the path will be encoded as specified, otherwise is supposed
 
492
        to be utf8
439
493
    """
440
 
    if format_cls is None:
441
 
        format_cls = DiffTree
442
494
    old_tree.lock_read()
443
495
    try:
444
496
        if extra_trees is not None:
446
498
                tree.lock_read()
447
499
        new_tree.lock_read()
448
500
        try:
449
 
            differ = format_cls.from_trees_options(old_tree, new_tree, to_file,
450
 
                                                   path_encoding,
451
 
                                                   external_diff_options,
452
 
                                                   old_label, new_label, using)
 
501
            differ = DiffTree.from_trees_options(old_tree, new_tree, to_file,
 
502
                                                 path_encoding,
 
503
                                                 external_diff_options,
 
504
                                                 old_label, new_label, using)
453
505
            return differ.show_diff(specific_files, extra_trees)
454
506
        finally:
455
507
            new_tree.unlock()
462
514
 
463
515
def _patch_header_date(tree, file_id, path):
464
516
    """Returns a timestamp suitable for use in a patch header."""
465
 
    try:
466
 
        mtime = tree.get_file_mtime(file_id, path)
467
 
    except errors.FileTimestampUnavailable:
468
 
        mtime = 0
 
517
    mtime = tree.get_file_mtime(file_id, path)
 
518
    assert mtime is not None, \
 
519
        "got an mtime of None for file-id %s, path %s in tree %s" % (
 
520
                file_id, path, tree)
469
521
    return timestamp.format_patch_date(mtime)
470
522
 
471
523
 
472
 
def get_executable_change(old_is_x, new_is_x):
473
 
    descr = { True:"+x", False:"-x", None:"??" }
474
 
    if old_is_x != new_is_x:
475
 
        return ["%s to %s" % (descr[old_is_x], descr[new_is_x],)]
 
524
def _raise_if_nonexistent(paths, old_tree, new_tree):
 
525
    """Complain if paths are not in either inventory or tree.
 
526
 
 
527
    It's OK with the files exist in either tree's inventory, or 
 
528
    if they exist in the tree but are not versioned.
 
529
    
 
530
    This can be used by operations such as bzr status that can accept
 
531
    unknown or ignored files.
 
532
    """
 
533
    mutter("check paths: %r", paths)
 
534
    if not paths:
 
535
        return
 
536
    s = old_tree.filter_unversioned_files(paths)
 
537
    s = new_tree.filter_unversioned_files(s)
 
538
    s = [path for path in s if not new_tree.has_filename(path)]
 
539
    if s:
 
540
        raise errors.PathsDoNotExist(sorted(s))
 
541
 
 
542
 
 
543
def get_prop_change(meta_modified):
 
544
    if meta_modified:
 
545
        return " (properties changed)"
476
546
    else:
477
 
        return []
 
547
        return  ""
478
548
 
479
549
 
480
550
class DiffPath(object):
649
719
            return self.CANNOT_DIFF
650
720
        from_label = '%s%s\t%s' % (self.old_label, old_path, old_date)
651
721
        to_label = '%s%s\t%s' % (self.new_label, new_path, new_date)
652
 
        return self.diff_text(from_file_id, to_file_id, from_label, to_label,
653
 
            old_path, new_path)
 
722
        return self.diff_text(from_file_id, to_file_id, from_label, to_label)
654
723
 
655
 
    def diff_text(self, from_file_id, to_file_id, from_label, to_label,
656
 
        from_path=None, to_path=None):
 
724
    def diff_text(self, from_file_id, to_file_id, from_label, to_label):
657
725
        """Diff the content of given files in two trees
658
726
 
659
727
        :param from_file_id: The id of the file in the from tree.  If None,
661
729
        :param to_file_id: The id of the file in the to tree.  This may refer
662
730
            to a different file from from_file_id.  If None,
663
731
            the file is not present in the to tree.
664
 
        :param from_path: The path in the from tree or None if unknown.
665
 
        :param to_path: The path in the to tree or None if unknown.
666
732
        """
667
 
        def _get_text(tree, file_id, path):
 
733
        def _get_text(tree, file_id):
668
734
            if file_id is not None:
669
 
                return tree.get_file_lines(file_id, path)
 
735
                return tree.get_file(file_id).readlines()
670
736
            else:
671
737
                return []
672
738
        try:
673
 
            from_text = _get_text(self.old_tree, from_file_id, from_path)
674
 
            to_text = _get_text(self.new_tree, to_file_id, to_path)
 
739
            from_text = _get_text(self.old_tree, from_file_id)
 
740
            to_text = _get_text(self.new_tree, to_file_id)
675
741
            self.text_differ(from_label, from_text, to_label, to_text,
676
 
                             self.to_file, path_encoding=self.path_encoding)
 
742
                             self.to_file)
677
743
        except errors.BinaryFile:
678
744
            self.to_file.write(
679
745
                  ("Binary files %s and %s differ\n" %
680
 
                  (from_label, to_label)).encode(self.path_encoding,'replace'))
 
746
                  (from_label, to_label)).encode(self.path_encoding))
681
747
        return self.CHANGED
682
748
 
683
749
 
687
753
                 path_encoding='utf-8'):
688
754
        DiffPath.__init__(self, old_tree, new_tree, to_file, path_encoding)
689
755
        self.command_template = command_template
690
 
        self._root = osutils.mkdtemp(prefix='bzr-diff-')
 
756
        self._root = tempfile.mkdtemp(prefix='bzr-diff-')
691
757
 
692
758
    @classmethod
693
759
    def from_string(klass, command_string, old_tree, new_tree, to_file,
694
760
                    path_encoding='utf-8'):
695
 
        command_template = cmdline.split(command_string)
696
 
        if '@' not in command_string:
697
 
            command_template.extend(['@old_path', '@new_path'])
 
761
        command_template = commands.shlex_split_unicode(command_string)
 
762
        command_template.extend(['%(old_path)s', '%(new_path)s'])
698
763
        return klass(command_template, old_tree, new_tree, to_file,
699
764
                     path_encoding)
700
765
 
701
766
    @classmethod
702
 
    def make_from_diff_tree(klass, command_string, external_diff_options=None):
 
767
    def make_from_diff_tree(klass, command_string):
703
768
        def from_diff_tree(diff_tree):
704
 
            full_command_string = [command_string]
705
 
            if external_diff_options is not None:
706
 
                full_command_string += ' ' + external_diff_options
707
 
            return klass.from_string(full_command_string, diff_tree.old_tree,
 
769
            return klass.from_string(command_string, diff_tree.old_tree,
708
770
                                     diff_tree.new_tree, diff_tree.to_file)
709
771
        return from_diff_tree
710
772
 
711
773
    def _get_command(self, old_path, new_path):
712
774
        my_map = {'old_path': old_path, 'new_path': new_path}
713
 
        command = [AtTemplate(t).substitute(my_map) for t in
714
 
                   self.command_template]
715
 
        if sys.platform == 'win32': # Popen doesn't accept unicode on win32
716
 
            command_encoded = []
717
 
            for c in command:
718
 
                if isinstance(c, unicode):
719
 
                    command_encoded.append(c.encode('mbcs'))
720
 
                else:
721
 
                    command_encoded.append(c)
722
 
            return command_encoded
723
 
        else:
724
 
            return command
 
775
        return [t % my_map for t in self.command_template]
725
776
 
726
777
    def _execute(self, old_path, new_path):
727
778
        command = self._get_command(old_path, new_path)
737
788
        return proc.wait()
738
789
 
739
790
    def _try_symlink_root(self, tree, prefix):
740
 
        if (getattr(tree, 'abspath', None) is None
741
 
            or not osutils.host_os_dereferences_symlinks()):
 
791
        if not (getattr(tree, 'abspath', None) is not None
 
792
                and osutils.has_symlinks()):
742
793
            return False
743
794
        try:
744
795
            os.symlink(tree.abspath(''), osutils.pathjoin(self._root, prefix))
747
798
                raise
748
799
        return True
749
800
 
750
 
    @staticmethod
751
 
    def _fenc():
752
 
        """Returns safe encoding for passing file path to diff tool"""
753
 
        if sys.platform == 'win32':
754
 
            return 'mbcs'
755
 
        else:
756
 
            # Don't fallback to 'utf-8' because subprocess may not be able to
757
 
            # handle utf-8 correctly when locale is not utf-8.
758
 
            return sys.getfilesystemencoding() or 'ascii'
759
 
 
760
 
    def _is_safepath(self, path):
761
 
        """Return true if `path` may be able to pass to subprocess."""
762
 
        fenc = self._fenc()
763
 
        try:
764
 
            return path == path.encode(fenc).decode(fenc)
765
 
        except UnicodeError:
766
 
            return False
767
 
 
768
 
    def _safe_filename(self, prefix, relpath):
769
 
        """Replace unsafe character in `relpath` then join `self._root`,
770
 
        `prefix` and `relpath`."""
771
 
        fenc = self._fenc()
772
 
        # encoded_str.replace('?', '_') may break multibyte char.
773
 
        # So we should encode, decode, then replace(u'?', u'_')
774
 
        relpath_tmp = relpath.encode(fenc, 'replace').decode(fenc, 'replace')
775
 
        relpath_tmp = relpath_tmp.replace(u'?', u'_')
776
 
        return osutils.pathjoin(self._root, prefix, relpath_tmp)
777
 
 
778
 
    def _write_file(self, file_id, tree, prefix, relpath, force_temp=False,
779
 
                    allow_write=False):
780
 
        if not force_temp and isinstance(tree, WorkingTree):
781
 
            full_path = tree.abspath(tree.id2path(file_id))
782
 
            if self._is_safepath(full_path):
783
 
                return full_path
784
 
 
785
 
        full_path = self._safe_filename(prefix, relpath)
786
 
        if not force_temp and self._try_symlink_root(tree, prefix):
 
801
    def _write_file(self, file_id, tree, prefix, relpath):
 
802
        full_path = osutils.pathjoin(self._root, prefix, relpath)
 
803
        if self._try_symlink_root(tree, prefix):
787
804
            return full_path
788
805
        parent_dir = osutils.dirname(full_path)
789
806
        try:
800
817
                target.close()
801
818
        finally:
802
819
            source.close()
803
 
        try:
804
 
            mtime = tree.get_file_mtime(file_id)
805
 
        except errors.FileTimestampUnavailable:
806
 
            pass
807
 
        else:
808
 
            os.utime(full_path, (mtime, mtime))
809
 
        if not allow_write:
810
 
            osutils.make_readonly(full_path)
 
820
        osutils.make_readonly(full_path)
 
821
        mtime = tree.get_file_mtime(file_id)
 
822
        os.utime(full_path, (mtime, mtime))
811
823
        return full_path
812
824
 
813
 
    def _prepare_files(self, file_id, old_path, new_path, force_temp=False,
814
 
                       allow_write_new=False):
 
825
    def _prepare_files(self, file_id, old_path, new_path):
815
826
        old_disk_path = self._write_file(file_id, self.old_tree, 'old',
816
 
                                         old_path, force_temp)
 
827
                                         old_path)
817
828
        new_disk_path = self._write_file(file_id, self.new_tree, 'new',
818
 
                                         new_path, force_temp,
819
 
                                         allow_write=allow_write_new)
 
829
                                         new_path)
820
830
        return old_disk_path, new_disk_path
821
831
 
822
832
    def finish(self):
823
 
        try:
824
 
            osutils.rmtree(self._root)
825
 
        except OSError, e:
826
 
            if e.errno != errno.ENOENT:
827
 
                mutter("The temporary directory \"%s\" was not "
828
 
                        "cleanly removed: %s." % (self._root, e))
 
833
        osutils.rmtree(self._root)
829
834
 
830
835
    def diff(self, file_id, old_path, new_path, old_kind, new_kind):
831
836
        if (old_kind, new_kind) != ('file', 'file'):
832
837
            return DiffPath.CANNOT_DIFF
833
 
        (old_disk_path, new_disk_path) = self._prepare_files(
834
 
                                                file_id, old_path, new_path)
835
 
        self._execute(old_disk_path, new_disk_path)
836
 
 
837
 
    def edit_file(self, file_id):
838
 
        """Use this tool to edit a file.
839
 
 
840
 
        A temporary copy will be edited, and the new contents will be
841
 
        returned.
842
 
 
843
 
        :param file_id: The id of the file to edit.
844
 
        :return: The new contents of the file.
845
 
        """
846
 
        old_path = self.old_tree.id2path(file_id)
847
 
        new_path = self.new_tree.id2path(file_id)
848
 
        old_abs_path, new_abs_path = self._prepare_files(
849
 
                                            file_id, old_path, new_path,
850
 
                                            allow_write_new=True,
851
 
                                            force_temp=True)
852
 
        command = self._get_command(old_abs_path, new_abs_path)
853
 
        subprocess.call(command, cwd=self._root)
854
 
        new_file = open(new_abs_path, 'rb')
855
 
        try:
856
 
            return new_file.read()
857
 
        finally:
858
 
            new_file.close()
 
838
        self._prepare_files(file_id, old_path, new_path)
 
839
        self._execute(osutils.pathjoin('old', old_path),
 
840
                      osutils.pathjoin('new', new_path))
859
841
 
860
842
 
861
843
class DiffTree(object):
907
889
        """Factory for producing a DiffTree.
908
890
 
909
891
        Designed to accept options used by show_diff_trees.
910
 
 
911
892
        :param old_tree: The tree to show as old in the comparison
912
893
        :param new_tree: The tree to show as new in the comparison
913
894
        :param to_file: File to write comparisons to
919
900
        :param using: Commandline to use to invoke an external diff tool
920
901
        """
921
902
        if using is not None:
922
 
            extra_factories = [DiffFromTool.make_from_diff_tree(using, external_diff_options)]
 
903
            extra_factories = [DiffFromTool.make_from_diff_tree(using)]
923
904
        else:
924
905
            extra_factories = []
925
906
        if external_diff_options:
 
907
            assert isinstance(external_diff_options, basestring)
926
908
            opts = external_diff_options.split()
927
 
            def diff_file(olab, olines, nlab, nlines, to_file, path_encoding=None):
928
 
                """:param path_encoding: not used but required
929
 
                        to match the signature of internal_diff.
930
 
                """
 
909
            def diff_file(olab, olines, nlab, nlines, to_file):
931
910
                external_diff(olab, olines, nlab, nlines, to_file, opts)
932
911
        else:
933
912
            diff_file = internal_diff
939
918
    def show_diff(self, specific_files, extra_trees=None):
940
919
        """Write tree diff to self.to_file
941
920
 
942
 
        :param specific_files: the specific files to compare (recursive)
 
921
        :param sepecific_files: the specific files to compare (recursive)
943
922
        :param extra_trees: extra trees to use for mapping paths to file_ids
944
923
        """
945
924
        try:
967
946
                return path.encode(self.path_encoding, "replace")
968
947
        for (file_id, paths, changed_content, versioned, parent, name, kind,
969
948
             executable) in sorted(iterator, key=changes_key):
970
 
            # The root does not get diffed, and items with no known kind (that
971
 
            # is, missing) in both trees are skipped as well.
972
 
            if parent == (None, None) or kind == (None, None):
 
949
            if parent == (None, None):
973
950
                continue
974
951
            oldpath, newpath = paths
975
952
            oldpath_encoded = get_encoded_path(paths[0])
977
954
            old_present = (kind[0] is not None and versioned[0])
978
955
            new_present = (kind[1] is not None and versioned[1])
979
956
            renamed = (parent[0], name[0]) != (parent[1], name[1])
980
 
 
981
 
            properties_changed = []
982
 
            properties_changed.extend(get_executable_change(executable[0], executable[1]))
983
 
 
984
 
            if properties_changed:
985
 
                prop_str = " (properties changed: %s)" % (", ".join(properties_changed),)
986
 
            else:
987
 
                prop_str = ""
988
 
 
 
957
            prop_str = get_prop_change(executable[0] != executable[1])
989
958
            if (old_present, new_present) == (True, False):
990
959
                self.to_file.write("=== removed %s '%s'\n" %
991
960
                                   (kind[0], oldpath_encoded))
1003
972
                self.to_file.write("=== modified %s '%s'%s\n" % (kind[0],
1004
973
                                   newpath_encoded, prop_str))
1005
974
            if changed_content:
1006
 
                self._diff(file_id, oldpath, newpath, kind[0], kind[1])
 
975
                self.diff(file_id, oldpath, newpath)
1007
976
                has_changes = 1
1008
977
            if renamed:
1009
978
                has_changes = 1
1024
993
            new_kind = self.new_tree.kind(file_id)
1025
994
        except (errors.NoSuchId, errors.NoSuchFile):
1026
995
            new_kind = None
1027
 
        self._diff(file_id, old_path, new_path, old_kind, new_kind)
1028
 
 
1029
 
 
1030
 
    def _diff(self, file_id, old_path, new_path, old_kind, new_kind):
 
996
 
1031
997
        result = DiffPath._diff_many(self.differs, file_id, old_path,
1032
998
                                       new_path, old_kind, new_kind)
1033
999
        if result is DiffPath.CANNOT_DIFF:
1035
1001
            if error_path is None:
1036
1002
                error_path = old_path
1037
1003
            raise errors.NoDiffFound(error_path)
1038
 
 
1039
 
 
1040
 
format_registry = Registry()
1041
 
format_registry.register('default', DiffTree)