~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: 2006-04-27 01:14:33 UTC
  • mfrom: (1686.1.1 integration)
  • Revision ID: pqm@pqm.ubuntu.com-20060427011433-95634ee1da8a2049
Merge in faster joins from weave to knit.

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 subprocess
20
 
import sys
21
 
import tempfile
22
 
import time
23
 
 
24
 
# compatability - plugins import compare_trees from diff!!!
25
 
# deprecated as of 0.10
26
17
from bzrlib.delta import compare_trees
27
18
from bzrlib.errors import BzrError
28
19
import bzrlib.errors as errors
29
 
import bzrlib.osutils
30
 
from bzrlib.patiencediff import unified_diff
31
 
import bzrlib.patiencediff
32
 
from bzrlib.symbol_versioning import (deprecated_function,
33
 
        zero_eight)
 
20
from bzrlib.symbol_versioning import *
34
21
from bzrlib.textfile import check_text_lines
35
 
from bzrlib.trace import mutter, warning
36
 
 
 
22
from bzrlib.trace import mutter
37
23
 
38
24
# TODO: Rather than building a changeset object, we should probably
39
25
# invoke callbacks on an object.  That object can either accumulate a
40
26
# list, write them out directly, etc etc.
41
27
 
42
28
def internal_diff(old_filename, oldlines, new_filename, newlines, to_file,
43
 
                  allow_binary=False, sequence_matcher=None,
44
 
                  path_encoding='utf8'):
 
29
                  allow_binary=False):
 
30
    import difflib
 
31
    
45
32
    # FIXME: difflib is wrong if there is no trailing newline.
46
33
    # The syntax used by patch seems to be "\ No newline at
47
34
    # end of file" following the last diff line from that
62
49
        check_text_lines(oldlines)
63
50
        check_text_lines(newlines)
64
51
 
65
 
    if sequence_matcher is None:
66
 
        sequence_matcher = bzrlib.patiencediff.PatienceSequenceMatcher
67
 
    ud = unified_diff(oldlines, newlines,
68
 
                      fromfile=old_filename.encode(path_encoding),
69
 
                      tofile=new_filename.encode(path_encoding),
70
 
                      sequencematcher=sequence_matcher)
 
52
    ud = difflib.unified_diff(oldlines, newlines,
 
53
                              fromfile=old_filename+'\t', 
 
54
                              tofile=new_filename+'\t')
71
55
 
72
56
    ud = list(ud)
73
57
    # work-around for difflib being too smart for its own good
90
74
def external_diff(old_filename, oldlines, new_filename, newlines, to_file,
91
75
                  diff_opts):
92
76
    """Display a diff by calling out to the external diff program."""
93
 
    if hasattr(to_file, 'fileno'):
94
 
        out_file = to_file
95
 
        have_fileno = True
96
 
    else:
97
 
        out_file = subprocess.PIPE
98
 
        have_fileno = False
 
77
    import sys
99
78
    
 
79
    if to_file != sys.stdout:
 
80
        raise NotImplementedError("sorry, can't send external diff other than to stdout yet",
 
81
                                  to_file)
 
82
 
100
83
    # make sure our own output is properly ordered before the diff
101
84
    to_file.flush()
102
85
 
103
 
    oldtmp_fd, old_abspath = tempfile.mkstemp(prefix='bzr-diff-old-')
104
 
    newtmp_fd, new_abspath = tempfile.mkstemp(prefix='bzr-diff-new-')
105
 
    oldtmpf = os.fdopen(oldtmp_fd, 'wb')
106
 
    newtmpf = os.fdopen(newtmp_fd, 'wb')
 
86
    from tempfile import NamedTemporaryFile
 
87
    import os
 
88
 
 
89
    oldtmpf = NamedTemporaryFile()
 
90
    newtmpf = NamedTemporaryFile()
107
91
 
108
92
    try:
109
93
        # TODO: perhaps a special case for comparing to or from the empty
116
100
        oldtmpf.writelines(oldlines)
117
101
        newtmpf.writelines(newlines)
118
102
 
119
 
        oldtmpf.close()
120
 
        newtmpf.close()
 
103
        oldtmpf.flush()
 
104
        newtmpf.flush()
121
105
 
122
106
        if not diff_opts:
123
107
            diff_opts = []
124
108
        diffcmd = ['diff',
125
 
                   '--label', old_filename,
126
 
                   old_abspath,
127
 
                   '--label', new_filename,
128
 
                   new_abspath,
129
 
                   '--binary',
130
 
                  ]
 
109
                   '--label', old_filename+'\t',
 
110
                   oldtmpf.name,
 
111
                   '--label', new_filename+'\t',
 
112
                   newtmpf.name]
131
113
 
132
114
        # diff only allows one style to be specified; they don't override.
133
115
        # note that some of these take optargs, and the optargs can be
153
135
        if diff_opts:
154
136
            diffcmd.extend(diff_opts)
155
137
 
156
 
        try:
157
 
            pipe = subprocess.Popen(diffcmd,
158
 
                                    stdin=subprocess.PIPE,
159
 
                                    stdout=out_file)
160
 
        except OSError, e:
161
 
            if e.errno == errno.ENOENT:
162
 
                raise errors.NoDiff(str(e))
163
 
            raise
164
 
        pipe.stdin.close()
165
 
 
166
 
        if not have_fileno:
167
 
            bzrlib.osutils.pumpfile(pipe.stdout, to_file)
168
 
        rc = pipe.wait()
 
138
        rc = os.spawnvp(os.P_WAIT, 'diff', diffcmd)
169
139
        
170
140
        if rc != 0 and rc != 1:
171
141
            # returns 1 if files differ; that's OK
178
148
    finally:
179
149
        oldtmpf.close()                 # and delete
180
150
        newtmpf.close()
181
 
        # Clean up. Warn in case the files couldn't be deleted
182
 
        # (in case windows still holds the file open, but not
183
 
        # if the files have already been deleted)
184
 
        try:
185
 
            os.remove(old_abspath)
186
 
        except OSError, e:
187
 
            if e.errno not in (errno.ENOENT,):
188
 
                warning('Failed to delete temporary file: %s %s',
189
 
                        old_abspath, e)
190
 
        try:
191
 
            os.remove(new_abspath)
192
 
        except OSError:
193
 
            if e.errno not in (errno.ENOENT,):
194
 
                warning('Failed to delete temporary file: %s %s',
195
 
                        new_abspath, e)
196
151
 
197
152
 
198
153
@deprecated_function(zero_eight)
212
167
    supplies any two trees.
213
168
    """
214
169
    if output is None:
 
170
        import sys
215
171
        output = sys.stdout
216
172
 
217
173
    if from_spec is None:
234
190
 
235
191
 
236
192
def diff_cmd_helper(tree, specific_files, external_diff_options, 
237
 
                    old_revision_spec=None, new_revision_spec=None,
238
 
                    old_label='a/', new_label='b/'):
 
193
                    old_revision_spec=None, new_revision_spec=None):
239
194
    """Helper for cmd_diff.
240
195
 
241
196
   tree 
258
213
    The more general form is show_diff_trees(), where the caller
259
214
    supplies any two trees.
260
215
    """
 
216
    import sys
 
217
    output = sys.stdout
261
218
    def spec_tree(spec):
262
 
        if tree:
263
 
            revision = spec.in_store(tree.branch)
264
 
        else:
265
 
            revision = spec.in_store(None)
266
 
        revision_id = revision.rev_id
267
 
        branch = revision.branch
268
 
        return branch.repository.revision_tree(revision_id)
 
219
        revision_id = spec.in_store(tree.branch).rev_id
 
220
        return tree.branch.repository.revision_tree(revision_id)
269
221
    if old_revision_spec is None:
270
222
        old_tree = tree.basis_tree()
271
223
    else:
275
227
        new_tree = tree
276
228
    else:
277
229
        new_tree = spec_tree(new_revision_spec)
278
 
    if new_tree is not tree:
279
 
        extra_trees = (tree,)
280
 
    else:
281
 
        extra_trees = None
282
230
 
283
231
    return show_diff_trees(old_tree, new_tree, sys.stdout, specific_files,
284
 
                           external_diff_options,
285
 
                           old_label=old_label, new_label=new_label,
286
 
                           extra_trees=extra_trees)
 
232
                           external_diff_options)
287
233
 
288
234
 
289
235
def show_diff_trees(old_tree, new_tree, to_file, specific_files=None,
290
 
                    external_diff_options=None,
291
 
                    old_label='a/', new_label='b/',
292
 
                    extra_trees=None):
 
236
                    external_diff_options=None):
293
237
    """Show in text form the changes from one tree to another.
294
238
 
295
239
    to_files
297
241
 
298
242
    external_diff_options
299
243
        If set, use an external GNU diff and pass these options.
300
 
 
301
 
    extra_trees
302
 
        If set, more Trees to use for looking up file ids
303
244
    """
304
245
    old_tree.lock_read()
305
246
    try:
306
247
        new_tree.lock_read()
307
248
        try:
308
249
            return _show_diff_trees(old_tree, new_tree, to_file,
309
 
                                    specific_files, external_diff_options,
310
 
                                    old_label=old_label, new_label=new_label,
311
 
                                    extra_trees=extra_trees)
 
250
                                    specific_files, external_diff_options)
312
251
        finally:
313
252
            new_tree.unlock()
314
253
    finally:
316
255
 
317
256
 
318
257
def _show_diff_trees(old_tree, new_tree, to_file,
319
 
                     specific_files, external_diff_options, 
320
 
                     old_label='a/', new_label='b/', extra_trees=None):
321
 
 
322
 
    # GNU Patch uses the epoch date to detect files that are being added
323
 
    # or removed in a diff.
324
 
    EPOCH_DATE = '1970-01-01 00:00:00 +0000'
 
258
                     specific_files, external_diff_options):
 
259
 
 
260
    # TODO: Options to control putting on a prefix or suffix, perhaps
 
261
    # as a format string?
 
262
    old_label = 'a/'
 
263
    new_label = 'b/'
 
264
 
 
265
    DEVNULL = '/dev/null'
 
266
    # Windows users, don't panic about this filename -- it is a
 
267
    # special signal to GNU patch that the file should be created or
 
268
    # deleted respectively.
325
269
 
326
270
    # TODO: Generation of pseudo-diffs for added/deleted files could
327
271
    # be usefully made into a much faster special case.
328
272
 
 
273
    _raise_if_doubly_unversioned(specific_files, old_tree, new_tree)
 
274
 
329
275
    if external_diff_options:
330
276
        assert isinstance(external_diff_options, basestring)
331
277
        opts = external_diff_options.split()
334
280
    else:
335
281
        diff_file = internal_diff
336
282
    
337
 
    delta = new_tree.changes_from(old_tree,
338
 
        specific_files=specific_files,
339
 
        extra_trees=extra_trees, require_versioned=True)
 
283
    delta = compare_trees(old_tree, new_tree, want_unchanged=False,
 
284
                          specific_files=specific_files)
340
285
 
341
286
    has_changes = 0
342
287
    for path, file_id, kind in delta.removed:
343
288
        has_changes = 1
344
 
        print >>to_file, '=== removed %s %r' % (kind, path.encode('utf8'))
345
 
        old_name = '%s%s\t%s' % (old_label, path,
346
 
                                 _patch_header_date(old_tree, file_id, path))
347
 
        new_name = '%s%s\t%s' % (new_label, path, EPOCH_DATE)
348
 
        old_tree.inventory[file_id].diff(diff_file, old_name, old_tree,
349
 
                                         new_name, None, None, to_file)
 
289
        print >>to_file, '=== removed %s %r' % (kind, old_label + path)
 
290
        old_tree.inventory[file_id].diff(diff_file, old_label + path, old_tree,
 
291
                                         DEVNULL, None, None, to_file)
350
292
    for path, file_id, kind in delta.added:
351
293
        has_changes = 1
352
 
        print >>to_file, '=== added %s %r' % (kind, path.encode('utf8'))
353
 
        old_name = '%s%s\t%s' % (old_label, path, EPOCH_DATE)
354
 
        new_name = '%s%s\t%s' % (new_label, path,
355
 
                                 _patch_header_date(new_tree, file_id, path))
356
 
        new_tree.inventory[file_id].diff(diff_file, new_name, new_tree,
357
 
                                         old_name, None, None, to_file, 
 
294
        print >>to_file, '=== added %s %r' % (kind, new_label + path)
 
295
        new_tree.inventory[file_id].diff(diff_file, new_label + path, new_tree,
 
296
                                         DEVNULL, None, None, to_file, 
358
297
                                         reverse=True)
359
298
    for (old_path, new_path, file_id, kind,
360
299
         text_modified, meta_modified) in delta.renamed:
361
300
        has_changes = 1
362
301
        prop_str = get_prop_change(meta_modified)
363
302
        print >>to_file, '=== renamed %s %r => %r%s' % (
364
 
                    kind, old_path.encode('utf8'),
365
 
                    new_path.encode('utf8'), prop_str)
366
 
        old_name = '%s%s\t%s' % (old_label, old_path,
367
 
                                 _patch_header_date(old_tree, file_id,
368
 
                                                    old_path))
369
 
        new_name = '%s%s\t%s' % (new_label, new_path,
370
 
                                 _patch_header_date(new_tree, file_id,
371
 
                                                    new_path))
372
 
        _maybe_diff_file_or_symlink(old_name, old_tree, file_id,
373
 
                                    new_name, new_tree,
 
303
                    kind, old_label + old_path, new_label + new_path, prop_str)
 
304
        _maybe_diff_file_or_symlink(old_label, old_path, old_tree, file_id,
 
305
                                    new_label, new_path, new_tree,
374
306
                                    text_modified, kind, to_file, diff_file)
375
307
    for path, file_id, kind, text_modified, meta_modified in delta.modified:
376
308
        has_changes = 1
377
309
        prop_str = get_prop_change(meta_modified)
378
 
        print >>to_file, '=== modified %s %r%s' % (kind, path.encode('utf8'), prop_str)
379
 
        old_name = '%s%s\t%s' % (old_label, path,
380
 
                                 _patch_header_date(old_tree, file_id, path))
381
 
        new_name = '%s%s\t%s' % (new_label, path,
382
 
                                 _patch_header_date(new_tree, file_id, path))
 
310
        print >>to_file, '=== modified %s %r%s' % (kind, old_label + path,
 
311
                    prop_str)
383
312
        if text_modified:
384
 
            _maybe_diff_file_or_symlink(old_name, old_tree, file_id,
385
 
                                        new_name, new_tree,
 
313
            _maybe_diff_file_or_symlink(old_label, path, old_tree, file_id,
 
314
                                        new_label, path, new_tree,
386
315
                                        True, kind, to_file, diff_file)
387
316
 
388
317
    return has_changes
389
318
 
390
319
 
391
 
def _patch_header_date(tree, file_id, path):
392
 
    """Returns a timestamp suitable for use in a patch header."""
393
 
    tm = time.gmtime(tree.get_file_mtime(file_id, path))
394
 
    return time.strftime('%Y-%m-%d %H:%M:%S +0000', tm)
395
 
 
 
320
def _raise_if_doubly_unversioned(specific_files, old_tree, new_tree):
 
321
    """Complain if paths are not versioned in either tree."""
 
322
    if not specific_files:
 
323
        return
 
324
    old_unversioned = old_tree.filter_unversioned_files(specific_files)
 
325
    new_unversioned = new_tree.filter_unversioned_files(specific_files)
 
326
    unversioned = old_unversioned.intersection(new_unversioned)
 
327
    if unversioned:
 
328
        raise errors.PathsNotVersionedError(sorted(unversioned))
 
329
    
396
330
 
397
331
def _raise_if_nonexistent(paths, old_tree, new_tree):
398
332
    """Complain if paths are not in either inventory or tree.
420
354
        return  ""
421
355
 
422
356
 
423
 
def _maybe_diff_file_or_symlink(old_path, old_tree, file_id,
424
 
                                new_path, new_tree, text_modified,
 
357
def _maybe_diff_file_or_symlink(old_label, old_path, old_tree, file_id,
 
358
                                new_label, new_path, new_tree, text_modified,
425
359
                                kind, to_file, diff_file):
426
360
    if text_modified:
427
361
        new_entry = new_tree.inventory[file_id]
428
362
        old_tree.inventory[file_id].diff(diff_file,
429
 
                                         old_path, old_tree,
430
 
                                         new_path, new_entry, 
 
363
                                         old_label + old_path, old_tree,
 
364
                                         new_label + new_path, new_entry, 
431
365
                                         new_tree, to_file)