/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
1608.2.1 by Martin Pool
[merge] Storage filename escaping
1
# Copyright (C) 2005, 2006 Canonical Ltd
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
2
#
1196 by Martin Pool
- [WIP] retrieve historical texts from weaves
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.
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
7
#
1196 by Martin Pool
- [WIP] retrieve historical texts from weaves
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.
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
12
#
1196 by Martin Pool
- [WIP] retrieve historical texts from weaves
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
1393.1.19 by Martin Pool
- add WeaveStore.__iter__, __contains__ and copy_multi()
17
# XXX: Some consideration of the problems that might occur if there are
18
# files whose id differs only in case.  That should probably be forbidden.
19
20
1471 by Robert Collins
Bugfix to previous url escaping patch - include weave stores
21
import errno
22
import os
1393.1.19 by Martin Pool
- add WeaveStore.__iter__, __contains__ and copy_multi()
23
from cStringIO import StringIO
1471 by Robert Collins
Bugfix to previous url escaping patch - include weave stores
24
import urllib
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
25
from warnings import warn
1223 by Martin Pool
- store inventories in weave
26
2294.1.10 by John Arbash Meinel
Switch all apis over to utf8 file ids. All tests pass
27
from bzrlib import (
28
    errors,
29
    osutils,
30
    )
1223 by Martin Pool
- store inventories in weave
31
from bzrlib.weavefile import read_weave, write_weave_v5
1608.2.1 by Martin Pool
[merge] Storage filename escaping
32
from bzrlib.weave import WeaveFile, Weave
1185.80.6 by John Arbash Meinel
Adding tests to make sure weave stores can retrieve the files they add.
33
from bzrlib.store import TransportStore
1223 by Martin Pool
- store inventories in weave
34
from bzrlib.atomicfile import AtomicFile
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
35
from bzrlib.symbol_versioning import (deprecated_method,
2696.1.1 by Martin Pool
Remove things deprecated in 0.11 and earlier
36
        )
1393.1.19 by Martin Pool
- add WeaveStore.__iter__, __contains__ and copy_multi()
37
from bzrlib.trace import mutter
1185.80.10 by John Arbash Meinel
Adding progress indicators and improved get order for 'bzr branch'
38
import bzrlib.ui
1393.2.2 by John Arbash Meinel
Updated stores to use Transport
39
40
1563.2.16 by Robert Collins
Change WeaveStore into VersionedFileStore and make its versoined file class parameterisable.
41
class VersionedFileStore(TransportStore):
42
    """Collection of many versioned files in a transport."""
1393.1.19 by Martin Pool
- add WeaveStore.__iter__, __contains__ and copy_multi()
43
1651.1.1 by Martin Pool
[merge][wip] Storage escaping
44
    # TODO: Rather than passing versionedfile_kwargs, perhaps pass in a
45
    # transport factory callable?
1185.58.4 by John Arbash Meinel
Added permission checking to Branch, and propogated that change into the stores.
46
    def __init__(self, transport, prefixed=False, precious=False,
1563.2.16 by Robert Collins
Change WeaveStore into VersionedFileStore and make its versoined file class parameterisable.
47
                 dir_mode=None, file_mode=None,
1608.2.1 by Martin Pool
[merge] Storage filename escaping
48
                 versionedfile_class=WeaveFile,
1651.1.1 by Martin Pool
[merge][wip] Storage escaping
49
                 versionedfile_kwargs={},
1608.2.1 by Martin Pool
[merge] Storage filename escaping
50
                 escaped=False):
51
        super(VersionedFileStore, self).__init__(transport,
1185.58.4 by John Arbash Meinel
Added permission checking to Branch, and propogated that change into the stores.
52
                dir_mode=dir_mode, file_mode=file_mode,
1185.80.1 by John Arbash Meinel
Text store and weave store both allow escaping fileid paths.
53
                prefixed=prefixed, compressed=False, escaped=escaped)
1417.1.10 by Robert Collins
add a cache bound to Transactions, and a precious facility, so that we keep inventory.weave in memory, but can discard weaves for other such files.
54
        self._precious = precious
1563.2.16 by Robert Collins
Change WeaveStore into VersionedFileStore and make its versoined file class parameterisable.
55
        self._versionedfile_class = versionedfile_class
1628.1.4 by Robert Collins
Change knit format to use non-delta, non-annotated revisions and signatures.
56
        self._versionedfile_kwargs = versionedfile_kwargs
1196 by Martin Pool
- [WIP] retrieve historical texts from weaves
57
1563.2.25 by Robert Collins
Merge in upstream.
58
    def _clear_cache_id(self, file_id, transaction):
59
        """WARNING may lead to inconsistent object references for file_id.
60
61
        Remove file_id from the transaction map. 
62
63
        NOT in the transaction api because theres no reliable way to clear
64
        callers. So its here for very specialised use rather than having an
65
        'api' that isn't.
66
        """
67
        weave = transaction.map.find_weave(file_id)
1563.2.34 by Robert Collins
Remove the commit and rollback transaction methods as misleading, and implement a WriteTransaction
68
        if weave is not None:
1563.2.25 by Robert Collins
Merge in upstream.
69
            mutter("old data in transaction in %s for %s", self, file_id)
1563.2.34 by Robert Collins
Remove the commit and rollback transaction methods as misleading, and implement a WriteTransaction
70
            # FIXME abstraction violation - transaction now has stale data.
71
            transaction.map.remove_object(weave)
1196 by Martin Pool
- [WIP] retrieve historical texts from weaves
72
1223 by Martin Pool
- store inventories in weave
73
    def filename(self, file_id):
1393.2.2 by John Arbash Meinel
Updated stores to use Transport
74
        """Return the path relative to the transport root."""
1608.2.1 by Martin Pool
[merge] Storage filename escaping
75
        return self._relpath(file_id)
1429 by Robert Collins
merge in niemeyers prefixed-store patch
76
1393.1.19 by Martin Pool
- add WeaveStore.__iter__, __contains__ and copy_multi()
77
    def __iter__(self):
1563.2.16 by Robert Collins
Change WeaveStore into VersionedFileStore and make its versoined file class parameterisable.
78
        suffixes = self._versionedfile_class.get_suffixes()
1563.2.15 by Robert Collins
remove the weavestore assumptions about the number and nature of files it manages.
79
        ids = set()
1479 by Robert Collins
More quoting at the transport layer bugfixes.
80
        for relpath in self._iter_files_recursive():
1563.2.15 by Robert Collins
remove the weavestore assumptions about the number and nature of files it manages.
81
            for suffix in suffixes:
82
                if relpath.endswith(suffix):
1608.2.1 by Martin Pool
[merge] Storage filename escaping
83
                    # TODO: use standard remove_suffix function
84
                    escaped_id = os.path.basename(relpath[:-len(suffix)])
85
                    file_id = self._unescape(escaped_id)
86
                    if file_id not in ids:
87
                        ids.add(file_id)
88
                        yield file_id
89
                    break # only one suffix can match
1393.1.19 by Martin Pool
- add WeaveStore.__iter__, __contains__ and copy_multi()
90
2294.1.10 by John Arbash Meinel
Switch all apis over to utf8 file ids. All tests pass
91
    def has_id(self, file_id):
1563.2.16 by Robert Collins
Change WeaveStore into VersionedFileStore and make its versoined file class parameterisable.
92
        suffixes = self._versionedfile_class.get_suffixes()
2294.1.10 by John Arbash Meinel
Switch all apis over to utf8 file ids. All tests pass
93
        filename = self.filename(file_id)
1563.2.15 by Robert Collins
remove the weavestore assumptions about the number and nature of files it manages.
94
        for suffix in suffixes:
95
            if not self._transport.has(filename + suffix):
96
                return False
97
        return True
1223 by Martin Pool
- store inventories in weave
98
1563.2.25 by Robert Collins
Merge in upstream.
99
    def get_empty(self, file_id, transaction):
100
        """Get an empty weave, which implies deleting the existing one first."""
101
        if self.has_id(file_id):
102
            self.delete(file_id, transaction)
103
        return self.get_weave_or_empty(file_id, transaction)
104
105
    def delete(self, file_id, transaction):
106
        """Remove file_id from the store."""
107
        suffixes = self._versionedfile_class.get_suffixes()
108
        filename = self.filename(file_id)
109
        for suffix in suffixes:
110
            self._transport.delete(filename + suffix)
111
        self._clear_cache_id(file_id, transaction)
1393.2.2 by John Arbash Meinel
Updated stores to use Transport
112
113
    def _get(self, file_id):
114
        return self._transport.get(self.filename(file_id))
115
116
    def _put(self, file_id, f):
1185.80.6 by John Arbash Meinel
Adding tests to make sure weave stores can retrieve the files they add.
117
        fn = self.filename(file_id)
118
        try:
1955.3.9 by John Arbash Meinel
Find more occurrances of put() and replace with put_file or put_bytes
119
            return self._transport.put_file(fn, f, mode=self._file_mode)
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
120
        except errors.NoSuchFile:
1185.80.6 by John Arbash Meinel
Adding tests to make sure weave stores can retrieve the files they add.
121
            if not self._prefixed:
122
                raise
123
            self._transport.mkdir(os.path.dirname(fn), mode=self._dir_mode)
1955.3.9 by John Arbash Meinel
Find more occurrances of put() and replace with put_file or put_bytes
124
            return self._transport.put_file(fn, f, mode=self._file_mode)
1223 by Martin Pool
- store inventories in weave
125
1725.2.2 by Robert Collins
reduce file path escaping calls during commit.
126
    def get_weave(self, file_id, transaction, _filename=None):
127
        """Return the VersionedFile for file_id.
128
129
        :param _filename: filename that would be returned from self.filename for
130
        file_id. This is used to reduce duplicate filename calculations when
131
        using 'get_weave_or_empty'. FOR INTERNAL USE ONLY.
132
        """
1417.1.8 by Robert Collins
use transactions in the weave store interface, which enables caching for log
133
        weave = transaction.map.find_weave(file_id)
1563.2.34 by Robert Collins
Remove the commit and rollback transaction methods as misleading, and implement a WriteTransaction
134
        if weave is not None:
1594.3.2 by Robert Collins
make trivial ranges work for HTTP really.
135
            #mutter("cache hit in %s for %s", self, file_id)
1417.1.8 by Robert Collins
use transactions in the weave store interface, which enables caching for log
136
            return weave
1725.2.2 by Robert Collins
reduce file path escaping calls during commit.
137
        if _filename is None:
138
            _filename = self.filename(file_id)
1594.2.23 by Robert Collins
Test versioned file storage handling of clean/dirty status for accessed versioned files.
139
        if transaction.writeable():
1725.2.2 by Robert Collins
reduce file path escaping calls during commit.
140
            w = self._versionedfile_class(_filename, self._transport, self._file_mode,
1628.1.4 by Robert Collins
Change knit format to use non-delta, non-annotated revisions and signatures.
141
                                          **self._versionedfile_kwargs)
1594.2.23 by Robert Collins
Test versioned file storage handling of clean/dirty status for accessed versioned files.
142
            transaction.map.add_weave(file_id, w)
143
            transaction.register_dirty(w)
144
        else:
1725.2.2 by Robert Collins
reduce file path escaping calls during commit.
145
            w = self._versionedfile_class(_filename,
1594.2.23 by Robert Collins
Test versioned file storage handling of clean/dirty status for accessed versioned files.
146
                                          self._transport,
147
                                          self._file_mode,
148
                                          create=False,
1628.1.4 by Robert Collins
Change knit format to use non-delta, non-annotated revisions and signatures.
149
                                          access_mode='r',
150
                                          **self._versionedfile_kwargs)
1594.2.23 by Robert Collins
Test versioned file storage handling of clean/dirty status for accessed versioned files.
151
            transaction.map.add_weave(file_id, w)
152
            transaction.register_clean(w, precious=self._precious)
1363 by Martin Pool
- add quick-and-dirty cache for weaves to speed check command
153
        return w
1262 by Martin Pool
- fetch should also copy ancestry records
154
1725.2.2 by Robert Collins
reduce file path escaping calls during commit.
155
    def _make_new_versionedfile(self, file_id, transaction,
156
        known_missing=False, _filename=None):
157
        """Make a new versioned file.
158
        
159
        :param _filename: filename that would be returned from self.filename for
160
        file_id. This is used to reduce duplicate filename calculations when
161
        using 'get_weave_or_empty'. FOR INTERNAL USE ONLY.
162
        """
163
        if not known_missing and self.has_id(file_id):
1563.2.34 by Robert Collins
Remove the commit and rollback transaction methods as misleading, and implement a WriteTransaction
164
            self.delete(file_id, transaction)
1725.2.2 by Robert Collins
reduce file path escaping calls during commit.
165
        if _filename is None:
166
            _filename = self.filename(file_id)
1563.2.14 by Robert Collins
Prepare weave store to delegate copy details to the versioned file.
167
        try:
1725.2.2 by Robert Collins
reduce file path escaping calls during commit.
168
            # we try without making the directory first because thats optimising
169
            # for the common case.
170
            weave = self._versionedfile_class(_filename, self._transport, self._file_mode, create=True,
1628.1.4 by Robert Collins
Change knit format to use non-delta, non-annotated revisions and signatures.
171
                                              **self._versionedfile_kwargs)
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
172
        except errors.NoSuchFile:
1563.2.14 by Robert Collins
Prepare weave store to delegate copy details to the versioned file.
173
            if not self._prefixed:
1725.2.2 by Robert Collins
reduce file path escaping calls during commit.
174
                # unexpected error - NoSuchFile is expected to be raised on a
175
                # missing dir only and that only occurs when we are prefixed.
1563.2.14 by Robert Collins
Prepare weave store to delegate copy details to the versioned file.
176
                raise
1608.2.1 by Martin Pool
[merge] Storage filename escaping
177
            self._transport.mkdir(self.hash_prefix(file_id), mode=self._dir_mode)
1725.2.2 by Robert Collins
reduce file path escaping calls during commit.
178
            weave = self._versionedfile_class(_filename, self._transport, 
1651.1.1 by Martin Pool
[merge][wip] Storage escaping
179
                                              self._file_mode, create=True,
1628.1.4 by Robert Collins
Change knit format to use non-delta, non-annotated revisions and signatures.
180
                                              **self._versionedfile_kwargs)
1563.2.14 by Robert Collins
Prepare weave store to delegate copy details to the versioned file.
181
        return weave
182
1417.1.8 by Robert Collins
use transactions in the weave store interface, which enables caching for log
183
    def get_weave_or_empty(self, file_id, transaction):
1725.2.2 by Robert Collins
reduce file path escaping calls during commit.
184
        """Return a weave, or an empty one if it doesn't exist."""
185
        # This is typically used from 'commit' and 'fetch/push/pull' where 
186
        # we scan across many versioned files once. As such the small overhead
187
        # of calculating the filename before doing a cache lookup is more than
188
        # compensated for by not calculating the filename when making new
189
        # versioned files.
190
        _filename = self.filename(file_id)
1224 by Martin Pool
- new method WeaveStore.get_weave_or_empty
191
        try:
1725.2.2 by Robert Collins
reduce file path escaping calls during commit.
192
            return self.get_weave(file_id, transaction, _filename=_filename)
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
193
        except errors.NoSuchFile:
1725.2.2 by Robert Collins
reduce file path escaping calls during commit.
194
            weave = self._make_new_versionedfile(file_id, transaction,
195
                known_missing=True, _filename=_filename)
196
            transaction.map.add_weave(file_id, weave)
197
            # has to be dirty - its able to mutate on its own.
198
            transaction.register_dirty(weave)
199
            return weave
1224 by Martin Pool
- new method WeaveStore.get_weave_or_empty
200
1563.2.10 by Robert Collins
Change weave store to be a versioned store, using WeaveFiles which maintain integrity without needing explicit 'put' operations.
201
    def _put_weave(self, file_id, weave, transaction):
202
        """Preserved here for upgrades-to-weaves to use."""
1563.2.34 by Robert Collins
Remove the commit and rollback transaction methods as misleading, and implement a WriteTransaction
203
        myweave = self._make_new_versionedfile(file_id, transaction)
1563.2.15 by Robert Collins
remove the weavestore assumptions about the number and nature of files it manages.
204
        myweave.join(weave)
1223 by Martin Pool
- store inventories in weave
205
1563.2.25 by Robert Collins
Merge in upstream.
206
    def copy(self, source, result_id, transaction):
207
        """Copy the source versioned file to result_id in this store."""
208
        self._clear_cache_id(result_id, transaction)
209
        source.copy_to(self.filename(result_id), self._transport)
210
 
1563.2.34 by Robert Collins
Remove the commit and rollback transaction methods as misleading, and implement a WriteTransaction
211
    def copy_all_ids(self, store_from, pb=None, from_transaction=None,
212
                     to_transaction=None):
1563.2.14 by Robert Collins
Prepare weave store to delegate copy details to the versioned file.
213
        """Copy all the file ids from store_from into self."""
214
        if from_transaction is None:
1563.2.34 by Robert Collins
Remove the commit and rollback transaction methods as misleading, and implement a WriteTransaction
215
            warn("Please pass from_transaction into "
216
                 "versioned_store.copy_all_ids.", stacklevel=2)
217
        if to_transaction is None:
218
            warn("Please pass to_transaction into "
1563.2.14 by Robert Collins
Prepare weave store to delegate copy details to the versioned file.
219
                 "versioned_store.copy_all_ids.", stacklevel=2)
220
        if not store_from.listable():
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
221
            raise errors.UnlistableStore(store_from)
1563.2.14 by Robert Collins
Prepare weave store to delegate copy details to the versioned file.
222
        ids = []
223
        for count, file_id in enumerate(store_from):
224
            if pb:
225
                pb.update('listing files', count, count)
226
            ids.append(file_id)
227
        if pb:
228
            pb.clear()
229
        mutter('copy_all ids: %r', ids)
230
        self.copy_multi(store_from, ids, pb=pb,
1563.2.34 by Robert Collins
Remove the commit and rollback transaction methods as misleading, and implement a WriteTransaction
231
                        from_transaction=from_transaction,
232
                        to_transaction=to_transaction)
1563.2.14 by Robert Collins
Prepare weave store to delegate copy details to the versioned file.
233
1563.2.34 by Robert Collins
Remove the commit and rollback transaction methods as misleading, and implement a WriteTransaction
234
    def copy_multi(self, from_store, file_ids, pb=None, from_transaction=None,
235
                   to_transaction=None):
1563.2.14 by Robert Collins
Prepare weave store to delegate copy details to the versioned file.
236
        """Copy all the versions for multiple file_ids from from_store.
237
        
238
        :param from_transaction: required current transaction in from_store.
239
        """
1563.2.34 by Robert Collins
Remove the commit and rollback transaction methods as misleading, and implement a WriteTransaction
240
        from bzrlib.transactions import PassThroughTransaction
1393.1.19 by Martin Pool
- add WeaveStore.__iter__, __contains__ and copy_multi()
241
        assert isinstance(from_store, WeaveStore)
1563.2.14 by Robert Collins
Prepare weave store to delegate copy details to the versioned file.
242
        if from_transaction is None:
243
            warn("WeaveStore.copy_multi without a from_transaction parameter "
244
                 "is deprecated. Please provide a from_transaction.",
245
                 DeprecationWarning,
246
                 stacklevel=2)
1563.2.34 by Robert Collins
Remove the commit and rollback transaction methods as misleading, and implement a WriteTransaction
247
            # we are reading one object - caching is irrelevant.
248
            from_transaction = PassThroughTransaction()
249
        if to_transaction is None:
250
            warn("WeaveStore.copy_multi without a to_transaction parameter "
251
                 "is deprecated. Please provide a to_transaction.",
252
                 DeprecationWarning,
253
                 stacklevel=2)
254
            # we are copying single objects, and there may be open tranasactions
255
            # so again with the passthrough
256
            to_transaction = PassThroughTransaction()
1608.2.1 by Martin Pool
[merge] Storage filename escaping
257
        pb = bzrlib.ui.ui_factory.nested_progress_bar()
2127.1.1 by John Arbash Meinel
use try/finally to clean up a nested progress bar during weave fetching
258
        try:
259
            for count, f in enumerate(file_ids):
260
                mutter("copy weave {%s} into %s", f, self)
261
                pb.update('copy', count, len(file_ids))
262
                # if we have it in cache, its faster.
263
                # joining is fast with knits, and bearable for weaves -
264
                # indeed the new case can be optimised if needed.
265
                target = self._make_new_versionedfile(f, to_transaction)
266
                target.join(from_store.get_weave(f, from_transaction))
267
        finally:
268
            pb.finished()
1563.2.16 by Robert Collins
Change WeaveStore into VersionedFileStore and make its versoined file class parameterisable.
269
1563.2.31 by Robert Collins
Convert Knit repositories to use knits.
270
    def total_size(self):
271
        count, bytes =  super(VersionedFileStore, self).total_size()
272
        return (count / len(self._versionedfile_class.get_suffixes())), bytes
1563.2.16 by Robert Collins
Change WeaveStore into VersionedFileStore and make its versoined file class parameterisable.
273
274
WeaveStore = VersionedFileStore