~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/repofmt/pack_repo.py

  • Committer: Canonical.com Patch Queue Manager
  • Date: 2007-11-15 14:47:59 UTC
  • mfrom: (2984.1.1 update_basis_161131)
  • Revision ID: pqm@pqm.ubuntu.com-20071115144759-zx0nd44rgp38riwr
(John Arbash Meinel) Fix bug #161131: when exactly 2 items were
        deleted, it would remove all items in a directory.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2005, 2006, 2007 Canonical Ltd
 
2
#
 
3
# This program is free software; you can redistribute it and/or modify
 
4
# it under the terms of the GNU General Public License as published by
 
5
# the Free Software Foundation; either version 2 of the License, or
 
6
# (at your option) any later version.
 
7
#
 
8
# This program is distributed in the hope that it will be useful,
 
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
11
# GNU General Public License for more details.
 
12
#
 
13
# You should have received a copy of the GNU General Public License
 
14
# along with this program; if not, write to the Free Software
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
16
 
 
17
from bzrlib.lazy_import import lazy_import
 
18
lazy_import(globals(), """
 
19
from itertools import izip
 
20
import math
 
21
import md5
 
22
import time
 
23
 
 
24
from bzrlib import (
 
25
        debug,
 
26
        pack,
 
27
        ui,
 
28
        )
 
29
from bzrlib.index import (
 
30
    GraphIndex,
 
31
    GraphIndexBuilder,
 
32
    InMemoryGraphIndex,
 
33
    CombinedGraphIndex,
 
34
    GraphIndexPrefixAdapter,
 
35
    )
 
36
from bzrlib.knit import KnitGraphIndex, _PackAccess, _KnitData
 
37
from bzrlib.osutils import rand_chars
 
38
from bzrlib.pack import ContainerWriter
 
39
from bzrlib.store import revision
 
40
""")
 
41
from bzrlib import (
 
42
    bzrdir,
 
43
    deprecated_graph,
 
44
    errors,
 
45
    knit,
 
46
    lockable_files,
 
47
    lockdir,
 
48
    osutils,
 
49
    transactions,
 
50
    xml5,
 
51
    xml7,
 
52
    )
 
53
 
 
54
from bzrlib.decorators import needs_read_lock, needs_write_lock
 
55
from bzrlib.repofmt.knitrepo import KnitRepository
 
56
from bzrlib.repository import (
 
57
    CommitBuilder,
 
58
    MetaDirRepository,
 
59
    MetaDirRepositoryFormat,
 
60
    RootCommitBuilder,
 
61
    )
 
62
import bzrlib.revision as _mod_revision
 
63
from bzrlib.store.revision.knit import KnitRevisionStore
 
64
from bzrlib.store.versioned import VersionedFileStore
 
65
from bzrlib.trace import mutter, note, warning
 
66
 
 
67
 
 
68
class PackCommitBuilder(CommitBuilder):
 
69
    """A subclass of CommitBuilder to add texts with pack semantics.
 
70
    
 
71
    Specifically this uses one knit object rather than one knit object per
 
72
    added text, reducing memory and object pressure.
 
73
    """
 
74
 
 
75
    def _add_text_to_weave(self, file_id, new_lines, parents, nostore_sha):
 
76
        return self.repository._pack_collection._add_text_to_weave(file_id,
 
77
            self._new_revision_id, new_lines, parents, nostore_sha,
 
78
            self.random_revid)
 
79
 
 
80
 
 
81
class PackRootCommitBuilder(RootCommitBuilder):
 
82
    """A subclass of RootCommitBuilder to add texts with pack semantics.
 
83
    
 
84
    Specifically this uses one knit object rather than one knit object per
 
85
    added text, reducing memory and object pressure.
 
86
    """
 
87
 
 
88
    def _add_text_to_weave(self, file_id, new_lines, parents, nostore_sha):
 
89
        return self.repository._pack_collection._add_text_to_weave(file_id,
 
90
            self._new_revision_id, new_lines, parents, nostore_sha,
 
91
            self.random_revid)
 
92
 
 
93
 
 
94
class Pack(object):
 
95
    """An in memory proxy for a pack and its indices.
 
96
 
 
97
    This is a base class that is not directly used, instead the classes
 
98
    ExistingPack and NewPack are used.
 
99
    """
 
100
 
 
101
    def __init__(self, revision_index, inventory_index, text_index,
 
102
        signature_index):
 
103
        """Create a pack instance.
 
104
 
 
105
        :param revision_index: A GraphIndex for determining what revisions are
 
106
            present in the Pack and accessing the locations of their texts.
 
107
        :param inventory_index: A GraphIndex for determining what inventories are
 
108
            present in the Pack and accessing the locations of their
 
109
            texts/deltas.
 
110
        :param text_index: A GraphIndex for determining what file texts
 
111
            are present in the pack and accessing the locations of their
 
112
            texts/deltas (via (fileid, revisionid) tuples).
 
113
        :param revision_index: A GraphIndex for determining what signatures are
 
114
            present in the Pack and accessing the locations of their texts.
 
115
        """
 
116
        self.revision_index = revision_index
 
117
        self.inventory_index = inventory_index
 
118
        self.text_index = text_index
 
119
        self.signature_index = signature_index
 
120
 
 
121
    def access_tuple(self):
 
122
        """Return a tuple (transport, name) for the pack content."""
 
123
        return self.pack_transport, self.file_name()
 
124
 
 
125
    def file_name(self):
 
126
        """Get the file name for the pack on disk."""
 
127
        return self.name + '.pack'
 
128
 
 
129
    def get_revision_count(self):
 
130
        return self.revision_index.key_count()
 
131
 
 
132
    def inventory_index_name(self, name):
 
133
        """The inv index is the name + .iix."""
 
134
        return self.index_name('inventory', name)
 
135
 
 
136
    def revision_index_name(self, name):
 
137
        """The revision index is the name + .rix."""
 
138
        return self.index_name('revision', name)
 
139
 
 
140
    def signature_index_name(self, name):
 
141
        """The signature index is the name + .six."""
 
142
        return self.index_name('signature', name)
 
143
 
 
144
    def text_index_name(self, name):
 
145
        """The text index is the name + .tix."""
 
146
        return self.index_name('text', name)
 
147
 
 
148
 
 
149
class ExistingPack(Pack):
 
150
    """An in memory proxy for an existing .pack and its disk indices."""
 
151
 
 
152
    def __init__(self, pack_transport, name, revision_index, inventory_index,
 
153
        text_index, signature_index):
 
154
        """Create an ExistingPack object.
 
155
 
 
156
        :param pack_transport: The transport where the pack file resides.
 
157
        :param name: The name of the pack on disk in the pack_transport.
 
158
        """
 
159
        Pack.__init__(self, revision_index, inventory_index, text_index,
 
160
            signature_index)
 
161
        self.name = name
 
162
        self.pack_transport = pack_transport
 
163
        assert None not in (revision_index, inventory_index, text_index,
 
164
            signature_index, name, pack_transport)
 
165
 
 
166
    def __eq__(self, other):
 
167
        return self.__dict__ == other.__dict__
 
168
 
 
169
    def __ne__(self, other):
 
170
        return not self.__eq__(other)
 
171
 
 
172
    def __repr__(self):
 
173
        return "<bzrlib.repofmt.pack_repo.Pack object at 0x%x, %s, %s" % (
 
174
            id(self), self.transport, self.name)
 
175
 
 
176
 
 
177
class NewPack(Pack):
 
178
    """An in memory proxy for a pack which is being created."""
 
179
 
 
180
    # A map of index 'type' to the file extension and position in the
 
181
    # index_sizes array.
 
182
    index_definitions = {
 
183
        'revision': ('.rix', 0),
 
184
        'inventory': ('.iix', 1),
 
185
        'text': ('.tix', 2),
 
186
        'signature': ('.six', 3),
 
187
        }
 
188
 
 
189
    def __init__(self, upload_transport, index_transport, pack_transport,
 
190
        upload_suffix=''):
 
191
        """Create a NewPack instance.
 
192
 
 
193
        :param upload_transport: A writable transport for the pack to be
 
194
            incrementally uploaded to.
 
195
        :param index_transport: A writable transport for the pack's indices to
 
196
            be written to when the pack is finished.
 
197
        :param pack_transport: A writable transport for the pack to be renamed
 
198
            to when the upload is complete. This *must* be the same as
 
199
            upload_transport.clone('../packs').
 
200
        :param upload_suffix: An optional suffix to be given to any temporary
 
201
            files created during the pack creation. e.g '.autopack'
 
202
        """
 
203
        # The relative locations of the packs are constrained, but all are
 
204
        # passed in because the caller has them, so as to avoid object churn.
 
205
        Pack.__init__(self,
 
206
            # Revisions: parents list, no text compression.
 
207
            InMemoryGraphIndex(reference_lists=1),
 
208
            # Inventory: We want to map compression only, but currently the
 
209
            # knit code hasn't been updated enough to understand that, so we
 
210
            # have a regular 2-list index giving parents and compression
 
211
            # source.
 
212
            InMemoryGraphIndex(reference_lists=2),
 
213
            # Texts: compression and per file graph, for all fileids - so two
 
214
            # reference lists and two elements in the key tuple.
 
215
            InMemoryGraphIndex(reference_lists=2, key_elements=2),
 
216
            # Signatures: Just blobs to store, no compression, no parents
 
217
            # listing.
 
218
            InMemoryGraphIndex(reference_lists=0),
 
219
            )
 
220
        # where should the new pack be opened
 
221
        self.upload_transport = upload_transport
 
222
        # where are indices written out to
 
223
        self.index_transport = index_transport
 
224
        # where is the pack renamed to when it is finished?
 
225
        self.pack_transport = pack_transport
 
226
        # tracks the content written to the .pack file.
 
227
        self._hash = md5.new()
 
228
        # a four-tuple with the length in bytes of the indices, once the pack
 
229
        # is finalised. (rev, inv, text, sigs)
 
230
        self.index_sizes = None
 
231
        # How much data to cache when writing packs. Note that this is not
 
232
        # synchronised with reads, because it's not in the transport layer, so
 
233
        # is not safe unless the client knows it won't be reading from the pack
 
234
        # under creation.
 
235
        self._cache_limit = 0
 
236
        # the temporary pack file name.
 
237
        self.random_name = rand_chars(20) + upload_suffix
 
238
        # when was this pack started ?
 
239
        self.start_time = time.time()
 
240
        # open an output stream for the data added to the pack.
 
241
        self.write_stream = self.upload_transport.open_write_stream(
 
242
            self.random_name)
 
243
        if 'pack' in debug.debug_flags:
 
244
            mutter('%s: create_pack: pack stream open: %s%s t+%6.3fs',
 
245
                time.ctime(), self.upload_transport.base, self.random_name,
 
246
                time.time() - self.start_time)
 
247
        # A list of byte sequences to be written to the new pack, and the 
 
248
        # aggregate size of them.  Stored as a list rather than separate 
 
249
        # variables so that the _write_data closure below can update them.
 
250
        self._buffer = [[], 0]
 
251
        # create a callable for adding data 
 
252
        #
 
253
        # robertc says- this is a closure rather than a method on the object
 
254
        # so that the variables are locals, and faster than accessing object
 
255
        # members.
 
256
        def _write_data(bytes, flush=False, _buffer=self._buffer,
 
257
            _write=self.write_stream.write, _update=self._hash.update):
 
258
            _buffer[0].append(bytes)
 
259
            _buffer[1] += len(bytes)
 
260
            # buffer cap
 
261
            if _buffer[1] > self._cache_limit or flush:
 
262
                bytes = ''.join(_buffer[0])
 
263
                _write(bytes)
 
264
                _update(bytes)
 
265
                _buffer[:] = [[], 0]
 
266
        # expose this on self, for the occasion when clients want to add data.
 
267
        self._write_data = _write_data
 
268
        # a pack writer object to serialise pack records.
 
269
        self._writer = pack.ContainerWriter(self._write_data)
 
270
        self._writer.begin()
 
271
        # what state is the pack in? (open, finished, aborted)
 
272
        self._state = 'open'
 
273
 
 
274
    def abort(self):
 
275
        """Cancel creating this pack."""
 
276
        self._state = 'aborted'
 
277
        self.write_stream.close()
 
278
        # Remove the temporary pack file.
 
279
        self.upload_transport.delete(self.random_name)
 
280
        # The indices have no state on disk.
 
281
 
 
282
    def access_tuple(self):
 
283
        """Return a tuple (transport, name) for the pack content."""
 
284
        assert self._state in ('open', 'finished')
 
285
        if self._state == 'finished':
 
286
            return Pack.access_tuple(self)
 
287
        else:
 
288
            return self.upload_transport, self.random_name
 
289
 
 
290
    def data_inserted(self):
 
291
        """True if data has been added to this pack."""
 
292
        return bool(self.get_revision_count() or
 
293
            self.inventory_index.key_count() or
 
294
            self.text_index.key_count() or
 
295
            self.signature_index.key_count())
 
296
 
 
297
    def finish(self):
 
298
        """Finish the new pack.
 
299
 
 
300
        This:
 
301
         - finalises the content
 
302
         - assigns a name (the md5 of the content, currently)
 
303
         - writes out the associated indices
 
304
         - renames the pack into place.
 
305
         - stores the index size tuple for the pack in the index_sizes
 
306
           attribute.
 
307
        """
 
308
        self._writer.end()
 
309
        if self._buffer[1]:
 
310
            self._write_data('', flush=True)
 
311
        self.name = self._hash.hexdigest()
 
312
        # write indices
 
313
        # XXX: It'd be better to write them all to temporary names, then
 
314
        # rename them all into place, so that the window when only some are
 
315
        # visible is smaller.  On the other hand none will be seen until
 
316
        # they're in the names list.
 
317
        self.index_sizes = [None, None, None, None]
 
318
        self._write_index('revision', self.revision_index, 'revision')
 
319
        self._write_index('inventory', self.inventory_index, 'inventory')
 
320
        self._write_index('text', self.text_index, 'file texts')
 
321
        self._write_index('signature', self.signature_index,
 
322
            'revision signatures')
 
323
        self.write_stream.close()
 
324
        # Note that this will clobber an existing pack with the same name,
 
325
        # without checking for hash collisions. While this is undesirable this
 
326
        # is something that can be rectified in a subsequent release. One way
 
327
        # to rectify it may be to leave the pack at the original name, writing
 
328
        # its pack-names entry as something like 'HASH: index-sizes
 
329
        # temporary-name'. Allocate that and check for collisions, if it is
 
330
        # collision free then rename it into place. If clients know this scheme
 
331
        # they can handle missing-file errors by:
 
332
        #  - try for HASH.pack
 
333
        #  - try for temporary-name
 
334
        #  - refresh the pack-list to see if the pack is now absent
 
335
        self.upload_transport.rename(self.random_name,
 
336
                '../packs/' + self.name + '.pack')
 
337
        self._state = 'finished'
 
338
        if 'pack' in debug.debug_flags:
 
339
            # XXX: size might be interesting?
 
340
            mutter('%s: create_pack: pack renamed into place: %s%s->%s%s t+%6.3fs',
 
341
                time.ctime(), self.upload_transport.base, self.random_name,
 
342
                self.pack_transport, self.name,
 
343
                time.time() - self.start_time)
 
344
 
 
345
    def index_name(self, index_type, name):
 
346
        """Get the disk name of an index type for pack name 'name'."""
 
347
        return name + NewPack.index_definitions[index_type][0]
 
348
 
 
349
    def index_offset(self, index_type):
 
350
        """Get the position in a index_size array for a given index type."""
 
351
        return NewPack.index_definitions[index_type][1]
 
352
 
 
353
    def _replace_index_with_readonly(self, index_type):
 
354
        setattr(self, index_type + '_index',
 
355
            GraphIndex(self.index_transport,
 
356
                self.index_name(index_type, self.name),
 
357
                self.index_sizes[self.index_offset(index_type)]))
 
358
 
 
359
    def set_write_cache_size(self, size):
 
360
        self._cache_limit = size
 
361
 
 
362
    def _write_index(self, index_type, index, label):
 
363
        """Write out an index.
 
364
 
 
365
        :param index_type: The type of index to write - e.g. 'revision'.
 
366
        :param index: The index object to serialise.
 
367
        :param label: What label to give the index e.g. 'revision'.
 
368
        """
 
369
        index_name = self.index_name(index_type, self.name)
 
370
        self.index_sizes[self.index_offset(index_type)] = \
 
371
            self.index_transport.put_file(index_name, index.finish())
 
372
        if 'pack' in debug.debug_flags:
 
373
            # XXX: size might be interesting?
 
374
            mutter('%s: create_pack: wrote %s index: %s%s t+%6.3fs',
 
375
                time.ctime(), label, self.upload_transport.base,
 
376
                self.random_name, time.time() - self.start_time)
 
377
        # Replace the writable index on this object with a readonly, 
 
378
        # presently unloaded index. We should alter
 
379
        # the index layer to make its finish() error if add_node is
 
380
        # subsequently used. RBC
 
381
        self._replace_index_with_readonly(index_type)
 
382
 
 
383
 
 
384
class AggregateIndex(object):
 
385
    """An aggregated index for the RepositoryPackCollection.
 
386
 
 
387
    AggregateIndex is reponsible for managing the PackAccess object,
 
388
    Index-To-Pack mapping, and all indices list for a specific type of index
 
389
    such as 'revision index'.
 
390
 
 
391
    A CombinedIndex provides an index on a single key space built up
 
392
    from several on-disk indices.  The AggregateIndex builds on this 
 
393
    to provide a knit access layer, and allows having up to one writable
 
394
    index within the collection.
 
395
    """
 
396
    # XXX: Probably 'can be written to' could/should be separated from 'acts
 
397
    # like a knit index' -- mbp 20071024
 
398
 
 
399
    def __init__(self):
 
400
        """Create an AggregateIndex."""
 
401
        self.index_to_pack = {}
 
402
        self.combined_index = CombinedGraphIndex([])
 
403
        self.knit_access = _PackAccess(self.index_to_pack)
 
404
 
 
405
    def replace_indices(self, index_to_pack, indices):
 
406
        """Replace the current mappings with fresh ones.
 
407
 
 
408
        This should probably not be used eventually, rather incremental add and
 
409
        removal of indices. It has been added during refactoring of existing
 
410
        code.
 
411
 
 
412
        :param index_to_pack: A mapping from index objects to
 
413
            (transport, name) tuples for the pack file data.
 
414
        :param indices: A list of indices.
 
415
        """
 
416
        # refresh the revision pack map dict without replacing the instance.
 
417
        self.index_to_pack.clear()
 
418
        self.index_to_pack.update(index_to_pack)
 
419
        # XXX: API break - clearly a 'replace' method would be good?
 
420
        self.combined_index._indices[:] = indices
 
421
        # the current add nodes callback for the current writable index if
 
422
        # there is one.
 
423
        self.add_callback = None
 
424
 
 
425
    def add_index(self, index, pack):
 
426
        """Add index to the aggregate, which is an index for Pack pack.
 
427
 
 
428
        Future searches on the aggregate index will seach this new index
 
429
        before all previously inserted indices.
 
430
        
 
431
        :param index: An Index for the pack.
 
432
        :param pack: A Pack instance.
 
433
        """
 
434
        # expose it to the index map
 
435
        self.index_to_pack[index] = pack.access_tuple()
 
436
        # put it at the front of the linear index list
 
437
        self.combined_index.insert_index(0, index)
 
438
 
 
439
    def add_writable_index(self, index, pack):
 
440
        """Add an index which is able to have data added to it.
 
441
 
 
442
        There can be at most one writable index at any time.  Any
 
443
        modifications made to the knit are put into this index.
 
444
        
 
445
        :param index: An index from the pack parameter.
 
446
        :param pack: A Pack instance.
 
447
        """
 
448
        assert self.add_callback is None, \
 
449
            "%s already has a writable index through %s" % \
 
450
            (self, self.add_callback)
 
451
        # allow writing: queue writes to a new index
 
452
        self.add_index(index, pack)
 
453
        # Updates the index to packs mapping as a side effect,
 
454
        self.knit_access.set_writer(pack._writer, index, pack.access_tuple())
 
455
        self.add_callback = index.add_nodes
 
456
 
 
457
    def clear(self):
 
458
        """Reset all the aggregate data to nothing."""
 
459
        self.knit_access.set_writer(None, None, (None, None))
 
460
        self.index_to_pack.clear()
 
461
        del self.combined_index._indices[:]
 
462
        self.add_callback = None
 
463
 
 
464
    def remove_index(self, index, pack):
 
465
        """Remove index from the indices used to answer queries.
 
466
        
 
467
        :param index: An index from the pack parameter.
 
468
        :param pack: A Pack instance.
 
469
        """
 
470
        del self.index_to_pack[index]
 
471
        self.combined_index._indices.remove(index)
 
472
        if (self.add_callback is not None and
 
473
            getattr(index, 'add_nodes', None) == self.add_callback):
 
474
            self.add_callback = None
 
475
            self.knit_access.set_writer(None, None, (None, None))
 
476
 
 
477
 
 
478
class Packer(object):
 
479
    """Create a pack from packs."""
 
480
 
 
481
    def __init__(self, pack_collection, packs, suffix, revision_ids=None):
 
482
        """Create a Packer.
 
483
 
 
484
        :param pack_collection: A RepositoryPackCollection object where the
 
485
            new pack is being written to.
 
486
        :param packs: The packs to combine.
 
487
        :param suffix: The suffix to use on the temporary files for the pack.
 
488
        :param revision_ids: Revision ids to limit the pack to.
 
489
        """
 
490
        self.packs = packs
 
491
        self.suffix = suffix
 
492
        self.revision_ids = revision_ids
 
493
        self._pack_collection = pack_collection
 
494
 
 
495
    def pack(self, pb=None):
 
496
        """Create a new pack by reading data from other packs.
 
497
 
 
498
        This does little more than a bulk copy of data. One key difference
 
499
        is that data with the same item key across multiple packs is elided
 
500
        from the output. The new pack is written into the current pack store
 
501
        along with its indices, and the name added to the pack names. The 
 
502
        source packs are not altered and are not required to be in the current
 
503
        pack collection.
 
504
 
 
505
        :param pb: An optional progress bar to use. A nested bar is created if
 
506
            this is None.
 
507
        :return: A Pack object, or None if nothing was copied.
 
508
        """
 
509
        # open a pack - using the same name as the last temporary file
 
510
        # - which has already been flushed, so its safe.
 
511
        # XXX: - duplicate code warning with start_write_group; fix before
 
512
        #      considering 'done'.
 
513
        if self._pack_collection._new_pack is not None:
 
514
            raise errors.BzrError('call to create_pack_from_packs while '
 
515
                'another pack is being written.')
 
516
        if self.revision_ids is not None:
 
517
            if len(self.revision_ids) == 0:
 
518
                # silly fetch request.
 
519
                return None
 
520
            else:
 
521
                self.revision_ids = frozenset(self.revision_ids)
 
522
        if pb is None:
 
523
            self.pb = ui.ui_factory.nested_progress_bar()
 
524
        else:
 
525
            self.pb = pb
 
526
        try:
 
527
            return self._create_pack_from_packs()
 
528
        finally:
 
529
            if pb is None:
 
530
                self.pb.finished()
 
531
 
 
532
    def open_pack(self):
 
533
        """Open a pack for the pack we are creating."""
 
534
        return NewPack(self._pack_collection._upload_transport,
 
535
            self._pack_collection._index_transport,
 
536
            self._pack_collection._pack_transport, upload_suffix=self.suffix)
 
537
 
 
538
    def _create_pack_from_packs(self):
 
539
        self.pb.update("Opening pack", 0, 5)
 
540
        new_pack = self.open_pack()
 
541
        # buffer data - we won't be reading-back during the pack creation and
 
542
        # this makes a significant difference on sftp pushes.
 
543
        new_pack.set_write_cache_size(1024*1024)
 
544
        if 'pack' in debug.debug_flags:
 
545
            plain_pack_list = ['%s%s' % (a_pack.pack_transport.base, a_pack.name)
 
546
                for a_pack in self.packs]
 
547
            if self.revision_ids is not None:
 
548
                rev_count = len(self.revision_ids)
 
549
            else:
 
550
                rev_count = 'all'
 
551
            mutter('%s: create_pack: creating pack from source packs: '
 
552
                '%s%s %s revisions wanted %s t=0',
 
553
                time.ctime(), self._pack_collection._upload_transport.base, new_pack.random_name,
 
554
                plain_pack_list, rev_count)
 
555
        # select revisions
 
556
        if self.revision_ids:
 
557
            revision_keys = [(revision_id,) for revision_id in self.revision_ids]
 
558
        else:
 
559
            revision_keys = None
 
560
 
 
561
        # select revision keys
 
562
        revision_index_map = self._pack_collection._packs_list_to_pack_map_and_index_list(
 
563
            self.packs, 'revision_index')[0]
 
564
        revision_nodes = self._pack_collection._index_contents(revision_index_map, revision_keys)
 
565
        # copy revision keys and adjust values
 
566
        self.pb.update("Copying revision texts", 1)
 
567
        list(self._copy_nodes_graph(revision_nodes, revision_index_map,
 
568
            new_pack._writer, new_pack.revision_index))
 
569
        if 'pack' in debug.debug_flags:
 
570
            mutter('%s: create_pack: revisions copied: %s%s %d items t+%6.3fs',
 
571
                time.ctime(), self._pack_collection._upload_transport.base, new_pack.random_name,
 
572
                new_pack.revision_index.key_count(),
 
573
                time.time() - new_pack.start_time)
 
574
        # select inventory keys
 
575
        inv_keys = revision_keys # currently the same keyspace, and note that
 
576
        # querying for keys here could introduce a bug where an inventory item
 
577
        # is missed, so do not change it to query separately without cross
 
578
        # checking like the text key check below.
 
579
        inventory_index_map = self._pack_collection._packs_list_to_pack_map_and_index_list(
 
580
            self.packs, 'inventory_index')[0]
 
581
        inv_nodes = self._pack_collection._index_contents(inventory_index_map, inv_keys)
 
582
        # copy inventory keys and adjust values
 
583
        # XXX: Should be a helper function to allow different inv representation
 
584
        # at this point.
 
585
        self.pb.update("Copying inventory texts", 2)
 
586
        inv_lines = self._copy_nodes_graph(inv_nodes, inventory_index_map,
 
587
            new_pack._writer, new_pack.inventory_index, output_lines=True)
 
588
        if self.revision_ids:
 
589
            fileid_revisions = self._pack_collection.repo._find_file_ids_from_xml_inventory_lines(
 
590
                inv_lines, self.revision_ids)
 
591
            text_filter = []
 
592
            for fileid, file_revids in fileid_revisions.iteritems():
 
593
                text_filter.extend(
 
594
                    [(fileid, file_revid) for file_revid in file_revids])
 
595
        else:
 
596
            # eat the iterator to cause it to execute.
 
597
            list(inv_lines)
 
598
            text_filter = None
 
599
        if 'pack' in debug.debug_flags:
 
600
            mutter('%s: create_pack: inventories copied: %s%s %d items t+%6.3fs',
 
601
                time.ctime(), self._pack_collection._upload_transport.base, new_pack.random_name,
 
602
                new_pack.inventory_index.key_count(),
 
603
                time.time() - new_pack.start_time)
 
604
        # select text keys
 
605
        text_index_map = self._pack_collection._packs_list_to_pack_map_and_index_list(
 
606
            self.packs, 'text_index')[0]
 
607
        text_nodes = self._pack_collection._index_contents(text_index_map, text_filter)
 
608
        if text_filter is not None:
 
609
            # We could return the keys copied as part of the return value from
 
610
            # _copy_nodes_graph but this doesn't work all that well with the
 
611
            # need to get line output too, so we check separately, and as we're
 
612
            # going to buffer everything anyway, we check beforehand, which
 
613
            # saves reading knit data over the wire when we know there are
 
614
            # mising records.
 
615
            text_nodes = set(text_nodes)
 
616
            present_text_keys = set(_node[1] for _node in text_nodes)
 
617
            missing_text_keys = set(text_filter) - present_text_keys
 
618
            if missing_text_keys:
 
619
                # TODO: raise a specific error that can handle many missing
 
620
                # keys.
 
621
                a_missing_key = missing_text_keys.pop()
 
622
                raise errors.RevisionNotPresent(a_missing_key[1],
 
623
                    a_missing_key[0])
 
624
        # copy text keys and adjust values
 
625
        self.pb.update("Copying content texts", 3)
 
626
        list(self._copy_nodes_graph(text_nodes, text_index_map,
 
627
            new_pack._writer, new_pack.text_index))
 
628
        if 'pack' in debug.debug_flags:
 
629
            mutter('%s: create_pack: file texts copied: %s%s %d items t+%6.3fs',
 
630
                time.ctime(), self._pack_collection._upload_transport.base, new_pack.random_name,
 
631
                new_pack.text_index.key_count(),
 
632
                time.time() - new_pack.start_time)
 
633
        # select signature keys
 
634
        signature_filter = revision_keys # same keyspace
 
635
        signature_index_map = self._pack_collection._packs_list_to_pack_map_and_index_list(
 
636
            self.packs, 'signature_index')[0]
 
637
        signature_nodes = self._pack_collection._index_contents(signature_index_map,
 
638
            signature_filter)
 
639
        # copy signature keys and adjust values
 
640
        self.pb.update("Copying signature texts", 4)
 
641
        self._copy_nodes(signature_nodes, signature_index_map, new_pack._writer,
 
642
            new_pack.signature_index)
 
643
        if 'pack' in debug.debug_flags:
 
644
            mutter('%s: create_pack: revision signatures copied: %s%s %d items t+%6.3fs',
 
645
                time.ctime(), self._pack_collection._upload_transport.base, new_pack.random_name,
 
646
                new_pack.signature_index.key_count(),
 
647
                time.time() - new_pack.start_time)
 
648
        if not new_pack.data_inserted():
 
649
            new_pack.abort()
 
650
            return None
 
651
        self.pb.update("Finishing pack", 5)
 
652
        new_pack.finish()
 
653
        self._pack_collection.allocate(new_pack)
 
654
        return new_pack
 
655
 
 
656
    def _copy_nodes(self, nodes, index_map, writer, write_index):
 
657
        """Copy knit nodes between packs with no graph references."""
 
658
        pb = ui.ui_factory.nested_progress_bar()
 
659
        try:
 
660
            return self._do_copy_nodes(nodes, index_map, writer,
 
661
                write_index, pb)
 
662
        finally:
 
663
            pb.finished()
 
664
 
 
665
    def _do_copy_nodes(self, nodes, index_map, writer, write_index, pb):
 
666
        # for record verification
 
667
        knit_data = _KnitData(None)
 
668
        # plan a readv on each source pack:
 
669
        # group by pack
 
670
        nodes = sorted(nodes)
 
671
        # how to map this into knit.py - or knit.py into this?
 
672
        # we don't want the typical knit logic, we want grouping by pack
 
673
        # at this point - perhaps a helper library for the following code 
 
674
        # duplication points?
 
675
        request_groups = {}
 
676
        for index, key, value in nodes:
 
677
            if index not in request_groups:
 
678
                request_groups[index] = []
 
679
            request_groups[index].append((key, value))
 
680
        record_index = 0
 
681
        pb.update("Copied record", record_index, len(nodes))
 
682
        for index, items in request_groups.iteritems():
 
683
            pack_readv_requests = []
 
684
            for key, value in items:
 
685
                # ---- KnitGraphIndex.get_position
 
686
                bits = value[1:].split(' ')
 
687
                offset, length = int(bits[0]), int(bits[1])
 
688
                pack_readv_requests.append((offset, length, (key, value[0])))
 
689
            # linear scan up the pack
 
690
            pack_readv_requests.sort()
 
691
            # copy the data
 
692
            transport, path = index_map[index]
 
693
            reader = pack.make_readv_reader(transport, path,
 
694
                [offset[0:2] for offset in pack_readv_requests])
 
695
            for (names, read_func), (_1, _2, (key, eol_flag)) in \
 
696
                izip(reader.iter_records(), pack_readv_requests):
 
697
                raw_data = read_func(None)
 
698
                # check the header only
 
699
                df, _ = knit_data._parse_record_header(key[-1], raw_data)
 
700
                df.close()
 
701
                pos, size = writer.add_bytes_record(raw_data, names)
 
702
                write_index.add_node(key, eol_flag + "%d %d" % (pos, size))
 
703
                pb.update("Copied record", record_index)
 
704
                record_index += 1
 
705
 
 
706
    def _copy_nodes_graph(self, nodes, index_map, writer, write_index,
 
707
        output_lines=False):
 
708
        """Copy knit nodes between packs.
 
709
 
 
710
        :param output_lines: Return lines present in the copied data as
 
711
            an iterator of line,version_id.
 
712
        """
 
713
        pb = ui.ui_factory.nested_progress_bar()
 
714
        try:
 
715
            return self._do_copy_nodes_graph(nodes, index_map, writer,
 
716
                write_index, output_lines, pb)
 
717
        finally:
 
718
            pb.finished()
 
719
 
 
720
    def _do_copy_nodes_graph(self, nodes, index_map, writer, write_index,
 
721
        output_lines, pb):
 
722
        # for record verification
 
723
        knit_data = _KnitData(None)
 
724
        # for line extraction when requested (inventories only)
 
725
        if output_lines:
 
726
            factory = knit.KnitPlainFactory()
 
727
        # plan a readv on each source pack:
 
728
        # group by pack
 
729
        nodes = sorted(nodes)
 
730
        # how to map this into knit.py - or knit.py into this?
 
731
        # we don't want the typical knit logic, we want grouping by pack
 
732
        # at this point - perhaps a helper library for the following code 
 
733
        # duplication points?
 
734
        request_groups = {}
 
735
        record_index = 0
 
736
        pb.update("Copied record", record_index, len(nodes))
 
737
        for index, key, value, references in nodes:
 
738
            if index not in request_groups:
 
739
                request_groups[index] = []
 
740
            request_groups[index].append((key, value, references))
 
741
        for index, items in request_groups.iteritems():
 
742
            pack_readv_requests = []
 
743
            for key, value, references in items:
 
744
                # ---- KnitGraphIndex.get_position
 
745
                bits = value[1:].split(' ')
 
746
                offset, length = int(bits[0]), int(bits[1])
 
747
                pack_readv_requests.append((offset, length, (key, value[0], references)))
 
748
            # linear scan up the pack
 
749
            pack_readv_requests.sort()
 
750
            # copy the data
 
751
            transport, path = index_map[index]
 
752
            reader = pack.make_readv_reader(transport, path,
 
753
                [offset[0:2] for offset in pack_readv_requests])
 
754
            for (names, read_func), (_1, _2, (key, eol_flag, references)) in \
 
755
                izip(reader.iter_records(), pack_readv_requests):
 
756
                raw_data = read_func(None)
 
757
                version_id = key[-1]
 
758
                if output_lines:
 
759
                    # read the entire thing
 
760
                    content, _ = knit_data._parse_record(version_id, raw_data)
 
761
                    if len(references[-1]) == 0:
 
762
                        line_iterator = factory.get_fulltext_content(content)
 
763
                    else:
 
764
                        line_iterator = factory.get_linedelta_content(content)
 
765
                    for line in line_iterator:
 
766
                        yield line, version_id
 
767
                else:
 
768
                    # check the header only
 
769
                    df, _ = knit_data._parse_record_header(version_id, raw_data)
 
770
                    df.close()
 
771
                pos, size = writer.add_bytes_record(raw_data, names)
 
772
                write_index.add_node(key, eol_flag + "%d %d" % (pos, size), references)
 
773
                pb.update("Copied record", record_index)
 
774
                record_index += 1
 
775
 
 
776
 
 
777
class ReconcilePacker(Packer):
 
778
    """A packer which regenerates indices etc as it copies.
 
779
    
 
780
    This is used by ``bzr reconcile`` to cause parent text pointers to be
 
781
    regenerated.
 
782
    """
 
783
 
 
784
 
 
785
class RepositoryPackCollection(object):
 
786
    """Management of packs within a repository."""
 
787
 
 
788
    def __init__(self, repo, transport, index_transport, upload_transport,
 
789
                 pack_transport):
 
790
        """Create a new RepositoryPackCollection.
 
791
 
 
792
        :param transport: Addresses the repository base directory 
 
793
            (typically .bzr/repository/).
 
794
        :param index_transport: Addresses the directory containing indices.
 
795
        :param upload_transport: Addresses the directory into which packs are written
 
796
            while they're being created.
 
797
        :param pack_transport: Addresses the directory of existing complete packs.
 
798
        """
 
799
        self.repo = repo
 
800
        self.transport = transport
 
801
        self._index_transport = index_transport
 
802
        self._upload_transport = upload_transport
 
803
        self._pack_transport = pack_transport
 
804
        self._suffix_offsets = {'.rix': 0, '.iix': 1, '.tix': 2, '.six': 3}
 
805
        self.packs = []
 
806
        # name:Pack mapping
 
807
        self._packs_by_name = {}
 
808
        # the previous pack-names content
 
809
        self._packs_at_load = None
 
810
        # when a pack is being created by this object, the state of that pack.
 
811
        self._new_pack = None
 
812
        # aggregated revision index data
 
813
        self.revision_index = AggregateIndex()
 
814
        self.inventory_index = AggregateIndex()
 
815
        self.text_index = AggregateIndex()
 
816
        self.signature_index = AggregateIndex()
 
817
 
 
818
    def add_pack_to_memory(self, pack):
 
819
        """Make a Pack object available to the repository to satisfy queries.
 
820
        
 
821
        :param pack: A Pack object.
 
822
        """
 
823
        assert pack.name not in self._packs_by_name
 
824
        self.packs.append(pack)
 
825
        self._packs_by_name[pack.name] = pack
 
826
        self.revision_index.add_index(pack.revision_index, pack)
 
827
        self.inventory_index.add_index(pack.inventory_index, pack)
 
828
        self.text_index.add_index(pack.text_index, pack)
 
829
        self.signature_index.add_index(pack.signature_index, pack)
 
830
        
 
831
    def _add_text_to_weave(self, file_id, revision_id, new_lines, parents,
 
832
        nostore_sha, random_revid):
 
833
        file_id_index = GraphIndexPrefixAdapter(
 
834
            self.text_index.combined_index,
 
835
            (file_id, ), 1,
 
836
            add_nodes_callback=self.text_index.add_callback)
 
837
        self.repo._text_knit._index._graph_index = file_id_index
 
838
        self.repo._text_knit._index._add_callback = file_id_index.add_nodes
 
839
        return self.repo._text_knit.add_lines_with_ghosts(
 
840
            revision_id, parents, new_lines, nostore_sha=nostore_sha,
 
841
            random_id=random_revid, check_content=False)[0:2]
 
842
 
 
843
    def all_packs(self):
 
844
        """Return a list of all the Pack objects this repository has.
 
845
 
 
846
        Note that an in-progress pack being created is not returned.
 
847
 
 
848
        :return: A list of Pack objects for all the packs in the repository.
 
849
        """
 
850
        result = []
 
851
        for name in self.names():
 
852
            result.append(self.get_pack_by_name(name))
 
853
        return result
 
854
 
 
855
    def autopack(self):
 
856
        """Pack the pack collection incrementally.
 
857
        
 
858
        This will not attempt global reorganisation or recompression,
 
859
        rather it will just ensure that the total number of packs does
 
860
        not grow without bound. It uses the _max_pack_count method to
 
861
        determine if autopacking is needed, and the pack_distribution
 
862
        method to determine the number of revisions in each pack.
 
863
 
 
864
        If autopacking takes place then the packs name collection will have
 
865
        been flushed to disk - packing requires updating the name collection
 
866
        in synchronisation with certain steps. Otherwise the names collection
 
867
        is not flushed.
 
868
 
 
869
        :return: True if packing took place.
 
870
        """
 
871
        # XXX: Should not be needed when the management of indices is sane.
 
872
        total_revisions = self.revision_index.combined_index.key_count()
 
873
        total_packs = len(self._names)
 
874
        if self._max_pack_count(total_revisions) >= total_packs:
 
875
            return False
 
876
        # XXX: the following may want to be a class, to pack with a given
 
877
        # policy.
 
878
        mutter('Auto-packing repository %s, which has %d pack files, '
 
879
            'containing %d revisions into %d packs.', self, total_packs,
 
880
            total_revisions, self._max_pack_count(total_revisions))
 
881
        # determine which packs need changing
 
882
        pack_distribution = self.pack_distribution(total_revisions)
 
883
        existing_packs = []
 
884
        for pack in self.all_packs():
 
885
            revision_count = pack.get_revision_count()
 
886
            if revision_count == 0:
 
887
                # revision less packs are not generated by normal operation,
 
888
                # only by operations like sign-my-commits, and thus will not
 
889
                # tend to grow rapdily or without bound like commit containing
 
890
                # packs do - leave them alone as packing them really should
 
891
                # group their data with the relevant commit, and that may
 
892
                # involve rewriting ancient history - which autopack tries to
 
893
                # avoid. Alternatively we could not group the data but treat
 
894
                # each of these as having a single revision, and thus add 
 
895
                # one revision for each to the total revision count, to get
 
896
                # a matching distribution.
 
897
                continue
 
898
            existing_packs.append((revision_count, pack))
 
899
        pack_operations = self.plan_autopack_combinations(
 
900
            existing_packs, pack_distribution)
 
901
        self._execute_pack_operations(pack_operations)
 
902
        return True
 
903
 
 
904
    def _execute_pack_operations(self, pack_operations):
 
905
        """Execute a series of pack operations.
 
906
 
 
907
        :param pack_operations: A list of [revision_count, packs_to_combine].
 
908
        :return: None.
 
909
        """
 
910
        for revision_count, packs in pack_operations:
 
911
            # we may have no-ops from the setup logic
 
912
            if len(packs) == 0:
 
913
                continue
 
914
            Packer(self, packs, '.autopack').pack()
 
915
            for pack in packs:
 
916
                self._remove_pack_from_memory(pack)
 
917
        # record the newly available packs and stop advertising the old
 
918
        # packs
 
919
        self._save_pack_names(clear_obsolete_packs=True)
 
920
        # Move the old packs out of the way now they are no longer referenced.
 
921
        for revision_count, packs in pack_operations:
 
922
            self._obsolete_packs(packs)
 
923
 
 
924
    def lock_names(self):
 
925
        """Acquire the mutex around the pack-names index.
 
926
        
 
927
        This cannot be used in the middle of a read-only transaction on the
 
928
        repository.
 
929
        """
 
930
        self.repo.control_files.lock_write()
 
931
 
 
932
    def pack(self):
 
933
        """Pack the pack collection totally."""
 
934
        self.ensure_loaded()
 
935
        total_packs = len(self._names)
 
936
        if total_packs < 2:
 
937
            return
 
938
        total_revisions = self.revision_index.combined_index.key_count()
 
939
        # XXX: the following may want to be a class, to pack with a given
 
940
        # policy.
 
941
        mutter('Packing repository %s, which has %d pack files, '
 
942
            'containing %d revisions into 1 packs.', self, total_packs,
 
943
            total_revisions)
 
944
        # determine which packs need changing
 
945
        pack_distribution = [1]
 
946
        pack_operations = [[0, []]]
 
947
        for pack in self.all_packs():
 
948
            revision_count = pack.get_revision_count()
 
949
            pack_operations[-1][0] += revision_count
 
950
            pack_operations[-1][1].append(pack)
 
951
        self._execute_pack_operations(pack_operations)
 
952
 
 
953
    def plan_autopack_combinations(self, existing_packs, pack_distribution):
 
954
        """Plan a pack operation.
 
955
 
 
956
        :param existing_packs: The packs to pack. (A list of (revcount, Pack)
 
957
            tuples).
 
958
        :param pack_distribution: A list with the number of revisions desired
 
959
            in each pack.
 
960
        """
 
961
        if len(existing_packs) <= len(pack_distribution):
 
962
            return []
 
963
        existing_packs.sort(reverse=True)
 
964
        pack_operations = [[0, []]]
 
965
        # plan out what packs to keep, and what to reorganise
 
966
        while len(existing_packs):
 
967
            # take the largest pack, and if its less than the head of the
 
968
            # distribution chart we will include its contents in the new pack for
 
969
            # that position. If its larger, we remove its size from the
 
970
            # distribution chart
 
971
            next_pack_rev_count, next_pack = existing_packs.pop(0)
 
972
            if next_pack_rev_count >= pack_distribution[0]:
 
973
                # this is already packed 'better' than this, so we can
 
974
                # not waste time packing it.
 
975
                while next_pack_rev_count > 0:
 
976
                    next_pack_rev_count -= pack_distribution[0]
 
977
                    if next_pack_rev_count >= 0:
 
978
                        # more to go
 
979
                        del pack_distribution[0]
 
980
                    else:
 
981
                        # didn't use that entire bucket up
 
982
                        pack_distribution[0] = -next_pack_rev_count
 
983
            else:
 
984
                # add the revisions we're going to add to the next output pack
 
985
                pack_operations[-1][0] += next_pack_rev_count
 
986
                # allocate this pack to the next pack sub operation
 
987
                pack_operations[-1][1].append(next_pack)
 
988
                if pack_operations[-1][0] >= pack_distribution[0]:
 
989
                    # this pack is used up, shift left.
 
990
                    del pack_distribution[0]
 
991
                    pack_operations.append([0, []])
 
992
        
 
993
        return pack_operations
 
994
 
 
995
    def ensure_loaded(self):
 
996
        # NB: if you see an assertion error here, its probably access against
 
997
        # an unlocked repo. Naughty.
 
998
        assert self.repo.is_locked()
 
999
        if self._names is None:
 
1000
            self._names = {}
 
1001
            self._packs_at_load = set()
 
1002
            for index, key, value in self._iter_disk_pack_index():
 
1003
                name = key[0]
 
1004
                self._names[name] = self._parse_index_sizes(value)
 
1005
                self._packs_at_load.add((key, value))
 
1006
        # populate all the metadata.
 
1007
        self.all_packs()
 
1008
 
 
1009
    def _parse_index_sizes(self, value):
 
1010
        """Parse a string of index sizes."""
 
1011
        return tuple([int(digits) for digits in value.split(' ')])
 
1012
 
 
1013
    def get_pack_by_name(self, name):
 
1014
        """Get a Pack object by name.
 
1015
 
 
1016
        :param name: The name of the pack - e.g. '123456'
 
1017
        :return: A Pack object.
 
1018
        """
 
1019
        try:
 
1020
            return self._packs_by_name[name]
 
1021
        except KeyError:
 
1022
            rev_index = self._make_index(name, '.rix')
 
1023
            inv_index = self._make_index(name, '.iix')
 
1024
            txt_index = self._make_index(name, '.tix')
 
1025
            sig_index = self._make_index(name, '.six')
 
1026
            result = ExistingPack(self._pack_transport, name, rev_index,
 
1027
                inv_index, txt_index, sig_index)
 
1028
            self.add_pack_to_memory(result)
 
1029
            return result
 
1030
 
 
1031
    def allocate(self, a_new_pack):
 
1032
        """Allocate name in the list of packs.
 
1033
 
 
1034
        :param a_new_pack: A NewPack instance to be added to the collection of
 
1035
            packs for this repository.
 
1036
        """
 
1037
        self.ensure_loaded()
 
1038
        if a_new_pack.name in self._names:
 
1039
            # a collision with the packs we know about (not the only possible
 
1040
            # collision, see NewPack.finish() for some discussion). Remove our
 
1041
            # prior reference to it.
 
1042
            self._remove_pack_from_memory(a_new_pack)
 
1043
        self._names[a_new_pack.name] = tuple(a_new_pack.index_sizes)
 
1044
        self.add_pack_to_memory(a_new_pack)
 
1045
 
 
1046
    def _iter_disk_pack_index(self):
 
1047
        """Iterate over the contents of the pack-names index.
 
1048
        
 
1049
        This is used when loading the list from disk, and before writing to
 
1050
        detect updates from others during our write operation.
 
1051
        :return: An iterator of the index contents.
 
1052
        """
 
1053
        return GraphIndex(self.transport, 'pack-names', None
 
1054
                ).iter_all_entries()
 
1055
 
 
1056
    def _make_index(self, name, suffix):
 
1057
        size_offset = self._suffix_offsets[suffix]
 
1058
        index_name = name + suffix
 
1059
        index_size = self._names[name][size_offset]
 
1060
        return GraphIndex(
 
1061
            self._index_transport, index_name, index_size)
 
1062
 
 
1063
    def _max_pack_count(self, total_revisions):
 
1064
        """Return the maximum number of packs to use for total revisions.
 
1065
        
 
1066
        :param total_revisions: The total number of revisions in the
 
1067
            repository.
 
1068
        """
 
1069
        if not total_revisions:
 
1070
            return 1
 
1071
        digits = str(total_revisions)
 
1072
        result = 0
 
1073
        for digit in digits:
 
1074
            result += int(digit)
 
1075
        return result
 
1076
 
 
1077
    def names(self):
 
1078
        """Provide an order to the underlying names."""
 
1079
        return sorted(self._names.keys())
 
1080
 
 
1081
    def _obsolete_packs(self, packs):
 
1082
        """Move a number of packs which have been obsoleted out of the way.
 
1083
 
 
1084
        Each pack and its associated indices are moved out of the way.
 
1085
 
 
1086
        Note: for correctness this function should only be called after a new
 
1087
        pack names index has been written without these pack names, and with
 
1088
        the names of packs that contain the data previously available via these
 
1089
        packs.
 
1090
 
 
1091
        :param packs: The packs to obsolete.
 
1092
        :param return: None.
 
1093
        """
 
1094
        for pack in packs:
 
1095
            pack.pack_transport.rename(pack.file_name(),
 
1096
                '../obsolete_packs/' + pack.file_name())
 
1097
            # TODO: Probably needs to know all possible indices for this pack
 
1098
            # - or maybe list the directory and move all indices matching this
 
1099
            # name whether we recognize it or not?
 
1100
            for suffix in ('.iix', '.six', '.tix', '.rix'):
 
1101
                self._index_transport.rename(pack.name + suffix,
 
1102
                    '../obsolete_packs/' + pack.name + suffix)
 
1103
 
 
1104
    def pack_distribution(self, total_revisions):
 
1105
        """Generate a list of the number of revisions to put in each pack.
 
1106
 
 
1107
        :param total_revisions: The total number of revisions in the
 
1108
            repository.
 
1109
        """
 
1110
        if total_revisions == 0:
 
1111
            return [0]
 
1112
        digits = reversed(str(total_revisions))
 
1113
        result = []
 
1114
        for exponent, count in enumerate(digits):
 
1115
            size = 10 ** exponent
 
1116
            for pos in range(int(count)):
 
1117
                result.append(size)
 
1118
        return list(reversed(result))
 
1119
 
 
1120
    def _pack_tuple(self, name):
 
1121
        """Return a tuple with the transport and file name for a pack name."""
 
1122
        return self._pack_transport, name + '.pack'
 
1123
 
 
1124
    def _remove_pack_from_memory(self, pack):
 
1125
        """Remove pack from the packs accessed by this repository.
 
1126
        
 
1127
        Only affects memory state, until self._save_pack_names() is invoked.
 
1128
        """
 
1129
        self._names.pop(pack.name)
 
1130
        self._packs_by_name.pop(pack.name)
 
1131
        self._remove_pack_indices(pack)
 
1132
 
 
1133
    def _remove_pack_indices(self, pack):
 
1134
        """Remove the indices for pack from the aggregated indices."""
 
1135
        self.revision_index.remove_index(pack.revision_index, pack)
 
1136
        self.inventory_index.remove_index(pack.inventory_index, pack)
 
1137
        self.text_index.remove_index(pack.text_index, pack)
 
1138
        self.signature_index.remove_index(pack.signature_index, pack)
 
1139
 
 
1140
    def reset(self):
 
1141
        """Clear all cached data."""
 
1142
        # cached revision data
 
1143
        self.repo._revision_knit = None
 
1144
        self.revision_index.clear()
 
1145
        # cached signature data
 
1146
        self.repo._signature_knit = None
 
1147
        self.signature_index.clear()
 
1148
        # cached file text data
 
1149
        self.text_index.clear()
 
1150
        self.repo._text_knit = None
 
1151
        # cached inventory data
 
1152
        self.inventory_index.clear()
 
1153
        # remove the open pack
 
1154
        self._new_pack = None
 
1155
        # information about packs.
 
1156
        self._names = None
 
1157
        self.packs = []
 
1158
        self._packs_by_name = {}
 
1159
        self._packs_at_load = None
 
1160
 
 
1161
    def _make_index_map(self, index_suffix):
 
1162
        """Return information on existing indices.
 
1163
 
 
1164
        :param suffix: Index suffix added to pack name.
 
1165
 
 
1166
        :returns: (pack_map, indices) where indices is a list of GraphIndex 
 
1167
        objects, and pack_map is a mapping from those objects to the 
 
1168
        pack tuple they describe.
 
1169
        """
 
1170
        # TODO: stop using this; it creates new indices unnecessarily.
 
1171
        self.ensure_loaded()
 
1172
        suffix_map = {'.rix': 'revision_index',
 
1173
            '.six': 'signature_index',
 
1174
            '.iix': 'inventory_index',
 
1175
            '.tix': 'text_index',
 
1176
        }
 
1177
        return self._packs_list_to_pack_map_and_index_list(self.all_packs(),
 
1178
            suffix_map[index_suffix])
 
1179
 
 
1180
    def _packs_list_to_pack_map_and_index_list(self, packs, index_attribute):
 
1181
        """Convert a list of packs to an index pack map and index list.
 
1182
 
 
1183
        :param packs: The packs list to process.
 
1184
        :param index_attribute: The attribute that the desired index is found
 
1185
            on.
 
1186
        :return: A tuple (map, list) where map contains the dict from
 
1187
            index:pack_tuple, and lsit contains the indices in the same order
 
1188
            as the packs list.
 
1189
        """
 
1190
        indices = []
 
1191
        pack_map = {}
 
1192
        for pack in packs:
 
1193
            index = getattr(pack, index_attribute)
 
1194
            indices.append(index)
 
1195
            pack_map[index] = (pack.pack_transport, pack.file_name())
 
1196
        return pack_map, indices
 
1197
 
 
1198
    def _index_contents(self, pack_map, key_filter=None):
 
1199
        """Get an iterable of the index contents from a pack_map.
 
1200
 
 
1201
        :param pack_map: A map from indices to pack details.
 
1202
        :param key_filter: An optional filter to limit the
 
1203
            keys returned.
 
1204
        """
 
1205
        indices = [index for index in pack_map.iterkeys()]
 
1206
        all_index = CombinedGraphIndex(indices)
 
1207
        if key_filter is None:
 
1208
            return all_index.iter_all_entries()
 
1209
        else:
 
1210
            return all_index.iter_entries(key_filter)
 
1211
 
 
1212
    def _unlock_names(self):
 
1213
        """Release the mutex around the pack-names index."""
 
1214
        self.repo.control_files.unlock()
 
1215
 
 
1216
    def _save_pack_names(self, clear_obsolete_packs=False):
 
1217
        """Save the list of packs.
 
1218
 
 
1219
        This will take out the mutex around the pack names list for the
 
1220
        duration of the method call. If concurrent updates have been made, a
 
1221
        three-way merge between the current list and the current in memory list
 
1222
        is performed.
 
1223
 
 
1224
        :param clear_obsolete_packs: If True, clear out the contents of the
 
1225
            obsolete_packs directory.
 
1226
        """
 
1227
        self.lock_names()
 
1228
        try:
 
1229
            builder = GraphIndexBuilder()
 
1230
            # load the disk nodes across
 
1231
            disk_nodes = set()
 
1232
            for index, key, value in self._iter_disk_pack_index():
 
1233
                disk_nodes.add((key, value))
 
1234
            # do a two-way diff against our original content
 
1235
            current_nodes = set()
 
1236
            for name, sizes in self._names.iteritems():
 
1237
                current_nodes.add(
 
1238
                    ((name, ), ' '.join(str(size) for size in sizes)))
 
1239
            deleted_nodes = self._packs_at_load - current_nodes
 
1240
            new_nodes = current_nodes - self._packs_at_load
 
1241
            disk_nodes.difference_update(deleted_nodes)
 
1242
            disk_nodes.update(new_nodes)
 
1243
            # TODO: handle same-name, index-size-changes here - 
 
1244
            # e.g. use the value from disk, not ours, *unless* we're the one
 
1245
            # changing it.
 
1246
            for key, value in disk_nodes:
 
1247
                builder.add_node(key, value)
 
1248
            self.transport.put_file('pack-names', builder.finish())
 
1249
            # move the baseline forward
 
1250
            self._packs_at_load = disk_nodes
 
1251
            # now clear out the obsolete packs directory
 
1252
            if clear_obsolete_packs:
 
1253
                self.transport.clone('obsolete_packs').delete_multi(
 
1254
                    self.transport.list_dir('obsolete_packs'))
 
1255
        finally:
 
1256
            self._unlock_names()
 
1257
        # synchronise the memory packs list with what we just wrote:
 
1258
        new_names = dict(disk_nodes)
 
1259
        # drop no longer present nodes
 
1260
        for pack in self.all_packs():
 
1261
            if (pack.name,) not in new_names:
 
1262
                self._remove_pack_from_memory(pack)
 
1263
        # add new nodes/refresh existing ones
 
1264
        for key, value in disk_nodes:
 
1265
            name = key[0]
 
1266
            sizes = self._parse_index_sizes(value)
 
1267
            if name in self._names:
 
1268
                # existing
 
1269
                if sizes != self._names[name]:
 
1270
                    # the pack for name has had its indices replaced - rare but
 
1271
                    # important to handle. XXX: probably can never happen today
 
1272
                    # because the three-way merge code above does not handle it
 
1273
                    # - you may end up adding the same key twice to the new
 
1274
                    # disk index because the set values are the same, unless
 
1275
                    # the only index shows up as deleted by the set difference
 
1276
                    # - which it may. Until there is a specific test for this,
 
1277
                    # assume its broken. RBC 20071017.
 
1278
                    self._remove_pack_from_memory(self.get_pack_by_name(name))
 
1279
                    self._names[name] = sizes
 
1280
                    self.get_pack_by_name(name)
 
1281
            else:
 
1282
                # new
 
1283
                self._names[name] = sizes
 
1284
                self.get_pack_by_name(name)
 
1285
 
 
1286
    def _start_write_group(self):
 
1287
        # Do not permit preparation for writing if we're not in a 'write lock'.
 
1288
        if not self.repo.is_write_locked():
 
1289
            raise errors.NotWriteLocked(self)
 
1290
        self._new_pack = NewPack(self._upload_transport, self._index_transport,
 
1291
            self._pack_transport, upload_suffix='.pack')
 
1292
        # allow writing: queue writes to a new index
 
1293
        self.revision_index.add_writable_index(self._new_pack.revision_index,
 
1294
            self._new_pack)
 
1295
        self.inventory_index.add_writable_index(self._new_pack.inventory_index,
 
1296
            self._new_pack)
 
1297
        self.text_index.add_writable_index(self._new_pack.text_index,
 
1298
            self._new_pack)
 
1299
        self.signature_index.add_writable_index(self._new_pack.signature_index,
 
1300
            self._new_pack)
 
1301
 
 
1302
        # reused revision and signature knits may need updating
 
1303
        #
 
1304
        # "Hysterical raisins. client code in bzrlib grabs those knits outside
 
1305
        # of write groups and then mutates it inside the write group."
 
1306
        if self.repo._revision_knit is not None:
 
1307
            self.repo._revision_knit._index._add_callback = \
 
1308
                self.revision_index.add_callback
 
1309
        if self.repo._signature_knit is not None:
 
1310
            self.repo._signature_knit._index._add_callback = \
 
1311
                self.signature_index.add_callback
 
1312
        # create a reused knit object for text addition in commit.
 
1313
        self.repo._text_knit = self.repo.weave_store.get_weave_or_empty(
 
1314
            'all-texts', None)
 
1315
 
 
1316
    def _abort_write_group(self):
 
1317
        # FIXME: just drop the transient index.
 
1318
        # forget what names there are
 
1319
        self._new_pack.abort()
 
1320
        self._remove_pack_indices(self._new_pack)
 
1321
        self._new_pack = None
 
1322
        self.repo._text_knit = None
 
1323
 
 
1324
    def _commit_write_group(self):
 
1325
        self._remove_pack_indices(self._new_pack)
 
1326
        if self._new_pack.data_inserted():
 
1327
            # get all the data to disk and read to use
 
1328
            self._new_pack.finish()
 
1329
            self.allocate(self._new_pack)
 
1330
            self._new_pack = None
 
1331
            if not self.autopack():
 
1332
                # when autopack takes no steps, the names list is still
 
1333
                # unsaved.
 
1334
                self._save_pack_names()
 
1335
        else:
 
1336
            self._new_pack.abort()
 
1337
            self._new_pack = None
 
1338
        self.repo._text_knit = None
 
1339
 
 
1340
 
 
1341
class KnitPackRevisionStore(KnitRevisionStore):
 
1342
    """An object to adapt access from RevisionStore's to use KnitPacks.
 
1343
 
 
1344
    This class works by replacing the original RevisionStore.
 
1345
    We need to do this because the KnitPackRevisionStore is less
 
1346
    isolated in its layering - it uses services from the repo.
 
1347
    """
 
1348
 
 
1349
    def __init__(self, repo, transport, revisionstore):
 
1350
        """Create a KnitPackRevisionStore on repo with revisionstore.
 
1351
 
 
1352
        This will store its state in the Repository, use the
 
1353
        indices to provide a KnitGraphIndex,
 
1354
        and at the end of transactions write new indices.
 
1355
        """
 
1356
        KnitRevisionStore.__init__(self, revisionstore.versioned_file_store)
 
1357
        self.repo = repo
 
1358
        self._serializer = revisionstore._serializer
 
1359
        self.transport = transport
 
1360
 
 
1361
    def get_revision_file(self, transaction):
 
1362
        """Get the revision versioned file object."""
 
1363
        if getattr(self.repo, '_revision_knit', None) is not None:
 
1364
            return self.repo._revision_knit
 
1365
        self.repo._pack_collection.ensure_loaded()
 
1366
        add_callback = self.repo._pack_collection.revision_index.add_callback
 
1367
        # setup knit specific objects
 
1368
        knit_index = KnitGraphIndex(
 
1369
            self.repo._pack_collection.revision_index.combined_index,
 
1370
            add_callback=add_callback)
 
1371
        self.repo._revision_knit = knit.KnitVersionedFile(
 
1372
            'revisions', self.transport.clone('..'),
 
1373
            self.repo.control_files._file_mode,
 
1374
            create=False, access_mode=self.repo._access_mode(),
 
1375
            index=knit_index, delta=False, factory=knit.KnitPlainFactory(),
 
1376
            access_method=self.repo._pack_collection.revision_index.knit_access)
 
1377
        return self.repo._revision_knit
 
1378
 
 
1379
    def get_signature_file(self, transaction):
 
1380
        """Get the signature versioned file object."""
 
1381
        if getattr(self.repo, '_signature_knit', None) is not None:
 
1382
            return self.repo._signature_knit
 
1383
        self.repo._pack_collection.ensure_loaded()
 
1384
        add_callback = self.repo._pack_collection.signature_index.add_callback
 
1385
        # setup knit specific objects
 
1386
        knit_index = KnitGraphIndex(
 
1387
            self.repo._pack_collection.signature_index.combined_index,
 
1388
            add_callback=add_callback, parents=False)
 
1389
        self.repo._signature_knit = knit.KnitVersionedFile(
 
1390
            'signatures', self.transport.clone('..'),
 
1391
            self.repo.control_files._file_mode,
 
1392
            create=False, access_mode=self.repo._access_mode(),
 
1393
            index=knit_index, delta=False, factory=knit.KnitPlainFactory(),
 
1394
            access_method=self.repo._pack_collection.signature_index.knit_access)
 
1395
        return self.repo._signature_knit
 
1396
 
 
1397
 
 
1398
class KnitPackTextStore(VersionedFileStore):
 
1399
    """Presents a TextStore abstraction on top of packs.
 
1400
 
 
1401
    This class works by replacing the original VersionedFileStore.
 
1402
    We need to do this because the KnitPackRevisionStore is less
 
1403
    isolated in its layering - it uses services from the repo and shares them
 
1404
    with all the data written in a single write group.
 
1405
    """
 
1406
 
 
1407
    def __init__(self, repo, transport, weavestore):
 
1408
        """Create a KnitPackTextStore on repo with weavestore.
 
1409
 
 
1410
        This will store its state in the Repository, use the
 
1411
        indices FileNames to provide a KnitGraphIndex,
 
1412
        and at the end of transactions write new indices.
 
1413
        """
 
1414
        # don't call base class constructor - it's not suitable.
 
1415
        # no transient data stored in the transaction
 
1416
        # cache.
 
1417
        self._precious = False
 
1418
        self.repo = repo
 
1419
        self.transport = transport
 
1420
        self.weavestore = weavestore
 
1421
        # XXX for check() which isn't updated yet
 
1422
        self._transport = weavestore._transport
 
1423
 
 
1424
    def get_weave_or_empty(self, file_id, transaction):
 
1425
        """Get a 'Knit' backed by the .tix indices.
 
1426
 
 
1427
        The transaction parameter is ignored.
 
1428
        """
 
1429
        self.repo._pack_collection.ensure_loaded()
 
1430
        add_callback = self.repo._pack_collection.text_index.add_callback
 
1431
        # setup knit specific objects
 
1432
        file_id_index = GraphIndexPrefixAdapter(
 
1433
            self.repo._pack_collection.text_index.combined_index,
 
1434
            (file_id, ), 1, add_nodes_callback=add_callback)
 
1435
        knit_index = KnitGraphIndex(file_id_index,
 
1436
            add_callback=file_id_index.add_nodes,
 
1437
            deltas=True, parents=True)
 
1438
        return knit.KnitVersionedFile('text:' + file_id,
 
1439
            self.transport.clone('..'),
 
1440
            None,
 
1441
            index=knit_index,
 
1442
            access_method=self.repo._pack_collection.text_index.knit_access,
 
1443
            factory=knit.KnitPlainFactory())
 
1444
 
 
1445
    get_weave = get_weave_or_empty
 
1446
 
 
1447
    def __iter__(self):
 
1448
        """Generate a list of the fileids inserted, for use by check."""
 
1449
        self.repo._pack_collection.ensure_loaded()
 
1450
        ids = set()
 
1451
        for index, key, value, refs in \
 
1452
            self.repo._pack_collection.text_index.combined_index.iter_all_entries():
 
1453
            ids.add(key[0])
 
1454
        return iter(ids)
 
1455
 
 
1456
 
 
1457
class InventoryKnitThunk(object):
 
1458
    """An object to manage thunking get_inventory_weave to pack based knits."""
 
1459
 
 
1460
    def __init__(self, repo, transport):
 
1461
        """Create an InventoryKnitThunk for repo at transport.
 
1462
 
 
1463
        This will store its state in the Repository, use the
 
1464
        indices FileNames to provide a KnitGraphIndex,
 
1465
        and at the end of transactions write a new index..
 
1466
        """
 
1467
        self.repo = repo
 
1468
        self.transport = transport
 
1469
 
 
1470
    def get_weave(self):
 
1471
        """Get a 'Knit' that contains inventory data."""
 
1472
        self.repo._pack_collection.ensure_loaded()
 
1473
        add_callback = self.repo._pack_collection.inventory_index.add_callback
 
1474
        # setup knit specific objects
 
1475
        knit_index = KnitGraphIndex(
 
1476
            self.repo._pack_collection.inventory_index.combined_index,
 
1477
            add_callback=add_callback, deltas=True, parents=True)
 
1478
        return knit.KnitVersionedFile(
 
1479
            'inventory', self.transport.clone('..'),
 
1480
            self.repo.control_files._file_mode,
 
1481
            create=False, access_mode=self.repo._access_mode(),
 
1482
            index=knit_index, delta=True, factory=knit.KnitPlainFactory(),
 
1483
            access_method=self.repo._pack_collection.inventory_index.knit_access)
 
1484
 
 
1485
 
 
1486
class KnitPackRepository(KnitRepository):
 
1487
    """Experimental graph-knit using repository."""
 
1488
 
 
1489
    def __init__(self, _format, a_bzrdir, control_files, _revision_store,
 
1490
        control_store, text_store, _commit_builder_class, _serializer):
 
1491
        KnitRepository.__init__(self, _format, a_bzrdir, control_files,
 
1492
            _revision_store, control_store, text_store, _commit_builder_class,
 
1493
            _serializer)
 
1494
        index_transport = control_files._transport.clone('indices')
 
1495
        self._pack_collection = RepositoryPackCollection(self, control_files._transport,
 
1496
            index_transport,
 
1497
            control_files._transport.clone('upload'),
 
1498
            control_files._transport.clone('packs'))
 
1499
        self._revision_store = KnitPackRevisionStore(self, index_transport, self._revision_store)
 
1500
        self.weave_store = KnitPackTextStore(self, index_transport, self.weave_store)
 
1501
        self._inv_thunk = InventoryKnitThunk(self, index_transport)
 
1502
        # True when the repository object is 'write locked' (as opposed to the
 
1503
        # physical lock only taken out around changes to the pack-names list.) 
 
1504
        # Another way to represent this would be a decorator around the control
 
1505
        # files object that presents logical locks as physical ones - if this
 
1506
        # gets ugly consider that alternative design. RBC 20071011
 
1507
        self._write_lock_count = 0
 
1508
        self._transaction = None
 
1509
        # for tests
 
1510
        self._reconcile_does_inventory_gc = True
 
1511
        self._reconcile_fixes_text_parents = False
 
1512
        self._reconcile_backsup_inventory = False
 
1513
 
 
1514
    def _abort_write_group(self):
 
1515
        self._pack_collection._abort_write_group()
 
1516
 
 
1517
    def _access_mode(self):
 
1518
        """Return 'w' or 'r' for depending on whether a write lock is active.
 
1519
        
 
1520
        This method is a helper for the Knit-thunking support objects.
 
1521
        """
 
1522
        if self.is_write_locked():
 
1523
            return 'w'
 
1524
        return 'r'
 
1525
 
 
1526
    def _find_inconsistent_revision_parents(self):
 
1527
        """Find revisions with incorrectly cached parents.
 
1528
 
 
1529
        :returns: an iterator yielding tuples of (revison-id, parents-in-index,
 
1530
            parents-in-revision).
 
1531
        """
 
1532
        assert self.is_locked()
 
1533
        pb = ui.ui_factory.nested_progress_bar()
 
1534
        result = []
 
1535
        try:
 
1536
            revision_nodes = self._pack_collection.revision_index \
 
1537
                .combined_index.iter_all_entries()
 
1538
            index_positions = []
 
1539
            # Get the cached index values for all revisions, and also the location
 
1540
            # in each index of the revision text so we can perform linear IO.
 
1541
            for index, key, value, refs in revision_nodes:
 
1542
                pos, length = value[1:].split(' ')
 
1543
                index_positions.append((index, int(pos), key[0],
 
1544
                    tuple(parent[0] for parent in refs[0])))
 
1545
                pb.update("Reading revision index.", 0, 0)
 
1546
            index_positions.sort()
 
1547
            batch_count = len(index_positions) / 1000 + 1
 
1548
            pb.update("Checking cached revision graph.", 0, batch_count)
 
1549
            for offset in xrange(batch_count):
 
1550
                pb.update("Checking cached revision graph.", offset)
 
1551
                to_query = index_positions[offset * 1000:(offset + 1) * 1000]
 
1552
                if not to_query:
 
1553
                    break
 
1554
                rev_ids = [item[2] for item in to_query]
 
1555
                revs = self.get_revisions(rev_ids)
 
1556
                for revision, item in zip(revs, to_query):
 
1557
                    index_parents = item[3]
 
1558
                    rev_parents = tuple(revision.parent_ids)
 
1559
                    if index_parents != rev_parents:
 
1560
                        result.append((revision.revision_id, index_parents, rev_parents))
 
1561
        finally:
 
1562
            pb.finished()
 
1563
        return result
 
1564
 
 
1565
    def get_parents(self, revision_ids):
 
1566
        """See StackedParentsProvider.get_parents.
 
1567
        
 
1568
        This implementation accesses the combined revision index to provide
 
1569
        answers.
 
1570
        """
 
1571
        self._pack_collection.ensure_loaded()
 
1572
        index = self._pack_collection.revision_index.combined_index
 
1573
        search_keys = set()
 
1574
        for revision_id in revision_ids:
 
1575
            if revision_id != _mod_revision.NULL_REVISION:
 
1576
                search_keys.add((revision_id,))
 
1577
        found_parents = {_mod_revision.NULL_REVISION:[]}
 
1578
        for index, key, value, refs in index.iter_entries(search_keys):
 
1579
            parents = refs[0]
 
1580
            if not parents:
 
1581
                parents = (_mod_revision.NULL_REVISION,)
 
1582
            else:
 
1583
                parents = tuple(parent[0] for parent in parents)
 
1584
            found_parents[key[0]] = parents
 
1585
        result = []
 
1586
        for revision_id in revision_ids:
 
1587
            try:
 
1588
                result.append(found_parents[revision_id])
 
1589
            except KeyError:
 
1590
                result.append(None)
 
1591
        return result
 
1592
 
 
1593
    def _make_parents_provider(self):
 
1594
        return self
 
1595
 
 
1596
    def _refresh_data(self):
 
1597
        if self._write_lock_count == 1 or (
 
1598
            self.control_files._lock_count == 1 and
 
1599
            self.control_files._lock_mode == 'r'):
 
1600
            # forget what names there are
 
1601
            self._pack_collection.reset()
 
1602
            # XXX: Better to do an in-memory merge when acquiring a new lock -
 
1603
            # factor out code from _save_pack_names.
 
1604
            self._pack_collection.ensure_loaded()
 
1605
 
 
1606
    def _start_write_group(self):
 
1607
        self._pack_collection._start_write_group()
 
1608
 
 
1609
    def _commit_write_group(self):
 
1610
        return self._pack_collection._commit_write_group()
 
1611
 
 
1612
    def get_inventory_weave(self):
 
1613
        return self._inv_thunk.get_weave()
 
1614
 
 
1615
    def get_transaction(self):
 
1616
        if self._write_lock_count:
 
1617
            return self._transaction
 
1618
        else:
 
1619
            return self.control_files.get_transaction()
 
1620
 
 
1621
    def is_locked(self):
 
1622
        return self._write_lock_count or self.control_files.is_locked()
 
1623
 
 
1624
    def is_write_locked(self):
 
1625
        return self._write_lock_count
 
1626
 
 
1627
    def lock_write(self, token=None):
 
1628
        if not self._write_lock_count and self.is_locked():
 
1629
            raise errors.ReadOnlyError(self)
 
1630
        self._write_lock_count += 1
 
1631
        if self._write_lock_count == 1:
 
1632
            from bzrlib import transactions
 
1633
            self._transaction = transactions.WriteTransaction()
 
1634
        self._refresh_data()
 
1635
 
 
1636
    def lock_read(self):
 
1637
        if self._write_lock_count:
 
1638
            self._write_lock_count += 1
 
1639
        else:
 
1640
            self.control_files.lock_read()
 
1641
        self._refresh_data()
 
1642
 
 
1643
    def leave_lock_in_place(self):
 
1644
        # not supported - raise an error
 
1645
        raise NotImplementedError(self.leave_lock_in_place)
 
1646
 
 
1647
    def dont_leave_lock_in_place(self):
 
1648
        # not supported - raise an error
 
1649
        raise NotImplementedError(self.dont_leave_lock_in_place)
 
1650
 
 
1651
    @needs_write_lock
 
1652
    def pack(self):
 
1653
        """Compress the data within the repository.
 
1654
 
 
1655
        This will pack all the data to a single pack. In future it may
 
1656
        recompress deltas or do other such expensive operations.
 
1657
        """
 
1658
        self._pack_collection.pack()
 
1659
 
 
1660
    @needs_write_lock
 
1661
    def reconcile(self, other=None, thorough=False):
 
1662
        """Reconcile this repository."""
 
1663
        from bzrlib.reconcile import PackReconciler
 
1664
        reconciler = PackReconciler(self, thorough=thorough)
 
1665
        reconciler.reconcile()
 
1666
        return reconciler
 
1667
 
 
1668
    def unlock(self):
 
1669
        if self._write_lock_count == 1 and self._write_group is not None:
 
1670
            self.abort_write_group()
 
1671
            self._transaction = None
 
1672
            self._write_lock_count = 0
 
1673
            raise errors.BzrError(
 
1674
                'Must end write group before releasing write lock on %s'
 
1675
                % self)
 
1676
        if self._write_lock_count:
 
1677
            self._write_lock_count -= 1
 
1678
            if not self._write_lock_count:
 
1679
                transaction = self._transaction
 
1680
                self._transaction = None
 
1681
                transaction.finish()
 
1682
        else:
 
1683
            self.control_files.unlock()
 
1684
 
 
1685
 
 
1686
class RepositoryFormatPack(MetaDirRepositoryFormat):
 
1687
    """Format logic for pack structured repositories.
 
1688
 
 
1689
    This repository format has:
 
1690
     - a list of packs in pack-names
 
1691
     - packs in packs/NAME.pack
 
1692
     - indices in indices/NAME.{iix,six,tix,rix}
 
1693
     - knit deltas in the packs, knit indices mapped to the indices.
 
1694
     - thunk objects to support the knits programming API.
 
1695
     - a format marker of its own
 
1696
     - an optional 'shared-storage' flag
 
1697
     - an optional 'no-working-trees' flag
 
1698
     - a LockDir lock
 
1699
    """
 
1700
 
 
1701
    # Set this attribute in derived classes to control the repository class
 
1702
    # created by open and initialize.
 
1703
    repository_class = None
 
1704
    # Set this attribute in derived classes to control the
 
1705
    # _commit_builder_class that the repository objects will have passed to
 
1706
    # their constructor.
 
1707
    _commit_builder_class = None
 
1708
    # Set this attribute in derived clases to control the _serializer that the
 
1709
    # repository objects will have passed to their constructor.
 
1710
    _serializer = None
 
1711
 
 
1712
    def _get_control_store(self, repo_transport, control_files):
 
1713
        """Return the control store for this repository."""
 
1714
        return VersionedFileStore(
 
1715
            repo_transport,
 
1716
            prefixed=False,
 
1717
            file_mode=control_files._file_mode,
 
1718
            versionedfile_class=knit.KnitVersionedFile,
 
1719
            versionedfile_kwargs={'factory': knit.KnitPlainFactory()},
 
1720
            )
 
1721
 
 
1722
    def _get_revision_store(self, repo_transport, control_files):
 
1723
        """See RepositoryFormat._get_revision_store()."""
 
1724
        versioned_file_store = VersionedFileStore(
 
1725
            repo_transport,
 
1726
            file_mode=control_files._file_mode,
 
1727
            prefixed=False,
 
1728
            precious=True,
 
1729
            versionedfile_class=knit.KnitVersionedFile,
 
1730
            versionedfile_kwargs={'delta': False,
 
1731
                                  'factory': knit.KnitPlainFactory(),
 
1732
                                 },
 
1733
            escaped=True,
 
1734
            )
 
1735
        return KnitRevisionStore(versioned_file_store)
 
1736
 
 
1737
    def _get_text_store(self, transport, control_files):
 
1738
        """See RepositoryFormat._get_text_store()."""
 
1739
        return self._get_versioned_file_store('knits',
 
1740
                                  transport,
 
1741
                                  control_files,
 
1742
                                  versionedfile_class=knit.KnitVersionedFile,
 
1743
                                  versionedfile_kwargs={
 
1744
                                      'create_parent_dir': True,
 
1745
                                      'delay_create': True,
 
1746
                                      'dir_mode': control_files._dir_mode,
 
1747
                                  },
 
1748
                                  escaped=True)
 
1749
 
 
1750
    def initialize(self, a_bzrdir, shared=False):
 
1751
        """Create a pack based repository.
 
1752
 
 
1753
        :param a_bzrdir: bzrdir to contain the new repository; must already
 
1754
            be initialized.
 
1755
        :param shared: If true the repository will be initialized as a shared
 
1756
                       repository.
 
1757
        """
 
1758
        mutter('creating repository in %s.', a_bzrdir.transport.base)
 
1759
        dirs = ['indices', 'obsolete_packs', 'packs', 'upload']
 
1760
        builder = GraphIndexBuilder()
 
1761
        files = [('pack-names', builder.finish())]
 
1762
        utf8_files = [('format', self.get_format_string())]
 
1763
        
 
1764
        self._upload_blank_content(a_bzrdir, dirs, files, utf8_files, shared)
 
1765
        return self.open(a_bzrdir=a_bzrdir, _found=True)
 
1766
 
 
1767
    def open(self, a_bzrdir, _found=False, _override_transport=None):
 
1768
        """See RepositoryFormat.open().
 
1769
        
 
1770
        :param _override_transport: INTERNAL USE ONLY. Allows opening the
 
1771
                                    repository at a slightly different url
 
1772
                                    than normal. I.e. during 'upgrade'.
 
1773
        """
 
1774
        if not _found:
 
1775
            format = RepositoryFormat.find_format(a_bzrdir)
 
1776
            assert format.__class__ ==  self.__class__
 
1777
        if _override_transport is not None:
 
1778
            repo_transport = _override_transport
 
1779
        else:
 
1780
            repo_transport = a_bzrdir.get_repository_transport(None)
 
1781
        control_files = lockable_files.LockableFiles(repo_transport,
 
1782
                                'lock', lockdir.LockDir)
 
1783
        text_store = self._get_text_store(repo_transport, control_files)
 
1784
        control_store = self._get_control_store(repo_transport, control_files)
 
1785
        _revision_store = self._get_revision_store(repo_transport, control_files)
 
1786
        return self.repository_class(_format=self,
 
1787
                              a_bzrdir=a_bzrdir,
 
1788
                              control_files=control_files,
 
1789
                              _revision_store=_revision_store,
 
1790
                              control_store=control_store,
 
1791
                              text_store=text_store,
 
1792
                              _commit_builder_class=self._commit_builder_class,
 
1793
                              _serializer=self._serializer)
 
1794
 
 
1795
 
 
1796
class RepositoryFormatKnitPack1(RepositoryFormatPack):
 
1797
    """A no-subtrees parameterised Pack repository.
 
1798
 
 
1799
    This format was introduced in 0.92.
 
1800
    """
 
1801
 
 
1802
    repository_class = KnitPackRepository
 
1803
    _commit_builder_class = PackCommitBuilder
 
1804
    _serializer = xml5.serializer_v5
 
1805
 
 
1806
    def _get_matching_bzrdir(self):
 
1807
        return bzrdir.format_registry.make_bzrdir('knitpack-experimental')
 
1808
 
 
1809
    def _ignore_setting_bzrdir(self, format):
 
1810
        pass
 
1811
 
 
1812
    _matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
 
1813
 
 
1814
    def get_format_string(self):
 
1815
        """See RepositoryFormat.get_format_string()."""
 
1816
        return "Bazaar pack repository format 1 (needs bzr 0.92)\n"
 
1817
 
 
1818
    def get_format_description(self):
 
1819
        """See RepositoryFormat.get_format_description()."""
 
1820
        return "Packs containing knits without subtree support"
 
1821
 
 
1822
    def check_conversion_target(self, target_format):
 
1823
        pass
 
1824
 
 
1825
 
 
1826
class RepositoryFormatKnitPack3(RepositoryFormatPack):
 
1827
    """A subtrees parameterised Pack repository.
 
1828
 
 
1829
    This repository format uses the xml7 serializer to get:
 
1830
     - support for recording full info about the tree root
 
1831
     - support for recording tree-references
 
1832
 
 
1833
    This format was introduced in 0.92.
 
1834
    """
 
1835
 
 
1836
    repository_class = KnitPackRepository
 
1837
    _commit_builder_class = PackRootCommitBuilder
 
1838
    rich_root_data = True
 
1839
    supports_tree_reference = True
 
1840
    _serializer = xml7.serializer_v7
 
1841
 
 
1842
    def _get_matching_bzrdir(self):
 
1843
        return bzrdir.format_registry.make_bzrdir(
 
1844
            'knitpack-subtree-experimental')
 
1845
 
 
1846
    def _ignore_setting_bzrdir(self, format):
 
1847
        pass
 
1848
 
 
1849
    _matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
 
1850
 
 
1851
    def check_conversion_target(self, target_format):
 
1852
        if not target_format.rich_root_data:
 
1853
            raise errors.BadConversionTarget(
 
1854
                'Does not support rich root data.', target_format)
 
1855
        if not getattr(target_format, 'supports_tree_reference', False):
 
1856
            raise errors.BadConversionTarget(
 
1857
                'Does not support nested trees', target_format)
 
1858
            
 
1859
    def get_format_string(self):
 
1860
        """See RepositoryFormat.get_format_string()."""
 
1861
        return "Bazaar pack repository format 1 with subtree support (needs bzr 0.92)\n"
 
1862
 
 
1863
    def get_format_description(self):
 
1864
        """See RepositoryFormat.get_format_description()."""
 
1865
        return "Packs containing knits with subtree support\n"