~bzr-pqm/bzr/bzr.dev

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
4183.7.1 by Sabin Iacob
update FSF mailing address
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
1196 by Martin Pool
- [WIP] retrieve historical texts from weaves
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 os
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
22
from warnings import warn
1223 by Martin Pool
- store inventories in weave
23
2294.1.10 by John Arbash Meinel
Switch all apis over to utf8 file ids. All tests pass
24
from bzrlib import (
25
    errors,
26
    osutils,
27
    )
1185.80.6 by John Arbash Meinel
Adding tests to make sure weave stores can retrieve the files they add.
28
from bzrlib.store import TransportStore
1393.1.19 by Martin Pool
- add WeaveStore.__iter__, __contains__ and copy_multi()
29
from bzrlib.trace import mutter
1185.80.10 by John Arbash Meinel
Adding progress indicators and improved get order for 'bzr branch'
30
import bzrlib.ui
1393.2.2 by John Arbash Meinel
Updated stores to use Transport
31
32
1563.2.16 by Robert Collins
Change WeaveStore into VersionedFileStore and make its versoined file class parameterisable.
33
class VersionedFileStore(TransportStore):
34
    """Collection of many versioned files in a transport."""
1393.1.19 by Martin Pool
- add WeaveStore.__iter__, __contains__ and copy_multi()
35
1651.1.1 by Martin Pool
[merge][wip] Storage escaping
36
    # TODO: Rather than passing versionedfile_kwargs, perhaps pass in a
37
    # transport factory callable?
1185.58.4 by John Arbash Meinel
Added permission checking to Branch, and propogated that change into the stores.
38
    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.
39
                 dir_mode=None, file_mode=None,
5582.10.23 by Jelmer Vernooij
Move bzrlib.weavefile.
40
                 versionedfile_class=None,
1651.1.1 by Martin Pool
[merge][wip] Storage escaping
41
                 versionedfile_kwargs={},
1608.2.1 by Martin Pool
[merge] Storage filename escaping
42
                 escaped=False):
43
        super(VersionedFileStore, self).__init__(transport,
1185.58.4 by John Arbash Meinel
Added permission checking to Branch, and propogated that change into the stores.
44
                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.
45
                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.
46
        self._precious = precious
1563.2.16 by Robert Collins
Change WeaveStore into VersionedFileStore and make its versoined file class parameterisable.
47
        self._versionedfile_class = versionedfile_class
1628.1.4 by Robert Collins
Change knit format to use non-delta, non-annotated revisions and signatures.
48
        self._versionedfile_kwargs = versionedfile_kwargs
3316.2.3 by Robert Collins
Remove manual notification of transaction finishing on versioned files.
49
        # Used for passing get_scope to versioned file constructors;
50
        self.get_scope = None
1196 by Martin Pool
- [WIP] retrieve historical texts from weaves
51
1223 by Martin Pool
- store inventories in weave
52
    def filename(self, file_id):
1393.2.2 by John Arbash Meinel
Updated stores to use Transport
53
        """Return the path relative to the transport root."""
1608.2.1 by Martin Pool
[merge] Storage filename escaping
54
        return self._relpath(file_id)
1429 by Robert Collins
merge in niemeyers prefixed-store patch
55
1393.1.19 by Martin Pool
- add WeaveStore.__iter__, __contains__ and copy_multi()
56
    def __iter__(self):
1563.2.16 by Robert Collins
Change WeaveStore into VersionedFileStore and make its versoined file class parameterisable.
57
        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.
58
        ids = set()
1479 by Robert Collins
More quoting at the transport layer bugfixes.
59
        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.
60
            for suffix in suffixes:
61
                if relpath.endswith(suffix):
1608.2.1 by Martin Pool
[merge] Storage filename escaping
62
                    # TODO: use standard remove_suffix function
63
                    escaped_id = os.path.basename(relpath[:-len(suffix)])
3350.6.1 by Robert Collins
* New ``versionedfile.KeyMapper`` interface to abstract out the access to
64
                    file_id = self._mapper.unmap(escaped_id)[0]
1608.2.1 by Martin Pool
[merge] Storage filename escaping
65
                    if file_id not in ids:
66
                        ids.add(file_id)
67
                        yield file_id
68
                    break # only one suffix can match
1393.1.19 by Martin Pool
- add WeaveStore.__iter__, __contains__ and copy_multi()
69
2294.1.10 by John Arbash Meinel
Switch all apis over to utf8 file ids. All tests pass
70
    def has_id(self, file_id):
1563.2.16 by Robert Collins
Change WeaveStore into VersionedFileStore and make its versoined file class parameterisable.
71
        suffixes = self._versionedfile_class.get_suffixes()
2294.1.10 by John Arbash Meinel
Switch all apis over to utf8 file ids. All tests pass
72
        filename = self.filename(file_id)
1563.2.15 by Robert Collins
remove the weavestore assumptions about the number and nature of files it manages.
73
        for suffix in suffixes:
74
            if not self._transport.has(filename + suffix):
75
                return False
76
        return True
1223 by Martin Pool
- store inventories in weave
77
1563.2.25 by Robert Collins
Merge in upstream.
78
    def get_empty(self, file_id, transaction):
79
        """Get an empty weave, which implies deleting the existing one first."""
80
        if self.has_id(file_id):
81
            self.delete(file_id, transaction)
82
        return self.get_weave_or_empty(file_id, transaction)
83
84
    def delete(self, file_id, transaction):
85
        """Remove file_id from the store."""
86
        suffixes = self._versionedfile_class.get_suffixes()
87
        filename = self.filename(file_id)
88
        for suffix in suffixes:
89
            self._transport.delete(filename + suffix)
1393.2.2 by John Arbash Meinel
Updated stores to use Transport
90
91
    def _get(self, file_id):
92
        return self._transport.get(self.filename(file_id))
93
94
    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.
95
        fn = self.filename(file_id)
96
        try:
1955.3.9 by John Arbash Meinel
Find more occurrances of put() and replace with put_file or put_bytes
97
            return self._transport.put_file(fn, f, mode=self._file_mode)
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
98
        except errors.NoSuchFile:
1185.80.6 by John Arbash Meinel
Adding tests to make sure weave stores can retrieve the files they add.
99
            if not self._prefixed:
100
                raise
101
            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
102
            return self._transport.put_file(fn, f, mode=self._file_mode)
1223 by Martin Pool
- store inventories in weave
103
1725.2.2 by Robert Collins
reduce file path escaping calls during commit.
104
    def get_weave(self, file_id, transaction, _filename=None):
105
        """Return the VersionedFile for file_id.
106
107
        :param _filename: filename that would be returned from self.filename for
108
        file_id. This is used to reduce duplicate filename calculations when
109
        using 'get_weave_or_empty'. FOR INTERNAL USE ONLY.
110
        """
111
        if _filename is None:
112
            _filename = self.filename(file_id)
1594.2.23 by Robert Collins
Test versioned file storage handling of clean/dirty status for accessed versioned files.
113
        if transaction.writeable():
1725.2.2 by Robert Collins
reduce file path escaping calls during commit.
114
            w = self._versionedfile_class(_filename, self._transport, self._file_mode,
3316.2.3 by Robert Collins
Remove manual notification of transaction finishing on versioned files.
115
                get_scope=self.get_scope, **self._versionedfile_kwargs)
1594.2.23 by Robert Collins
Test versioned file storage handling of clean/dirty status for accessed versioned files.
116
        else:
1725.2.2 by Robert Collins
reduce file path escaping calls during commit.
117
            w = self._versionedfile_class(_filename,
1594.2.23 by Robert Collins
Test versioned file storage handling of clean/dirty status for accessed versioned files.
118
                                          self._transport,
119
                                          self._file_mode,
120
                                          create=False,
1628.1.4 by Robert Collins
Change knit format to use non-delta, non-annotated revisions and signatures.
121
                                          access_mode='r',
3316.2.3 by Robert Collins
Remove manual notification of transaction finishing on versioned files.
122
                                          get_scope=self.get_scope,
1628.1.4 by Robert Collins
Change knit format to use non-delta, non-annotated revisions and signatures.
123
                                          **self._versionedfile_kwargs)
1363 by Martin Pool
- add quick-and-dirty cache for weaves to speed check command
124
        return w
1262 by Martin Pool
- fetch should also copy ancestry records
125
1725.2.2 by Robert Collins
reduce file path escaping calls during commit.
126
    def _make_new_versionedfile(self, file_id, transaction,
127
        known_missing=False, _filename=None):
128
        """Make a new versioned file.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
129
1725.2.2 by Robert Collins
reduce file path escaping calls during commit.
130
        :param _filename: filename that would be returned from self.filename for
131
        file_id. This is used to reduce duplicate filename calculations when
132
        using 'get_weave_or_empty'. FOR INTERNAL USE ONLY.
133
        """
134
        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
135
            self.delete(file_id, transaction)
1725.2.2 by Robert Collins
reduce file path escaping calls during commit.
136
        if _filename is None:
137
            _filename = self.filename(file_id)
1563.2.14 by Robert Collins
Prepare weave store to delegate copy details to the versioned file.
138
        try:
1725.2.2 by Robert Collins
reduce file path escaping calls during commit.
139
            # we try without making the directory first because thats optimising
140
            # for the common case.
141
            weave = self._versionedfile_class(_filename, self._transport, self._file_mode, create=True,
3316.2.3 by Robert Collins
Remove manual notification of transaction finishing on versioned files.
142
                get_scope=self.get_scope, **self._versionedfile_kwargs)
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
143
        except errors.NoSuchFile:
1563.2.14 by Robert Collins
Prepare weave store to delegate copy details to the versioned file.
144
            if not self._prefixed:
1725.2.2 by Robert Collins
reduce file path escaping calls during commit.
145
                # unexpected error - NoSuchFile is expected to be raised on a
146
                # 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.
147
                raise
3350.6.1 by Robert Collins
* New ``versionedfile.KeyMapper`` interface to abstract out the access to
148
            dirname = osutils.dirname(_filename)
149
            self._transport.mkdir(dirname, mode=self._dir_mode)
3316.2.3 by Robert Collins
Remove manual notification of transaction finishing on versioned files.
150
            weave = self._versionedfile_class(_filename, self._transport,
1651.1.1 by Martin Pool
[merge][wip] Storage escaping
151
                                              self._file_mode, create=True,
3316.2.3 by Robert Collins
Remove manual notification of transaction finishing on versioned files.
152
                                              get_scope=self.get_scope,
1628.1.4 by Robert Collins
Change knit format to use non-delta, non-annotated revisions and signatures.
153
                                              **self._versionedfile_kwargs)
1563.2.14 by Robert Collins
Prepare weave store to delegate copy details to the versioned file.
154
        return weave
155
1417.1.8 by Robert Collins
use transactions in the weave store interface, which enables caching for log
156
    def get_weave_or_empty(self, file_id, transaction):
1725.2.2 by Robert Collins
reduce file path escaping calls during commit.
157
        """Return a weave, or an empty one if it doesn't exist."""
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
158
        # This is typically used from 'commit' and 'fetch/push/pull' where
1725.2.2 by Robert Collins
reduce file path escaping calls during commit.
159
        # we scan across many versioned files once. As such the small overhead
160
        # of calculating the filename before doing a cache lookup is more than
161
        # compensated for by not calculating the filename when making new
162
        # versioned files.
163
        _filename = self.filename(file_id)
1224 by Martin Pool
- new method WeaveStore.get_weave_or_empty
164
        try:
1725.2.2 by Robert Collins
reduce file path escaping calls during commit.
165
            return self.get_weave(file_id, transaction, _filename=_filename)
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
166
        except errors.NoSuchFile:
1725.2.2 by Robert Collins
reduce file path escaping calls during commit.
167
            weave = self._make_new_versionedfile(file_id, transaction,
168
                known_missing=True, _filename=_filename)
169
            return weave
1224 by Martin Pool
- new method WeaveStore.get_weave_or_empty
170
1563.2.10 by Robert Collins
Change weave store to be a versioned store, using WeaveFiles which maintain integrity without needing explicit 'put' operations.
171
    def _put_weave(self, file_id, weave, transaction):
172
        """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
173
        myweave = self._make_new_versionedfile(file_id, transaction)
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
174
        myweave.insert_record_stream(weave.get_record_stream(
175
            [(version,) for version in weave.versions()],
3350.3.20 by Robert Collins
Remove more uses of versionedfile.join() and fix a bug with weave's insert_record_stream.
176
            'topological', False))
1223 by Martin Pool
- store inventories in weave
177
1563.2.34 by Robert Collins
Remove the commit and rollback transaction methods as misleading, and implement a WriteTransaction
178
    def copy_all_ids(self, store_from, pb=None, from_transaction=None,
179
                     to_transaction=None):
1563.2.14 by Robert Collins
Prepare weave store to delegate copy details to the versioned file.
180
        """Copy all the file ids from store_from into self."""
181
        if from_transaction is None:
1563.2.34 by Robert Collins
Remove the commit and rollback transaction methods as misleading, and implement a WriteTransaction
182
            warn("Please pass from_transaction into "
183
                 "versioned_store.copy_all_ids.", stacklevel=2)
184
        if to_transaction is None:
185
            warn("Please pass to_transaction into "
1563.2.14 by Robert Collins
Prepare weave store to delegate copy details to the versioned file.
186
                 "versioned_store.copy_all_ids.", stacklevel=2)
187
        if not store_from.listable():
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
188
            raise errors.UnlistableStore(store_from)
1563.2.14 by Robert Collins
Prepare weave store to delegate copy details to the versioned file.
189
        ids = []
190
        for count, file_id in enumerate(store_from):
191
            if pb:
192
                pb.update('listing files', count, count)
193
            ids.append(file_id)
194
        if pb:
195
            pb.clear()
196
        mutter('copy_all ids: %r', ids)
197
        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
198
                        from_transaction=from_transaction,
199
                        to_transaction=to_transaction)
1563.2.14 by Robert Collins
Prepare weave store to delegate copy details to the versioned file.
200
1563.2.34 by Robert Collins
Remove the commit and rollback transaction methods as misleading, and implement a WriteTransaction
201
    def copy_multi(self, from_store, file_ids, pb=None, from_transaction=None,
202
                   to_transaction=None):
1563.2.14 by Robert Collins
Prepare weave store to delegate copy details to the versioned file.
203
        """Copy all the versions for multiple file_ids from from_store.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
204
1563.2.14 by Robert Collins
Prepare weave store to delegate copy details to the versioned file.
205
        :param from_transaction: required current transaction in from_store.
206
        """
1563.2.34 by Robert Collins
Remove the commit and rollback transaction methods as misleading, and implement a WriteTransaction
207
        from bzrlib.transactions import PassThroughTransaction
1563.2.14 by Robert Collins
Prepare weave store to delegate copy details to the versioned file.
208
        if from_transaction is None:
5582.10.23 by Jelmer Vernooij
Move bzrlib.weavefile.
209
            warn("VersionedFileStore.copy_multi without a from_transaction parameter "
1563.2.14 by Robert Collins
Prepare weave store to delegate copy details to the versioned file.
210
                 "is deprecated. Please provide a from_transaction.",
211
                 DeprecationWarning,
212
                 stacklevel=2)
1563.2.34 by Robert Collins
Remove the commit and rollback transaction methods as misleading, and implement a WriteTransaction
213
            # we are reading one object - caching is irrelevant.
214
            from_transaction = PassThroughTransaction()
215
        if to_transaction is None:
5582.10.23 by Jelmer Vernooij
Move bzrlib.weavefile.
216
            warn("VersionedFileStore.copy_multi without a to_transaction parameter "
1563.2.34 by Robert Collins
Remove the commit and rollback transaction methods as misleading, and implement a WriteTransaction
217
                 "is deprecated. Please provide a to_transaction.",
218
                 DeprecationWarning,
219
                 stacklevel=2)
220
            # we are copying single objects, and there may be open tranasactions
221
            # so again with the passthrough
222
            to_transaction = PassThroughTransaction()
1608.2.1 by Martin Pool
[merge] Storage filename escaping
223
        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
224
        try:
225
            for count, f in enumerate(file_ids):
226
                mutter("copy weave {%s} into %s", f, self)
227
                pb.update('copy', count, len(file_ids))
228
                # if we have it in cache, its faster.
229
                # joining is fast with knits, and bearable for weaves -
230
                # indeed the new case can be optimised if needed.
231
                target = self._make_new_versionedfile(f, to_transaction)
3350.3.20 by Robert Collins
Remove more uses of versionedfile.join() and fix a bug with weave's insert_record_stream.
232
                source = from_store.get_weave(f, from_transaction)
233
                target.insert_record_stream(source.get_record_stream(
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
234
                    [(version,) for version in source.versions()],
235
                    'topological', False))
2127.1.1 by John Arbash Meinel
use try/finally to clean up a nested progress bar during weave fetching
236
        finally:
237
            pb.finished()
1563.2.16 by Robert Collins
Change WeaveStore into VersionedFileStore and make its versoined file class parameterisable.
238
1563.2.31 by Robert Collins
Convert Knit repositories to use knits.
239
    def total_size(self):
240
        count, bytes =  super(VersionedFileStore, self).total_size()
241
        return (count / len(self._versionedfile_class.get_suffixes())), bytes