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