/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
70 by mbp at sourcefrog
Prepare for smart recursive add.
1
# Copyright (C) 2005 Canonical Ltd
2
1 by mbp at sourcefrog
import from baz patch-364
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
1497 by Robert Collins
Move Branch.read_working_inventory to WorkingTree.
18
import shutil
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
19
import sys
20
import os
1371 by Martin Pool
- raise NotBranchError if format file can't be read
21
import errno
1372 by Martin Pool
- avoid converting inventories to/from StringIO
22
from warnings import warn
1393.2.1 by John Arbash Meinel
Merged in split-storage-2 branch. Need to cleanup a little bit more still.
23
from cStringIO import StringIO
1372 by Martin Pool
- avoid converting inventories to/from StringIO
24
1 by mbp at sourcefrog
import from baz patch-364
25
26
import bzrlib
1399.1.1 by Robert Collins
move checks for versionability of file kinds into InventoryEntry
27
from bzrlib.inventory import InventoryEntry
1399.1.8 by Robert Collins
factor out inventory directory logic into 'InventoryDirectory' class
28
import bzrlib.inventory as inventory
800 by Martin Pool
Merge John's import-speedup branch:
29
from bzrlib.trace import mutter, note
1390 by Robert Collins
pair programming worx... merge integration and weave
30
from bzrlib.osutils import (isdir, quotefn, compact_date, rand_bytes, 
31
                            rename, splitpath, sha_file, appendpath, 
1185.16.70 by Martin Pool
- improved handling of non-ascii branch names and test
32
                            file_kind, abspath)
1417.1.6 by Robert Collins
introduce transactions for grouping actions done to and with branches
33
import bzrlib.errors as errors
1192 by Martin Pool
- clean up code for retrieving stored inventories
34
from bzrlib.errors import (BzrError, InvalidRevisionNumber, InvalidRevisionId,
1299 by Martin Pool
- tidy up imports
35
                           NoSuchRevision, HistoryMissing, NotBranchError,
1391 by Robert Collins
merge from integration
36
                           DivergedBranches, LockError, UnlistableStore,
1497 by Robert Collins
Move Branch.read_working_inventory to WorkingTree.
37
                           UnlistableBranch, NoSuchFile, NotVersionedError,
38
                           NoWorkingTree)
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
39
from bzrlib.textui import show_status
1185.12.98 by Aaron Bentley
Support for forcing merges of unrelated trees
40
from bzrlib.revision import (Revision, is_ancestor, get_intervening_revisions,
41
                             NULL_REVISION)
1185.12.44 by abentley
Restored branch convergence to bzr pull
42
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
43
from bzrlib.delta import compare_trees
44
from bzrlib.tree import EmptyTree, RevisionTree
1192 by Martin Pool
- clean up code for retrieving stored inventories
45
from bzrlib.inventory import Inventory
1393.2.1 by John Arbash Meinel
Merged in split-storage-2 branch. Need to cleanup a little bit more still.
46
from bzrlib.store import copy_all
47
from bzrlib.store.compressed_text import CompressedTextStore
1393.2.2 by John Arbash Meinel
Updated stores to use Transport
48
from bzrlib.store.text import TextStore
1393.2.3 by John Arbash Meinel
Fixing typos, updating stores, getting tests to pass.
49
from bzrlib.store.weave import WeaveStore
1442.1.60 by Robert Collins
gpg sign commits if the policy says we need to
50
from bzrlib.testament import Testament
1417.1.6 by Robert Collins
introduce transactions for grouping actions done to and with branches
51
import bzrlib.transactions as transactions
1393.2.4 by John Arbash Meinel
All tests pass.
52
from bzrlib.transport import Transport, get_transport
1189 by Martin Pool
- BROKEN: partial support for commit into weave
53
import bzrlib.xml5
1104 by Martin Pool
- Add a simple UIFactory
54
import bzrlib.ui
1185.35.11 by Aaron Bentley
Added support for branch nicks
55
from config import TreeConfig
1104 by Martin Pool
- Add a simple UIFactory
56
1094 by Martin Pool
- merge aaron's merge improvements 999..1008
57
1186 by Martin Pool
- start implementing v5 format; Branch refuses to operate on old branches
58
BZR_BRANCH_FORMAT_4 = "Bazaar-NG branch, format 0.0.4\n"
59
BZR_BRANCH_FORMAT_5 = "Bazaar-NG branch, format 5\n"
1429 by Robert Collins
merge in niemeyers prefixed-store patch
60
BZR_BRANCH_FORMAT_6 = "Bazaar-NG branch, format 6\n"
1 by mbp at sourcefrog
import from baz patch-364
61
## TODO: Maybe include checks for common corruption of newlines, etc?
62
63
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
64
# TODO: Some operations like log might retrieve the same revisions
65
# repeatedly to calculate deltas.  We could perhaps have a weakref
1223 by Martin Pool
- store inventories in weave
66
# cache in memory to make this faster.  In general anything can be
67
# cached in memory between lock and unlock operations.
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
68
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
69
def find_branch(*ignored, **ignored_too):
70
    # XXX: leave this here for about one release, then remove it
71
    raise NotImplementedError('find_branch() is not supported anymore, '
72
                              'please use one of the new branch constructors')
416 by Martin Pool
- bzr log and bzr root now accept an http URL
73
1442.1.63 by Robert Collins
Remove self.lock_*...finally: self.unlock() dead chickens from branch.py.
74
75
def needs_read_lock(unbound):
76
    """Decorate unbound to take out and release a read lock."""
77
    def decorated(self, *args, **kwargs):
78
        self.lock_read()
79
        try:
80
            return unbound(self, *args, **kwargs)
81
        finally:
82
            self.unlock()
83
    return decorated
84
85
86
def needs_write_lock(unbound):
87
    """Decorate unbound to take out and release a write lock."""
88
    def decorated(self, *args, **kwargs):
89
        self.lock_write()
90
        try:
91
            return unbound(self, *args, **kwargs)
92
        finally:
93
            self.unlock()
94
    return decorated
95
1 by mbp at sourcefrog
import from baz patch-364
96
######################################################################
97
# branch objects
98
558 by Martin Pool
- All top-level classes inherit from object
99
class Branch(object):
1 by mbp at sourcefrog
import from baz patch-364
100
    """Branch holding a history of revisions.
101
343 by Martin Pool
doc
102
    base
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
103
        Base directory/url of the branch.
104
    """
105
    base = None
106
107
    def __init__(self, *ignored, **ignored_too):
108
        raise NotImplementedError('The Branch class is abstract')
109
110
    @staticmethod
1393.1.2 by Martin Pool
- better representation in Branch factories of opening old formats
111
    def open_downlevel(base):
112
        """Open a branch which may be of an old format.
113
        
114
        Only local branches are supported."""
1393.1.16 by Martin Pool
- fix up Branch.open_downlevel for Transport
115
        return _Branch(get_transport(base), relax_version_check=True)
1393.1.2 by Martin Pool
- better representation in Branch factories of opening old formats
116
        
117
    @staticmethod
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
118
    def open(base):
119
        """Open an existing branch, rooted at 'base' (url)"""
1393.2.4 by John Arbash Meinel
All tests pass.
120
        t = get_transport(base)
1393.1.63 by Martin Pool
- add some trace statements
121
        mutter("trying to open %r with transport %r", base, t)
1185.11.11 by John Arbash Meinel
Removing the remotebranch object.
122
        return _Branch(t)
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
123
124
    @staticmethod
1185.2.8 by Lalo Martins
creating the new branch constructors
125
    def open_containing(url):
1185.1.41 by Robert Collins
massive patch from Alexander Belchenko - many PEP8 fixes, removes unused function uuid
126
        """Open an existing branch which contains url.
127
        
128
        This probes for a branch at url, and searches upwards from there.
1185.17.2 by Martin Pool
[pick] avoid problems in fetching when .bzr is not listable
129
130
        Basically we keep looking up until we find the control directory or
131
        run into the root.  If there isn't one, raises NotBranchError.
1442.1.64 by Robert Collins
Branch.open_containing now returns a tuple (Branch, relative-path).
132
        If there is one, it is returned, along with the unused portion of url.
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
133
        """
1393.2.4 by John Arbash Meinel
All tests pass.
134
        t = get_transport(url)
1185.17.2 by Martin Pool
[pick] avoid problems in fetching when .bzr is not listable
135
        while True:
136
            try:
1442.1.64 by Robert Collins
Branch.open_containing now returns a tuple (Branch, relative-path).
137
                return _Branch(t), t.relpath(url)
1185.17.2 by Martin Pool
[pick] avoid problems in fetching when .bzr is not listable
138
            except NotBranchError:
139
                pass
140
            new_t = t.clone('..')
141
            if new_t.base == t.base:
142
                # reached the root, whatever that may be
1185.16.61 by mbp at sourcefrog
- start introducing hct error classes
143
                raise NotBranchError(path=url)
1185.17.2 by Martin Pool
[pick] avoid problems in fetching when .bzr is not listable
144
            t = new_t
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
145
146
    @staticmethod
147
    def initialize(base):
148
        """Create a new branch, rooted at 'base' (url)"""
1393.2.4 by John Arbash Meinel
All tests pass.
149
        t = get_transport(base)
1185.11.11 by John Arbash Meinel
Removing the remotebranch object.
150
        return _Branch(t, init=True)
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
151
152
    def setup_caching(self, cache_root):
153
        """Subclasses that care about caching should override this, and set
154
        up cached stores located under cache_root.
155
        """
1400.1.1 by Robert Collins
implement a basic test for the ui branch command from http servers
156
        self.cache_root = cache_root
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
157
1185.35.11 by Aaron Bentley
Added support for branch nicks
158
    def _get_nick(self):
159
        cfg = self.tree_config()
160
        return cfg.get_option(u"nickname", default=self.base.split('/')[-1])
161
162
    def _set_nick(self, nick):
163
        cfg = self.tree_config()
164
        cfg.set_option(nick, "nickname")
165
        assert cfg.get_option("nickname") == nick
166
167
    nick = property(_get_nick, _set_nick)
168
        
169
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
170
1185.11.11 by John Arbash Meinel
Removing the remotebranch object.
171
class _Branch(Branch):
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
172
    """A branch stored in the actual filesystem.
173
174
    Note that it's "local" in the context of the filesystem; it doesn't
175
    really matter if it's on an nfs/smb/afs/coda/... share, as long as
176
    it's writable, and can be accessed via the normal filesystem API.
578 by Martin Pool
- start to move toward Branch.lock and unlock methods,
177
178
    _lock_mode
580 by Martin Pool
- Use explicit lock methods on a branch, rather than doing it
179
        None, or 'r' or 'w'
180
181
    _lock_count
182
        If _lock_mode is true, a positive count of the number of times the
183
        lock has been taken.
578 by Martin Pool
- start to move toward Branch.lock and unlock methods,
184
614 by Martin Pool
- unify two defintions of LockError
185
    _lock
186
        Lock object from bzrlib.lock.
1 by mbp at sourcefrog
import from baz patch-364
187
    """
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
188
    # We actually expect this class to be somewhat short-lived; part of its
189
    # purpose is to try to isolate what bits of the branch logic are tied to
190
    # filesystem access, so that in a later step, we can extricate them to
191
    # a separarte ("storage") class.
578 by Martin Pool
- start to move toward Branch.lock and unlock methods,
192
    _lock_mode = None
580 by Martin Pool
- Use explicit lock methods on a branch, rather than doing it
193
    _lock_count = None
615 by Martin Pool
Major rework of locking code:
194
    _lock = None
1223 by Martin Pool
- store inventories in weave
195
    _inventory_weave = None
353 by Martin Pool
- Per-branch locks in read and write modes.
196
    
897 by Martin Pool
- merge john's revision-naming code
197
    # Map some sort of prefix into a namespace
198
    # stuff like "revno:10", "revid:", etc.
199
    # This should match a prefix with a function which accepts
200
    REVISION_NAMESPACES = {}
201
1391 by Robert Collins
merge from integration
202
    def push_stores(self, branch_to):
203
        """Copy the content of this branches store to branch_to."""
204
        if (self._branch_format != branch_to._branch_format
205
            or self._branch_format != 4):
206
            from bzrlib.fetch import greedy_fetch
1393 by Robert Collins
reenable remotebranch tests
207
            mutter("falling back to fetch logic to push between %s(%s) and %s(%s)",
208
                   self, self._branch_format, branch_to, branch_to._branch_format)
1391 by Robert Collins
merge from integration
209
            greedy_fetch(to_branch=branch_to, from_branch=self,
210
                         revision=self.last_revision())
211
            return
212
213
        store_pairs = ((self.text_store,      branch_to.text_store),
214
                       (self.inventory_store, branch_to.inventory_store),
215
                       (self.revision_store,  branch_to.revision_store))
216
        try:
217
            for from_store, to_store in store_pairs: 
218
                copy_all(from_store, to_store)
219
        except UnlistableStore:
220
            raise UnlistableBranch(from_store)
221
1393.2.1 by John Arbash Meinel
Merged in split-storage-2 branch. Need to cleanup a little bit more still.
222
    def __init__(self, transport, init=False,
1293 by Martin Pool
- add Branch constructor option to relax version check
223
                 relax_version_check=False):
1 by mbp at sourcefrog
import from baz patch-364
224
        """Create new branch object at a particular location.
225
907.1.2 by John Arbash Meinel
Working on making Branch() do all of it's work over a Transport.
226
        transport -- A Transport object, defining how to access files.
62 by mbp at sourcefrog
- new find_branch_root function; based on suggestion from aaron
227
        
254 by Martin Pool
- Doc cleanups from Magnus Therning
228
        init -- If True, create new control files in a previously
1 by mbp at sourcefrog
import from baz patch-364
229
             unversioned directory.  If False, the branch must already
230
             be versioned.
231
1293 by Martin Pool
- add Branch constructor option to relax version check
232
        relax_version_check -- If true, the usual check for the branch
233
            version is not applied.  This is intended only for
234
            upgrade/recovery type use; it's not guaranteed that
235
            all operations will work on old format branches.
236
1 by mbp at sourcefrog
import from baz patch-364
237
        In the test suite, creation of new trees is tested using the
238
        `ScratchBranch` class.
239
        """
1393.1.15 by Martin Pool
- better assertion message
240
        assert isinstance(transport, Transport), \
241
            "%r is not a Transport" % transport
907.1.8 by John Arbash Meinel
Changed the format for abspath. Updated branch to use a hidden _transport
242
        self._transport = transport
1 by mbp at sourcefrog
import from baz patch-364
243
        if init:
244
            self._make_control()
1293 by Martin Pool
- add Branch constructor option to relax version check
245
        self._check_format(relax_version_check)
1393.2.2 by John Arbash Meinel
Updated stores to use Transport
246
1429 by Robert Collins
merge in niemeyers prefixed-store patch
247
        def get_store(name, compressed=True, prefixed=False):
1393.1.41 by Martin Pool
doc
248
            # FIXME: This approach of assuming stores are all entirely compressed
249
            # or entirely uncompressed is tidy, but breaks upgrade from 
250
            # some existing branches where there's a mixture; we probably 
251
            # still want the option to look for both.
1393.2.2 by John Arbash Meinel
Updated stores to use Transport
252
            relpath = self._rel_controlfilename(name)
253
            if compressed:
1429 by Robert Collins
merge in niemeyers prefixed-store patch
254
                store = CompressedTextStore(self._transport.clone(relpath),
255
                                            prefixed=prefixed)
1393.2.2 by John Arbash Meinel
Updated stores to use Transport
256
            else:
1429 by Robert Collins
merge in niemeyers prefixed-store patch
257
                store = TextStore(self._transport.clone(relpath),
258
                                  prefixed=prefixed)
1400.1.1 by Robert Collins
implement a basic test for the ui branch command from http servers
259
            #if self._transport.should_cache():
260
            #    cache_path = os.path.join(self.cache_root, name)
261
            #    os.mkdir(cache_path)
262
            #    store = bzrlib.store.CachedStore(store, cache_path)
1393.2.2 by John Arbash Meinel
Updated stores to use Transport
263
            return store
1429 by Robert Collins
merge in niemeyers prefixed-store patch
264
        def get_weave(name, prefixed=False):
1393.2.2 by John Arbash Meinel
Updated stores to use Transport
265
            relpath = self._rel_controlfilename(name)
1429 by Robert Collins
merge in niemeyers prefixed-store patch
266
            ws = WeaveStore(self._transport.clone(relpath), prefixed=prefixed)
1393.2.2 by John Arbash Meinel
Updated stores to use Transport
267
            if self._transport.should_cache():
268
                ws.enable_cache = True
269
            return ws
270
1296 by Martin Pool
- v4 branch should allow access to inventory and text stores
271
        if self._branch_format == 4:
1393.2.2 by John Arbash Meinel
Updated stores to use Transport
272
            self.inventory_store = get_store('inventory-store')
273
            self.text_store = get_store('text-store')
274
            self.revision_store = get_store('revision-store')
1390 by Robert Collins
pair programming worx... merge integration and weave
275
        elif self._branch_format == 5:
1469 by Robert Collins
Change Transport.* to work with URL's.
276
            self.control_weaves = get_weave('')
1393.2.3 by John Arbash Meinel
Fixing typos, updating stores, getting tests to pass.
277
            self.weave_store = get_weave('weaves')
1393.2.2 by John Arbash Meinel
Updated stores to use Transport
278
            self.revision_store = get_store('revision-store', compressed=False)
1429 by Robert Collins
merge in niemeyers prefixed-store patch
279
        elif self._branch_format == 6:
1469 by Robert Collins
Change Transport.* to work with URL's.
280
            self.control_weaves = get_weave('')
1429 by Robert Collins
merge in niemeyers prefixed-store patch
281
            self.weave_store = get_weave('weaves', prefixed=True)
282
            self.revision_store = get_store('revision-store', compressed=False,
283
                                            prefixed=True)
1442.1.59 by Robert Collins
Add re-sign command to generate a digital signature on a single revision.
284
        self.revision_store.register_suffix('sig')
1417.1.6 by Robert Collins
introduce transactions for grouping actions done to and with branches
285
        self._transaction = None
1 by mbp at sourcefrog
import from baz patch-364
286
287
    def __str__(self):
907.1.5 by John Arbash Meinel
Some more work, including ScratchBranch changes.
288
        return '%s(%r)' % (self.__class__.__name__, self._transport.base)
1 by mbp at sourcefrog
import from baz patch-364
289
290
    __repr__ = __str__
291
578 by Martin Pool
- start to move toward Branch.lock and unlock methods,
292
    def __del__(self):
615 by Martin Pool
Major rework of locking code:
293
        if self._lock_mode or self._lock:
1390 by Robert Collins
pair programming worx... merge integration and weave
294
            # XXX: This should show something every time, and be suitable for
295
            # headless operation and embedding
578 by Martin Pool
- start to move toward Branch.lock and unlock methods,
296
            warn("branch %r was not explicitly unlocked" % self)
615 by Martin Pool
Major rework of locking code:
297
            self._lock.unlock()
578 by Martin Pool
- start to move toward Branch.lock and unlock methods,
298
907.1.23 by John Arbash Meinel
Branch objects now automatically create Cached stores if the protocol is_remote.
299
        # TODO: It might be best to do this somewhere else,
300
        # but it is nice for a Branch object to automatically
301
        # cache it's information.
302
        # Alternatively, we could have the Transport objects cache requests
303
        # See the earlier discussion about how major objects (like Branch)
304
        # should never expect their __del__ function to run.
1185.11.9 by John Arbash Meinel
Most tests pass, some problems with unavailable socket recv
305
        if hasattr(self, 'cache_root') and self.cache_root is not None:
907.1.23 by John Arbash Meinel
Branch objects now automatically create Cached stores if the protocol is_remote.
306
            try:
307
                shutil.rmtree(self.cache_root)
308
            except:
309
                pass
310
            self.cache_root = None
311
907.1.17 by John Arbash Meinel
Adding a Branch.base property, removing pull_loc()
312
    def _get_base(self):
907.1.19 by John Arbash Meinel
Updated ScratchBranch and Branch.base, All Tests PASS !!!
313
        if self._transport:
314
            return self._transport.base
315
        return None
907.1.17 by John Arbash Meinel
Adding a Branch.base property, removing pull_loc()
316
1442.1.5 by Robert Collins
Give branch.base a docstring.
317
    base = property(_get_base, doc="The URL for the root of this branch.")
578 by Martin Pool
- start to move toward Branch.lock and unlock methods,
318
1417.1.6 by Robert Collins
introduce transactions for grouping actions done to and with branches
319
    def _finish_transaction(self):
320
        """Exit the current transaction."""
321
        if self._transaction is None:
322
            raise errors.LockError('Branch %s is not in a transaction' %
323
                                   self)
324
        transaction = self._transaction
325
        self._transaction = None
326
        transaction.finish()
327
328
    def get_transaction(self):
329
        """Return the current active transaction.
330
331
        If no transaction is active, this returns a passthrough object
1185.21.1 by Jelmer Vernooij
Fix typo
332
        for which all data is immediately flushed and no caching happens.
1417.1.6 by Robert Collins
introduce transactions for grouping actions done to and with branches
333
        """
334
        if self._transaction is None:
335
            return transactions.PassThroughTransaction()
336
        else:
337
            return self._transaction
338
339
    def _set_transaction(self, new_transaction):
340
        """Set a new active transaction."""
341
        if self._transaction is not None:
342
            raise errors.LockError('Branch %s is in a transaction already.' %
343
                                   self)
344
        self._transaction = new_transaction
610 by Martin Pool
- replace Branch.lock(mode) with separate lock_read and lock_write
345
346
    def lock_write(self):
1437 by Robert Collins
lock during fetch, which is a separate code path to the special case of cloning
347
        mutter("lock write: %s (%s)", self, self._lock_count)
907.1.2 by John Arbash Meinel
Working on making Branch() do all of it's work over a Transport.
348
        # TODO: Upgrade locking to support using a Transport,
349
        # and potentially a remote locking protocol
610 by Martin Pool
- replace Branch.lock(mode) with separate lock_read and lock_write
350
        if self._lock_mode:
351
            if self._lock_mode != 'w':
352
                raise LockError("can't upgrade to a write lock from %r" %
353
                                self._lock_mode)
354
            self._lock_count += 1
355
        else:
907.1.24 by John Arbash Meinel
Remote functionality work.
356
            self._lock = self._transport.lock_write(
357
                    self._rel_controlfilename('branch-lock'))
610 by Martin Pool
- replace Branch.lock(mode) with separate lock_read and lock_write
358
            self._lock_mode = 'w'
359
            self._lock_count = 1
1417.1.6 by Robert Collins
introduce transactions for grouping actions done to and with branches
360
            self._set_transaction(transactions.PassThroughTransaction())
610 by Martin Pool
- replace Branch.lock(mode) with separate lock_read and lock_write
361
362
    def lock_read(self):
1437 by Robert Collins
lock during fetch, which is a separate code path to the special case of cloning
363
        mutter("lock read: %s (%s)", self, self._lock_count)
610 by Martin Pool
- replace Branch.lock(mode) with separate lock_read and lock_write
364
        if self._lock_mode:
365
            assert self._lock_mode in ('r', 'w'), \
366
                   "invalid lock mode %r" % self._lock_mode
367
            self._lock_count += 1
368
        else:
907.1.24 by John Arbash Meinel
Remote functionality work.
369
            self._lock = self._transport.lock_read(
370
                    self._rel_controlfilename('branch-lock'))
610 by Martin Pool
- replace Branch.lock(mode) with separate lock_read and lock_write
371
            self._lock_mode = 'r'
372
            self._lock_count = 1
1417.1.6 by Robert Collins
introduce transactions for grouping actions done to and with branches
373
            self._set_transaction(transactions.ReadOnlyTransaction())
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.
374
            # 5K may be excessive, but hey, its a knob.
375
            self.get_transaction().set_cache_size(5000)
610 by Martin Pool
- replace Branch.lock(mode) with separate lock_read and lock_write
376
                        
578 by Martin Pool
- start to move toward Branch.lock and unlock methods,
377
    def unlock(self):
1437 by Robert Collins
lock during fetch, which is a separate code path to the special case of cloning
378
        mutter("unlock: %s (%s)", self, self._lock_count)
578 by Martin Pool
- start to move toward Branch.lock and unlock methods,
379
        if not self._lock_mode:
610 by Martin Pool
- replace Branch.lock(mode) with separate lock_read and lock_write
380
            raise LockError('branch %r is not locked' % (self))
580 by Martin Pool
- Use explicit lock methods on a branch, rather than doing it
381
382
        if self._lock_count > 1:
383
            self._lock_count -= 1
384
        else:
1417.1.6 by Robert Collins
introduce transactions for grouping actions done to and with branches
385
            self._finish_transaction()
615 by Martin Pool
Major rework of locking code:
386
            self._lock.unlock()
387
            self._lock = None
580 by Martin Pool
- Use explicit lock methods on a branch, rather than doing it
388
            self._lock_mode = self._lock_count = None
353 by Martin Pool
- Per-branch locks in read and write modes.
389
67 by mbp at sourcefrog
use abspath() for the function that makes an absolute
390
    def abspath(self, name):
1457.1.2 by Robert Collins
move branch._relpath into osutils as relpath
391
        """Return absolute filename for something in the branch
392
        
393
        XXX: Robert Collins 20051017 what is this used for? why is it a branch
394
        method and not a tree method.
395
        """
907.1.5 by John Arbash Meinel
Some more work, including ScratchBranch changes.
396
        return self._transport.abspath(name)
67 by mbp at sourcefrog
use abspath() for the function that makes an absolute
397
907.1.2 by John Arbash Meinel
Working on making Branch() do all of it's work over a Transport.
398
    def _rel_controlfilename(self, file_or_path):
1469 by Robert Collins
Change Transport.* to work with URL's.
399
        if not isinstance(file_or_path, basestring):
400
            file_or_path = '/'.join(file_or_path)
401
        if file_or_path == '':
402
            return bzrlib.BZRDIR
403
        return bzrlib.transport.urlescape(bzrlib.BZRDIR + '/' + file_or_path)
907.1.2 by John Arbash Meinel
Working on making Branch() do all of it's work over a Transport.
404
1 by mbp at sourcefrog
import from baz patch-364
405
    def controlfilename(self, file_or_path):
406
        """Return location relative to branch."""
907.1.8 by John Arbash Meinel
Changed the format for abspath. Updated branch to use a hidden _transport
407
        return self._transport.abspath(self._rel_controlfilename(file_or_path))
1 by mbp at sourcefrog
import from baz patch-364
408
409
    def controlfile(self, file_or_path, mode='r'):
245 by mbp at sourcefrog
- control files always in utf-8-unix format
410
        """Open a control file for this branch.
411
412
        There are two classes of file in the control directory: text
413
        and binary.  binary files are untranslated byte streams.  Text
414
        control files are stored with Unix newlines and in UTF-8, even
415
        if the platform or locale defaults are different.
430 by Martin Pool
doc
416
417
        Controlfiles should almost never be opened in write mode but
418
        rather should be atomically copied and replaced using atomicfile.
245 by mbp at sourcefrog
- control files always in utf-8-unix format
419
        """
907.1.2 by John Arbash Meinel
Working on making Branch() do all of it's work over a Transport.
420
        import codecs
421
422
        relpath = self._rel_controlfilename(file_or_path)
423
        #TODO: codecs.open() buffers linewise, so it was overloaded with
424
        # a much larger buffer, do we need to do the same for getreader/getwriter?
425
        if mode == 'rb': 
907.1.8 by John Arbash Meinel
Changed the format for abspath. Updated branch to use a hidden _transport
426
            return self._transport.get(relpath)
907.1.2 by John Arbash Meinel
Working on making Branch() do all of it's work over a Transport.
427
        elif mode == 'wb':
907.1.50 by John Arbash Meinel
Removed encode/decode from Transport.put/get, added more exceptions that can be thrown.
428
            raise BzrError("Branch.controlfile(mode='wb') is not supported, use put_controlfiles")
907.1.2 by John Arbash Meinel
Working on making Branch() do all of it's work over a Transport.
429
        elif mode == 'r':
907.1.50 by John Arbash Meinel
Removed encode/decode from Transport.put/get, added more exceptions that can be thrown.
430
            return codecs.getreader('utf-8')(self._transport.get(relpath), errors='replace')
907.1.2 by John Arbash Meinel
Working on making Branch() do all of it's work over a Transport.
431
        elif mode == 'w':
907.1.50 by John Arbash Meinel
Removed encode/decode from Transport.put/get, added more exceptions that can be thrown.
432
            raise BzrError("Branch.controlfile(mode='w') is not supported, use put_controlfiles")
245 by mbp at sourcefrog
- control files always in utf-8-unix format
433
        else:
434
            raise BzrError("invalid controlfile mode %r" % mode)
435
907.1.50 by John Arbash Meinel
Removed encode/decode from Transport.put/get, added more exceptions that can be thrown.
436
    def put_controlfile(self, path, f, encode=True):
907.1.20 by John Arbash Meinel
Removed Transport.open(), making get + put encode/decode to utf-8
437
        """Write an entry as a controlfile.
438
907.1.50 by John Arbash Meinel
Removed encode/decode from Transport.put/get, added more exceptions that can be thrown.
439
        :param path: The path to put the file, relative to the .bzr control
440
                     directory
441
        :param f: A file-like or string object whose contents should be copied.
442
        :param encode:  If true, encode the contents as utf-8
443
        """
444
        self.put_controlfiles([(path, f)], encode=encode)
445
446
    def put_controlfiles(self, files, encode=True):
447
        """Write several entries as controlfiles.
448
449
        :param files: A list of [(path, file)] pairs, where the path is the directory
450
                      underneath the bzr control directory
451
        :param encode:  If true, encode the contents as utf-8
452
        """
453
        import codecs
454
        ctrl_files = []
455
        for path, f in files:
456
            if encode:
457
                if isinstance(f, basestring):
458
                    f = f.encode('utf-8', 'replace')
459
                else:
460
                    f = codecs.getwriter('utf-8')(f, errors='replace')
461
            path = self._rel_controlfilename(path)
462
            ctrl_files.append((path, f))
463
        self._transport.put_multi(ctrl_files)
1 by mbp at sourcefrog
import from baz patch-364
464
465
    def _make_control(self):
800 by Martin Pool
Merge John's import-speedup branch:
466
        from bzrlib.inventory import Inventory
1393.2.2 by John Arbash Meinel
Updated stores to use Transport
467
        from bzrlib.weavefile import write_weave_v5
468
        from bzrlib.weave import Weave
802 by Martin Pool
- Remove XMLMixin class in favour of simple pack_xml, unpack_xml functions
469
        
1185.11.1 by John Arbash Meinel
(broken) Transport work is merged in. Tests do not pass yet.
470
        # Create an empty inventory
907.1.47 by John Arbash Meinel
Created mkdir_multi, modified branch to use _multi forms when initializing a branch, creating a full test routine for transports
471
        sio = StringIO()
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
472
        # if we want per-tree root ids then this is the place to set
473
        # them; they're not needed for now and so ommitted for
474
        # simplicity.
1393.2.1 by John Arbash Meinel
Merged in split-storage-2 branch. Need to cleanup a little bit more still.
475
        bzrlib.xml5.serializer_v5.write_inventory(Inventory(), sio)
1393.2.2 by John Arbash Meinel
Updated stores to use Transport
476
        empty_inv = sio.getvalue()
477
        sio = StringIO()
478
        bzrlib.weavefile.write_weave_v5(Weave(), sio)
479
        empty_weave = sio.getvalue()
907.1.47 by John Arbash Meinel
Created mkdir_multi, modified branch to use _multi forms when initializing a branch, creating a full test routine for transports
480
1393.2.1 by John Arbash Meinel
Merged in split-storage-2 branch. Need to cleanup a little bit more still.
481
        dirs = [[], 'revision-store', 'weaves']
907.1.47 by John Arbash Meinel
Created mkdir_multi, modified branch to use _multi forms when initializing a branch, creating a full test routine for transports
482
        files = [('README', 
1 by mbp at sourcefrog
import from baz patch-364
483
            "This is a Bazaar-NG control directory.\n"
907.1.47 by John Arbash Meinel
Created mkdir_multi, modified branch to use _multi forms when initializing a branch, creating a full test routine for transports
484
            "Do not change any files in this directory.\n"),
1429 by Robert Collins
merge in niemeyers prefixed-store patch
485
            ('branch-format', BZR_BRANCH_FORMAT_6),
907.1.47 by John Arbash Meinel
Created mkdir_multi, modified branch to use _multi forms when initializing a branch, creating a full test routine for transports
486
            ('revision-history', ''),
487
            ('branch-name', ''),
488
            ('branch-lock', ''),
489
            ('pending-merges', ''),
1393.2.2 by John Arbash Meinel
Updated stores to use Transport
490
            ('inventory', empty_inv),
491
            ('inventory.weave', empty_weave),
492
            ('ancestry.weave', empty_weave)
907.1.47 by John Arbash Meinel
Created mkdir_multi, modified branch to use _multi forms when initializing a branch, creating a full test routine for transports
493
        ]
1393.2.1 by John Arbash Meinel
Merged in split-storage-2 branch. Need to cleanup a little bit more still.
494
        cfn = self._rel_controlfilename
495
        self._transport.mkdir_multi([cfn(d) for d in dirs])
907.1.50 by John Arbash Meinel
Removed encode/decode from Transport.put/get, added more exceptions that can be thrown.
496
        self.put_controlfiles(files)
907.1.5 by John Arbash Meinel
Some more work, including ScratchBranch changes.
497
        mutter('created control directory in ' + self._transport.base)
802 by Martin Pool
- Remove XMLMixin class in favour of simple pack_xml, unpack_xml functions
498
1293 by Martin Pool
- add Branch constructor option to relax version check
499
    def _check_format(self, relax_version_check):
1 by mbp at sourcefrog
import from baz patch-364
500
        """Check this branch format is supported.
501
1187 by Martin Pool
- improved check for branch version
502
        The format level is stored, as an integer, in
503
        self._branch_format for code that needs to check it later.
1 by mbp at sourcefrog
import from baz patch-364
504
505
        In the future, we might need different in-memory Branch
506
        classes to support downlevel branches.  But not yet.
163 by mbp at sourcefrog
merge win32 portability fixes
507
        """
1185.11.9 by John Arbash Meinel
Most tests pass, some problems with unavailable socket recv
508
        try:
509
            fmt = self.controlfile('branch-format', 'r').read()
510
        except NoSuchFile:
1185.16.61 by mbp at sourcefrog
- start introducing hct error classes
511
            raise NotBranchError(path=self.base)
1393.1.63 by Martin Pool
- add some trace statements
512
        mutter("got branch format %r", fmt)
1429 by Robert Collins
merge in niemeyers prefixed-store patch
513
        if fmt == BZR_BRANCH_FORMAT_6:
514
            self._branch_format = 6
515
        elif fmt == BZR_BRANCH_FORMAT_5:
1187 by Martin Pool
- improved check for branch version
516
            self._branch_format = 5
1294 by Martin Pool
- refactor branch version detection
517
        elif fmt == BZR_BRANCH_FORMAT_4:
518
            self._branch_format = 4
519
520
        if (not relax_version_check
1429 by Robert Collins
merge in niemeyers prefixed-store patch
521
            and self._branch_format not in (5, 6)):
1185.1.53 by Robert Collins
raise a specific error on unsupported branches so that they can be distinguished from generic errors
522
            raise errors.UnsupportedFormatError(
523
                           'sorry, branch format %r not supported' % fmt,
576 by Martin Pool
- raise exceptions rather than using bailout()
524
                           ['use a different bzr version',
1393.2.1 by John Arbash Meinel
Merged in split-storage-2 branch. Need to cleanup a little bit more still.
525
                            'or remove the .bzr directory'
526
                            ' and "bzr init" again'])
907.1.2 by John Arbash Meinel
Working on making Branch() do all of it's work over a Transport.
527
909 by Martin Pool
- merge John's code to give the tree root an explicit file id
528
    def get_root_id(self):
529
        """Return the id of this branches root"""
1497 by Robert Collins
Move Branch.read_working_inventory to WorkingTree.
530
        inv = self.get_inventory(self.last_revision())
909 by Martin Pool
- merge John's code to give the tree root an explicit file id
531
        return inv.root.file_id
1 by mbp at sourcefrog
import from baz patch-364
532
1497 by Robert Collins
Move Branch.read_working_inventory to WorkingTree.
533
    @needs_write_lock
909 by Martin Pool
- merge John's code to give the tree root an explicit file id
534
    def set_root_id(self, file_id):
1497 by Robert Collins
Move Branch.read_working_inventory to WorkingTree.
535
        inv = self.working_tree().read_working_inventory()
909 by Martin Pool
- merge John's code to give the tree root an explicit file id
536
        orig_root_id = inv.root.file_id
537
        del inv._byid[inv.root.file_id]
538
        inv.root.file_id = file_id
539
        inv._byid[inv.root.file_id] = inv.root
540
        for fid in inv:
541
            entry = inv[fid]
542
            if entry.parent_id in (None, orig_root_id):
543
                entry.parent_id = inv.root.file_id
544
        self._write_inventory(inv)
580 by Martin Pool
- Use explicit lock methods on a branch, rather than doing it
545
1442.1.63 by Robert Collins
Remove self.lock_*...finally: self.unlock() dead chickens from branch.py.
546
    @needs_write_lock
1 by mbp at sourcefrog
import from baz patch-364
547
    def _write_inventory(self, inv):
548
        """Update the working inventory.
549
550
        That is to say, the inventory describing changes underway, that
551
        will be committed to the next revision.
552
        """
907.1.2 by John Arbash Meinel
Working on making Branch() do all of it's work over a Transport.
553
        from cStringIO import StringIO
1442.1.63 by Robert Collins
Remove self.lock_*...finally: self.unlock() dead chickens from branch.py.
554
        sio = StringIO()
555
        bzrlib.xml5.serializer_v5.write_inventory(inv, sio)
556
        sio.seek(0)
557
        # Transport handles atomicity
558
        self.put_controlfile('inventory', sio)
770 by Martin Pool
- write new working inventory using AtomicFile
559
        
14 by mbp at sourcefrog
write inventory to temporary file and atomically replace
560
        mutter('wrote working inventory')
580 by Martin Pool
- Use explicit lock methods on a branch, rather than doing it
561
            
1442.1.63 by Robert Collins
Remove self.lock_*...finally: self.unlock() dead chickens from branch.py.
562
    @needs_write_lock
1129 by Martin Pool
- Branch.add shouldn't write to stdout either
563
    def add(self, files, ids=None):
1 by mbp at sourcefrog
import from baz patch-364
564
        """Make files versioned.
565
1129 by Martin Pool
- Branch.add shouldn't write to stdout either
566
        Note that the command line normally calls smart_add instead,
567
        which can automatically recurse.
247 by mbp at sourcefrog
doc
568
1 by mbp at sourcefrog
import from baz patch-364
569
        This puts the files in the Added state, so that they will be
570
        recorded by the next commit.
571
596 by Martin Pool
doc
572
        files
573
            List of paths to add, relative to the base of the tree.
574
575
        ids
576
            If set, use these instead of automatically generated ids.
577
            Must be the same length as the list of files, but may
578
            contain None for ids that are to be autogenerated.
579
254 by Martin Pool
- Doc cleanups from Magnus Therning
580
        TODO: Perhaps have an option to add the ids even if the files do
596 by Martin Pool
doc
581
              not (yet) exist.
1 by mbp at sourcefrog
import from baz patch-364
582
1129 by Martin Pool
- Branch.add shouldn't write to stdout either
583
        TODO: Perhaps yield the ids and paths as they're added.
1 by mbp at sourcefrog
import from baz patch-364
584
        """
585
        # TODO: Re-adding a file that is removed in the working copy
586
        # should probably put it back with the previous ID.
800 by Martin Pool
Merge John's import-speedup branch:
587
        if isinstance(files, basestring):
588
            assert(ids is None or isinstance(ids, basestring))
1 by mbp at sourcefrog
import from baz patch-364
589
            files = [files]
493 by Martin Pool
- Merge aaron's merge command
590
            if ids is not None:
591
                ids = [ids]
592
593
        if ids is None:
594
            ids = [None] * len(files)
595
        else:
596
            assert(len(ids) == len(files))
580 by Martin Pool
- Use explicit lock methods on a branch, rather than doing it
597
1497 by Robert Collins
Move Branch.read_working_inventory to WorkingTree.
598
        inv = self.working_tree().read_working_inventory()
1442.1.63 by Robert Collins
Remove self.lock_*...finally: self.unlock() dead chickens from branch.py.
599
        for f,file_id in zip(files, ids):
600
            if is_control_file(f):
601
                raise BzrError("cannot add control file %s" % quotefn(f))
602
603
            fp = splitpath(f)
604
605
            if len(fp) == 0:
606
                raise BzrError("cannot add top-level %r" % f)
607
608
            fullpath = os.path.normpath(self.abspath(f))
609
610
            try:
611
                kind = file_kind(fullpath)
612
            except OSError:
613
                # maybe something better?
614
                raise BzrError('cannot add: not a regular file, symlink or directory: %s' % quotefn(f))
615
616
            if not InventoryEntry.versionable_kind(kind):
617
                raise BzrError('cannot add: not a versionable file ('
618
                               'i.e. regular file, symlink or directory): %s' % quotefn(f))
619
620
            if file_id is None:
621
                file_id = gen_file_id(f)
622
            inv.add_path(f, kind=kind, file_id=file_id)
623
624
            mutter("add file %s file_id:{%s} kind=%r" % (f, file_id, kind))
625
626
        self._write_inventory(inv)
627
628
    @needs_read_lock
176 by mbp at sourcefrog
New cat command contributed by janmar.
629
    def print_file(self, file, revno):
630
        """Print `file` to stdout."""
1442.1.63 by Robert Collins
Remove self.lock_*...finally: self.unlock() dead chickens from branch.py.
631
        tree = self.revision_tree(self.get_rev_id(revno))
632
        # use inventory as it was in that revision
633
        file_id = tree.inventory.path2id(file)
634
        if not file_id:
635
            raise BzrError("%r is not present in revision %s" % (file, revno))
636
        tree.print_file(file_id)
637
1 by mbp at sourcefrog
import from baz patch-364
638
    def unknowns(self):
639
        """Return all unknown files.
640
641
        These are files in the working directory that are not versioned or
642
        control files or ignored.
643
        
1185.16.72 by Martin Pool
[merge] from robert and fix up tests
644
        >>> from bzrlib.workingtree import WorkingTree
1 by mbp at sourcefrog
import from baz patch-364
645
        >>> b = ScratchBranch(files=['foo', 'foo~'])
1185.16.70 by Martin Pool
- improved handling of non-ascii branch names and test
646
        >>> map(str, b.unknowns())
1 by mbp at sourcefrog
import from baz patch-364
647
        ['foo']
648
        >>> b.add('foo')
649
        >>> list(b.unknowns())
650
        []
1442.1.65 by Robert Collins
Branch.remove has been moved to WorkingTree.
651
        >>> WorkingTree(b.base, b).remove('foo')
1 by mbp at sourcefrog
import from baz patch-364
652
        >>> list(b.unknowns())
1185.22.5 by Michael Ellerman
Fix doctest failure in Branch
653
        [u'foo']
1 by mbp at sourcefrog
import from baz patch-364
654
        """
655
        return self.working_tree().unknowns()
656
1442.1.63 by Robert Collins
Remove self.lock_*...finally: self.unlock() dead chickens from branch.py.
657
    @needs_write_lock
905 by Martin Pool
- merge aaron's append_multiple.patch
658
    def append_revision(self, *revision_ids):
659
        for revision_id in revision_ids:
660
            mutter("add {%s} to revision-history" % revision_id)
1442.1.63 by Robert Collins
Remove self.lock_*...finally: self.unlock() dead chickens from branch.py.
661
        rev_history = self.revision_history()
662
        rev_history.extend(revision_ids)
1442.1.68 by Robert Collins
'bzr pull' now accepts '--clobber'.
663
        self.set_revision_history(rev_history)
664
665
    @needs_write_lock
666
    def set_revision_history(self, rev_history):
1442.1.63 by Robert Collins
Remove self.lock_*...finally: self.unlock() dead chickens from branch.py.
667
        self.put_controlfile('revision-history', '\n'.join(rev_history))
233 by mbp at sourcefrog
- more output from test.sh
668
1261 by Martin Pool
- new method Branch.has_revision
669
    def has_revision(self, revision_id):
670
        """True if this branch has a copy of the revision.
671
672
        This does not necessarily imply the revision is merge
673
        or on the mainline."""
1390 by Robert Collins
pair programming worx... merge integration and weave
674
        return (revision_id is None
1442.1.45 by Robert Collins
replace __contains__ calls in stores with has_id
675
                or self.revision_store.has_id(revision_id))
1261 by Martin Pool
- new method Branch.has_revision
676
1442.1.63 by Robert Collins
Remove self.lock_*...finally: self.unlock() dead chickens from branch.py.
677
    @needs_read_lock
1182 by Martin Pool
- more disentangling of xml storage format from objects
678
    def get_revision_xml_file(self, revision_id):
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
679
        """Return XML file object for revision object."""
680
        if not revision_id or not isinstance(revision_id, basestring):
1185.16.103 by mbp at sourcefrog
Fix up all calls to InvalidRevisionId() to specify parameters.
681
            raise InvalidRevisionId(revision_id=revision_id, branch=self)
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
682
        try:
1442.1.63 by Robert Collins
Remove self.lock_*...finally: self.unlock() dead chickens from branch.py.
683
            return self.revision_store.get(revision_id)
684
        except (IndexError, KeyError):
685
            raise bzrlib.errors.NoSuchRevision(self, revision_id)
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
686
1182 by Martin Pool
- more disentangling of xml storage format from objects
687
    #deprecated
688
    get_revision_xml = get_revision_xml_file
689
1231 by Martin Pool
- more progress on fetch on top of weaves
690
    def get_revision_xml(self, revision_id):
691
        return self.get_revision_xml_file(revision_id).read()
692
693
1 by mbp at sourcefrog
import from baz patch-364
694
    def get_revision(self, revision_id):
695
        """Return the Revision object for a named revision"""
1182 by Martin Pool
- more disentangling of xml storage format from objects
696
        xml_file = self.get_revision_xml_file(revision_id)
1027 by Martin Pool
- better error message when failing to get revision from store
697
698
        try:
1189 by Martin Pool
- BROKEN: partial support for commit into weave
699
            r = bzrlib.xml5.serializer_v5.read_revision(xml_file)
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
700
        except SyntaxError, e:
701
            raise bzrlib.errors.BzrError('failed to unpack revision_xml',
702
                                         [revision_id,
703
                                          str(e)])
802 by Martin Pool
- Remove XMLMixin class in favour of simple pack_xml, unpack_xml functions
704
            
1 by mbp at sourcefrog
import from baz patch-364
705
        assert r.revision_id == revision_id
706
        return r
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
707
708
    def get_revision_delta(self, revno):
709
        """Return the delta for one revision.
710
711
        The delta is relative to its mainline predecessor, or the
712
        empty tree for revision 1.
713
        """
714
        assert isinstance(revno, int)
715
        rh = self.revision_history()
716
        if not (1 <= revno <= len(rh)):
717
            raise InvalidRevisionNumber(revno)
718
719
        # revno is 1-based; list is 0-based
720
721
        new_tree = self.revision_tree(rh[revno-1])
722
        if revno == 1:
723
            old_tree = EmptyTree()
724
        else:
725
            old_tree = self.revision_tree(rh[revno-2])
726
727
        return compare_trees(old_tree, new_tree)
728
672 by Martin Pool
- revision records include the hash of their inventory and
729
    def get_revision_sha1(self, revision_id):
730
        """Hash the stored value of a revision, and return it."""
731
        # In the future, revision entries will be signed. At that
732
        # point, it is probably best *not* to include the signature
733
        # in the revision hash. Because that lets you re-sign
734
        # the revision, (add signatures/remove signatures) and still
735
        # have all hash pointers stay consistent.
736
        # But for now, just hash the contents.
1230 by Martin Pool
- remove Branch.get_revision_xml; use get_revision_xml_file instead
737
        return bzrlib.osutils.sha_file(self.get_revision_xml_file(revision_id))
672 by Martin Pool
- revision records include the hash of their inventory and
738
1225 by Martin Pool
- branch now tracks ancestry - all merged revisions
739
    def get_ancestry(self, revision_id):
1415 by Robert Collins
remove the ancestry weave file
740
        """Return a list of revision-ids integrated by a revision.
741
        
742
        This currently returns a list, but the ordering is not guaranteed:
743
        treat it as a set.
744
        """
1390 by Robert Collins
pair programming worx... merge integration and weave
745
        if revision_id is None:
746
            return [None]
1417.1.8 by Robert Collins
use transactions in the weave store interface, which enables caching for log
747
        w = self.get_inventory_weave()
1415 by Robert Collins
remove the ancestry weave file
748
        return [None] + map(w.idx_to_name,
749
                            w.inclusions([w.lookup(revision_id)]))
1225 by Martin Pool
- branch now tracks ancestry - all merged revisions
750
1223 by Martin Pool
- store inventories in weave
751
    def get_inventory_weave(self):
1417.1.8 by Robert Collins
use transactions in the weave store interface, which enables caching for log
752
        return self.control_weaves.get_weave('inventory',
753
                                             self.get_transaction())
1223 by Martin Pool
- store inventories in weave
754
1192 by Martin Pool
- clean up code for retrieving stored inventories
755
    def get_inventory(self, revision_id):
1223 by Martin Pool
- store inventories in weave
756
        """Get Inventory object by hash."""
1372 by Martin Pool
- avoid converting inventories to/from StringIO
757
        xml = self.get_inventory_xml(revision_id)
758
        return bzrlib.xml5.serializer_v5.read_inventory_from_string(xml)
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
759
1192 by Martin Pool
- clean up code for retrieving stored inventories
760
    def get_inventory_xml(self, revision_id):
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
761
        """Get inventory XML as a file object."""
1192 by Martin Pool
- clean up code for retrieving stored inventories
762
        try:
763
            assert isinstance(revision_id, basestring), type(revision_id)
1223 by Martin Pool
- store inventories in weave
764
            iw = self.get_inventory_weave()
765
            return iw.get_text(iw.lookup(revision_id))
1192 by Martin Pool
- clean up code for retrieving stored inventories
766
        except IndexError:
767
            raise bzrlib.errors.HistoryMissing(self, 'inventory', revision_id)
1180 by Martin Pool
- start splitting code for xml (de)serialization away from objects
768
1192 by Martin Pool
- clean up code for retrieving stored inventories
769
    def get_inventory_sha1(self, revision_id):
672 by Martin Pool
- revision records include the hash of their inventory and
770
        """Return the sha1 hash of the inventory entry
771
        """
1223 by Martin Pool
- store inventories in weave
772
        return self.get_revision(revision_id).inventory_sha1
672 by Martin Pool
- revision records include the hash of their inventory and
773
1 by mbp at sourcefrog
import from baz patch-364
774
    def get_revision_inventory(self, revision_id):
775
        """Return inventory of a past revision."""
1372 by Martin Pool
- avoid converting inventories to/from StringIO
776
        # TODO: Unify this with get_inventory()
1218 by Martin Pool
- fix up import
777
        # bzr 0.0.6 and later imposes the constraint that the inventory_id
820 by Martin Pool
- faster Branch.get_revision_inventory now we know the ids are the same
778
        # must be the same as its revision, so this is trivial.
1 by mbp at sourcefrog
import from baz patch-364
779
        if revision_id == None:
1497 by Robert Collins
Move Branch.read_working_inventory to WorkingTree.
780
            # This does not make sense: if there is no revision,
781
            # then it is the current tree inventory surely ?!
782
            # and thus get_root_id() is something that looks at the last
783
            # commit on the branch, and the get_root_id is an inventory check.
784
            raise NotImplementedError
785
            # return Inventory(self.get_root_id())
1 by mbp at sourcefrog
import from baz patch-364
786
        else:
820 by Martin Pool
- faster Branch.get_revision_inventory now we know the ids are the same
787
            return self.get_inventory(revision_id)
1 by mbp at sourcefrog
import from baz patch-364
788
1442.1.63 by Robert Collins
Remove self.lock_*...finally: self.unlock() dead chickens from branch.py.
789
    @needs_read_lock
1 by mbp at sourcefrog
import from baz patch-364
790
    def revision_history(self):
1295 by Martin Pool
- remove pointless doctest
791
        """Return sequence of revision hashes on to this branch."""
1442.1.63 by Robert Collins
Remove self.lock_*...finally: self.unlock() dead chickens from branch.py.
792
        transaction = self.get_transaction()
793
        history = transaction.map.find_revision_history()
794
        if history is not None:
795
            mutter("cache hit for revision-history in %s", self)
1417.1.12 by Robert Collins
cache revision history during read transactions
796
            return list(history)
1442.1.63 by Robert Collins
Remove self.lock_*...finally: self.unlock() dead chickens from branch.py.
797
        history = [l.rstrip('\r\n') for l in
798
                self.controlfile('revision-history', 'r').readlines()]
799
        transaction.map.add_revision_history(history)
800
        # this call is disabled because revision_history is 
801
        # not really an object yet, and the transaction is for objects.
802
        # transaction.register_clean(history, precious=True)
803
        return list(history)
1 by mbp at sourcefrog
import from baz patch-364
804
805
    def revno(self):
806
        """Return current revision number for this branch.
807
808
        That is equivalent to the number of revisions committed to
809
        this branch.
810
        """
811
        return len(self.revision_history())
812
1241 by Martin Pool
- rename last_patch to last_revision
813
    def last_revision(self):
1 by mbp at sourcefrog
import from baz patch-364
814
        """Return last patch hash, or None if no history.
815
        """
816
        ph = self.revision_history()
817
        if ph:
818
            return ph[-1]
184 by mbp at sourcefrog
pychecker fixups
819
        else:
820
            return None
485 by Martin Pool
- move commit code into its own module
821
974.1.27 by aaron.bentley at utoronto
Initial greedy fetch work
822
    def missing_revisions(self, other, stop_revision=None, diverged_ok=False):
1260 by Martin Pool
- some updates for fetch/update function
823
        """Return a list of new revisions that would perfectly fit.
824
        
628 by Martin Pool
- merge aaron's updated merge/pull code
825
        If self and other have not diverged, return a list of the revisions
826
        present in other, but missing from self.
827
828
        >>> from bzrlib.commit import commit
829
        >>> bzrlib.trace.silent = True
830
        >>> br1 = ScratchBranch()
831
        >>> br2 = ScratchBranch()
832
        >>> br1.missing_revisions(br2)
833
        []
834
        >>> commit(br2, "lala!", rev_id="REVISION-ID-1")
835
        >>> br1.missing_revisions(br2)
836
        [u'REVISION-ID-1']
837
        >>> br2.missing_revisions(br1)
838
        []
839
        >>> commit(br1, "lala!", rev_id="REVISION-ID-1")
840
        >>> br1.missing_revisions(br2)
841
        []
842
        >>> commit(br2, "lala!", rev_id="REVISION-ID-2A")
843
        >>> br1.missing_revisions(br2)
844
        [u'REVISION-ID-2A']
845
        >>> commit(br1, "lala!", rev_id="REVISION-ID-2B")
846
        >>> br1.missing_revisions(br2)
847
        Traceback (most recent call last):
848
        DivergedBranches: These branches have diverged.
849
        """
850
        self_history = self.revision_history()
851
        self_len = len(self_history)
852
        other_history = other.revision_history()
853
        other_len = len(other_history)
854
        common_index = min(self_len, other_len) -1
855
        if common_index >= 0 and \
856
            self_history[common_index] != other_history[common_index]:
857
            raise DivergedBranches(self, other)
685 by Martin Pool
- add -r option to the branch command
858
859
        if stop_revision is None:
860
            stop_revision = other_len
1273 by Martin Pool
- fix up copy_branch, etc
861
        else:
862
            assert isinstance(stop_revision, int)
863
            if stop_revision > other_len:
864
                raise bzrlib.errors.NoSuchRevision(self, stop_revision)
685 by Martin Pool
- add -r option to the branch command
865
        return other_history[self_len:stop_revision]
866
974.1.28 by aaron.bentley at utoronto
factored install_revisions out of update_revisions, updated test cases for greedy_fetch
867
    def update_revisions(self, other, stop_revision=None):
1390 by Robert Collins
pair programming worx... merge integration and weave
868
        """Pull in new perfect-fit revisions."""
974.1.33 by aaron.bentley at utoronto
Added greedy_fetch to update_revisions
869
        from bzrlib.fetch import greedy_fetch
974.1.75 by Aaron Bentley
Sped up pull by copying locally first
870
        if stop_revision is None:
1390 by Robert Collins
pair programming worx... merge integration and weave
871
            stop_revision = other.last_revision()
1185.12.44 by abentley
Restored branch convergence to bzr pull
872
        ### Should this be checking is_ancestor instead of revision_history?
1441 by Robert Collins
tests passing is a good idea - move the branch open in cmd_branch to ensure this, and remove noise from the test suite
873
        if (stop_revision is not None and 
874
            stop_revision in self.revision_history()):
1440 by Robert Collins
further tuning of pull, do not do a local merge or fetch at all, if the remote branch is no newer than we are
875
            return
1260 by Martin Pool
- some updates for fetch/update function
876
        greedy_fetch(to_branch=self, from_branch=other,
1261 by Martin Pool
- new method Branch.has_revision
877
                     revision=stop_revision)
1185.12.44 by abentley
Restored branch convergence to bzr pull
878
        pullable_revs = self.pullable_revisions(other, stop_revision)
1185.12.45 by abentley
Cleanups for pull
879
        if len(pullable_revs) > 0:
1261 by Martin Pool
- new method Branch.has_revision
880
            self.append_revision(*pullable_revs)
1185.12.44 by abentley
Restored branch convergence to bzr pull
881
882
    def pullable_revisions(self, other, stop_revision):
883
        other_revno = other.revision_id_to_revno(stop_revision)
884
        try:
885
            return self.missing_revisions(other, other_revno)
886
        except DivergedBranches, e:
887
            try:
888
                pullable_revs = get_intervening_revisions(self.last_revision(),
889
                                                          stop_revision, self)
890
                assert self.last_revision() not in pullable_revs
891
                return pullable_revs
892
            except bzrlib.errors.NotAncestor:
893
                if is_ancestor(self.last_revision(), stop_revision, self):
894
                    return []
895
                else:
896
                    raise e
897
        
485 by Martin Pool
- move commit code into its own module
898
    def commit(self, *args, **kw):
1189 by Martin Pool
- BROKEN: partial support for commit into weave
899
        from bzrlib.commit import Commit
900
        Commit().commit(self, *args, **kw)
1390 by Robert Collins
pair programming worx... merge integration and weave
901
    
1105 by Martin Pool
- expose 'find-merge-base' as a new expert command,
902
    def revision_id_to_revno(self, revision_id):
903
        """Given a revision id, return its revno"""
1390 by Robert Collins
pair programming worx... merge integration and weave
904
        if revision_id is None:
905
            return 0
1105 by Martin Pool
- expose 'find-merge-base' as a new expert command,
906
        history = self.revision_history()
907
        try:
908
            return history.index(revision_id) + 1
909
        except ValueError:
910
            raise bzrlib.errors.NoSuchRevision(self, revision_id)
911
974.2.7 by aaron.bentley at utoronto
Merged from bzr.24
912
    def get_rev_id(self, revno, history=None):
913
        """Find the revision id of the specified revno."""
914
        if revno == 0:
915
            return None
916
        if history is None:
917
            history = self.revision_history()
918
        elif revno <= 0 or revno > len(history):
919
            raise bzrlib.errors.NoSuchRevision(self, revno)
920
        return history[revno - 1]
921
1 by mbp at sourcefrog
import from baz patch-364
922
    def revision_tree(self, revision_id):
923
        """Return Tree for a revision on this branch.
924
925
        `revision_id` may be None for the null revision, in which case
926
        an `EmptyTree` is returned."""
529 by Martin Pool
todo
927
        # TODO: refactor this to use an existing revision object
928
        # so we don't need to read it in twice.
1185.12.98 by Aaron Bentley
Support for forcing merges of unrelated trees
929
        if revision_id == None or revision_id == NULL_REVISION:
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
930
            return EmptyTree()
1 by mbp at sourcefrog
import from baz patch-364
931
        else:
932
            inv = self.get_revision_inventory(revision_id)
1196 by Martin Pool
- [WIP] retrieve historical texts from weaves
933
            return RevisionTree(self.weave_store, inv, revision_id)
1 by mbp at sourcefrog
import from baz patch-364
934
935
    def working_tree(self):
936
        """Return a `Tree` for the working copy."""
1185.2.2 by Lalo Martins
cleaning up and refactoring the branch module.
937
        from bzrlib.workingtree import WorkingTree
1185.16.72 by Martin Pool
[merge] from robert and fix up tests
938
        # TODO: In the future, perhaps WorkingTree should utilize Transport
1399.1.2 by Robert Collins
push kind character creation into InventoryEntry and TreeEntry
939
        # RobertCollins 20051003 - I don't think it should - working trees are
940
        # much more complex to keep consistent than our careful .bzr subset.
941
        # instead, we should say that working trees are local only, and optimise
942
        # for that.
1497 by Robert Collins
Move Branch.read_working_inventory to WorkingTree.
943
        if self._transport.base.find('://') != -1:
944
            raise NoWorkingTree(self.base)
1457.1.1 by Robert Collins
rather than getting the branch inventory, WorkingTree can use the whole Branch, or make its own.
945
        return WorkingTree(self.base, branch=self)
1 by mbp at sourcefrog
import from baz patch-364
946
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
947
    @needs_write_lock
948
    def pull(self, source, overwrite=False):
949
        source.lock_read()
950
        try:
951
            try:
952
                self.update_revisions(source)
953
            except DivergedBranches:
954
                if not overwrite:
955
                    raise
956
                self.set_revision_history(source.revision_history())
957
        finally:
958
            source.unlock()
1 by mbp at sourcefrog
import from baz patch-364
959
960
    def basis_tree(self):
961
        """Return `Tree` object for last revision.
962
963
        If there are no revisions yet, return an `EmptyTree`.
964
        """
1241 by Martin Pool
- rename last_patch to last_revision
965
        return self.revision_tree(self.last_revision())
1 by mbp at sourcefrog
import from baz patch-364
966
1442.1.63 by Robert Collins
Remove self.lock_*...finally: self.unlock() dead chickens from branch.py.
967
    @needs_write_lock
168 by mbp at sourcefrog
new "rename" command
968
    def rename_one(self, from_rel, to_rel):
309 by Martin Pool
doc
969
        """Rename one file.
970
971
        This can change the directory or the filename or both.
353 by Martin Pool
- Per-branch locks in read and write modes.
972
        """
1442.1.63 by Robert Collins
Remove self.lock_*...finally: self.unlock() dead chickens from branch.py.
973
        tree = self.working_tree()
974
        inv = tree.inventory
975
        if not tree.has_filename(from_rel):
976
            raise BzrError("can't rename: old working file %r does not exist" % from_rel)
977
        if tree.has_filename(to_rel):
978
            raise BzrError("can't rename: new working file %r already exists" % to_rel)
979
980
        file_id = inv.path2id(from_rel)
981
        if file_id == None:
982
            raise BzrError("can't rename: old name %r is not versioned" % from_rel)
983
984
        if inv.path2id(to_rel):
985
            raise BzrError("can't rename: new name %r is already versioned" % to_rel)
986
987
        to_dir, to_tail = os.path.split(to_rel)
988
        to_dir_id = inv.path2id(to_dir)
989
        if to_dir_id == None and to_dir != '':
990
            raise BzrError("can't determine destination directory id for %r" % to_dir)
991
992
        mutter("rename_one:")
993
        mutter("  file_id    {%s}" % file_id)
994
        mutter("  from_rel   %r" % from_rel)
995
        mutter("  to_rel     %r" % to_rel)
996
        mutter("  to_dir     %r" % to_dir)
997
        mutter("  to_dir_id  {%s}" % to_dir_id)
998
999
        inv.rename(file_id, to_dir_id, to_tail)
1000
1001
        from_abs = self.abspath(from_rel)
1002
        to_abs = self.abspath(to_rel)
171 by mbp at sourcefrog
better error message when working file rename fails
1003
        try:
1442.1.63 by Robert Collins
Remove self.lock_*...finally: self.unlock() dead chickens from branch.py.
1004
            rename(from_abs, to_abs)
1005
        except OSError, e:
1006
            raise BzrError("failed to rename %r to %r: %s"
1007
                    % (from_abs, to_abs, e[1]),
1008
                    ["rename rolled back"])
1009
1010
        self._write_inventory(inv)
1011
1012
    @needs_write_lock
174 by mbp at sourcefrog
- New 'move' command; now separated out from rename
1013
    def move(self, from_paths, to_name):
160 by mbp at sourcefrog
- basic support for moving files to different directories - have not done support for renaming them yet, but should be straightforward - some tests, but many cases are not handled yet i think
1014
        """Rename files.
1015
174 by mbp at sourcefrog
- New 'move' command; now separated out from rename
1016
        to_name must exist as a versioned directory.
1017
160 by mbp at sourcefrog
- basic support for moving files to different directories - have not done support for renaming them yet, but should be straightforward - some tests, but many cases are not handled yet i think
1018
        If to_name exists and is a directory, the files are moved into
1019
        it, keeping their old names.  If it is a directory, 
1020
1021
        Note that to_name is only the last component of the new name;
1022
        this doesn't change the directory.
1131 by Martin Pool
- remove more extraneous print statements from Branch.move
1023
1024
        This returns a list of (from_path, to_path) pairs for each
1025
        entry that is moved.
160 by mbp at sourcefrog
- basic support for moving files to different directories - have not done support for renaming them yet, but should be straightforward - some tests, but many cases are not handled yet i think
1026
        """
1131 by Martin Pool
- remove more extraneous print statements from Branch.move
1027
        result = []
1442.1.63 by Robert Collins
Remove self.lock_*...finally: self.unlock() dead chickens from branch.py.
1028
        ## TODO: Option to move IDs only
1029
        assert not isinstance(from_paths, basestring)
1030
        tree = self.working_tree()
1031
        inv = tree.inventory
1032
        to_abs = self.abspath(to_name)
1033
        if not isdir(to_abs):
1034
            raise BzrError("destination %r is not a directory" % to_abs)
1035
        if not tree.has_filename(to_name):
1036
            raise BzrError("destination %r not in working directory" % to_abs)
1037
        to_dir_id = inv.path2id(to_name)
1038
        if to_dir_id == None and to_name != '':
1039
            raise BzrError("destination %r is not a versioned directory" % to_name)
1040
        to_dir_ie = inv[to_dir_id]
1041
        if to_dir_ie.kind not in ('directory', 'root_directory'):
1042
            raise BzrError("destination %r is not a directory" % to_abs)
1043
1044
        to_idpath = inv.get_idpath(to_dir_id)
1045
1046
        for f in from_paths:
1047
            if not tree.has_filename(f):
1048
                raise BzrError("%r does not exist in working tree" % f)
1049
            f_id = inv.path2id(f)
1050
            if f_id == None:
1051
                raise BzrError("%r is not versioned" % f)
1052
            name_tail = splitpath(f)[-1]
1053
            dest_path = appendpath(to_name, name_tail)
1054
            if tree.has_filename(dest_path):
1055
                raise BzrError("destination %r already exists" % dest_path)
1056
            if f_id in to_idpath:
1057
                raise BzrError("can't move %r to a subdirectory of itself" % f)
1058
1059
        # OK, so there's a race here, it's possible that someone will
1060
        # create a file in this interval and then the rename might be
1061
        # left half-done.  But we should have caught most problems.
1062
1063
        for f in from_paths:
1064
            name_tail = splitpath(f)[-1]
1065
            dest_path = appendpath(to_name, name_tail)
1066
            result.append((f, dest_path))
1067
            inv.rename(inv.path2id(f), to_dir_id, name_tail)
1068
            try:
1069
                rename(self.abspath(f), self.abspath(dest_path))
1070
            except OSError, e:
1071
                raise BzrError("failed to rename %r to %r: %s" % (f, dest_path, e[1]),
1072
                        ["rename rolled back"])
1073
1074
        self._write_inventory(inv)
1131 by Martin Pool
- remove more extraneous print statements from Branch.move
1075
        return result
1076
160 by mbp at sourcefrog
- basic support for moving files to different directories - have not done support for renaming them yet, but should be straightforward - some tests, but many cases are not handled yet i think
1077
782 by Martin Pool
- Branch.revert copies files to backups before reverting them
1078
    def revert(self, filenames, old_tree=None, backups=True):
778 by Martin Pool
- simple revert of text files
1079
        """Restore selected files to the versions from a previous tree.
782 by Martin Pool
- Branch.revert copies files to backups before reverting them
1080
1081
        backups
1082
            If true (default) backups are made of files before
1083
            they're renamed.
778 by Martin Pool
- simple revert of text files
1084
        """
1085
        from bzrlib.atomicfile import AtomicFile
782 by Martin Pool
- Branch.revert copies files to backups before reverting them
1086
        from bzrlib.osutils import backup_file
778 by Martin Pool
- simple revert of text files
1087
        
1497 by Robert Collins
Move Branch.read_working_inventory to WorkingTree.
1088
        inv = self.working_tree().read_working_inventory()
778 by Martin Pool
- simple revert of text files
1089
        if old_tree is None:
1090
            old_tree = self.basis_tree()
1091
        old_inv = old_tree.inventory
1092
1093
        nids = []
1094
        for fn in filenames:
1095
            file_id = inv.path2id(fn)
1096
            if not file_id:
1185.16.72 by Martin Pool
[merge] from robert and fix up tests
1097
                raise NotVersionedError(path=fn)
782 by Martin Pool
- Branch.revert copies files to backups before reverting them
1098
            if not old_inv.has_id(file_id):
1099
                raise BzrError("file not present in old tree", fn, file_id)
778 by Martin Pool
- simple revert of text files
1100
            nids.append((fn, file_id))
1101
            
1102
        # TODO: Rename back if it was previously at a different location
1103
1104
        # TODO: If given a directory, restore the entire contents from
1105
        # the previous version.
1106
1107
        # TODO: Make a backup to a temporary file.
1108
1109
        # TODO: If the file previously didn't exist, delete it?
1110
        for fn, file_id in nids:
782 by Martin Pool
- Branch.revert copies files to backups before reverting them
1111
            backup_file(fn)
1112
            
778 by Martin Pool
- simple revert of text files
1113
            f = AtomicFile(fn, 'wb')
1114
            try:
1115
                f.write(old_tree.get_file(file_id).read())
1116
                f.commit()
1117
            finally:
1118
                f.close()
1119
1120
815 by Martin Pool
- track pending-merges
1121
    def pending_merges(self):
1122
        """Return a list of pending merges.
1123
1124
        These are revisions that have been merged into the working
1125
        directory but not yet committed.
1126
        """
907.1.2 by John Arbash Meinel
Working on making Branch() do all of it's work over a Transport.
1127
        cfn = self._rel_controlfilename('pending-merges')
907.1.8 by John Arbash Meinel
Changed the format for abspath. Updated branch to use a hidden _transport
1128
        if not self._transport.has(cfn):
815 by Martin Pool
- track pending-merges
1129
            return []
1130
        p = []
1131
        for l in self.controlfile('pending-merges', 'r').readlines():
1132
            p.append(l.rstrip('\n'))
1133
        return p
1134
1135
907.1.4 by John Arbash Meinel
Add pending_merge can take multiple entries.
1136
    def add_pending_merge(self, *revision_ids):
1263 by Martin Pool
- clean up imports
1137
        # TODO: Perhaps should check at this point that the
1138
        # history of the revision is actually present?
815 by Martin Pool
- track pending-merges
1139
        p = self.pending_merges()
907.1.4 by John Arbash Meinel
Add pending_merge can take multiple entries.
1140
        updated = False
1141
        for rev_id in revision_ids:
1142
            if rev_id in p:
1143
                continue
1144
            p.append(rev_id)
1145
            updated = True
1146
        if updated:
1147
            self.set_pending_merges(p)
815 by Martin Pool
- track pending-merges
1148
1442.1.63 by Robert Collins
Remove self.lock_*...finally: self.unlock() dead chickens from branch.py.
1149
    @needs_write_lock
815 by Martin Pool
- track pending-merges
1150
    def set_pending_merges(self, rev_list):
1442.1.63 by Robert Collins
Remove self.lock_*...finally: self.unlock() dead chickens from branch.py.
1151
        self.put_controlfile('pending-merges', '\n'.join(rev_list))
815 by Martin Pool
- track pending-merges
1152
1149 by Martin Pool
- make get_parent() be a method of Branch; add simple tests for it
1153
    def get_parent(self):
1154
        """Return the parent location of the branch.
1155
1156
        This is the default location for push/pull/missing.  The usual
1157
        pattern is that the user can override it by specifying a
1158
        location.
1159
        """
1160
        import errno
1161
        _locs = ['parent', 'pull', 'x-pull']
1162
        for l in _locs:
1163
            try:
1164
                return self.controlfile(l, 'r').read().strip('\n')
1165
            except IOError, e:
1166
                if e.errno != errno.ENOENT:
1167
                    raise
1168
        return None
1169
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
1170
    def get_push_location(self):
1171
        """Return the None or the location to push this branch to."""
1172
        config = bzrlib.config.BranchConfig(self)
1173
        push_loc = config.get_user_option('push_location')
1174
        return push_loc
1175
1176
    def set_push_location(self, location):
1177
        """Set a new push location for this branch."""
1178
        config = bzrlib.config.LocationConfig(self.base)
1179
        config.set_user_option('push_location', location)
1180
1442.1.63 by Robert Collins
Remove self.lock_*...finally: self.unlock() dead chickens from branch.py.
1181
    @needs_write_lock
1150 by Martin Pool
- add new Branch.set_parent and tests
1182
    def set_parent(self, url):
1183
        # TODO: Maybe delete old location files?
1184
        from bzrlib.atomicfile import AtomicFile
1442.1.63 by Robert Collins
Remove self.lock_*...finally: self.unlock() dead chickens from branch.py.
1185
        f = AtomicFile(self.controlfilename('parent'))
1150 by Martin Pool
- add new Branch.set_parent and tests
1186
        try:
1442.1.63 by Robert Collins
Remove self.lock_*...finally: self.unlock() dead chickens from branch.py.
1187
            f.write(url + '\n')
1188
            f.commit()
1150 by Martin Pool
- add new Branch.set_parent and tests
1189
        finally:
1442.1.63 by Robert Collins
Remove self.lock_*...finally: self.unlock() dead chickens from branch.py.
1190
            f.close()
1150 by Martin Pool
- add new Branch.set_parent and tests
1191
1185.35.11 by Aaron Bentley
Added support for branch nicks
1192
    def tree_config(self):
1193
        return TreeConfig(self)
1194
974.1.54 by aaron.bentley at utoronto
Fixed the revno bug in log
1195
    def check_revno(self, revno):
1196
        """\
1197
        Check whether a revno corresponds to any revision.
1198
        Zero (the NULL revision) is considered valid.
1199
        """
1200
        if revno != 0:
1201
            self.check_real_revno(revno)
1202
            
1203
    def check_real_revno(self, revno):
1204
        """\
1205
        Check whether a revno corresponds to a real revision.
1206
        Zero (the NULL revision) is considered invalid
1207
        """
1208
        if revno < 1 or revno > self.revno():
1209
            raise InvalidRevisionNumber(revno)
1210
        
1442.1.60 by Robert Collins
gpg sign commits if the policy says we need to
1211
    def sign_revision(self, revision_id, gpg_strategy):
1442.1.62 by Robert Collins
Allow creation of testaments from uncommitted data, and use that to get signatures before committing revisions.
1212
        plaintext = Testament.from_revision(self, revision_id).as_short_text()
1213
        self.store_revision_signature(gpg_strategy, plaintext, revision_id)
1214
1442.1.63 by Robert Collins
Remove self.lock_*...finally: self.unlock() dead chickens from branch.py.
1215
    @needs_write_lock
1442.1.62 by Robert Collins
Allow creation of testaments from uncommitted data, and use that to get signatures before committing revisions.
1216
    def store_revision_signature(self, gpg_strategy, plaintext, revision_id):
1442.1.63 by Robert Collins
Remove self.lock_*...finally: self.unlock() dead chickens from branch.py.
1217
        self.revision_store.add(StringIO(gpg_strategy.sign(plaintext)), 
1218
                                revision_id, "sig")
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
1219
1220
1185.35.11 by Aaron Bentley
Added support for branch nicks
1221
1185.11.11 by John Arbash Meinel
Removing the remotebranch object.
1222
class ScratchBranch(_Branch):
1 by mbp at sourcefrog
import from baz patch-364
1223
    """Special test class: a branch that cleans up after itself.
1224
1225
    >>> b = ScratchBranch()
1226
    >>> isdir(b.base)
1227
    True
1228
    >>> bd = b.base
1442.1.42 by Robert Collins
rebuild ScratchBranch on top of ScratchTransport
1229
    >>> b._transport.__del__()
1 by mbp at sourcefrog
import from baz patch-364
1230
    >>> isdir(bd)
1231
    False
1232
    """
1442.1.42 by Robert Collins
rebuild ScratchBranch on top of ScratchTransport
1233
1234
    def __init__(self, files=[], dirs=[], transport=None):
1 by mbp at sourcefrog
import from baz patch-364
1235
        """Make a test branch.
1236
1237
        This creates a temporary directory and runs init-tree in it.
1238
1239
        If any files are listed, they are created in the working copy.
1240
        """
1442.1.42 by Robert Collins
rebuild ScratchBranch on top of ScratchTransport
1241
        if transport is None:
1242
            transport = bzrlib.transport.local.ScratchTransport()
1243
            super(ScratchBranch, self).__init__(transport, init=True)
1244
        else:
1245
            super(ScratchBranch, self).__init__(transport)
1246
100 by mbp at sourcefrog
- add test case for ignore files
1247
        for d in dirs:
907.1.8 by John Arbash Meinel
Changed the format for abspath. Updated branch to use a hidden _transport
1248
            self._transport.mkdir(d)
100 by mbp at sourcefrog
- add test case for ignore files
1249
            
1 by mbp at sourcefrog
import from baz patch-364
1250
        for f in files:
907.1.8 by John Arbash Meinel
Changed the format for abspath. Updated branch to use a hidden _transport
1251
            self._transport.put(f, 'content of %s' % f)
1 by mbp at sourcefrog
import from baz patch-364
1252
1253
622 by Martin Pool
Updated merge patch from Aaron
1254
    def clone(self):
1255
        """
1256
        >>> orig = ScratchBranch(files=["file1", "file2"])
1257
        >>> clone = orig.clone()
1185.1.40 by Robert Collins
Merge what applied of Alexander Belchenko's win32 patch.
1258
        >>> if os.name != 'nt':
1259
        ...   os.path.samefile(orig.base, clone.base)
1260
        ... else:
1261
        ...   orig.base == clone.base
1262
        ...
622 by Martin Pool
Updated merge patch from Aaron
1263
        False
1264
        >>> os.path.isfile(os.path.join(clone.base, "file1"))
1265
        True
1266
        """
800 by Martin Pool
Merge John's import-speedup branch:
1267
        from shutil import copytree
1268
        from tempfile import mkdtemp
1269
        base = mkdtemp()
622 by Martin Pool
Updated merge patch from Aaron
1270
        os.rmdir(base)
800 by Martin Pool
Merge John's import-speedup branch:
1271
        copytree(self.base, base, symlinks=True)
1442.1.42 by Robert Collins
rebuild ScratchBranch on top of ScratchTransport
1272
        return ScratchBranch(
1273
            transport=bzrlib.transport.local.ScratchTransport(base))
1 by mbp at sourcefrog
import from baz patch-364
1274
    
1275
1276
######################################################################
1277
# predicates
1278
1279
1280
def is_control_file(filename):
1281
    ## FIXME: better check
1282
    filename = os.path.normpath(filename)
1283
    while filename != '':
1284
        head, tail = os.path.split(filename)
1285
        ## mutter('check %r for control file' % ((head, tail), ))
1286
        if tail == bzrlib.BZRDIR:
1287
            return True
70 by mbp at sourcefrog
Prepare for smart recursive add.
1288
        if filename == head:
1289
            break
1 by mbp at sourcefrog
import from baz patch-364
1290
        filename = head
1291
    return False
1292
1293
1294
70 by mbp at sourcefrog
Prepare for smart recursive add.
1295
def gen_file_id(name):
1 by mbp at sourcefrog
import from baz patch-364
1296
    """Return new file id.
1297
1298
    This should probably generate proper UUIDs, but for the moment we
1299
    cope with just randomness because running uuidgen every time is
1300
    slow."""
535 by Martin Pool
- try to eliminate wierd characters from file names when they're
1301
    import re
800 by Martin Pool
Merge John's import-speedup branch:
1302
    from binascii import hexlify
1303
    from time import time
535 by Martin Pool
- try to eliminate wierd characters from file names when they're
1304
1305
    # get last component
70 by mbp at sourcefrog
Prepare for smart recursive add.
1306
    idx = name.rfind('/')
1307
    if idx != -1:
1308
        name = name[idx+1 : ]
262 by Martin Pool
- gen_file_id: break the file on either / or \ when looking
1309
    idx = name.rfind('\\')
1310
    if idx != -1:
1311
        name = name[idx+1 : ]
70 by mbp at sourcefrog
Prepare for smart recursive add.
1312
535 by Martin Pool
- try to eliminate wierd characters from file names when they're
1313
    # make it not a hidden file
70 by mbp at sourcefrog
Prepare for smart recursive add.
1314
    name = name.lstrip('.')
1315
535 by Martin Pool
- try to eliminate wierd characters from file names when they're
1316
    # remove any wierd characters; we don't escape them but rather
1317
    # just pull them out
1318
    name = re.sub(r'[^\w.]', '', name)
1319
190 by mbp at sourcefrog
64 bits of randomness in file/revision ids
1320
    s = hexlify(rand_bytes(8))
800 by Martin Pool
Merge John's import-speedup branch:
1321
    return '-'.join((name, compact_date(time()), s))
909 by Martin Pool
- merge John's code to give the tree root an explicit file id
1322
1323
1324
def gen_root_id():
1325
    """Return a new tree-root file id."""
1326
    return gen_file_id('TREE_ROOT')
1327
1092.1.34 by Robert Collins
unbreak cmd_branch now that something tests the core of it..
1328