~bzr-pqm/bzr/bzr.dev

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