/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

  • Committer: Aaron Bentley
  • Date: 2005-11-11 17:46:11 UTC
  • mto: (1185.65.2 bzr.revision-storage)
  • mto: This revision was merged to the branch mainline in revision 1509.
  • Revision ID: aaron.bentley@utoronto.ca-20051111174611-05c622f83aca3d78
Support whitespace in diff filenames

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