/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
5752.3.8 by John Arbash Meinel
Merge bzr.dev 5764 to resolve release-notes (aka NEWS) conflicts
1
# Copyright (C) 2005-2011 Canonical Ltd
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
2
#
1185.65.22 by Robert Collins
lockable_files was extracted from branch.py - give it a copyright statement
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
#
1185.65.22 by Robert Collins
lockable_files was extracted from branch.py - give it a copyright statement
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
#
1185.65.22 by Robert Collins
lockable_files was extracted from branch.py - give it a copyright statement
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
1185.65.22 by Robert Collins
lockable_files was extracted from branch.py - give it a copyright statement
16
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
17
from .lazy_import import lazy_import
3535.5.1 by John Arbash Meinel
cleanup a few imports to be lazily loaded.
18
lazy_import(globals(), """
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
19
from breezy import (
3468.3.3 by Martin Pool
Fix import
20
    counted_lock,
6754.8.9 by Jelmer Vernooij
Fix more tests.
21
    lock,
3535.5.1 by John Arbash Meinel
cleanup a few imports to be lazily loaded.
22
    transactions,
23
    urlutils,
24
    )
25
""")
26
7413.8.11 by Jelmer Vernooij
Don't lazy-import errors.
27
from . import (
28
    errors,
29
    )
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
30
from .decorators import (
4634.85.9 by Andrew Bennetts
Add some experimental decorators: @only_raises(..) and @cleanup_method.
31
    only_raises,
3535.5.1 by John Arbash Meinel
cleanup a few imports to be lazily loaded.
32
    )
1685.1.45 by John Arbash Meinel
Moved url functions into bzrlib.urlutils
33
1185.65.10 by Robert Collins
Rename Controlfiles to LockableFiles.
34
1185.66.3 by Aaron Bentley
Renamed ControlFiles to LockableFiles
35
class LockableFiles(object):
1553.5.38 by Martin Pool
More explanation for LockableFiles
36
    """Object representing a set of related files locked within the same scope.
37
4570.3.1 by Martin Pool
Update LockableFiles docstring
38
    This coordinates access to the lock along with providing a transaction.
1553.5.38 by Martin Pool
More explanation for LockableFiles
39
1553.5.39 by Martin Pool
More lock docs
40
    LockableFiles manage a lock count and can be locked repeatedly by
41
    a single caller.  (The underlying lock implementation generally does not
42
    support this.)
43
1553.5.38 by Martin Pool
More explanation for LockableFiles
44
    Instances of this class are often called control_files.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
45
46
    This class is now deprecated; code should move to using the Transport
47
    directly for file operations and using the lock or CountedLock for
3407.2.9 by Martin Pool
doc
48
    locking.
5967.8.1 by Martin Pool
Also remove LockWarner and its del method (see bug 721166)
49
3407.2.19 by Martin Pool
CountedLock should manage lock tokens
50
    :ivar _lock: The real underlying lock (e.g. a LockDir)
5967.8.1 by Martin Pool
Also remove LockWarner and its del method (see bug 721166)
51
    :ivar _lock_count: If _lock_mode is true, a positive count of the number
52
        of times the lock has been taken (and not yet released) *by this
53
        process*, through this particular object instance.
54
    :ivar _lock_mode: None, or 'r' or 'w'
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
55
    """
1185.65.10 by Robert Collins
Rename Controlfiles to LockableFiles.
56
1553.5.63 by Martin Pool
Lock type is now mandatory for LockableFiles constructor
57
    def __init__(self, transport, lock_name, lock_class):
1553.5.43 by Martin Pool
Get LockableFiles tests running against LockDir
58
        """Create a LockableFiles group
59
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
60
        :param transport: Transport pointing to the directory holding the
1553.5.43 by Martin Pool
Get LockableFiles tests running against LockDir
61
            control files and lock.
62
        :param lock_name: Name of the lock guarding these files.
1553.5.47 by Martin Pool
cleanup LockableFiles
63
        :param lock_class: Class of lock strategy to use: typically
64
            either LockDir or TransportLock.
1553.5.43 by Martin Pool
Get LockableFiles tests running against LockDir
65
        """
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
66
        self._transport = transport
67
        self.lock_name = lock_name
68
        self._transaction = None
1553.5.47 by Martin Pool
cleanup LockableFiles
69
        self._lock_mode = None
5967.8.1 by Martin Pool
Also remove LockWarner and its del method (see bug 721166)
70
        self._lock_count = 0
1685.1.43 by John Arbash Meinel
Bug in lockable files when _find_mode throws
71
        self._find_modes()
1553.5.43 by Martin Pool
Get LockableFiles tests running against LockDir
72
        esc_name = self._escape(lock_name)
1608.2.1 by Martin Pool
[merge] Storage filename escaping
73
        self._lock = lock_class(transport, esc_name,
1553.5.59 by Martin Pool
Pass file/mode bits through to creation of lock files/dirs
74
                                file_modebits=self._file_mode,
75
                                dir_modebits=self._dir_mode)
3468.3.3 by Martin Pool
Fix import
76
        self._counted_lock = counted_lock.CountedLock(self._lock)
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
77
1553.5.60 by Martin Pool
New LockableFiles.create_lock() method
78
    def create_lock(self):
79
        """Create the lock.
80
81
        This should normally be called only when the LockableFiles directory
82
        is first created on disk.
83
        """
1666.1.4 by Robert Collins
* 'Metadir' is now the default disk format. This improves behaviour in
84
        self._lock.create(mode=self._dir_mode)
1553.5.60 by Martin Pool
New LockableFiles.create_lock() method
85
1553.5.53 by Martin Pool
Add LockableFiles __repr__
86
    def __repr__(self):
87
        return '%s(%r)' % (self.__class__.__name__,
88
                           self._transport)
5967.8.1 by Martin Pool
Also remove LockWarner and its del method (see bug 721166)
89
1185.80.2 by John Arbash Meinel
Traced double locking code to WorkingTree creating its own control files.
90
    def __str__(self):
91
        return 'LockableFiles(%s, %s)' % (self.lock_name, self._transport.base)
92
1687.1.6 by Robert Collins
Extend LockableFiles to support break_lock() calls.
93
    def break_lock(self):
94
        """Break the lock of this lockable files group if it is held.
95
96
        The current ui factory will be used to prompt for user conformation.
97
        """
98
        self._lock.break_lock()
99
1185.69.2 by John Arbash Meinel
Changed LockableFiles to take the root directory directly. Moved mode information into LockableFiles instead of Branch
100
    def _escape(self, file_or_path):
3834.2.2 by Martin Pool
Deprecated LockableFiles._escape
101
        """DEPRECATED: Do not use outside this class"""
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
102
        if file_or_path == '':
1185.69.2 by John Arbash Meinel
Changed LockableFiles to take the root directory directly. Moved mode information into LockableFiles instead of Branch
103
            return u''
6677.1.1 by Martin
Go back to native str for urls and many other py3 changes
104
        return urlutils.escape(file_or_path)
1185.69.2 by John Arbash Meinel
Changed LockableFiles to take the root directory directly. Moved mode information into LockableFiles instead of Branch
105
106
    def _find_modes(self):
3416.2.1 by Martin Pool
Add BzrDir._get_file_mode and _get_dir_mode
107
        """Determine the appropriate modes for files and directories.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
108
4570.3.4 by Martin Pool
Doc
109
        :deprecated: Replaced by BzrDir._find_creation_modes.
3416.2.1 by Martin Pool
Add BzrDir._get_file_mode and _get_dir_mode
110
        """
3407.2.19 by Martin Pool
CountedLock should manage lock tokens
111
        # XXX: The properties created by this can be removed or deprecated
112
        # once all the _get_text_store methods etc no longer use them.
113
        # -- mbp 20080512
1185.69.2 by John Arbash Meinel
Changed LockableFiles to take the root directory directly. Moved mode information into LockableFiles instead of Branch
114
        try:
1534.4.28 by Robert Collins
first cut at merge from integration.
115
            st = self._transport.stat('.')
116
        except errors.TransportNotPossible:
6619.3.14 by Jelmer Vernooij
Convert some octal numbers to new notations.
117
            self._dir_mode = 0o755
118
            self._file_mode = 0o644
1185.69.2 by John Arbash Meinel
Changed LockableFiles to take the root directory directly. Moved mode information into LockableFiles instead of Branch
119
        else:
3107.2.1 by John Arbash Meinel
Fix LockableFiles to not use modes that allow the user to write to things they create.
120
            # Check the directory mode, but also make sure the created
121
            # directories and files are read-write for this user. This is
122
            # mostly a workaround for filesystems which lie about being able to
123
            # write to a directory (cygwin & win32)
6619.3.14 by Jelmer Vernooij
Convert some octal numbers to new notations.
124
            self._dir_mode = (st.st_mode & 0o7777) | 0o0700
1185.69.2 by John Arbash Meinel
Changed LockableFiles to take the root directory directly. Moved mode information into LockableFiles instead of Branch
125
            # Remove the sticky and execute bits for files
6619.3.14 by Jelmer Vernooij
Convert some octal numbers to new notations.
126
            self._file_mode = self._dir_mode & ~0o7111
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
127
2018.5.75 by Andrew Bennetts
Add Repository.{dont_,}leave_lock_in_place.
128
    def leave_in_place(self):
129
        """Set this LockableFiles to not clear the physical lock on unlock."""
130
        self._lock.leave_in_place()
131
132
    def dont_leave_in_place(self):
133
        """Set this LockableFiles to clear the physical lock on unlock."""
134
        self._lock.dont_leave_in_place()
135
2279.7.1 by Andrew Bennetts
``LockableFiles.lock_write()`` now accepts a ``token`` keyword argument, so that
136
    def lock_write(self, token=None):
137
        """Lock this group of files for writing.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
138
2279.7.1 by Andrew Bennetts
``LockableFiles.lock_write()`` now accepts a ``token`` keyword argument, so that
139
        :param token: if this is already locked, then lock_write will fail
140
            unless the token matches the existing lock.
141
        :returns: a token if this instance supports tokens, otherwise None.
142
        :raises TokenLockingNotSupported: when a token is given but this
143
            instance doesn't support using token locks.
144
        :raises MismatchedToken: if the specified token doesn't match the token
145
            of the existing lock.
2018.5.145 by Andrew Bennetts
Add a brief explanation of what tokens are used for to lock_write docstrings.
146
147
        A token should be passed in if you know that you have locked the object
148
        some other way, and need to synchronise this object's state with that
149
        fact.
2279.7.1 by Andrew Bennetts
``LockableFiles.lock_write()`` now accepts a ``token`` keyword argument, so that
150
        """
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
151
        if self._lock_mode:
5967.8.1 by Martin Pool
Also remove LockWarner and its del method (see bug 721166)
152
            if (self._lock_mode != 'w'
7143.15.2 by Jelmer Vernooij
Run autopep8.
153
                    or not self.get_transaction().writeable()):
1694.2.6 by Martin Pool
[merge] bzr.dev
154
                raise errors.ReadOnlyError(self)
2279.7.1 by Andrew Bennetts
``LockableFiles.lock_write()`` now accepts a ``token`` keyword argument, so that
155
            self._lock.validate_token(token)
5967.8.1 by Martin Pool
Also remove LockWarner and its del method (see bug 721166)
156
            self._lock_count += 1
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
157
            return self._token_from_lock
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
158
        else:
2279.7.1 by Andrew Bennetts
``LockableFiles.lock_write()`` now accepts a ``token`` keyword argument, so that
159
            token_from_lock = self._lock.lock_write(token=token)
7143.15.2 by Jelmer Vernooij
Run autopep8.
160
            # traceback.print_stack()
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
161
            self._lock_mode = 'w'
5967.8.1 by Martin Pool
Also remove LockWarner and its del method (see bug 721166)
162
            self._lock_count = 1
4145.1.2 by Robert Collins
Add a refresh_data method on Repository allowing cleaner handling of insertions into RemoteRepository objects with _real_repository instances.
163
            self._set_write_transaction()
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
164
            self._token_from_lock = token_from_lock
2279.7.1 by Andrew Bennetts
``LockableFiles.lock_write()`` now accepts a ``token`` keyword argument, so that
165
            return token_from_lock
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
166
167
    def lock_read(self):
168
        if self._lock_mode:
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
169
            if self._lock_mode not in ('r', 'w'):
170
                raise ValueError("invalid lock mode %r" % (self._lock_mode,))
5967.8.1 by Martin Pool
Also remove LockWarner and its del method (see bug 721166)
171
            self._lock_count += 1
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
172
        else:
1553.5.47 by Martin Pool
cleanup LockableFiles
173
            self._lock.lock_read()
7143.15.2 by Jelmer Vernooij
Run autopep8.
174
            # traceback.print_stack()
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
175
            self._lock_mode = 'r'
5967.8.1 by Martin Pool
Also remove LockWarner and its del method (see bug 721166)
176
            self._lock_count = 1
4145.1.2 by Robert Collins
Add a refresh_data method on Repository allowing cleaner handling of insertions into RemoteRepository objects with _real_repository instances.
177
            self._set_read_transaction()
178
179
    def _set_read_transaction(self):
180
        """Setup a read transaction."""
181
        self._set_transaction(transactions.ReadOnlyTransaction())
182
        # 5K may be excessive, but hey, its a knob.
183
        self.get_transaction().set_cache_size(5000)
184
185
    def _set_write_transaction(self):
186
        """Setup a write transaction."""
187
        self._set_transaction(transactions.WriteTransaction())
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
188
4634.85.9 by Andrew Bennetts
Add some experimental decorators: @only_raises(..) and @cleanup_method.
189
    @only_raises(errors.LockNotHeld, errors.LockBroken)
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
190
    def unlock(self):
191
        if not self._lock_mode:
4509.3.25 by Martin Pool
Add an option for unlock errors to be non-fatal
192
            return lock.cant_unlock_not_held(self)
5967.8.1 by Martin Pool
Also remove LockWarner and its del method (see bug 721166)
193
        if self._lock_count > 1:
194
            self._lock_count -= 1
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
195
        else:
7143.15.2 by Jelmer Vernooij
Run autopep8.
196
            # traceback.print_stack()
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
197
            self._finish_transaction()
1687.1.6 by Robert Collins
Extend LockableFiles to support break_lock() calls.
198
            try:
199
                self._lock.unlock()
200
            finally:
6677.1.1 by Martin
Go back to native str for urls and many other py3 changes
201
                self._lock_count = 0
202
                self._lock_mode = None
4104.4.1 by Robert Collins
Cherrypick bugfixes from bzr.dev for 1.13:
203
1553.5.35 by Martin Pool
Start break-lock --show
204
    def is_locked(self):
205
        """Return true if this LockableFiles group is locked"""
5967.8.1 by Martin Pool
Also remove LockWarner and its del method (see bug 721166)
206
        return self._lock_count >= 1
1553.5.35 by Martin Pool
Start break-lock --show
207
1694.2.6 by Martin Pool
[merge] bzr.dev
208
    def get_physical_lock_status(self):
209
        """Return physical lock status.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
210
1694.2.6 by Martin Pool
[merge] bzr.dev
211
        Returns true if a lock is held on the transport. If no lock is held, or
212
        the underlying locking mechanism does not support querying lock
213
        status, false is returned.
214
        """
215
        try:
216
            return self._lock.peek() is not None
217
        except NotImplementedError:
218
            return False
219
1185.65.1 by Aaron Bentley
Refactored out ControlFiles and RevisionStore from _Branch
220
    def get_transaction(self):
221
        """Return the current active transaction.
222
223
        If no transaction is active, this returns a passthrough object
224
        for which all data is immediately flushed and no caching happens.
225
        """
226
        if self._transaction is None:
227
            return transactions.PassThroughTransaction()
228
        else:
229
            return self._transaction
230
231
    def _set_transaction(self, new_transaction):
232
        """Set a new active transaction."""
233
        if self._transaction is not None:
234
            raise errors.LockError('Branch %s is in a transaction already.' %
235
                                   self)
236
        self._transaction = new_transaction
237
238
    def _finish_transaction(self):
239
        """Exit the current transaction."""
240
        if self._transaction is None:
241
            raise errors.LockError('Branch %s is not in a transaction' %
242
                                   self)
243
        transaction = self._transaction
244
        self._transaction = None
245
        transaction.finish()
1553.5.40 by Martin Pool
Factor locking strategy out of LockableFiles so that we can use LockDirs in new formats.
246
247
1553.5.45 by Martin Pool
Clean up Transport-based locks for old branches
248
class TransportLock(object):
249
    """Locking method which uses transport-dependent locks.
250
251
    On the local filesystem these transform into OS-managed locks.
252
253
    These do not guard against concurrent access via different
254
    transports.
255
256
    This is suitable for use only in WorkingTrees (which are at present
257
    always local).
1553.5.40 by Martin Pool
Factor locking strategy out of LockableFiles so that we can use LockDirs in new formats.
258
    """
7143.15.2 by Jelmer Vernooij
Run autopep8.
259
1553.5.59 by Martin Pool
Pass file/mode bits through to creation of lock files/dirs
260
    def __init__(self, transport, escaped_name, file_modebits, dir_modebits):
1553.5.40 by Martin Pool
Factor locking strategy out of LockableFiles so that we can use LockDirs in new formats.
261
        self._transport = transport
262
        self._escaped_name = escaped_name
1553.5.59 by Martin Pool
Pass file/mode bits through to creation of lock files/dirs
263
        self._file_modebits = file_modebits
264
        self._dir_modebits = dir_modebits
1553.5.40 by Martin Pool
Factor locking strategy out of LockableFiles so that we can use LockDirs in new formats.
265
1687.1.6 by Robert Collins
Extend LockableFiles to support break_lock() calls.
266
    def break_lock(self):
267
        raise NotImplementedError(self.break_lock)
268
2018.5.75 by Andrew Bennetts
Add Repository.{dont_,}leave_lock_in_place.
269
    def leave_in_place(self):
270
        raise NotImplementedError(self.leave_in_place)
271
2018.5.76 by Andrew Bennetts
Testing that repository.{dont_,}leave_lock_in_place raises NotImplementedError if lock_write returns None.
272
    def dont_leave_in_place(self):
273
        raise NotImplementedError(self.dont_leave_in_place)
274
2279.7.1 by Andrew Bennetts
``LockableFiles.lock_write()`` now accepts a ``token`` keyword argument, so that
275
    def lock_write(self, token=None):
276
        if token is not None:
277
            raise errors.TokenLockingNotSupported(self)
1553.5.40 by Martin Pool
Factor locking strategy out of LockableFiles so that we can use LockDirs in new formats.
278
        self._lock = self._transport.lock_write(self._escaped_name)
279
280
    def lock_read(self):
281
        self._lock = self._transport.lock_read(self._escaped_name)
282
283
    def unlock(self):
284
        self._lock.unlock()
285
        self._lock = None
286
1694.2.6 by Martin Pool
[merge] bzr.dev
287
    def peek(self):
288
        raise NotImplementedError()
289
1666.1.4 by Robert Collins
* 'Metadir' is now the default disk format. This improves behaviour in
290
    def create(self, mode=None):
1553.5.59 by Martin Pool
Pass file/mode bits through to creation of lock files/dirs
291
        """Create lock mechanism"""
292
        # for old-style locks, create the file now
6819.1.1 by Jelmer Vernooij
Some smaller fixes.
293
        self._transport.put_bytes(self._escaped_name, b'',
7143.15.2 by Jelmer Vernooij
Run autopep8.
294
                                  mode=self._file_modebits)
2279.7.1 by Andrew Bennetts
``LockableFiles.lock_write()`` now accepts a ``token`` keyword argument, so that
295
296
    def validate_token(self, token):
297
        if token is not None:
298
            raise errors.TokenLockingNotSupported(self)