~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/diff.py

Late bind to PatienceSequenceMatcher to allow plugin to override.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
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
5
5
# the Free Software Foundation; either version 2 of the License, or
6
6
# (at your option) any later version.
7
 
#
 
7
 
8
8
# This program is distributed in the hope that it will be useful,
9
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
11
# GNU General Public License for more details.
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
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
16
 
17
 
import errno
18
 
import os
19
 
import re
20
 
import subprocess
21
 
import sys
22
 
import tempfile
23
 
import time
24
 
 
25
 
# compatability - plugins import compare_trees from diff!!!
26
 
# deprecated as of 0.10
27
17
from bzrlib.delta import compare_trees
28
18
from bzrlib.errors import BzrError
29
19
import bzrlib.errors as errors
30
 
import bzrlib.osutils
31
20
from bzrlib.patiencediff import unified_diff
32
21
import bzrlib.patiencediff
33
 
from bzrlib.symbol_versioning import (deprecated_function,
34
 
        zero_eight)
 
22
from bzrlib.symbol_versioning import *
35
23
from bzrlib.textfile import check_text_lines
36
 
from bzrlib.trace import mutter, warning
 
24
from bzrlib.trace import mutter
37
25
 
38
26
 
39
27
# TODO: Rather than building a changeset object, we should probably
41
29
# list, write them out directly, etc etc.
42
30
 
43
31
def internal_diff(old_filename, oldlines, new_filename, newlines, to_file,
44
 
                  allow_binary=False, sequence_matcher=None,
45
 
                  path_encoding='utf8'):
 
32
                  allow_binary=False, sequence_matcher=None):
46
33
    # FIXME: difflib is wrong if there is no trailing newline.
47
34
    # The syntax used by patch seems to be "\ No newline at
48
35
    # end of file" following the last diff line from that
66
53
    if sequence_matcher is None:
67
54
        sequence_matcher = bzrlib.patiencediff.PatienceSequenceMatcher
68
55
    ud = unified_diff(oldlines, newlines,
69
 
                      fromfile=old_filename.encode(path_encoding),
70
 
                      tofile=new_filename.encode(path_encoding),
 
56
                      fromfile=old_filename+'\t', 
 
57
                      tofile=new_filename+'\t',
71
58
                      sequencematcher=sequence_matcher)
72
59
 
73
60
    ud = list(ud)
91
78
def external_diff(old_filename, oldlines, new_filename, newlines, to_file,
92
79
                  diff_opts):
93
80
    """Display a diff by calling out to the external diff program."""
 
81
    import sys
 
82
    
 
83
    if to_file != sys.stdout:
 
84
        raise NotImplementedError("sorry, can't send external diff other than to stdout yet",
 
85
                                  to_file)
 
86
 
94
87
    # make sure our own output is properly ordered before the diff
95
88
    to_file.flush()
96
89
 
97
 
    oldtmp_fd, old_abspath = tempfile.mkstemp(prefix='bzr-diff-old-')
98
 
    newtmp_fd, new_abspath = tempfile.mkstemp(prefix='bzr-diff-new-')
99
 
    oldtmpf = os.fdopen(oldtmp_fd, 'wb')
100
 
    newtmpf = os.fdopen(newtmp_fd, 'wb')
 
90
    from tempfile import NamedTemporaryFile
 
91
    import os
 
92
 
 
93
    oldtmpf = NamedTemporaryFile()
 
94
    newtmpf = NamedTemporaryFile()
101
95
 
102
96
    try:
103
97
        # TODO: perhaps a special case for comparing to or from the empty
110
104
        oldtmpf.writelines(oldlines)
111
105
        newtmpf.writelines(newlines)
112
106
 
113
 
        oldtmpf.close()
114
 
        newtmpf.close()
 
107
        oldtmpf.flush()
 
108
        newtmpf.flush()
115
109
 
116
110
        if not diff_opts:
117
111
            diff_opts = []
118
112
        diffcmd = ['diff',
119
 
                   '--label', old_filename,
120
 
                   old_abspath,
121
 
                   '--label', new_filename,
122
 
                   new_abspath,
123
 
                   '--binary',
124
 
                  ]
 
113
                   '--label', old_filename+'\t',
 
114
                   oldtmpf.name,
 
115
                   '--label', new_filename+'\t',
 
116
                   newtmpf.name]
125
117
 
126
118
        # diff only allows one style to be specified; they don't override.
127
119
        # note that some of these take optargs, and the optargs can be
147
139
        if diff_opts:
148
140
            diffcmd.extend(diff_opts)
149
141
 
150
 
        try:
151
 
            pipe = subprocess.Popen(diffcmd,
152
 
                                    stdin=subprocess.PIPE,
153
 
                                    stdout=subprocess.PIPE)
154
 
        except OSError, e:
155
 
            if e.errno == errno.ENOENT:
156
 
                raise errors.NoDiff(str(e))
157
 
            raise
158
 
        pipe.stdin.close()
159
 
 
160
 
        first_line = pipe.stdout.readline()
161
 
        to_file.write(first_line)
162
 
        bzrlib.osutils.pumpfile(pipe.stdout, to_file)
163
 
        rc = pipe.wait()
 
142
        rc = os.spawnvp(os.P_WAIT, 'diff', diffcmd)
164
143
        
165
 
        if rc == 2:
166
 
            # 'diff' gives retcode == 2 for all sorts of errors
167
 
            # one of those is 'Binary files differ'.
168
 
            # Bad options could also be the problem.
169
 
            # 'Binary files' is not a real error, so we suppress that error
170
 
            m = re.match('^binary files.*differ$', first_line, re.I)
171
 
            if not m:
172
 
                raise BzrError('external diff failed with exit code 2;'
173
 
                               ' command: %r' % (diffcmd,))
174
 
        elif rc not in (0, 1):
 
144
        if rc != 0 and rc != 1:
175
145
            # returns 1 if files differ; that's OK
176
146
            if rc < 0:
177
147
                msg = 'signal %d' % (-rc)
178
148
            else:
179
149
                msg = 'exit code %d' % rc
180
150
                
181
 
            raise BzrError('external diff failed with %s; command: %r' 
182
 
                           % (rc, diffcmd))
183
 
 
184
 
        # internal_diff() adds a trailing newline, add one here for consistency
185
 
        to_file.write('\n')
186
 
 
 
151
            raise BzrError('external diff failed with %s; command: %r' % (rc, diffcmd))
187
152
    finally:
188
153
        oldtmpf.close()                 # and delete
189
154
        newtmpf.close()
190
 
        # Clean up. Warn in case the files couldn't be deleted
191
 
        # (in case windows still holds the file open, but not
192
 
        # if the files have already been deleted)
193
 
        try:
194
 
            os.remove(old_abspath)
195
 
        except OSError, e:
196
 
            if e.errno not in (errno.ENOENT,):
197
 
                warning('Failed to delete temporary file: %s %s',
198
 
                        old_abspath, e)
199
 
        try:
200
 
            os.remove(new_abspath)
201
 
        except OSError:
202
 
            if e.errno not in (errno.ENOENT,):
203
 
                warning('Failed to delete temporary file: %s %s',
204
 
                        new_abspath, e)
205
155
 
206
156
 
207
157
@deprecated_function(zero_eight)
221
171
    supplies any two trees.
222
172
    """
223
173
    if output is None:
 
174
        import sys
224
175
        output = sys.stdout
225
176
 
226
177
    if from_spec is None:
267
218
    The more general form is show_diff_trees(), where the caller
268
219
    supplies any two trees.
269
220
    """
 
221
    import sys
 
222
    output = sys.stdout
270
223
    def spec_tree(spec):
271
 
        if tree:
272
 
            revision = spec.in_store(tree.branch)
273
 
        else:
274
 
            revision = spec.in_store(None)
275
 
        revision_id = revision.rev_id
276
 
        branch = revision.branch
277
 
        return branch.repository.revision_tree(revision_id)
 
224
        revision_id = spec.in_store(tree.branch).rev_id
 
225
        return tree.branch.repository.revision_tree(revision_id)
278
226
    if old_revision_spec is None:
279
227
        old_tree = tree.basis_tree()
280
228
    else:
284
232
        new_tree = tree
285
233
    else:
286
234
        new_tree = spec_tree(new_revision_spec)
287
 
    if new_tree is not tree:
288
 
        extra_trees = (tree,)
289
 
    else:
290
 
        extra_trees = None
291
235
 
292
236
    return show_diff_trees(old_tree, new_tree, sys.stdout, specific_files,
293
237
                           external_diff_options,
294
 
                           old_label=old_label, new_label=new_label,
295
 
                           extra_trees=extra_trees)
 
238
                           old_label=old_label, new_label=new_label)
296
239
 
297
240
 
298
241
def show_diff_trees(old_tree, new_tree, to_file, specific_files=None,
299
242
                    external_diff_options=None,
300
 
                    old_label='a/', new_label='b/',
301
 
                    extra_trees=None):
 
243
                    old_label='a/', new_label='b/'):
302
244
    """Show in text form the changes from one tree to another.
303
245
 
304
246
    to_files
306
248
 
307
249
    external_diff_options
308
250
        If set, use an external GNU diff and pass these options.
309
 
 
310
 
    extra_trees
311
 
        If set, more Trees to use for looking up file ids
312
251
    """
313
252
    old_tree.lock_read()
314
253
    try:
316
255
        try:
317
256
            return _show_diff_trees(old_tree, new_tree, to_file,
318
257
                                    specific_files, external_diff_options,
319
 
                                    old_label=old_label, new_label=new_label,
320
 
                                    extra_trees=extra_trees)
 
258
                                    old_label=old_label, new_label=new_label)
321
259
        finally:
322
260
            new_tree.unlock()
323
261
    finally:
326
264
 
327
265
def _show_diff_trees(old_tree, new_tree, to_file,
328
266
                     specific_files, external_diff_options, 
329
 
                     old_label='a/', new_label='b/', extra_trees=None):
 
267
                     old_label='a/', new_label='b/' ):
330
268
 
331
 
    # GNU Patch uses the epoch date to detect files that are being added
332
 
    # or removed in a diff.
333
 
    EPOCH_DATE = '1970-01-01 00:00:00 +0000'
 
269
    DEVNULL = '/dev/null'
 
270
    # Windows users, don't panic about this filename -- it is a
 
271
    # special signal to GNU patch that the file should be created or
 
272
    # deleted respectively.
334
273
 
335
274
    # TODO: Generation of pseudo-diffs for added/deleted files could
336
275
    # be usefully made into a much faster special case.
337
276
 
 
277
    _raise_if_doubly_unversioned(specific_files, old_tree, new_tree)
 
278
 
338
279
    if external_diff_options:
339
280
        assert isinstance(external_diff_options, basestring)
340
281
        opts = external_diff_options.split()
343
284
    else:
344
285
        diff_file = internal_diff
345
286
    
346
 
    delta = new_tree.changes_from(old_tree,
347
 
        specific_files=specific_files,
348
 
        extra_trees=extra_trees, require_versioned=True)
 
287
    delta = compare_trees(old_tree, new_tree, want_unchanged=False,
 
288
                          specific_files=specific_files)
349
289
 
350
290
    has_changes = 0
351
291
    for path, file_id, kind in delta.removed:
352
292
        has_changes = 1
353
 
        print >>to_file, '=== removed %s %r' % (kind, path.encode('utf8'))
354
 
        old_name = '%s%s\t%s' % (old_label, path,
355
 
                                 _patch_header_date(old_tree, file_id, path))
356
 
        new_name = '%s%s\t%s' % (new_label, path, EPOCH_DATE)
357
 
        old_tree.inventory[file_id].diff(diff_file, old_name, old_tree,
358
 
                                         new_name, None, None, to_file)
 
293
        print >>to_file, '=== removed %s %r' % (kind, path)
 
294
        old_tree.inventory[file_id].diff(diff_file, old_label + path, old_tree,
 
295
                                         DEVNULL, None, None, to_file)
359
296
    for path, file_id, kind in delta.added:
360
297
        has_changes = 1
361
 
        print >>to_file, '=== added %s %r' % (kind, path.encode('utf8'))
362
 
        old_name = '%s%s\t%s' % (old_label, path, EPOCH_DATE)
363
 
        new_name = '%s%s\t%s' % (new_label, path,
364
 
                                 _patch_header_date(new_tree, file_id, path))
365
 
        new_tree.inventory[file_id].diff(diff_file, new_name, new_tree,
366
 
                                         old_name, None, None, to_file, 
 
298
        print >>to_file, '=== added %s %r' % (kind, path)
 
299
        new_tree.inventory[file_id].diff(diff_file, new_label + path, new_tree,
 
300
                                         DEVNULL, None, None, to_file, 
367
301
                                         reverse=True)
368
302
    for (old_path, new_path, file_id, kind,
369
303
         text_modified, meta_modified) in delta.renamed:
370
304
        has_changes = 1
371
305
        prop_str = get_prop_change(meta_modified)
372
306
        print >>to_file, '=== renamed %s %r => %r%s' % (
373
 
                    kind, old_path.encode('utf8'),
374
 
                    new_path.encode('utf8'), prop_str)
375
 
        old_name = '%s%s\t%s' % (old_label, old_path,
376
 
                                 _patch_header_date(old_tree, file_id,
377
 
                                                    old_path))
378
 
        new_name = '%s%s\t%s' % (new_label, new_path,
379
 
                                 _patch_header_date(new_tree, file_id,
380
 
                                                    new_path))
381
 
        _maybe_diff_file_or_symlink(old_name, old_tree, file_id,
382
 
                                    new_name, new_tree,
 
307
                    kind, old_path, new_path, prop_str)
 
308
        _maybe_diff_file_or_symlink(old_label, old_path, old_tree, file_id,
 
309
                                    new_label, new_path, new_tree,
383
310
                                    text_modified, kind, to_file, diff_file)
384
311
    for path, file_id, kind, text_modified, meta_modified in delta.modified:
385
312
        has_changes = 1
386
313
        prop_str = get_prop_change(meta_modified)
387
 
        print >>to_file, '=== modified %s %r%s' % (kind, path.encode('utf8'), prop_str)
388
 
        old_name = '%s%s\t%s' % (old_label, path,
389
 
                                 _patch_header_date(old_tree, file_id, path))
390
 
        new_name = '%s%s\t%s' % (new_label, path,
391
 
                                 _patch_header_date(new_tree, file_id, path))
 
314
        print >>to_file, '=== modified %s %r%s' % (kind, path, prop_str)
392
315
        if text_modified:
393
 
            _maybe_diff_file_or_symlink(old_name, old_tree, file_id,
394
 
                                        new_name, new_tree,
 
316
            _maybe_diff_file_or_symlink(old_label, path, old_tree, file_id,
 
317
                                        new_label, path, new_tree,
395
318
                                        True, kind, to_file, diff_file)
396
319
 
397
320
    return has_changes
398
321
 
399
322
 
400
 
def _patch_header_date(tree, file_id, path):
401
 
    """Returns a timestamp suitable for use in a patch header."""
402
 
    tm = time.gmtime(tree.get_file_mtime(file_id, path))
403
 
    return time.strftime('%Y-%m-%d %H:%M:%S +0000', tm)
404
 
 
 
323
def _raise_if_doubly_unversioned(specific_files, old_tree, new_tree):
 
324
    """Complain if paths are not versioned in either tree."""
 
325
    if not specific_files:
 
326
        return
 
327
    old_unversioned = old_tree.filter_unversioned_files(specific_files)
 
328
    new_unversioned = new_tree.filter_unversioned_files(specific_files)
 
329
    unversioned = old_unversioned.intersection(new_unversioned)
 
330
    if unversioned:
 
331
        raise errors.PathsNotVersionedError(sorted(unversioned))
 
332
    
405
333
 
406
334
def _raise_if_nonexistent(paths, old_tree, new_tree):
407
335
    """Complain if paths are not in either inventory or tree.
429
357
        return  ""
430
358
 
431
359
 
432
 
def _maybe_diff_file_or_symlink(old_path, old_tree, file_id,
433
 
                                new_path, new_tree, text_modified,
 
360
def _maybe_diff_file_or_symlink(old_label, old_path, old_tree, file_id,
 
361
                                new_label, new_path, new_tree, text_modified,
434
362
                                kind, to_file, diff_file):
435
363
    if text_modified:
436
364
        new_entry = new_tree.inventory[file_id]
437
365
        old_tree.inventory[file_id].diff(diff_file,
438
 
                                         old_path, old_tree,
439
 
                                         new_path, new_entry, 
 
366
                                         old_label + old_path, old_tree,
 
367
                                         new_label + new_path, new_entry, 
440
368
                                         new_tree, to_file)