~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/diff.py

  • Committer: Robert Collins
  • Date: 2005-10-11 07:00:25 UTC
  • mto: This revision was merged to the branch mainline in revision 1443.
  • Revision ID: robertc@robertcollins.net-20051011070025-bac6b53cb6186dfd
create a config module - there is enough config logic to make this worthwhile, and start testing config processing.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
#! /usr/bin/env python
2
1
# -*- coding: UTF-8 -*-
3
2
 
4
3
# This program is free software; you can redistribute it and/or modify
15
14
# along with this program; if not, write to the Free Software
16
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
17
16
 
18
 
from trace import mutter
19
 
from errors import BzrError
 
17
from bzrlib.trace import mutter
 
18
from bzrlib.errors import BzrError
 
19
from bzrlib.delta import compare_trees
20
20
 
 
21
# TODO: Rather than building a changeset object, we should probably
 
22
# invoke callbacks on an object.  That object can either accumulate a
 
23
# list, write them out directly, etc etc.
21
24
 
22
25
def internal_diff(old_label, oldlines, new_label, newlines, to_file):
23
26
    import difflib
38
41
    if not oldlines and not newlines:
39
42
        return
40
43
 
41
 
    nonl = False
42
 
 
43
 
    if oldlines and (oldlines[-1][-1] != '\n'):
44
 
        oldlines[-1] += '\n'
45
 
        nonl = True
46
 
    if newlines and (newlines[-1][-1] != '\n'):
47
 
        newlines[-1] += '\n'
48
 
        nonl = True
49
 
 
50
44
    ud = difflib.unified_diff(oldlines, newlines,
51
45
                              fromfile=old_label, tofile=new_label)
52
46
 
 
47
    ud = list(ud)
53
48
    # work-around for difflib being too smart for its own good
54
49
    # if /dev/null is "1,0", patch won't recognize it as /dev/null
55
50
    if not oldlines:
56
 
        ud = list(ud)
57
51
        ud[2] = ud[2].replace('-1,0', '-0,0')
58
52
    elif not newlines:
59
 
        ud = list(ud)
60
53
        ud[2] = ud[2].replace('+1,0', '+0,0')
 
54
    # work around for difflib emitting random spaces after the label
 
55
    ud[0] = ud[0][:-2] + '\n'
 
56
    ud[1] = ud[1][:-2] + '\n'
61
57
 
62
 
    to_file.writelines(ud)
63
 
    if nonl:
64
 
        print >>to_file, "\\ No newline at end of file"
 
58
    for line in ud:
 
59
        to_file.write(line)
 
60
        if not line.endswith('\n'):
 
61
            to_file.write("\n\\ No newline at end of file\n")
65
62
    print >>to_file
66
63
 
67
64
 
68
 
 
69
 
 
70
 
def external_diff(old_label, oldlines, new_label, newlines, to_file):
 
65
def external_diff(old_label, oldlines, new_label, newlines, to_file,
 
66
                  diff_opts):
71
67
    """Display a diff by calling out to the external diff program."""
72
68
    import sys
73
69
    
75
71
        raise NotImplementedError("sorry, can't send external diff other than to stdout yet",
76
72
                                  to_file)
77
73
 
 
74
    # make sure our own output is properly ordered before the diff
 
75
    to_file.flush()
 
76
 
78
77
    from tempfile import NamedTemporaryFile
79
 
    from os import system
 
78
    import os
80
79
 
81
80
    oldtmpf = NamedTemporaryFile()
82
81
    newtmpf = NamedTemporaryFile()
89
88
        # regular named file (e.g. in the working directory) then we can
90
89
        # compare directly to that, rather than copying it.
91
90
 
92
 
        # TODO: Set the labels appropriately
93
 
 
94
91
        oldtmpf.writelines(oldlines)
95
92
        newtmpf.writelines(newlines)
96
93
 
97
94
        oldtmpf.flush()
98
95
        newtmpf.flush()
99
96
 
100
 
        system('diff -u --label %s %s --label %s %s' % (old_label, oldtmpf.name, new_label, newtmpf.name))
 
97
        if not diff_opts:
 
98
            diff_opts = []
 
99
        diffcmd = ['diff',
 
100
                   '--label', old_label,
 
101
                   oldtmpf.name,
 
102
                   '--label', new_label,
 
103
                   newtmpf.name]
 
104
 
 
105
        # diff only allows one style to be specified; they don't override.
 
106
        # note that some of these take optargs, and the optargs can be
 
107
        # directly appended to the options.
 
108
        # this is only an approximate parser; it doesn't properly understand
 
109
        # the grammar.
 
110
        for s in ['-c', '-u', '-C', '-U',
 
111
                  '-e', '--ed',
 
112
                  '-q', '--brief',
 
113
                  '--normal',
 
114
                  '-n', '--rcs',
 
115
                  '-y', '--side-by-side',
 
116
                  '-D', '--ifdef']:
 
117
            for j in diff_opts:
 
118
                if j.startswith(s):
 
119
                    break
 
120
            else:
 
121
                continue
 
122
            break
 
123
        else:
 
124
            diffcmd.append('-u')
 
125
                  
 
126
        if diff_opts:
 
127
            diffcmd.extend(diff_opts)
 
128
 
 
129
        rc = os.spawnvp(os.P_WAIT, 'diff', diffcmd)
 
130
        
 
131
        if rc != 0 and rc != 1:
 
132
            # returns 1 if files differ; that's OK
 
133
            if rc < 0:
 
134
                msg = 'signal %d' % (-rc)
 
135
            else:
 
136
                msg = 'exit code %d' % rc
 
137
                
 
138
            raise BzrError('external diff failed with %s; command: %r' % (rc, diffcmd))
101
139
    finally:
102
140
        oldtmpf.close()                 # and delete
103
141
        newtmpf.close()
 
142
 
 
143
def show_diff(b, from_spec, specific_files, external_diff_options=None,
 
144
              revision2=None, output=None):
 
145
    """Shortcut for showing the diff to the working tree.
 
146
 
 
147
    b
 
148
        Branch.
 
149
 
 
150
    revision
 
151
        None for 'basis tree', or otherwise the old revision to compare against.
104
152
    
105
 
 
106
 
 
107
 
def diff_file(old_label, oldlines, new_label, newlines, to_file):
108
 
    if False:
109
 
        differ = external_diff
110
 
    else:
111
 
        differ = internal_diff
112
 
 
113
 
    differ(old_label, oldlines, new_label, newlines, to_file)
114
 
 
115
 
 
116
 
 
117
 
def show_diff(b, revision, specific_files):
118
 
    import sys
119
 
 
120
 
    if revision == None:
 
153
    The more general form is show_diff_trees(), where the caller
 
154
    supplies any two trees.
 
155
    """
 
156
    if output is None:
 
157
        import sys
 
158
        output = sys.stdout
 
159
 
 
160
    if from_spec is None:
121
161
        old_tree = b.basis_tree()
122
162
    else:
123
 
        old_tree = b.revision_tree(b.lookup_revision(revision))
124
 
        
125
 
    new_tree = b.working_tree()
126
 
 
127
 
    show_diff_trees(old_tree, new_tree, sys.stdout, specific_files)
128
 
 
129
 
 
130
 
 
131
 
def show_diff_trees(old_tree, new_tree, to_file, specific_files=None):
 
163
        old_tree = b.revision_tree(from_spec.in_history(b).rev_id)
 
164
 
 
165
    if revision2 is None:
 
166
        new_tree = b.working_tree()
 
167
    else:
 
168
        new_tree = b.revision_tree(revision2.in_history(b).rev_id)
 
169
 
 
170
    show_diff_trees(old_tree, new_tree, output, specific_files,
 
171
                    external_diff_options)
 
172
 
 
173
 
 
174
 
 
175
def show_diff_trees(old_tree, new_tree, to_file, specific_files=None,
 
176
                    external_diff_options=None):
132
177
    """Show in text form the changes from one tree to another.
133
178
 
134
179
    to_files
135
180
        If set, include only changes to these files.
 
181
 
 
182
    external_diff_options
 
183
        If set, use an external GNU diff and pass these options.
136
184
    """
137
185
 
138
186
    # TODO: Options to control putting on a prefix or suffix, perhaps as a format string
147
195
    # TODO: Generation of pseudo-diffs for added/deleted files could
148
196
    # be usefully made into a much faster special case.
149
197
 
 
198
    if external_diff_options:
 
199
        assert isinstance(external_diff_options, basestring)
 
200
        opts = external_diff_options.split()
 
201
        def diff_file(olab, olines, nlab, nlines, to_file):
 
202
            external_diff(olab, olines, nlab, nlines, to_file, opts)
 
203
    else:
 
204
        diff_file = internal_diff
 
205
    
 
206
 
150
207
    delta = compare_trees(old_tree, new_tree, want_unchanged=False,
151
208
                          specific_files=specific_files)
152
209
 
153
210
    for path, file_id, kind in delta.removed:
154
 
        print '*** removed %s %r' % (kind, path)
155
 
        if kind == 'file':
156
 
            diff_file(old_label + path,
157
 
                      old_tree.get_file(file_id).readlines(),
158
 
                      DEVNULL, 
159
 
                      [],
160
 
                      to_file)
161
 
 
 
211
        print >>to_file, '=== removed %s %r' % (kind, path)
 
212
        old_tree.inventory[file_id].diff(diff_file, old_label + path, old_tree,
 
213
                                         DEVNULL, None, None, to_file)
162
214
    for path, file_id, kind in delta.added:
163
 
        print '*** added %s %r' % (kind, path)
164
 
        if kind == 'file':
165
 
            diff_file(DEVNULL,
166
 
                      [],
167
 
                      new_label + path,
168
 
                      new_tree.get_file(file_id).readlines(),
169
 
                      to_file)
170
 
 
171
 
    for old_path, new_path, file_id, kind, text_modified in delta.renamed:
172
 
        print '*** renamed %s %r => %r' % (kind, old_path, new_path)
 
215
        print >>to_file, '=== added %s %r' % (kind, path)
 
216
        new_tree.inventory[file_id].diff(diff_file, new_label + path, new_tree,
 
217
                                         DEVNULL, None, None, to_file, 
 
218
                                         reverse=True)
 
219
    for (old_path, new_path, file_id, kind,
 
220
         text_modified, meta_modified) in delta.renamed:
 
221
        prop_str = get_prop_change(meta_modified)
 
222
        print >>to_file, '=== renamed %s %r => %r%s' % (
 
223
                          kind, old_path, new_path, prop_str)
 
224
        _maybe_diff_file_or_symlink(old_label, old_path, old_tree, file_id,
 
225
                                    new_label, new_path, new_tree,
 
226
                                    text_modified, kind, to_file, diff_file)
 
227
    for path, file_id, kind, text_modified, meta_modified in delta.modified:
 
228
        prop_str = get_prop_change(meta_modified)
 
229
        print >>to_file, '=== modified %s %r%s' % (kind, path, prop_str)
173
230
        if text_modified:
174
 
            diff_file(old_label + old_path,
175
 
                      old_tree.get_file(file_id).readlines(),
176
 
                      new_label + new_path,
177
 
                      new_tree.get_file(file_id).readlines(),
178
 
                      to_file)
179
 
 
180
 
    for path, file_id, kind in delta.modified:
181
 
        print '*** modified %s %r' % (kind, path)
182
 
        if kind == 'file':
183
 
            diff_file(old_label + path,
184
 
                      old_tree.get_file(file_id).readlines(),
185
 
                      new_label + path,
186
 
                      new_tree.get_file(file_id).readlines(),
187
 
                      to_file)
188
 
 
189
 
 
190
 
 
191
 
class TreeDelta(object):
192
 
    """Describes changes from one tree to another.
193
 
 
194
 
    Contains four lists:
195
 
 
196
 
    added
197
 
        (path, id, kind)
198
 
    removed
199
 
        (path, id, kind)
200
 
    renamed
201
 
        (oldpath, newpath, id, kind, text_modified)
202
 
    modified
203
 
        (path, id, kind)
204
 
    unchanged
205
 
        (path, id, kind)
206
 
 
207
 
    Each id is listed only once.
208
 
 
209
 
    Files that are both modified and renamed are listed only in
210
 
    renamed, with the text_modified flag true.
211
 
 
212
 
    The lists are normally sorted when the delta is created.
213
 
    """
214
 
    def __init__(self):
215
 
        self.added = []
216
 
        self.removed = []
217
 
        self.renamed = []
218
 
        self.modified = []
219
 
        self.unchanged = []
220
 
 
221
 
 
222
 
    def touches_file_id(self, file_id):
223
 
        """Return True if file_id is modified by this delta."""
224
 
        for l in self.added, self.removed, self.modified:
225
 
            for v in l:
226
 
                if v[1] == file_id:
227
 
                    return True
228
 
        for v in self.renamed:
229
 
            if v[2] == file_id:
230
 
                return True
231
 
        return False
232
 
            
233
 
 
234
 
    def show(self, to_file, show_ids=False, show_unchanged=False):
235
 
        def show_list(files):
236
 
            for path, fid, kind in files:
237
 
                if kind == 'directory':
238
 
                    path += '/'
239
 
                elif kind == 'symlink':
240
 
                    path += '@'
241
 
                    
242
 
                if show_ids:
243
 
                    print >>to_file, '  %-30s %s' % (path, fid)
244
 
                else:
245
 
                    print >>to_file, ' ', path
246
 
            
247
 
        if self.removed:
248
 
            print >>to_file, 'removed:'
249
 
            show_list(self.removed)
250
 
                
251
 
        if self.added:
252
 
            print >>to_file, 'added:'
253
 
            show_list(self.added)
254
 
 
255
 
        if self.renamed:
256
 
            print >>to_file, 'renamed:'
257
 
            for oldpath, newpath, fid, kind, text_modified in self.renamed:
258
 
                if show_ids:
259
 
                    print >>to_file, '  %s => %s %s' % (oldpath, newpath, fid)
260
 
                else:
261
 
                    print >>to_file, '  %s => %s' % (oldpath, newpath)
262
 
                    
263
 
        if self.modified:
264
 
            print >>to_file, 'modified:'
265
 
            show_list(self.modified)
266
 
            
267
 
        if show_unchanged and self.unchanged:
268
 
            print >>to_file, 'unchanged:'
269
 
            show_list(self.unchanged)
270
 
 
271
 
 
272
 
 
273
 
def compare_trees(old_tree, new_tree, want_unchanged, specific_files=None):
274
 
    """Describe changes from one tree to another.
275
 
 
276
 
    Returns a TreeDelta with details of added, modified, renamed, and
277
 
    deleted entries.
278
 
 
279
 
    The root entry is specifically exempt.
280
 
 
281
 
    This only considers versioned files.
282
 
 
283
 
    want_unchanged
284
 
        If true, also list files unchanged from one version to
285
 
        the next.
286
 
 
287
 
    specific_files
288
 
        If true, only check for changes to specified names or
289
 
        files within them.
290
 
    """
291
 
 
292
 
    from osutils import is_inside_any
 
231
            _maybe_diff_file_or_symlink(old_label, path, old_tree, file_id,
 
232
                                        new_label, path, new_tree,
 
233
                                        True, kind, to_file, diff_file)
293
234
    
294
 
    old_inv = old_tree.inventory
295
 
    new_inv = new_tree.inventory
296
 
    delta = TreeDelta()
297
 
    mutter('start compare_trees')
298
 
 
299
 
    # TODO: match for specific files can be rather smarter by finding
300
 
    # the IDs of those files up front and then considering only that.
301
 
 
302
 
    for file_id in old_tree:
303
 
        if file_id in new_tree:
304
 
            kind = old_inv.get_file_kind(file_id)
305
 
            assert kind == new_inv.get_file_kind(file_id)
306
 
            
307
 
            assert kind in ('file', 'directory', 'symlink', 'root_directory'), \
308
 
                   'invalid file kind %r' % kind
309
 
 
310
 
            if kind == 'root_directory':
311
 
                continue
312
 
            
313
 
            old_path = old_inv.id2path(file_id)
314
 
            new_path = new_inv.id2path(file_id)
315
 
 
316
 
            if specific_files:
317
 
                if (not is_inside_any(specific_files, old_path) 
318
 
                    and not is_inside_any(specific_files, new_path)):
319
 
                    continue
320
 
 
321
 
            if kind == 'file':
322
 
                old_sha1 = old_tree.get_file_sha1(file_id)
323
 
                new_sha1 = new_tree.get_file_sha1(file_id)
324
 
                text_modified = (old_sha1 != new_sha1)
325
 
            else:
326
 
                ## mutter("no text to check for %r %r" % (file_id, kind))
327
 
                text_modified = False
328
 
 
329
 
            # TODO: Can possibly avoid calculating path strings if the
330
 
            # two files are unchanged and their names and parents are
331
 
            # the same and the parents are unchanged all the way up.
332
 
            # May not be worthwhile.
333
 
            
334
 
            if old_path != new_path:
335
 
                delta.renamed.append((old_path, new_path, file_id, kind,
336
 
                                      text_modified))
337
 
            elif text_modified:
338
 
                delta.modified.append((new_path, file_id, kind))
339
 
            elif want_unchanged:
340
 
                delta.unchanged.append((new_path, file_id, kind))
341
 
        else:
342
 
            kind = old_inv.get_file_kind(file_id)
343
 
            old_path = old_inv.id2path(file_id)
344
 
            if specific_files:
345
 
                if not is_inside_any(specific_files, old_path):
346
 
                    continue
347
 
            delta.removed.append((old_path, file_id, kind))
348
 
 
349
 
    mutter('start looking for new files')
350
 
    for file_id in new_inv:
351
 
        if file_id in old_inv:
352
 
            continue
353
 
        new_path = new_inv.id2path(file_id)
354
 
        if specific_files:
355
 
            if not is_inside_any(specific_files, new_path):
356
 
                continue
357
 
        kind = new_inv.get_file_kind(file_id)
358
 
        delta.added.append((new_path, file_id, kind))
359
 
            
360
 
    delta.removed.sort()
361
 
    delta.added.sort()
362
 
    delta.renamed.sort()
363
 
    delta.modified.sort()
364
 
    delta.unchanged.sort()
365
 
 
366
 
    return delta
 
235
 
 
236
def get_prop_change(meta_modified):
 
237
    if meta_modified:
 
238
        return " (properties changed)"
 
239
    else:
 
240
        return  ""
 
241
 
 
242
 
 
243
def _maybe_diff_file_or_symlink(old_label, old_path, old_tree, file_id,
 
244
                                new_label, new_path, new_tree, text_modified,
 
245
                                kind, to_file, diff_file):
 
246
    if text_modified:
 
247
        new_entry = new_tree.inventory[file_id]
 
248
        old_tree.inventory[file_id].diff(diff_file,
 
249
                                         old_label + old_path, old_tree,
 
250
                                         new_label + new_path, new_entry, 
 
251
                                         new_tree, to_file)