~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/bundle/serializer/v07.py

  • Committer: Aaron Bentley
  • Date: 2006-06-21 14:30:57 UTC
  • mfrom: (1801.1.1 bzr.dev)
  • mto: This revision was merged to the branch mainline in revision 1803.
  • Revision ID: abentley@panoramicfeedback.com-20060621143057-776e4b8d707e430e
Install benchmarks. (Jelmer Vernooij)

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2006, 2009 Canonical Ltd
 
1
# (C) 2005 Canonical Development 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
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
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
16
 
17
17
"""Serializer factory for reading and writing bundles.
18
18
"""
19
19
 
20
20
import os
21
21
 
22
 
from bzrlib import (
23
 
    errors,
24
 
    ui,
25
 
    )
26
 
from bzrlib.bundle.serializer import (BundleSerializer,
27
 
                                      _get_bundle_header,
 
22
from bzrlib.bundle.serializer import (BundleSerializer, 
 
23
                                      BUNDLE_HEADER, 
 
24
                                      format_highres_date,
 
25
                                      unpack_highres_date,
28
26
                                     )
29
27
from bzrlib.bundle.serializer import binary_diff
30
28
from bzrlib.bundle.bundle_data import (RevisionInfo, BundleInfo, BundleTree)
 
29
from bzrlib.delta import compare_trees
31
30
from bzrlib.diff import internal_diff
 
31
import bzrlib.errors as errors
32
32
from bzrlib.osutils import pathjoin
 
33
from bzrlib.progress import DummyProgress
33
34
from bzrlib.revision import NULL_REVISION
 
35
from bzrlib.rio import RioWriter, read_stanzas
 
36
import bzrlib.ui
34
37
from bzrlib.testament import StrictTestament
35
 
from bzrlib.timestamp import (
36
 
    format_highres_date,
37
 
    unpack_highres_date,
38
 
)
39
38
from bzrlib.textfile import text_file
40
39
from bzrlib.trace import mutter
41
40
 
56
55
        else:
57
56
            self.properties = properties
58
57
 
59
 
    def add_utf8_property(self, name, value):
60
 
        """Add a property whose value is currently utf8 to the action."""
61
 
        self.properties.append((name, value.decode('utf8')))
62
 
 
63
58
    def add_property(self, name, value):
64
59
        """Add a property to the action"""
65
60
        self.properties.append((name, value))
91
86
        to_file.write(text_line+'\n')
92
87
 
93
88
 
94
 
class BundleSerializerV08(BundleSerializer):
 
89
class BundleSerializerV07(BundleSerializer):
95
90
    def read(self, f):
96
91
        """Read the rest of the bundles from the supplied file.
97
92
 
100
95
        """
101
96
        return BundleReader(f).info
102
97
 
103
 
    def check_compatible(self):
104
 
        if self.source.supports_rich_root():
105
 
            raise errors.IncompatibleBundleFormat('0.8', repr(self.source))
106
 
 
107
98
    def write(self, source, revision_ids, forced_bases, f):
108
99
        """Write the bundless to the supplied files.
109
100
 
116
107
        self.revision_ids = revision_ids
117
108
        self.forced_bases = forced_bases
118
109
        self.to_file = f
119
 
        self.check_compatible()
120
110
        source.lock_read()
121
111
        try:
122
112
            self._write_main_header()
123
 
            pb = ui.ui_factory.nested_progress_bar()
 
113
            pb = DummyProgress()
124
114
            try:
125
115
                self._write_revisions(pb)
126
116
            finally:
127
 
                pb.finished()
 
117
                pass
 
118
                #pb.finished()
128
119
        finally:
129
120
            source.unlock()
130
121
 
131
 
    def write_bundle(self, repository, target, base, fileobj):
132
 
        return self._write_bundle(repository, target, base, fileobj)
133
 
 
134
122
    def _write_main_header(self):
135
123
        """Write the header for the changes"""
136
124
        f = self.to_file
137
 
        f.write(_get_bundle_header('0.8'))
 
125
        f.write(BUNDLE_HEADER)
 
126
        f.write('0.7\n')
138
127
        f.write('#\n')
139
128
 
140
 
    def _write(self, key, value, indent=1, trailing_space_when_empty=False):
141
 
        """Write out meta information, with proper indenting, etc.
142
 
 
143
 
        :param trailing_space_when_empty: To work around a bug in earlier
144
 
            bundle readers, when writing an empty property, we use "prop: \n"
145
 
            rather than writing "prop:\n".
146
 
            If this parameter is True, and value is the empty string, we will
147
 
            write an extra space.
148
 
        """
149
 
        if indent < 1:
150
 
            raise ValueError('indentation must be greater than 0')
 
129
    def _write(self, key, value, indent=1):
 
130
        """Write out meta information, with proper indenting, etc"""
 
131
        assert indent > 0, 'indentation must be greater than 0'
151
132
        f = self.to_file
152
133
        f.write('#' + (' ' * indent))
153
134
        f.write(key.encode('utf-8'))
154
135
        if not value:
155
 
            if trailing_space_when_empty and value == '':
156
 
                f.write(': \n')
157
 
            else:
158
 
                f.write(':\n')
159
 
        elif isinstance(value, str):
160
 
            f.write(': ')
161
 
            f.write(value)
162
 
            f.write('\n')
163
 
        elif isinstance(value, unicode):
 
136
            f.write(':\n')
 
137
        elif isinstance(value, basestring):
164
138
            f.write(': ')
165
139
            f.write(value.encode('utf-8'))
166
140
            f.write('\n')
168
142
            f.write(':\n')
169
143
            for entry in value:
170
144
                f.write('#' + (' ' * (indent+2)))
171
 
                if isinstance(entry, str):
172
 
                    f.write(entry)
173
 
                else:
174
 
                    f.write(entry.encode('utf-8'))
 
145
                f.write(entry.encode('utf-8'))
175
146
                f.write('\n')
176
147
 
177
148
    def _write_revisions(self, pb):
181
152
        last_rev_id = None
182
153
        last_rev_tree = None
183
154
 
184
 
        i_max = len(self.revision_ids)
 
155
        i_max = len(self.revision_ids) 
185
156
        for i, rev_id in enumerate(self.revision_ids):
186
 
            pb.update("Generating revision data", i, i_max)
 
157
            pb.update("Generating revsion data", i, i_max)
187
158
            rev = self.source.get_revision(rev_id)
188
159
            if rev_id == last_rev_id:
189
160
                rev_tree = last_rev_tree
190
161
            else:
191
 
                rev_tree = self.source.revision_tree(rev_id)
 
162
                base_tree = self.source.revision_tree(rev_id)
 
163
            rev_tree = self.source.revision_tree(rev_id)
192
164
            if rev_id in self.forced_bases:
193
165
                explicit_base = True
194
166
                base_id = self.forced_bases[rev_id]
206
178
            else:
207
179
                base_tree = self.source.revision_tree(base_id)
208
180
            force_binary = (i != 0)
209
 
            self._write_revision(rev, rev_tree, base_id, base_tree,
 
181
            self._write_revision(rev, rev_tree, base_id, base_tree, 
210
182
                                 explicit_base, force_binary)
211
183
 
212
184
            last_rev_id = base_id
213
185
            last_rev_tree = base_tree
214
186
 
215
 
    def _testament_sha1(self, revision_id):
216
 
        return StrictTestament.from_revision(self.source,
217
 
                                             revision_id).as_sha1()
218
 
 
219
 
    def _write_revision(self, rev, rev_tree, base_rev, base_tree,
 
187
    def _write_revision(self, rev, rev_tree, base_rev, base_tree, 
220
188
                        explicit_base, force_binary):
221
189
        """Write out the information for a revision."""
222
190
        def w(key, value):
230
198
        self._write_delta(rev_tree, base_tree, rev.revision_id, force_binary)
231
199
 
232
200
        w('revision id', rev.revision_id)
233
 
        w('sha1', self._testament_sha1(rev.revision_id))
 
201
        w('sha1', StrictTestament.from_revision(self.source, 
 
202
                                                rev.revision_id).as_sha1())
234
203
        w('inventory sha1', rev.inventory_sha1)
235
204
        if rev.parent_ids:
236
205
            w('parent ids', rev.parent_ids)
238
207
            w('base id', base_rev)
239
208
        if rev.properties:
240
209
            self._write('properties', None, indent=1)
241
 
            for name, value in sorted(rev.properties.items()):
242
 
                self._write(name, value, indent=3,
243
 
                            trailing_space_when_empty=True)
244
 
 
 
210
            for name, value in rev.properties.items():
 
211
                self._write(name, value, indent=3)
 
212
        
245
213
        # Add an extra blank space at the end
246
214
        self.to_file.write('\n')
247
215
 
254
222
        self.to_file.write(' // '.join(p_texts).encode('utf-8'))
255
223
        self.to_file.write('\n')
256
224
 
257
 
    def _write_delta(self, new_tree, old_tree, default_revision_id,
 
225
    def _write_delta(self, new_tree, old_tree, default_revision_id, 
258
226
                     force_binary):
259
227
        """Write out the changes between the trees."""
260
228
        DEVNULL = '/dev/null'
277
245
                old_lines = tree_lines(old_tree, require_text=True)
278
246
                new_lines = tree_lines(new_tree, require_text=True)
279
247
                action.write(self.to_file)
280
 
                internal_diff(old_path, old_lines, new_path, new_lines,
 
248
                internal_diff(old_path, old_lines, new_path, new_lines, 
281
249
                              self.to_file)
282
250
            except errors.BinaryFile:
283
251
                old_lines = tree_lines(old_tree, require_text=False)
284
252
                new_lines = tree_lines(new_tree, require_text=False)
285
253
                action.add_property('encoding', 'base64')
286
254
                action.write(self.to_file)
287
 
                binary_diff(old_path, old_lines, new_path, new_lines,
 
255
                binary_diff(old_path, old_lines, new_path, new_lines, 
288
256
                            self.to_file)
289
257
 
290
258
        def finish_action(action, file_id, kind, meta_modified, text_modified,
291
259
                          old_path, new_path):
292
260
            entry = new_tree.inventory[file_id]
293
261
            if entry.revision != default_revision_id:
294
 
                action.add_utf8_property('last-changed', entry.revision)
 
262
                action.add_property('last-changed', entry.revision)
295
263
            if meta_modified:
296
264
                action.add_bool_property('executable', entry.executable)
297
265
            if text_modified and kind == "symlink":
301
269
            else:
302
270
                action.write(self.to_file)
303
271
 
304
 
        delta = new_tree.changes_from(old_tree, want_unchanged=True,
305
 
                                      include_root=True)
 
272
        delta = compare_trees(old_tree, new_tree, want_unchanged=True)
306
273
        for path, file_id, kind in delta.removed:
307
274
            action = Action('removed', [kind, path]).write(self.to_file)
308
275
 
309
276
        for path, file_id, kind in delta.added:
310
277
            action = Action('added', [kind, path], [('file-id', file_id)])
311
 
            meta_modified = (kind=='file' and
 
278
            meta_modified = (kind=='file' and 
312
279
                             new_tree.is_executable(file_id))
313
280
            finish_action(action, file_id, kind, meta_modified, True,
314
281
                          DEVNULL, path)
332
299
                continue
333
300
            old_rev = getattr(old_tree.inventory[ie.file_id], 'revision', None)
334
301
            if new_rev != old_rev:
335
 
                action = Action('modified', [ie.kind,
 
302
                action = Action('modified', [ie.kind, 
336
303
                                             new_tree.id2path(ie.file_id)])
337
 
                action.add_utf8_property('last-changed', ie.revision)
 
304
                action.add_property('last-changed', ie.revision)
338
305
                action.write(self.to_file)
339
306
 
340
307
 
350
317
        object.__init__(self)
351
318
        self.from_file = iter(from_file)
352
319
        self._next_line = None
353
 
 
354
 
        self.info = self._get_info()
 
320
        
 
321
        self.info = BundleInfo()
355
322
        # We put the actual inventory ids in the footer, so that the patch
356
323
        # is easier to read for humans.
357
324
        # Unfortunately, that means we need to read everything before we
359
326
        self._read()
360
327
        self._validate()
361
328
 
362
 
    def _get_info(self):
363
 
        return BundleInfo08()
364
 
 
365
329
    def _read(self):
366
330
        self._next().next()
367
331
        while self._next_line is not None:
368
 
            if not self._read_revision_header():
369
 
                break
 
332
            self._read_revision_header()
370
333
            if self._next_line is None:
371
334
                break
372
335
            self._read_patches()
396
359
        yield last
397
360
 
398
361
    def _read_revision_header(self):
399
 
        found_something = False
400
362
        self.info.revisions.append(RevisionInfo(None))
401
363
        for line in self._next():
402
364
            # The bzr header is terminated with a blank line
403
365
            # which does not start with '#'
404
366
            if line is None or line == '\n':
405
367
                break
406
 
            if not line.startswith('#'):
407
 
                continue
408
 
            found_something = True
409
368
            self._handle_next(line)
410
 
        if not found_something:
411
 
            # Nothing was there, so remove the added revision
412
 
            self.info.revisions.pop()
413
 
        return found_something
414
369
 
415
370
    def _read_next_entry(self, line, indent=1):
416
371
        """Read in a key-value pair
417
372
        """
418
373
        if not line.startswith('#'):
419
 
            raise errors.MalformedHeader('Bzr header did not start with #')
 
374
            raise MalformedHeader('Bzr header did not start with #')
420
375
        line = line[1:-1].decode('utf-8') # Remove the '#' and '\n'
421
376
        if line[:indent] == ' '*indent:
422
377
            line = line[indent:]
433
388
            key = line[:-1]
434
389
            value = self._read_many(indent=indent+2)
435
390
        else:
436
 
            raise errors.MalformedHeader('While looking for key: value pairs,'
 
391
            raise MalformedHeader('While looking for key: value pairs,'
437
392
                    ' did not find the colon %r' % (line))
438
393
 
439
394
        key = key.replace(' ', '_')
449
404
            return
450
405
 
451
406
        revision_info = self.info.revisions[-1]
452
 
        if key in revision_info.__dict__:
 
407
        if hasattr(revision_info, key):
453
408
            if getattr(revision_info, key) is None:
454
 
                if key in ('file_id', 'revision_id', 'base_id'):
455
 
                    value = value.encode('utf8')
456
 
                elif key in ('parent_ids'):
457
 
                    value = [v.encode('utf8') for v in value]
458
409
                setattr(revision_info, key, value)
459
410
            else:
460
 
                raise errors.MalformedHeader('Duplicated Key: %s' % key)
 
411
                raise MalformedHeader('Duplicated Key: %s' % key)
461
412
        else:
462
413
            # What do we do with a key we don't recognize
463
 
            raise errors.MalformedHeader('Unknown Key: "%s"' % key)
464
 
 
 
414
            raise MalformedHeader('Unknown Key: "%s"' % key)
 
415
    
465
416
    def _read_many(self, indent):
466
417
        """If a line ends with no entry, that means that it should be
467
418
        followed with multiple lines of values.
497
448
        for line in self._next():
498
449
            if first:
499
450
                if not line.startswith('==='):
500
 
                    raise errors.MalformedPatches('The first line of all patches'
 
451
                    raise MalformedPatches('The first line of all patches'
501
452
                        ' should be a bzr meta line "==="'
502
453
                        ': %r' % line)
503
454
                action = line[4:-1].decode('utf-8')
504
455
            elif line.startswith('... '):
505
456
                action += line[len('... '):-1].decode('utf-8')
506
457
 
507
 
            if (self._next_line is not None and
 
458
            if (self._next_line is not None and 
508
459
                self._next_line.startswith('===')):
509
460
                return action, lines, True
510
461
            elif self._next_line is None or self._next_line.startswith('#'):
516
467
                lines.append(line)
517
468
 
518
469
        return action, lines, False
519
 
 
 
470
            
520
471
    def _read_patches(self):
521
472
        do_continue = True
522
473
        revision_actions = []
524
475
            action, lines, do_continue = self._read_one_patch()
525
476
            if action is not None:
526
477
                revision_actions.append((action, lines))
527
 
        if self.info.revisions[-1].tree_actions is not None:
528
 
            raise AssertionError()
 
478
        assert self.info.revisions[-1].tree_actions is None
529
479
        self.info.revisions[-1].tree_actions = revision_actions
530
480
 
531
481
    def _read_footer(self):
536
486
        """
537
487
        for line in self._next():
538
488
            self._handle_next(line)
539
 
            if self._next_line is None:
540
 
                break
541
489
            if not self._next_line.startswith('#'):
542
 
                # Consume the trailing \n and stop processing
543
490
                self._next().next()
544
491
                break
545
 
 
546
 
class BundleInfo08(BundleInfo):
547
 
 
548
 
    def _update_tree(self, bundle_tree, revision_id):
549
 
        bundle_tree.note_last_changed('', revision_id)
550
 
        BundleInfo._update_tree(self, bundle_tree, revision_id)
551
 
 
552
 
    def _testament_sha1_from_revision(self, repository, revision_id):
553
 
        testament = StrictTestament.from_revision(repository, revision_id)
554
 
        return testament.as_sha1()
555
 
 
556
 
    def _testament_sha1(self, revision, inventory):
557
 
        return StrictTestament(revision, inventory).as_sha1()
 
492
            if self._next_line is None:
 
493
                break