~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/delta.py

Refactored the export code to make it easier to add new export formats.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2010 Canonical Ltd
2
 
#
 
1
# -*- coding: UTF-8 -*-
 
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
 
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
 
 
17
 
from bzrlib import (
18
 
    osutils,
19
 
    )
20
 
from bzrlib.trace import is_quiet
21
 
 
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
16
 
 
17
from bzrlib.inventory import InventoryEntry
 
18
from bzrlib.trace import mutter
22
19
 
23
20
class TreeDelta(object):
24
21
    """Describes changes from one tree to another.
25
22
 
26
 
    Contains seven lists:
 
23
    Contains four lists:
27
24
 
28
25
    added
29
26
        (path, id, kind)
31
28
        (path, id, kind)
32
29
    renamed
33
30
        (oldpath, newpath, id, kind, text_modified, meta_modified)
34
 
    kind_changed
35
 
        (path, id, old_kind, new_kind)
36
31
    modified
37
32
        (path, id, kind, text_modified, meta_modified)
38
33
    unchanged
39
34
        (path, id, kind)
40
 
    unversioned
41
 
        (path, None, kind)
42
35
 
43
36
    Each id is listed only once.
44
37
 
45
38
    Files that are both modified and renamed are listed only in
46
39
    renamed, with the text_modified flag true. The text_modified
47
 
    applies either to the content of the file or the target of the
 
40
    applies either to the the content of the file or the target of the
48
41
    symbolic link, depending of the kind of file.
49
42
 
50
43
    Files are only considered renamed if their name has changed or
57
50
        self.added = []
58
51
        self.removed = []
59
52
        self.renamed = []
60
 
        self.kind_changed = []
61
53
        self.modified = []
62
54
        self.unchanged = []
63
 
        self.unversioned = []
64
 
        self.missing = []
65
55
 
66
56
    def __eq__(self, other):
67
57
        if not isinstance(other, TreeDelta):
70
60
               and self.removed == other.removed \
71
61
               and self.renamed == other.renamed \
72
62
               and self.modified == other.modified \
73
 
               and self.unchanged == other.unchanged \
74
 
               and self.kind_changed == other.kind_changed \
75
 
               and self.unversioned == other.unversioned
 
63
               and self.unchanged == other.unchanged
76
64
 
77
65
    def __ne__(self, other):
78
66
        return not (self == other)
79
67
 
80
68
    def __repr__(self):
81
 
        return "TreeDelta(added=%r, removed=%r, renamed=%r," \
82
 
            " kind_changed=%r, modified=%r, unchanged=%r," \
83
 
            " unversioned=%r)" % (self.added,
84
 
            self.removed, self.renamed, self.kind_changed, self.modified,
85
 
            self.unchanged, self.unversioned)
 
69
        return "TreeDelta(added=%r, removed=%r, renamed=%r, modified=%r," \
 
70
            " unchanged=%r)" % (self.added, self.removed, self.renamed,
 
71
            self.modified, self.unchanged)
86
72
 
87
73
    def has_changed(self):
88
74
        return bool(self.modified
89
75
                    or self.added
90
76
                    or self.removed
91
 
                    or self.renamed
92
 
                    or self.kind_changed)
 
77
                    or self.renamed)
93
78
 
94
79
    def touches_file_id(self, file_id):
95
80
        """Return True if file_id is modified by this delta."""
100
85
        for v in self.renamed:
101
86
            if v[2] == file_id:
102
87
                return True
103
 
        for v in self.kind_changed:
104
 
            if v[1] == file_id:
105
 
                return True
106
88
        return False
107
 
 
108
 
    def get_changes_as_text(self, show_ids=False, show_unchanged=False,
109
 
                            short_status=False):
110
 
        import StringIO
111
 
        output = StringIO.StringIO()
112
 
        report_delta(output, self, short_status, show_ids, show_unchanged)
113
 
        return output.getvalue()
114
 
 
115
 
 
116
 
def _compare_trees(old_tree, new_tree, want_unchanged, specific_files,
117
 
                   include_root, extra_trees=None,
118
 
                   require_versioned=False, want_unversioned=False):
119
 
    """Worker function that implements Tree.changes_from."""
 
89
            
 
90
 
 
91
    def show(self, to_file, show_ids=False, show_unchanged=False):
 
92
        def show_list(files):
 
93
            for item in files:
 
94
                path, fid, kind = item[:3]
 
95
 
 
96
                if kind == 'directory':
 
97
                    path += '/'
 
98
                elif kind == 'symlink':
 
99
                    path += '@'
 
100
 
 
101
                if len(item) == 5 and item[4]:
 
102
                    path += '*'
 
103
 
 
104
                if show_ids:
 
105
                    print >>to_file, '  %-30s %s' % (path, fid)
 
106
                else:
 
107
                    print >>to_file, ' ', path
 
108
            
 
109
        if self.removed:
 
110
            print >>to_file, 'removed:'
 
111
            show_list(self.removed)
 
112
                
 
113
        if self.added:
 
114
            print >>to_file, 'added:'
 
115
            show_list(self.added)
 
116
 
 
117
        if self.renamed:
 
118
            print >>to_file, 'renamed:'
 
119
            for (oldpath, newpath, fid, kind,
 
120
                 text_modified, meta_modified) in self.renamed:
 
121
                if meta_modified:
 
122
                    newpath += '*'
 
123
                if show_ids:
 
124
                    print >>to_file, '  %s => %s %s' % (oldpath, newpath, fid)
 
125
                else:
 
126
                    print >>to_file, '  %s => %s' % (oldpath, newpath)
 
127
                    
 
128
        if self.modified:
 
129
            print >>to_file, 'modified:'
 
130
            show_list(self.modified)
 
131
            
 
132
        if show_unchanged and self.unchanged:
 
133
            print >>to_file, 'unchanged:'
 
134
            show_list(self.unchanged)
 
135
 
 
136
 
 
137
 
 
138
def compare_trees(old_tree, new_tree, want_unchanged=False, specific_files=None):
 
139
    """Describe changes from one tree to another.
 
140
 
 
141
    Returns a TreeDelta with details of added, modified, renamed, and
 
142
    deleted entries.
 
143
 
 
144
    The root entry is specifically exempt.
 
145
 
 
146
    This only considers versioned files.
 
147
 
 
148
    want_unchanged
 
149
        If true, also list files unchanged from one version to
 
150
        the next.
 
151
 
 
152
    specific_files
 
153
        If true, only check for changes to specified names or
 
154
        files within them.
 
155
    """
 
156
 
 
157
    from osutils import is_inside_any
 
158
    
 
159
    old_inv = old_tree.inventory
 
160
    new_inv = new_tree.inventory
120
161
    delta = TreeDelta()
121
 
    # mutter('start compare_trees')
122
 
 
123
 
    for (file_id, path, content_change, versioned, parent_id, name, kind,
124
 
         executable) in new_tree.iter_changes(old_tree, want_unchanged,
125
 
            specific_files, extra_trees=extra_trees,
126
 
            require_versioned=require_versioned,
127
 
            want_unversioned=want_unversioned):
128
 
        if versioned == (False, False):
129
 
            delta.unversioned.append((path[1], None, kind[1]))
130
 
            continue
131
 
        if not include_root and (None, None) == parent_id:
132
 
            continue
133
 
        fully_present = tuple((versioned[x] and kind[x] is not None) for
134
 
                              x in range(2))
135
 
        if fully_present[0] != fully_present[1]:
136
 
            if fully_present[1] is True:
137
 
                delta.added.append((path[1], file_id, kind[1]))
138
 
            else:
139
 
                delta.removed.append((path[0], file_id, kind[0]))
140
 
        elif fully_present[0] is False:
141
 
            delta.missing.append((path[1], file_id, kind[1]))
142
 
        elif name[0] != name[1] or parent_id[0] != parent_id[1]:
143
 
            # If the name changes, or the parent_id changes, we have a rename
144
 
            # (if we move a parent, that doesn't count as a rename for the
145
 
            # file)
146
 
            delta.renamed.append((path[0],
147
 
                                  path[1],
148
 
                                  file_id,
149
 
                                  kind[1],
150
 
                                  content_change,
151
 
                                  (executable[0] != executable[1])))
152
 
        elif kind[0] != kind[1]:
153
 
            delta.kind_changed.append((path[1], file_id, kind[0], kind[1]))
154
 
        elif content_change or executable[0] != executable[1]:
155
 
            delta.modified.append((path[1], file_id, kind[1],
156
 
                                   content_change,
157
 
                                   (executable[0] != executable[1])))
 
162
    mutter('start compare_trees')
 
163
 
 
164
    # TODO: match for specific files can be rather smarter by finding
 
165
    # the IDs of those files up front and then considering only that.
 
166
 
 
167
    for file_id in old_tree:
 
168
        if file_id in new_tree:
 
169
            old_ie = old_inv[file_id]
 
170
            new_ie = new_inv[file_id]
 
171
 
 
172
            kind = old_ie.kind
 
173
            assert kind == new_ie.kind
 
174
            
 
175
            assert kind in InventoryEntry.known_kinds, \
 
176
                   'invalid file kind %r' % kind
 
177
 
 
178
            if kind == 'root_directory':
 
179
                continue
 
180
            
 
181
            if specific_files:
 
182
                if (not is_inside_any(specific_files, old_inv.id2path(file_id)) 
 
183
                    and not is_inside_any(specific_files, new_inv.id2path(file_id))):
 
184
                    continue
 
185
 
 
186
            # temporary hack until all entries are populated before clients 
 
187
            # get them
 
188
            old_path = old_inv.id2path(file_id)
 
189
            new_path = new_inv.id2path(file_id)
 
190
            old_ie._read_tree_state(old_path, old_tree)
 
191
            new_ie._read_tree_state(new_path, new_tree)
 
192
            text_modified, meta_modified = new_ie.detect_changes(old_ie)
 
193
 
 
194
            # TODO: Can possibly avoid calculating path strings if the
 
195
            # two files are unchanged and their names and parents are
 
196
            # the same and the parents are unchanged all the way up.
 
197
            # May not be worthwhile.
 
198
            
 
199
            if (old_ie.name != new_ie.name
 
200
                or old_ie.parent_id != new_ie.parent_id):
 
201
                delta.renamed.append((old_path,
 
202
                                      new_path,
 
203
                                      file_id, kind,
 
204
                                      text_modified, meta_modified))
 
205
            elif text_modified or meta_modified:
 
206
                delta.modified.append((new_path, file_id, kind,
 
207
                                       text_modified, meta_modified))
 
208
            elif want_unchanged:
 
209
                delta.unchanged.append((new_path, file_id, kind))
158
210
        else:
159
 
            delta.unchanged.append((path[1], file_id, kind[1]))
 
211
            kind = old_inv.get_file_kind(file_id)
 
212
            if kind == 'root_directory':
 
213
                continue
 
214
            old_path = old_inv.id2path(file_id)
 
215
            if specific_files:
 
216
                if not is_inside_any(specific_files, old_path):
 
217
                    continue
 
218
            delta.removed.append((old_path, file_id, kind))
160
219
 
 
220
    mutter('start looking for new files')
 
221
    for file_id in new_inv:
 
222
        if file_id in old_inv:
 
223
            continue
 
224
        kind = new_inv.get_file_kind(file_id)
 
225
        if kind == 'root_directory':
 
226
            continue
 
227
        new_path = new_inv.id2path(file_id)
 
228
        if specific_files:
 
229
            if not is_inside_any(specific_files, new_path):
 
230
                continue
 
231
        delta.added.append((new_path, file_id, kind))
 
232
            
161
233
    delta.removed.sort()
162
234
    delta.added.sort()
163
235
    delta.renamed.sort()
164
 
    delta.missing.sort()
165
 
    # TODO: jam 20060529 These lists shouldn't need to be sorted
166
 
    #       since we added them in alphabetical order.
167
236
    delta.modified.sort()
168
237
    delta.unchanged.sort()
169
238
 
170
239
    return delta
171
 
 
172
 
 
173
 
class _ChangeReporter(object):
174
 
    """Report changes between two trees"""
175
 
 
176
 
    def __init__(self, output=None, suppress_root_add=True,
177
 
                 output_file=None, unversioned_filter=None, view_info=None):
178
 
        """Constructor
179
 
 
180
 
        :param output: a function with the signature of trace.note, i.e.
181
 
            accepts a format and parameters.
182
 
        :param supress_root_add: If true, adding the root will be ignored
183
 
            (i.e. when a tree has just been initted)
184
 
        :param output_file: If supplied, a file-like object to write to.
185
 
            Only one of output and output_file may be supplied.
186
 
        :param unversioned_filter: A filter function to be called on
187
 
            unversioned files. This should return True to ignore a path.
188
 
            By default, no filtering takes place.
189
 
        :param view_info: A tuple of view_name,view_files if only
190
 
            items inside a view are to be reported on, or None for
191
 
            no view filtering.
192
 
        """
193
 
        if output_file is not None:
194
 
            if output is not None:
195
 
                raise BzrError('Cannot specify both output and output_file')
196
 
            def output(fmt, *args):
197
 
                output_file.write((fmt % args) + '\n')
198
 
        self.output = output
199
 
        if self.output is None:
200
 
            from bzrlib import trace
201
 
            self.output = trace.note
202
 
        self.suppress_root_add = suppress_root_add
203
 
        self.modified_map = {'kind changed': 'K',
204
 
                             'unchanged': ' ',
205
 
                             'created': 'N',
206
 
                             'modified': 'M',
207
 
                             'deleted': 'D',
208
 
                             'missing': '!',
209
 
                             }
210
 
        self.versioned_map = {'added': '+', # versioned target
211
 
                              'unchanged': ' ', # versioned in both
212
 
                              'removed': '-', # versioned in source
213
 
                              'unversioned': '?', # versioned in neither
214
 
                              }
215
 
        self.unversioned_filter = unversioned_filter
216
 
        if view_info is None:
217
 
            self.view_name = None
218
 
            self.view_files = []
219
 
        else:
220
 
            self.view_name = view_info[0]
221
 
            self.view_files = view_info[1]
222
 
            self.output("Operating on whole tree but only reporting on "
223
 
                        "'%s' view." % (self.view_name,))
224
 
 
225
 
    def report(self, file_id, paths, versioned, renamed, modified, exe_change,
226
 
               kind):
227
 
        """Report one change to a file
228
 
 
229
 
        :param file_id: The file_id of the file
230
 
        :param path: The old and new paths as generated by Tree.iter_changes.
231
 
        :param versioned: may be 'added', 'removed', 'unchanged', or
232
 
            'unversioned.
233
 
        :param renamed: may be True or False
234
 
        :param modified: may be 'created', 'deleted', 'kind changed',
235
 
            'modified' or 'unchanged'.
236
 
        :param exe_change: True if the execute bit has changed
237
 
        :param kind: A pair of file kinds, as generated by Tree.iter_changes.
238
 
            None indicates no file present.
239
 
        """
240
 
        if is_quiet():
241
 
            return
242
 
        if paths[1] == '' and versioned == 'added' and self.suppress_root_add:
243
 
            return
244
 
        if self.view_files and not osutils.is_inside_any(self.view_files,
245
 
            paths[1]):
246
 
            return
247
 
        if versioned == 'unversioned':
248
 
            # skip ignored unversioned files if needed.
249
 
            if self.unversioned_filter is not None:
250
 
                if self.unversioned_filter(paths[1]):
251
 
                    return
252
 
            # dont show a content change in the output.
253
 
            modified = 'unchanged'
254
 
        # we show both paths in the following situations:
255
 
        # the file versioning is unchanged AND
256
 
        # ( the path is different OR
257
 
        #   the kind is different)
258
 
        if (versioned == 'unchanged' and
259
 
            (renamed or modified == 'kind changed')):
260
 
            if renamed:
261
 
                # on a rename, we show old and new
262
 
                old_path, path = paths
263
 
            else:
264
 
                # if it's not renamed, we're showing both for kind changes
265
 
                # so only show the new path
266
 
                old_path, path = paths[1], paths[1]
267
 
            # if the file is not missing in the source, we show its kind
268
 
            # when we show two paths.
269
 
            if kind[0] is not None:
270
 
                old_path += osutils.kind_marker(kind[0])
271
 
            old_path += " => "
272
 
        elif versioned == 'removed':
273
 
            # not present in target
274
 
            old_path = ""
275
 
            path = paths[0]
276
 
        else:
277
 
            old_path = ""
278
 
            path = paths[1]
279
 
        if renamed:
280
 
            rename = "R"
281
 
        else:
282
 
            rename = self.versioned_map[versioned]
283
 
        # we show the old kind on the new path when the content is deleted.
284
 
        if modified == 'deleted':
285
 
            path += osutils.kind_marker(kind[0])
286
 
        # otherwise we always show the current kind when there is one
287
 
        elif kind[1] is not None:
288
 
            path += osutils.kind_marker(kind[1])
289
 
        if exe_change:
290
 
            exe = '*'
291
 
        else:
292
 
            exe = ' '
293
 
        self.output("%s%s%s %s%s", rename, self.modified_map[modified], exe,
294
 
                    old_path, path)
295
 
 
296
 
def report_changes(change_iterator, reporter):
297
 
    """Report the changes from a change iterator.
298
 
 
299
 
    This is essentially a translation from low-level to medium-level changes.
300
 
    Further processing may be required to produce a human-readable output.
301
 
    Unfortunately, some tree-changing operations are very complex
302
 
    :change_iterator: an iterator or sequence of changes in the format
303
 
        generated by Tree.iter_changes
304
 
    :param reporter: The _ChangeReporter that will report the changes.
305
 
    """
306
 
    versioned_change_map = {
307
 
        (True, True)  : 'unchanged',
308
 
        (True, False) : 'removed',
309
 
        (False, True) : 'added',
310
 
        (False, False): 'unversioned',
311
 
        }
312
 
    for (file_id, path, content_change, versioned, parent_id, name, kind,
313
 
         executable) in change_iterator:
314
 
        exe_change = False
315
 
        # files are "renamed" if they are moved or if name changes, as long
316
 
        # as it had a value
317
 
        if None not in name and None not in parent_id and\
318
 
            (name[0] != name[1] or parent_id[0] != parent_id[1]):
319
 
            renamed = True
320
 
        else:
321
 
            renamed = False
322
 
        if kind[0] != kind[1]:
323
 
            if kind[0] is None:
324
 
                modified = "created"
325
 
            elif kind[1] is None:
326
 
                modified = "deleted"
327
 
            else:
328
 
                modified = "kind changed"
329
 
        else:
330
 
            if content_change:
331
 
                modified = "modified"
332
 
            elif kind[0] is None:
333
 
                modified = "missing"
334
 
            else:
335
 
                modified = "unchanged"
336
 
            if kind[1] == "file":
337
 
                exe_change = (executable[0] != executable[1])
338
 
        versioned_change = versioned_change_map[versioned]
339
 
        reporter.report(file_id, path, versioned_change, renamed, modified,
340
 
                        exe_change, kind)
341
 
 
342
 
def report_delta(to_file, delta, short_status=False, show_ids=False, 
343
 
         show_unchanged=False, indent='', filter=None):
344
 
    """Output this delta in status-like form to to_file.
345
 
 
346
 
    :param to_file: A file-like object where the output is displayed.
347
 
 
348
 
    :param delta: A TreeDelta containing the changes to be displayed
349
 
 
350
 
    :param short_status: Single-line status if True.
351
 
 
352
 
    :param show_ids: Output the file ids if True.
353
 
 
354
 
    :param show_unchanged: Output the unchanged files if True.
355
 
 
356
 
    :param indent: Added at the beginning of all output lines (for merged
357
 
        revisions).
358
 
 
359
 
    :param filter: A callable receiving a path and a file id and
360
 
        returning True if the path should be displayed.
361
 
    """
362
 
 
363
 
    def decorate_path(path, kind, meta_modified=None):
364
 
        if kind == 'directory':
365
 
            path += '/'
366
 
        elif kind == 'symlink':
367
 
            path += '@'
368
 
        if meta_modified:
369
 
            path += '*'
370
 
        return path
371
 
 
372
 
    def show_more_renamed(item):
373
 
        (oldpath, file_id, kind,
374
 
         text_modified, meta_modified, newpath) = item
375
 
        dec_new_path = decorate_path(newpath, kind, meta_modified)
376
 
        to_file.write(' => %s' % dec_new_path)
377
 
        if text_modified or meta_modified:
378
 
            extra_modified.append((newpath, file_id, kind,
379
 
                                   text_modified, meta_modified))
380
 
 
381
 
    def show_more_kind_changed(item):
382
 
        (path, file_id, old_kind, new_kind) = item
383
 
        to_file.write(' (%s => %s)' % (old_kind, new_kind))
384
 
 
385
 
    def show_path(path, file_id, kind, meta_modified,
386
 
                  default_format, with_file_id_format):
387
 
        dec_path = decorate_path(path, kind, meta_modified)
388
 
        if show_ids:
389
 
            to_file.write(with_file_id_format % dec_path)
390
 
        else:
391
 
            to_file.write(default_format % dec_path)
392
 
 
393
 
    def show_list(files, long_status_name, short_status_letter,
394
 
                  default_format='%s', with_file_id_format='%-30s',
395
 
                  show_more=None):
396
 
        if files:
397
 
            header_shown = False
398
 
            if short_status:
399
 
                prefix = short_status_letter
400
 
            else:
401
 
                prefix = ''
402
 
            prefix = indent + prefix + '  '
403
 
 
404
 
            for item in files:
405
 
                path, file_id, kind = item[:3]
406
 
                if (filter is not None and not filter(path, file_id)):
407
 
                    continue
408
 
                if not header_shown and not short_status:
409
 
                    to_file.write(indent + long_status_name + ':\n')
410
 
                    header_shown = True
411
 
                meta_modified = None
412
 
                if len(item) == 5:
413
 
                    meta_modified = item[4]
414
 
 
415
 
                to_file.write(prefix)
416
 
                show_path(path, file_id, kind, meta_modified,
417
 
                          default_format, with_file_id_format)
418
 
                if show_more is not None:
419
 
                    show_more(item)
420
 
                if show_ids:
421
 
                    to_file.write(' %s' % file_id)
422
 
                to_file.write('\n')
423
 
 
424
 
    show_list(delta.removed, 'removed', 'D')
425
 
    show_list(delta.added, 'added', 'A')
426
 
    show_list(delta.missing, 'missing', '!')
427
 
    extra_modified = []
428
 
    # Reorder delta.renamed tuples so that all lists share the same
429
 
    # order for their 3 first fields and that they also begin like
430
 
    # the delta.modified tuples
431
 
    renamed = [(p, i, k, tm, mm, np)
432
 
               for  p, np, i, k, tm, mm  in delta.renamed]
433
 
    show_list(renamed, 'renamed', 'R', with_file_id_format='%s',
434
 
              show_more=show_more_renamed)
435
 
    show_list(delta.kind_changed, 'kind changed', 'K',
436
 
              with_file_id_format='%s',
437
 
              show_more=show_more_kind_changed)
438
 
    show_list(delta.modified + extra_modified, 'modified', 'M')
439
 
    if show_unchanged:
440
 
        show_list(delta.unchanged, 'unchanged', 'S')
441
 
 
442
 
    show_list(delta.unversioned, 'unknown', ' ')
443