/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/branch.py

Dont use Branch.open in smart_add when checking for child trees.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2005 Canonical Ltd
 
2
 
 
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
 
 
18
import shutil
 
19
import sys
 
20
import os
 
21
import errno
 
22
from warnings import warn
 
23
from cStringIO import StringIO
 
24
 
 
25
 
 
26
import bzrlib
 
27
import bzrlib.inventory as inventory
 
28
from bzrlib.trace import mutter, note
 
29
from bzrlib.osutils import (isdir, quotefn,
 
30
                            rename, splitpath, sha_file, appendpath, 
 
31
                            file_kind, abspath)
 
32
import bzrlib.errors as errors
 
33
from bzrlib.errors import (BzrError, InvalidRevisionNumber, InvalidRevisionId,
 
34
                           NoSuchRevision, HistoryMissing, NotBranchError,
 
35
                           DivergedBranches, LockError, UnlistableStore,
 
36
                           UnlistableBranch, NoSuchFile, NotVersionedError,
 
37
                           NoWorkingTree)
 
38
from bzrlib.textui import show_status
 
39
from bzrlib.revision import (Revision, is_ancestor, get_intervening_revisions,
 
40
                             NULL_REVISION)
 
41
 
 
42
from bzrlib.delta import compare_trees
 
43
from bzrlib.tree import EmptyTree, RevisionTree
 
44
from bzrlib.inventory import Inventory
 
45
from bzrlib.store import copy_all
 
46
from bzrlib.store.text import TextStore
 
47
from bzrlib.store.weave import WeaveStore
 
48
from bzrlib.testament import Testament
 
49
import bzrlib.transactions as transactions
 
50
from bzrlib.transport import Transport, get_transport
 
51
import bzrlib.xml5
 
52
import bzrlib.ui
 
53
 
 
54
 
 
55
BZR_BRANCH_FORMAT_4 = "Bazaar-NG branch, format 0.0.4\n"
 
56
BZR_BRANCH_FORMAT_5 = "Bazaar-NG branch, format 5\n"
 
57
BZR_BRANCH_FORMAT_6 = "Bazaar-NG branch, format 6\n"
 
58
## TODO: Maybe include checks for common corruption of newlines, etc?
 
59
 
 
60
 
 
61
# TODO: Some operations like log might retrieve the same revisions
 
62
# repeatedly to calculate deltas.  We could perhaps have a weakref
 
63
# cache in memory to make this faster.  In general anything can be
 
64
# cached in memory between lock and unlock operations.
 
65
 
 
66
def find_branch(*ignored, **ignored_too):
 
67
    # XXX: leave this here for about one release, then remove it
 
68
    raise NotImplementedError('find_branch() is not supported anymore, '
 
69
                              'please use one of the new branch constructors')
 
70
 
 
71
 
 
72
def needs_read_lock(unbound):
 
73
    """Decorate unbound to take out and release a read lock."""
 
74
    def decorated(self, *args, **kwargs):
 
75
        self.lock_read()
 
76
        try:
 
77
            return unbound(self, *args, **kwargs)
 
78
        finally:
 
79
            self.unlock()
 
80
    return decorated
 
81
 
 
82
 
 
83
def needs_write_lock(unbound):
 
84
    """Decorate unbound to take out and release a write lock."""
 
85
    def decorated(self, *args, **kwargs):
 
86
        self.lock_write()
 
87
        try:
 
88
            return unbound(self, *args, **kwargs)
 
89
        finally:
 
90
            self.unlock()
 
91
    return decorated
 
92
 
 
93
######################################################################
 
94
# branch objects
 
95
 
 
96
class Branch(object):
 
97
    """Branch holding a history of revisions.
 
98
 
 
99
    base
 
100
        Base directory/url of the branch.
 
101
    """
 
102
    base = None
 
103
 
 
104
    def __init__(self, *ignored, **ignored_too):
 
105
        raise NotImplementedError('The Branch class is abstract')
 
106
 
 
107
    @staticmethod
 
108
    def open_downlevel(base):
 
109
        """Open a branch which may be of an old format.
 
110
        
 
111
        Only local branches are supported."""
 
112
        return _Branch(get_transport(base), relax_version_check=True)
 
113
        
 
114
    @staticmethod
 
115
    def open(base):
 
116
        """Open an existing branch, rooted at 'base' (url)"""
 
117
        t = get_transport(base)
 
118
        mutter("trying to open %r with transport %r", base, t)
 
119
        return _Branch(t)
 
120
 
 
121
    @staticmethod
 
122
    def open_containing(url):
 
123
        """Open an existing branch which contains url.
 
124
        
 
125
        This probes for a branch at url, and searches upwards from there.
 
126
 
 
127
        Basically we keep looking up until we find the control directory or
 
128
        run into the root.  If there isn't one, raises NotBranchError.
 
129
        If there is one, it is returned, along with the unused portion of url.
 
130
        """
 
131
        t = get_transport(url)
 
132
        while True:
 
133
            try:
 
134
                return _Branch(t), t.relpath(url)
 
135
            except NotBranchError:
 
136
                pass
 
137
            new_t = t.clone('..')
 
138
            if new_t.base == t.base:
 
139
                # reached the root, whatever that may be
 
140
                raise NotBranchError(path=url)
 
141
            t = new_t
 
142
 
 
143
    @staticmethod
 
144
    def initialize(base):
 
145
        """Create a new branch, rooted at 'base' (url)"""
 
146
        t = get_transport(base)
 
147
        return _Branch(t, init=True)
 
148
 
 
149
    def setup_caching(self, cache_root):
 
150
        """Subclasses that care about caching should override this, and set
 
151
        up cached stores located under cache_root.
 
152
        """
 
153
        self.cache_root = cache_root
 
154
 
 
155
 
 
156
class _Branch(Branch):
 
157
    """A branch stored in the actual filesystem.
 
158
 
 
159
    Note that it's "local" in the context of the filesystem; it doesn't
 
160
    really matter if it's on an nfs/smb/afs/coda/... share, as long as
 
161
    it's writable, and can be accessed via the normal filesystem API.
 
162
 
 
163
    _lock_mode
 
164
        None, or 'r' or 'w'
 
165
 
 
166
    _lock_count
 
167
        If _lock_mode is true, a positive count of the number of times the
 
168
        lock has been taken.
 
169
 
 
170
    _lock
 
171
        Lock object from bzrlib.lock.
 
172
    """
 
173
    # We actually expect this class to be somewhat short-lived; part of its
 
174
    # purpose is to try to isolate what bits of the branch logic are tied to
 
175
    # filesystem access, so that in a later step, we can extricate them to
 
176
    # a separarte ("storage") class.
 
177
    _lock_mode = None
 
178
    _lock_count = None
 
179
    _lock = None
 
180
    _inventory_weave = None
 
181
    
 
182
    # Map some sort of prefix into a namespace
 
183
    # stuff like "revno:10", "revid:", etc.
 
184
    # This should match a prefix with a function which accepts
 
185
    REVISION_NAMESPACES = {}
 
186
 
 
187
    def push_stores(self, branch_to):
 
188
        """Copy the content of this branches store to branch_to."""
 
189
        if (self._branch_format != branch_to._branch_format
 
190
            or self._branch_format != 4):
 
191
            from bzrlib.fetch import greedy_fetch
 
192
            mutter("falling back to fetch logic to push between %s(%s) and %s(%s)",
 
193
                   self, self._branch_format, branch_to, branch_to._branch_format)
 
194
            greedy_fetch(to_branch=branch_to, from_branch=self,
 
195
                         revision=self.last_revision())
 
196
            return
 
197
 
 
198
        store_pairs = ((self.text_store,      branch_to.text_store),
 
199
                       (self.inventory_store, branch_to.inventory_store),
 
200
                       (self.revision_store,  branch_to.revision_store))
 
201
        try:
 
202
            for from_store, to_store in store_pairs: 
 
203
                copy_all(from_store, to_store)
 
204
        except UnlistableStore:
 
205
            raise UnlistableBranch(from_store)
 
206
 
 
207
    def __init__(self, transport, init=False,
 
208
                 relax_version_check=False):
 
209
        """Create new branch object at a particular location.
 
210
 
 
211
        transport -- A Transport object, defining how to access files.
 
212
        
 
213
        init -- If True, create new control files in a previously
 
214
             unversioned directory.  If False, the branch must already
 
215
             be versioned.
 
216
 
 
217
        relax_version_check -- If true, the usual check for the branch
 
218
            version is not applied.  This is intended only for
 
219
            upgrade/recovery type use; it's not guaranteed that
 
220
            all operations will work on old format branches.
 
221
 
 
222
        In the test suite, creation of new trees is tested using the
 
223
        `ScratchBranch` class.
 
224
        """
 
225
        assert isinstance(transport, Transport), \
 
226
            "%r is not a Transport" % transport
 
227
        self._transport = transport
 
228
        if init:
 
229
            self._make_control()
 
230
        self._check_format(relax_version_check)
 
231
 
 
232
        def get_store(name, compressed=True, prefixed=False):
 
233
            # FIXME: This approach of assuming stores are all entirely compressed
 
234
            # or entirely uncompressed is tidy, but breaks upgrade from 
 
235
            # some existing branches where there's a mixture; we probably 
 
236
            # still want the option to look for both.
 
237
            relpath = self._rel_controlfilename(name)
 
238
            store = TextStore(self._transport.clone(relpath),
 
239
                              prefixed=prefixed,
 
240
                              compressed=compressed)
 
241
            #if self._transport.should_cache():
 
242
            #    cache_path = os.path.join(self.cache_root, name)
 
243
            #    os.mkdir(cache_path)
 
244
            #    store = bzrlib.store.CachedStore(store, cache_path)
 
245
            return store
 
246
        def get_weave(name, prefixed=False):
 
247
            relpath = self._rel_controlfilename(name)
 
248
            ws = WeaveStore(self._transport.clone(relpath), prefixed=prefixed)
 
249
            if self._transport.should_cache():
 
250
                ws.enable_cache = True
 
251
            return ws
 
252
 
 
253
        if self._branch_format == 4:
 
254
            self.inventory_store = get_store('inventory-store')
 
255
            self.text_store = get_store('text-store')
 
256
            self.revision_store = get_store('revision-store')
 
257
        elif self._branch_format == 5:
 
258
            self.control_weaves = get_weave('')
 
259
            self.weave_store = get_weave('weaves')
 
260
            self.revision_store = get_store('revision-store', compressed=False)
 
261
        elif self._branch_format == 6:
 
262
            self.control_weaves = get_weave('')
 
263
            self.weave_store = get_weave('weaves', prefixed=True)
 
264
            self.revision_store = get_store('revision-store', compressed=False,
 
265
                                            prefixed=True)
 
266
        self.revision_store.register_suffix('sig')
 
267
        self._transaction = None
 
268
 
 
269
    def __str__(self):
 
270
        return '%s(%r)' % (self.__class__.__name__, self._transport.base)
 
271
 
 
272
    __repr__ = __str__
 
273
 
 
274
    def __del__(self):
 
275
        if self._lock_mode or self._lock:
 
276
            # XXX: This should show something every time, and be suitable for
 
277
            # headless operation and embedding
 
278
            warn("branch %r was not explicitly unlocked" % self)
 
279
            self._lock.unlock()
 
280
 
 
281
        # TODO: It might be best to do this somewhere else,
 
282
        # but it is nice for a Branch object to automatically
 
283
        # cache it's information.
 
284
        # Alternatively, we could have the Transport objects cache requests
 
285
        # See the earlier discussion about how major objects (like Branch)
 
286
        # should never expect their __del__ function to run.
 
287
        if hasattr(self, 'cache_root') and self.cache_root is not None:
 
288
            try:
 
289
                shutil.rmtree(self.cache_root)
 
290
            except:
 
291
                pass
 
292
            self.cache_root = None
 
293
 
 
294
    def _get_base(self):
 
295
        if self._transport:
 
296
            return self._transport.base
 
297
        return None
 
298
 
 
299
    base = property(_get_base, doc="The URL for the root of this branch.")
 
300
 
 
301
    def _finish_transaction(self):
 
302
        """Exit the current transaction."""
 
303
        if self._transaction is None:
 
304
            raise errors.LockError('Branch %s is not in a transaction' %
 
305
                                   self)
 
306
        transaction = self._transaction
 
307
        self._transaction = None
 
308
        transaction.finish()
 
309
 
 
310
    def get_transaction(self):
 
311
        """Return the current active transaction.
 
312
 
 
313
        If no transaction is active, this returns a passthrough object
 
314
        for which all data is immediately flushed and no caching happens.
 
315
        """
 
316
        if self._transaction is None:
 
317
            return transactions.PassThroughTransaction()
 
318
        else:
 
319
            return self._transaction
 
320
 
 
321
    def _set_transaction(self, new_transaction):
 
322
        """Set a new active transaction."""
 
323
        if self._transaction is not None:
 
324
            raise errors.LockError('Branch %s is in a transaction already.' %
 
325
                                   self)
 
326
        self._transaction = new_transaction
 
327
 
 
328
    def lock_write(self):
 
329
        mutter("lock write: %s (%s)", self, self._lock_count)
 
330
        # TODO: Upgrade locking to support using a Transport,
 
331
        # and potentially a remote locking protocol
 
332
        if self._lock_mode:
 
333
            if self._lock_mode != 'w':
 
334
                raise LockError("can't upgrade to a write lock from %r" %
 
335
                                self._lock_mode)
 
336
            self._lock_count += 1
 
337
        else:
 
338
            self._lock = self._transport.lock_write(
 
339
                    self._rel_controlfilename('branch-lock'))
 
340
            self._lock_mode = 'w'
 
341
            self._lock_count = 1
 
342
            self._set_transaction(transactions.PassThroughTransaction())
 
343
 
 
344
    def lock_read(self):
 
345
        mutter("lock read: %s (%s)", self, self._lock_count)
 
346
        if self._lock_mode:
 
347
            assert self._lock_mode in ('r', 'w'), \
 
348
                   "invalid lock mode %r" % self._lock_mode
 
349
            self._lock_count += 1
 
350
        else:
 
351
            self._lock = self._transport.lock_read(
 
352
                    self._rel_controlfilename('branch-lock'))
 
353
            self._lock_mode = 'r'
 
354
            self._lock_count = 1
 
355
            self._set_transaction(transactions.ReadOnlyTransaction())
 
356
            # 5K may be excessive, but hey, its a knob.
 
357
            self.get_transaction().set_cache_size(5000)
 
358
                        
 
359
    def unlock(self):
 
360
        mutter("unlock: %s (%s)", self, self._lock_count)
 
361
        if not self._lock_mode:
 
362
            raise LockError('branch %r is not locked' % (self))
 
363
 
 
364
        if self._lock_count > 1:
 
365
            self._lock_count -= 1
 
366
        else:
 
367
            self._finish_transaction()
 
368
            self._lock.unlock()
 
369
            self._lock = None
 
370
            self._lock_mode = self._lock_count = None
 
371
 
 
372
    def abspath(self, name):
 
373
        """Return absolute filename for something in the branch
 
374
        
 
375
        XXX: Robert Collins 20051017 what is this used for? why is it a branch
 
376
        method and not a tree method.
 
377
        """
 
378
        return self._transport.abspath(name)
 
379
 
 
380
    def _rel_controlfilename(self, file_or_path):
 
381
        if not isinstance(file_or_path, basestring):
 
382
            file_or_path = '/'.join(file_or_path)
 
383
        if file_or_path == '':
 
384
            return bzrlib.BZRDIR
 
385
        return bzrlib.transport.urlescape(bzrlib.BZRDIR + '/' + file_or_path)
 
386
 
 
387
    def controlfilename(self, file_or_path):
 
388
        """Return location relative to branch."""
 
389
        return self._transport.abspath(self._rel_controlfilename(file_or_path))
 
390
 
 
391
    def controlfile(self, file_or_path, mode='r'):
 
392
        """Open a control file for this branch.
 
393
 
 
394
        There are two classes of file in the control directory: text
 
395
        and binary.  binary files are untranslated byte streams.  Text
 
396
        control files are stored with Unix newlines and in UTF-8, even
 
397
        if the platform or locale defaults are different.
 
398
 
 
399
        Controlfiles should almost never be opened in write mode but
 
400
        rather should be atomically copied and replaced using atomicfile.
 
401
        """
 
402
        import codecs
 
403
 
 
404
        relpath = self._rel_controlfilename(file_or_path)
 
405
        #TODO: codecs.open() buffers linewise, so it was overloaded with
 
406
        # a much larger buffer, do we need to do the same for getreader/getwriter?
 
407
        if mode == 'rb': 
 
408
            return self._transport.get(relpath)
 
409
        elif mode == 'wb':
 
410
            raise BzrError("Branch.controlfile(mode='wb') is not supported, use put_controlfiles")
 
411
        elif mode == 'r':
 
412
            # XXX: Do we really want errors='replace'?   Perhaps it should be
 
413
            # an error, or at least reported, if there's incorrectly-encoded
 
414
            # data inside a file.
 
415
            # <https://launchpad.net/products/bzr/+bug/3823>
 
416
            return codecs.getreader('utf-8')(self._transport.get(relpath), errors='replace')
 
417
        elif mode == 'w':
 
418
            raise BzrError("Branch.controlfile(mode='w') is not supported, use put_controlfiles")
 
419
        else:
 
420
            raise BzrError("invalid controlfile mode %r" % mode)
 
421
 
 
422
    def put_controlfile(self, path, f, encode=True):
 
423
        """Write an entry as a controlfile.
 
424
 
 
425
        :param path: The path to put the file, relative to the .bzr control
 
426
                     directory
 
427
        :param f: A file-like or string object whose contents should be copied.
 
428
        :param encode:  If true, encode the contents as utf-8
 
429
        """
 
430
        self.put_controlfiles([(path, f)], encode=encode)
 
431
 
 
432
    def put_controlfiles(self, files, encode=True):
 
433
        """Write several entries as controlfiles.
 
434
 
 
435
        :param files: A list of [(path, file)] pairs, where the path is the directory
 
436
                      underneath the bzr control directory
 
437
        :param encode:  If true, encode the contents as utf-8
 
438
        """
 
439
        import codecs
 
440
        ctrl_files = []
 
441
        for path, f in files:
 
442
            if encode:
 
443
                if isinstance(f, basestring):
 
444
                    f = f.encode('utf-8', 'replace')
 
445
                else:
 
446
                    f = codecs.getwriter('utf-8')(f, errors='replace')
 
447
            path = self._rel_controlfilename(path)
 
448
            ctrl_files.append((path, f))
 
449
        self._transport.put_multi(ctrl_files)
 
450
 
 
451
    def _make_control(self):
 
452
        from bzrlib.inventory import Inventory
 
453
        from bzrlib.weavefile import write_weave_v5
 
454
        from bzrlib.weave import Weave
 
455
        
 
456
        # Create an empty inventory
 
457
        sio = StringIO()
 
458
        # if we want per-tree root ids then this is the place to set
 
459
        # them; they're not needed for now and so ommitted for
 
460
        # simplicity.
 
461
        bzrlib.xml5.serializer_v5.write_inventory(Inventory(), sio)
 
462
        empty_inv = sio.getvalue()
 
463
        sio = StringIO()
 
464
        bzrlib.weavefile.write_weave_v5(Weave(), sio)
 
465
        empty_weave = sio.getvalue()
 
466
 
 
467
        dirs = [[], 'revision-store', 'weaves']
 
468
        files = [('README', 
 
469
            "This is a Bazaar-NG control directory.\n"
 
470
            "Do not change any files in this directory.\n"),
 
471
            ('branch-format', BZR_BRANCH_FORMAT_6),
 
472
            ('revision-history', ''),
 
473
            ('branch-name', ''),
 
474
            ('branch-lock', ''),
 
475
            ('pending-merges', ''),
 
476
            ('inventory', empty_inv),
 
477
            ('inventory.weave', empty_weave),
 
478
            ('ancestry.weave', empty_weave)
 
479
        ]
 
480
        cfn = self._rel_controlfilename
 
481
        self._transport.mkdir_multi([cfn(d) for d in dirs])
 
482
        self.put_controlfiles(files)
 
483
        mutter('created control directory in ' + self._transport.base)
 
484
 
 
485
    def _check_format(self, relax_version_check):
 
486
        """Check this branch format is supported.
 
487
 
 
488
        The format level is stored, as an integer, in
 
489
        self._branch_format for code that needs to check it later.
 
490
 
 
491
        In the future, we might need different in-memory Branch
 
492
        classes to support downlevel branches.  But not yet.
 
493
        """
 
494
        try:
 
495
            fmt = self.controlfile('branch-format', 'r').read()
 
496
        except NoSuchFile:
 
497
            raise NotBranchError(path=self.base)
 
498
        mutter("got branch format %r", fmt)
 
499
        if fmt == BZR_BRANCH_FORMAT_6:
 
500
            self._branch_format = 6
 
501
        elif fmt == BZR_BRANCH_FORMAT_5:
 
502
            self._branch_format = 5
 
503
        elif fmt == BZR_BRANCH_FORMAT_4:
 
504
            self._branch_format = 4
 
505
 
 
506
        if (not relax_version_check
 
507
            and self._branch_format not in (5, 6)):
 
508
            raise errors.UnsupportedFormatError(
 
509
                           'sorry, branch format %r not supported' % fmt,
 
510
                           ['use a different bzr version',
 
511
                            'or remove the .bzr directory'
 
512
                            ' and "bzr init" again'])
 
513
 
 
514
    def get_root_id(self):
 
515
        """Return the id of this branches root"""
 
516
        inv = self.get_inventory(self.last_revision())
 
517
        return inv.root.file_id
 
518
 
 
519
    @needs_read_lock
 
520
    def print_file(self, file, revno):
 
521
        """Print `file` to stdout."""
 
522
        tree = self.revision_tree(self.get_rev_id(revno))
 
523
        # use inventory as it was in that revision
 
524
        file_id = tree.inventory.path2id(file)
 
525
        if not file_id:
 
526
            raise BzrError("%r is not present in revision %s" % (file, revno))
 
527
        tree.print_file(file_id)
 
528
 
 
529
    @needs_write_lock
 
530
    def append_revision(self, *revision_ids):
 
531
        for revision_id in revision_ids:
 
532
            mutter("add {%s} to revision-history" % revision_id)
 
533
        rev_history = self.revision_history()
 
534
        rev_history.extend(revision_ids)
 
535
        self.set_revision_history(rev_history)
 
536
 
 
537
    @needs_write_lock
 
538
    def set_revision_history(self, rev_history):
 
539
        self.put_controlfile('revision-history', '\n'.join(rev_history))
 
540
 
 
541
    def has_revision(self, revision_id):
 
542
        """True if this branch has a copy of the revision.
 
543
 
 
544
        This does not necessarily imply the revision is merge
 
545
        or on the mainline."""
 
546
        return (revision_id is None
 
547
                or self.revision_store.has_id(revision_id))
 
548
 
 
549
    @needs_read_lock
 
550
    def get_revision_xml_file(self, revision_id):
 
551
        """Return XML file object for revision object."""
 
552
        if not revision_id or not isinstance(revision_id, basestring):
 
553
            raise InvalidRevisionId(revision_id=revision_id, branch=self)
 
554
        try:
 
555
            return self.revision_store.get(revision_id)
 
556
        except (IndexError, KeyError):
 
557
            raise bzrlib.errors.NoSuchRevision(self, revision_id)
 
558
 
 
559
    #deprecated
 
560
    get_revision_xml = get_revision_xml_file
 
561
 
 
562
    def get_revision_xml(self, revision_id):
 
563
        return self.get_revision_xml_file(revision_id).read()
 
564
 
 
565
 
 
566
    def get_revision(self, revision_id):
 
567
        """Return the Revision object for a named revision"""
 
568
        xml_file = self.get_revision_xml_file(revision_id)
 
569
 
 
570
        try:
 
571
            r = bzrlib.xml5.serializer_v5.read_revision(xml_file)
 
572
        except SyntaxError, e:
 
573
            raise bzrlib.errors.BzrError('failed to unpack revision_xml',
 
574
                                         [revision_id,
 
575
                                          str(e)])
 
576
            
 
577
        assert r.revision_id == revision_id
 
578
        return r
 
579
 
 
580
    def get_revision_delta(self, revno):
 
581
        """Return the delta for one revision.
 
582
 
 
583
        The delta is relative to its mainline predecessor, or the
 
584
        empty tree for revision 1.
 
585
        """
 
586
        assert isinstance(revno, int)
 
587
        rh = self.revision_history()
 
588
        if not (1 <= revno <= len(rh)):
 
589
            raise InvalidRevisionNumber(revno)
 
590
 
 
591
        # revno is 1-based; list is 0-based
 
592
 
 
593
        new_tree = self.revision_tree(rh[revno-1])
 
594
        if revno == 1:
 
595
            old_tree = EmptyTree()
 
596
        else:
 
597
            old_tree = self.revision_tree(rh[revno-2])
 
598
 
 
599
        return compare_trees(old_tree, new_tree)
 
600
 
 
601
    def get_revision_sha1(self, revision_id):
 
602
        """Hash the stored value of a revision, and return it."""
 
603
        # In the future, revision entries will be signed. At that
 
604
        # point, it is probably best *not* to include the signature
 
605
        # in the revision hash. Because that lets you re-sign
 
606
        # the revision, (add signatures/remove signatures) and still
 
607
        # have all hash pointers stay consistent.
 
608
        # But for now, just hash the contents.
 
609
        return bzrlib.osutils.sha_file(self.get_revision_xml_file(revision_id))
 
610
 
 
611
    def get_ancestry(self, revision_id):
 
612
        """Return a list of revision-ids integrated by a revision.
 
613
        
 
614
        This currently returns a list, but the ordering is not guaranteed:
 
615
        treat it as a set.
 
616
        """
 
617
        if revision_id is None:
 
618
            return [None]
 
619
        w = self.get_inventory_weave()
 
620
        return [None] + map(w.idx_to_name,
 
621
                            w.inclusions([w.lookup(revision_id)]))
 
622
 
 
623
    def get_inventory_weave(self):
 
624
        return self.control_weaves.get_weave('inventory',
 
625
                                             self.get_transaction())
 
626
 
 
627
    def get_inventory(self, revision_id):
 
628
        """Get Inventory object by hash."""
 
629
        xml = self.get_inventory_xml(revision_id)
 
630
        return bzrlib.xml5.serializer_v5.read_inventory_from_string(xml)
 
631
 
 
632
    def get_inventory_xml(self, revision_id):
 
633
        """Get inventory XML as a file object."""
 
634
        try:
 
635
            assert isinstance(revision_id, basestring), type(revision_id)
 
636
            iw = self.get_inventory_weave()
 
637
            return iw.get_text(iw.lookup(revision_id))
 
638
        except IndexError:
 
639
            raise bzrlib.errors.HistoryMissing(self, 'inventory', revision_id)
 
640
 
 
641
    def get_inventory_sha1(self, revision_id):
 
642
        """Return the sha1 hash of the inventory entry
 
643
        """
 
644
        return self.get_revision(revision_id).inventory_sha1
 
645
 
 
646
    def get_revision_inventory(self, revision_id):
 
647
        """Return inventory of a past revision."""
 
648
        # TODO: Unify this with get_inventory()
 
649
        # bzr 0.0.6 and later imposes the constraint that the inventory_id
 
650
        # must be the same as its revision, so this is trivial.
 
651
        if revision_id == None:
 
652
            # This does not make sense: if there is no revision,
 
653
            # then it is the current tree inventory surely ?!
 
654
            # and thus get_root_id() is something that looks at the last
 
655
            # commit on the branch, and the get_root_id is an inventory check.
 
656
            raise NotImplementedError
 
657
            # return Inventory(self.get_root_id())
 
658
        else:
 
659
            return self.get_inventory(revision_id)
 
660
 
 
661
    @needs_read_lock
 
662
    def revision_history(self):
 
663
        """Return sequence of revision hashes on to this branch."""
 
664
        transaction = self.get_transaction()
 
665
        history = transaction.map.find_revision_history()
 
666
        if history is not None:
 
667
            mutter("cache hit for revision-history in %s", self)
 
668
            return list(history)
 
669
        history = [l.rstrip('\r\n') for l in
 
670
                self.controlfile('revision-history', 'r').readlines()]
 
671
        transaction.map.add_revision_history(history)
 
672
        # this call is disabled because revision_history is 
 
673
        # not really an object yet, and the transaction is for objects.
 
674
        # transaction.register_clean(history, precious=True)
 
675
        return list(history)
 
676
 
 
677
    def revno(self):
 
678
        """Return current revision number for this branch.
 
679
 
 
680
        That is equivalent to the number of revisions committed to
 
681
        this branch.
 
682
        """
 
683
        return len(self.revision_history())
 
684
 
 
685
    def last_revision(self):
 
686
        """Return last patch hash, or None if no history.
 
687
        """
 
688
        ph = self.revision_history()
 
689
        if ph:
 
690
            return ph[-1]
 
691
        else:
 
692
            return None
 
693
 
 
694
    def missing_revisions(self, other, stop_revision=None, diverged_ok=False):
 
695
        """Return a list of new revisions that would perfectly fit.
 
696
        
 
697
        If self and other have not diverged, return a list of the revisions
 
698
        present in other, but missing from self.
 
699
 
 
700
        >>> from bzrlib.commit import commit
 
701
        >>> bzrlib.trace.silent = True
 
702
        >>> br1 = ScratchBranch()
 
703
        >>> br2 = ScratchBranch()
 
704
        >>> br1.missing_revisions(br2)
 
705
        []
 
706
        >>> commit(br2, "lala!", rev_id="REVISION-ID-1")
 
707
        >>> br1.missing_revisions(br2)
 
708
        [u'REVISION-ID-1']
 
709
        >>> br2.missing_revisions(br1)
 
710
        []
 
711
        >>> commit(br1, "lala!", rev_id="REVISION-ID-1")
 
712
        >>> br1.missing_revisions(br2)
 
713
        []
 
714
        >>> commit(br2, "lala!", rev_id="REVISION-ID-2A")
 
715
        >>> br1.missing_revisions(br2)
 
716
        [u'REVISION-ID-2A']
 
717
        >>> commit(br1, "lala!", rev_id="REVISION-ID-2B")
 
718
        >>> br1.missing_revisions(br2)
 
719
        Traceback (most recent call last):
 
720
        DivergedBranches: These branches have diverged.
 
721
        """
 
722
        self_history = self.revision_history()
 
723
        self_len = len(self_history)
 
724
        other_history = other.revision_history()
 
725
        other_len = len(other_history)
 
726
        common_index = min(self_len, other_len) -1
 
727
        if common_index >= 0 and \
 
728
            self_history[common_index] != other_history[common_index]:
 
729
            raise DivergedBranches(self, other)
 
730
 
 
731
        if stop_revision is None:
 
732
            stop_revision = other_len
 
733
        else:
 
734
            assert isinstance(stop_revision, int)
 
735
            if stop_revision > other_len:
 
736
                raise bzrlib.errors.NoSuchRevision(self, stop_revision)
 
737
        return other_history[self_len:stop_revision]
 
738
 
 
739
    def update_revisions(self, other, stop_revision=None):
 
740
        """Pull in new perfect-fit revisions."""
 
741
        from bzrlib.fetch import greedy_fetch
 
742
        if stop_revision is None:
 
743
            stop_revision = other.last_revision()
 
744
        ### Should this be checking is_ancestor instead of revision_history?
 
745
        if (stop_revision is not None and 
 
746
            stop_revision in self.revision_history()):
 
747
            return
 
748
        greedy_fetch(to_branch=self, from_branch=other,
 
749
                     revision=stop_revision)
 
750
        pullable_revs = self.pullable_revisions(other, stop_revision)
 
751
        if len(pullable_revs) > 0:
 
752
            self.append_revision(*pullable_revs)
 
753
 
 
754
    def pullable_revisions(self, other, stop_revision):
 
755
        other_revno = other.revision_id_to_revno(stop_revision)
 
756
        try:
 
757
            return self.missing_revisions(other, other_revno)
 
758
        except DivergedBranches, e:
 
759
            try:
 
760
                pullable_revs = get_intervening_revisions(self.last_revision(),
 
761
                                                          stop_revision, self)
 
762
                assert self.last_revision() not in pullable_revs
 
763
                return pullable_revs
 
764
            except bzrlib.errors.NotAncestor:
 
765
                if is_ancestor(self.last_revision(), stop_revision, self):
 
766
                    return []
 
767
                else:
 
768
                    raise e
 
769
        
 
770
    def revision_id_to_revno(self, revision_id):
 
771
        """Given a revision id, return its revno"""
 
772
        if revision_id is None:
 
773
            return 0
 
774
        history = self.revision_history()
 
775
        try:
 
776
            return history.index(revision_id) + 1
 
777
        except ValueError:
 
778
            raise bzrlib.errors.NoSuchRevision(self, revision_id)
 
779
 
 
780
    def get_rev_id(self, revno, history=None):
 
781
        """Find the revision id of the specified revno."""
 
782
        if revno == 0:
 
783
            return None
 
784
        if history is None:
 
785
            history = self.revision_history()
 
786
        elif revno <= 0 or revno > len(history):
 
787
            raise bzrlib.errors.NoSuchRevision(self, revno)
 
788
        return history[revno - 1]
 
789
 
 
790
    def revision_tree(self, revision_id):
 
791
        """Return Tree for a revision on this branch.
 
792
 
 
793
        `revision_id` may be None for the null revision, in which case
 
794
        an `EmptyTree` is returned."""
 
795
        # TODO: refactor this to use an existing revision object
 
796
        # so we don't need to read it in twice.
 
797
        if revision_id == None or revision_id == NULL_REVISION:
 
798
            return EmptyTree()
 
799
        else:
 
800
            inv = self.get_revision_inventory(revision_id)
 
801
            return RevisionTree(self.weave_store, inv, revision_id)
 
802
 
 
803
    def working_tree(self):
 
804
        """Return a `Tree` for the working copy if this is a local branch."""
 
805
        from bzrlib.workingtree import WorkingTree
 
806
        if self._transport.base.find('://') != -1:
 
807
            raise NoWorkingTree(self.base)
 
808
        return WorkingTree(self.base, branch=self)
 
809
 
 
810
    @needs_write_lock
 
811
    def pull(self, source, overwrite=False):
 
812
        source.lock_read()
 
813
        try:
 
814
            try:
 
815
                self.update_revisions(source)
 
816
            except DivergedBranches:
 
817
                if not overwrite:
 
818
                    raise
 
819
                self.set_revision_history(source.revision_history())
 
820
        finally:
 
821
            source.unlock()
 
822
 
 
823
    def basis_tree(self):
 
824
        """Return `Tree` object for last revision.
 
825
 
 
826
        If there are no revisions yet, return an `EmptyTree`.
 
827
        """
 
828
        return self.revision_tree(self.last_revision())
 
829
 
 
830
    def get_parent(self):
 
831
        """Return the parent location of the branch.
 
832
 
 
833
        This is the default location for push/pull/missing.  The usual
 
834
        pattern is that the user can override it by specifying a
 
835
        location.
 
836
        """
 
837
        import errno
 
838
        _locs = ['parent', 'pull', 'x-pull']
 
839
        for l in _locs:
 
840
            try:
 
841
                return self.controlfile(l, 'r').read().strip('\n')
 
842
            except IOError, e:
 
843
                if e.errno != errno.ENOENT:
 
844
                    raise
 
845
        return None
 
846
 
 
847
    def get_push_location(self):
 
848
        """Return the None or the location to push this branch to."""
 
849
        config = bzrlib.config.BranchConfig(self)
 
850
        push_loc = config.get_user_option('push_location')
 
851
        return push_loc
 
852
 
 
853
    def set_push_location(self, location):
 
854
        """Set a new push location for this branch."""
 
855
        config = bzrlib.config.LocationConfig(self.base)
 
856
        config.set_user_option('push_location', location)
 
857
 
 
858
    @needs_write_lock
 
859
    def set_parent(self, url):
 
860
        # TODO: Maybe delete old location files?
 
861
        from bzrlib.atomicfile import AtomicFile
 
862
        f = AtomicFile(self.controlfilename('parent'))
 
863
        try:
 
864
            f.write(url + '\n')
 
865
            f.commit()
 
866
        finally:
 
867
            f.close()
 
868
 
 
869
    def check_revno(self, revno):
 
870
        """\
 
871
        Check whether a revno corresponds to any revision.
 
872
        Zero (the NULL revision) is considered valid.
 
873
        """
 
874
        if revno != 0:
 
875
            self.check_real_revno(revno)
 
876
            
 
877
    def check_real_revno(self, revno):
 
878
        """\
 
879
        Check whether a revno corresponds to a real revision.
 
880
        Zero (the NULL revision) is considered invalid
 
881
        """
 
882
        if revno < 1 or revno > self.revno():
 
883
            raise InvalidRevisionNumber(revno)
 
884
        
 
885
    def sign_revision(self, revision_id, gpg_strategy):
 
886
        plaintext = Testament.from_revision(self, revision_id).as_short_text()
 
887
        self.store_revision_signature(gpg_strategy, plaintext, revision_id)
 
888
 
 
889
    @needs_write_lock
 
890
    def store_revision_signature(self, gpg_strategy, plaintext, revision_id):
 
891
        self.revision_store.add(StringIO(gpg_strategy.sign(plaintext)), 
 
892
                                revision_id, "sig")
 
893
 
 
894
 
 
895
class ScratchBranch(_Branch):
 
896
    """Special test class: a branch that cleans up after itself.
 
897
 
 
898
    >>> b = ScratchBranch()
 
899
    >>> isdir(b.base)
 
900
    True
 
901
    >>> bd = b.base
 
902
    >>> b._transport.__del__()
 
903
    >>> isdir(bd)
 
904
    False
 
905
    """
 
906
 
 
907
    def __init__(self, files=[], dirs=[], transport=None):
 
908
        """Make a test branch.
 
909
 
 
910
        This creates a temporary directory and runs init-tree in it.
 
911
 
 
912
        If any files are listed, they are created in the working copy.
 
913
        """
 
914
        if transport is None:
 
915
            transport = bzrlib.transport.local.ScratchTransport()
 
916
            super(ScratchBranch, self).__init__(transport, init=True)
 
917
        else:
 
918
            super(ScratchBranch, self).__init__(transport)
 
919
 
 
920
        for d in dirs:
 
921
            self._transport.mkdir(d)
 
922
            
 
923
        for f in files:
 
924
            self._transport.put(f, 'content of %s' % f)
 
925
 
 
926
 
 
927
    def clone(self):
 
928
        """
 
929
        >>> orig = ScratchBranch(files=["file1", "file2"])
 
930
        >>> clone = orig.clone()
 
931
        >>> if os.name != 'nt':
 
932
        ...   os.path.samefile(orig.base, clone.base)
 
933
        ... else:
 
934
        ...   orig.base == clone.base
 
935
        ...
 
936
        False
 
937
        >>> os.path.isfile(os.path.join(clone.base, "file1"))
 
938
        True
 
939
        """
 
940
        from shutil import copytree
 
941
        from tempfile import mkdtemp
 
942
        base = mkdtemp()
 
943
        os.rmdir(base)
 
944
        copytree(self.base, base, symlinks=True)
 
945
        return ScratchBranch(
 
946
            transport=bzrlib.transport.local.ScratchTransport(base))
 
947
    
 
948
 
 
949
######################################################################
 
950
# predicates
 
951
 
 
952
 
 
953
def is_control_file(filename):
 
954
    ## FIXME: better check
 
955
    filename = os.path.normpath(filename)
 
956
    while filename != '':
 
957
        head, tail = os.path.split(filename)
 
958
        ## mutter('check %r for control file' % ((head, tail), ))
 
959
        if tail == bzrlib.BZRDIR:
 
960
            return True
 
961
        if filename == head:
 
962
            break
 
963
        filename = head
 
964
    return False