/brz/remove-bazaar

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