/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: Matthieu Moy
  • Date: 2006-07-08 19:32:30 UTC
  • mfrom: (1845 +trunk)
  • mto: This revision was merged to the branch mainline in revision 1857.
  • Revision ID: Matthieu.Moy@imag.fr-20060708193230-3eb72d871471bd5b
merge

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