/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

Merged Martin

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
            return codecs.getreader('utf-8')(self._transport.get(relpath), errors='replace')
 
431
        elif mode == 'w':
 
432
            raise BzrError("Branch.controlfile(mode='w') is not supported, use put_controlfiles")
 
433
        else:
 
434
            raise BzrError("invalid controlfile mode %r" % mode)
 
435
 
 
436
    def put_controlfile(self, path, f, encode=True):
 
437
        """Write an entry as a controlfile.
 
438
 
 
439
        :param path: The path to put the file, relative to the .bzr control
 
440
                     directory
 
441
        :param f: A file-like or string object whose contents should be copied.
 
442
        :param encode:  If true, encode the contents as utf-8
 
443
        """
 
444
        self.put_controlfiles([(path, f)], encode=encode)
 
445
 
 
446
    def put_controlfiles(self, files, encode=True):
 
447
        """Write several entries as controlfiles.
 
448
 
 
449
        :param files: A list of [(path, file)] pairs, where the path is the directory
 
450
                      underneath the bzr control directory
 
451
        :param encode:  If true, encode the contents as utf-8
 
452
        """
 
453
        import codecs
 
454
        ctrl_files = []
 
455
        for path, f in files:
 
456
            if encode:
 
457
                if isinstance(f, basestring):
 
458
                    f = f.encode('utf-8', 'replace')
 
459
                else:
 
460
                    f = codecs.getwriter('utf-8')(f, errors='replace')
 
461
            path = self._rel_controlfilename(path)
 
462
            ctrl_files.append((path, f))
 
463
        self._transport.put_multi(ctrl_files)
 
464
 
 
465
    def _make_control(self):
 
466
        from bzrlib.inventory import Inventory
 
467
        from bzrlib.weavefile import write_weave_v5
 
468
        from bzrlib.weave import Weave
 
469
        
 
470
        # Create an empty inventory
 
471
        sio = StringIO()
 
472
        # if we want per-tree root ids then this is the place to set
 
473
        # them; they're not needed for now and so ommitted for
 
474
        # simplicity.
 
475
        bzrlib.xml5.serializer_v5.write_inventory(Inventory(), sio)
 
476
        empty_inv = sio.getvalue()
 
477
        sio = StringIO()
 
478
        bzrlib.weavefile.write_weave_v5(Weave(), sio)
 
479
        empty_weave = sio.getvalue()
 
480
 
 
481
        dirs = [[], 'revision-store', 'weaves']
 
482
        files = [('README', 
 
483
            "This is a Bazaar-NG control directory.\n"
 
484
            "Do not change any files in this directory.\n"),
 
485
            ('branch-format', BZR_BRANCH_FORMAT_6),
 
486
            ('revision-history', ''),
 
487
            ('branch-name', ''),
 
488
            ('branch-lock', ''),
 
489
            ('pending-merges', ''),
 
490
            ('inventory', empty_inv),
 
491
            ('inventory.weave', empty_weave),
 
492
            ('ancestry.weave', empty_weave)
 
493
        ]
 
494
        cfn = self._rel_controlfilename
 
495
        self._transport.mkdir_multi([cfn(d) for d in dirs])
 
496
        self.put_controlfiles(files)
 
497
        mutter('created control directory in ' + self._transport.base)
 
498
 
 
499
    def _check_format(self, relax_version_check):
 
500
        """Check this branch format is supported.
 
501
 
 
502
        The format level is stored, as an integer, in
 
503
        self._branch_format for code that needs to check it later.
 
504
 
 
505
        In the future, we might need different in-memory Branch
 
506
        classes to support downlevel branches.  But not yet.
 
507
        """
 
508
        try:
 
509
            fmt = self.controlfile('branch-format', 'r').read()
 
510
        except NoSuchFile:
 
511
            raise NotBranchError(path=self.base)
 
512
        mutter("got branch format %r", fmt)
 
513
        if fmt == BZR_BRANCH_FORMAT_6:
 
514
            self._branch_format = 6
 
515
        elif fmt == BZR_BRANCH_FORMAT_5:
 
516
            self._branch_format = 5
 
517
        elif fmt == BZR_BRANCH_FORMAT_4:
 
518
            self._branch_format = 4
 
519
 
 
520
        if (not relax_version_check
 
521
            and self._branch_format not in (5, 6)):
 
522
            raise errors.UnsupportedFormatError(
 
523
                           'sorry, branch format %r not supported' % fmt,
 
524
                           ['use a different bzr version',
 
525
                            'or remove the .bzr directory'
 
526
                            ' and "bzr init" again'])
 
527
 
 
528
    def get_root_id(self):
 
529
        """Return the id of this branches root"""
 
530
        inv = self.get_inventory(self.last_revision())
 
531
        return inv.root.file_id
 
532
 
 
533
    @needs_write_lock
 
534
    def set_root_id(self, file_id):
 
535
        inv = self.working_tree().read_working_inventory()
 
536
        orig_root_id = inv.root.file_id
 
537
        del inv._byid[inv.root.file_id]
 
538
        inv.root.file_id = file_id
 
539
        inv._byid[inv.root.file_id] = inv.root
 
540
        for fid in inv:
 
541
            entry = inv[fid]
 
542
            if entry.parent_id in (None, orig_root_id):
 
543
                entry.parent_id = inv.root.file_id
 
544
        self._write_inventory(inv)
 
545
 
 
546
    @needs_write_lock
 
547
    def _write_inventory(self, inv):
 
548
        """Update the working inventory.
 
549
 
 
550
        That is to say, the inventory describing changes underway, that
 
551
        will be committed to the next revision.
 
552
        """
 
553
        from cStringIO import StringIO
 
554
        sio = StringIO()
 
555
        bzrlib.xml5.serializer_v5.write_inventory(inv, sio)
 
556
        sio.seek(0)
 
557
        # Transport handles atomicity
 
558
        self.put_controlfile('inventory', sio)
 
559
        
 
560
        mutter('wrote working inventory')
 
561
            
 
562
    @needs_write_lock
 
563
    def add(self, files, ids=None):
 
564
        """Make files versioned.
 
565
 
 
566
        Note that the command line normally calls smart_add instead,
 
567
        which can automatically recurse.
 
568
 
 
569
        This puts the files in the Added state, so that they will be
 
570
        recorded by the next commit.
 
571
 
 
572
        files
 
573
            List of paths to add, relative to the base of the tree.
 
574
 
 
575
        ids
 
576
            If set, use these instead of automatically generated ids.
 
577
            Must be the same length as the list of files, but may
 
578
            contain None for ids that are to be autogenerated.
 
579
 
 
580
        TODO: Perhaps have an option to add the ids even if the files do
 
581
              not (yet) exist.
 
582
 
 
583
        TODO: Perhaps yield the ids and paths as they're added.
 
584
        """
 
585
        # TODO: Re-adding a file that is removed in the working copy
 
586
        # should probably put it back with the previous ID.
 
587
        if isinstance(files, basestring):
 
588
            assert(ids is None or isinstance(ids, basestring))
 
589
            files = [files]
 
590
            if ids is not None:
 
591
                ids = [ids]
 
592
 
 
593
        if ids is None:
 
594
            ids = [None] * len(files)
 
595
        else:
 
596
            assert(len(ids) == len(files))
 
597
 
 
598
        inv = self.working_tree().read_working_inventory()
 
599
        for f,file_id in zip(files, ids):
 
600
            if is_control_file(f):
 
601
                raise BzrError("cannot add control file %s" % quotefn(f))
 
602
 
 
603
            fp = splitpath(f)
 
604
 
 
605
            if len(fp) == 0:
 
606
                raise BzrError("cannot add top-level %r" % f)
 
607
 
 
608
            fullpath = os.path.normpath(self.abspath(f))
 
609
 
 
610
            try:
 
611
                kind = file_kind(fullpath)
 
612
            except OSError:
 
613
                # maybe something better?
 
614
                raise BzrError('cannot add: not a regular file, symlink or directory: %s' % quotefn(f))
 
615
 
 
616
            if not InventoryEntry.versionable_kind(kind):
 
617
                raise BzrError('cannot add: not a versionable file ('
 
618
                               'i.e. regular file, symlink or directory): %s' % quotefn(f))
 
619
 
 
620
            if file_id is None:
 
621
                file_id = gen_file_id(f)
 
622
            inv.add_path(f, kind=kind, file_id=file_id)
 
623
 
 
624
            mutter("add file %s file_id:{%s} kind=%r" % (f, file_id, kind))
 
625
 
 
626
        self._write_inventory(inv)
 
627
 
 
628
    @needs_read_lock
 
629
    def print_file(self, file, revno):
 
630
        """Print `file` to stdout."""
 
631
        tree = self.revision_tree(self.get_rev_id(revno))
 
632
        # use inventory as it was in that revision
 
633
        file_id = tree.inventory.path2id(file)
 
634
        if not file_id:
 
635
            raise BzrError("%r is not present in revision %s" % (file, revno))
 
636
        tree.print_file(file_id)
 
637
 
 
638
    def unknowns(self):
 
639
        """Return all unknown files.
 
640
 
 
641
        These are files in the working directory that are not versioned or
 
642
        control files or ignored.
 
643
        
 
644
        >>> from bzrlib.workingtree import WorkingTree
 
645
        >>> b = ScratchBranch(files=['foo', 'foo~'])
 
646
        >>> map(str, b.unknowns())
 
647
        ['foo']
 
648
        >>> b.add('foo')
 
649
        >>> list(b.unknowns())
 
650
        []
 
651
        >>> WorkingTree(b.base, b).remove('foo')
 
652
        >>> list(b.unknowns())
 
653
        [u'foo']
 
654
        """
 
655
        return self.working_tree().unknowns()
 
656
 
 
657
    @needs_write_lock
 
658
    def append_revision(self, *revision_ids):
 
659
        for revision_id in revision_ids:
 
660
            mutter("add {%s} to revision-history" % revision_id)
 
661
        rev_history = self.revision_history()
 
662
        rev_history.extend(revision_ids)
 
663
        self.set_revision_history(rev_history)
 
664
 
 
665
    @needs_write_lock
 
666
    def set_revision_history(self, rev_history):
 
667
        self.put_controlfile('revision-history', '\n'.join(rev_history))
 
668
 
 
669
    def has_revision(self, revision_id):
 
670
        """True if this branch has a copy of the revision.
 
671
 
 
672
        This does not necessarily imply the revision is merge
 
673
        or on the mainline."""
 
674
        return (revision_id is None
 
675
                or self.revision_store.has_id(revision_id))
 
676
 
 
677
    @needs_read_lock
 
678
    def get_revision_xml_file(self, revision_id):
 
679
        """Return XML file object for revision object."""
 
680
        if not revision_id or not isinstance(revision_id, basestring):
 
681
            raise InvalidRevisionId(revision_id=revision_id, branch=self)
 
682
        try:
 
683
            return self.revision_store.get(revision_id)
 
684
        except (IndexError, KeyError):
 
685
            raise bzrlib.errors.NoSuchRevision(self, revision_id)
 
686
 
 
687
    #deprecated
 
688
    get_revision_xml = get_revision_xml_file
 
689
 
 
690
    def get_revision_xml(self, revision_id):
 
691
        return self.get_revision_xml_file(revision_id).read()
 
692
 
 
693
 
 
694
    def get_revision(self, revision_id):
 
695
        """Return the Revision object for a named revision"""
 
696
        xml_file = self.get_revision_xml_file(revision_id)
 
697
 
 
698
        try:
 
699
            r = bzrlib.xml5.serializer_v5.read_revision(xml_file)
 
700
        except SyntaxError, e:
 
701
            raise bzrlib.errors.BzrError('failed to unpack revision_xml',
 
702
                                         [revision_id,
 
703
                                          str(e)])
 
704
            
 
705
        assert r.revision_id == revision_id
 
706
        return r
 
707
 
 
708
    def get_revision_delta(self, revno):
 
709
        """Return the delta for one revision.
 
710
 
 
711
        The delta is relative to its mainline predecessor, or the
 
712
        empty tree for revision 1.
 
713
        """
 
714
        assert isinstance(revno, int)
 
715
        rh = self.revision_history()
 
716
        if not (1 <= revno <= len(rh)):
 
717
            raise InvalidRevisionNumber(revno)
 
718
 
 
719
        # revno is 1-based; list is 0-based
 
720
 
 
721
        new_tree = self.revision_tree(rh[revno-1])
 
722
        if revno == 1:
 
723
            old_tree = EmptyTree()
 
724
        else:
 
725
            old_tree = self.revision_tree(rh[revno-2])
 
726
 
 
727
        return compare_trees(old_tree, new_tree)
 
728
 
 
729
    def get_revision_sha1(self, revision_id):
 
730
        """Hash the stored value of a revision, and return it."""
 
731
        # In the future, revision entries will be signed. At that
 
732
        # point, it is probably best *not* to include the signature
 
733
        # in the revision hash. Because that lets you re-sign
 
734
        # the revision, (add signatures/remove signatures) and still
 
735
        # have all hash pointers stay consistent.
 
736
        # But for now, just hash the contents.
 
737
        return bzrlib.osutils.sha_file(self.get_revision_xml_file(revision_id))
 
738
 
 
739
    def get_ancestry(self, revision_id):
 
740
        """Return a list of revision-ids integrated by a revision.
 
741
        
 
742
        This currently returns a list, but the ordering is not guaranteed:
 
743
        treat it as a set.
 
744
        """
 
745
        if revision_id is None:
 
746
            return [None]
 
747
        w = self.get_inventory_weave()
 
748
        return [None] + map(w.idx_to_name,
 
749
                            w.inclusions([w.lookup(revision_id)]))
 
750
 
 
751
    def get_inventory_weave(self):
 
752
        return self.control_weaves.get_weave('inventory',
 
753
                                             self.get_transaction())
 
754
 
 
755
    def get_inventory(self, revision_id):
 
756
        """Get Inventory object by hash."""
 
757
        xml = self.get_inventory_xml(revision_id)
 
758
        return bzrlib.xml5.serializer_v5.read_inventory_from_string(xml)
 
759
 
 
760
    def get_inventory_xml(self, revision_id):
 
761
        """Get inventory XML as a file object."""
 
762
        try:
 
763
            assert isinstance(revision_id, basestring), type(revision_id)
 
764
            iw = self.get_inventory_weave()
 
765
            return iw.get_text(iw.lookup(revision_id))
 
766
        except IndexError:
 
767
            raise bzrlib.errors.HistoryMissing(self, 'inventory', revision_id)
 
768
 
 
769
    def get_inventory_sha1(self, revision_id):
 
770
        """Return the sha1 hash of the inventory entry
 
771
        """
 
772
        return self.get_revision(revision_id).inventory_sha1
 
773
 
 
774
    def get_revision_inventory(self, revision_id):
 
775
        """Return inventory of a past revision."""
 
776
        # TODO: Unify this with get_inventory()
 
777
        # bzr 0.0.6 and later imposes the constraint that the inventory_id
 
778
        # must be the same as its revision, so this is trivial.
 
779
        if revision_id == None:
 
780
            # This does not make sense: if there is no revision,
 
781
            # then it is the current tree inventory surely ?!
 
782
            # and thus get_root_id() is something that looks at the last
 
783
            # commit on the branch, and the get_root_id is an inventory check.
 
784
            raise NotImplementedError
 
785
            # return Inventory(self.get_root_id())
 
786
        else:
 
787
            return self.get_inventory(revision_id)
 
788
 
 
789
    @needs_read_lock
 
790
    def revision_history(self):
 
791
        """Return sequence of revision hashes on to this branch."""
 
792
        transaction = self.get_transaction()
 
793
        history = transaction.map.find_revision_history()
 
794
        if history is not None:
 
795
            mutter("cache hit for revision-history in %s", self)
 
796
            return list(history)
 
797
        history = [l.rstrip('\r\n') for l in
 
798
                self.controlfile('revision-history', 'r').readlines()]
 
799
        transaction.map.add_revision_history(history)
 
800
        # this call is disabled because revision_history is 
 
801
        # not really an object yet, and the transaction is for objects.
 
802
        # transaction.register_clean(history, precious=True)
 
803
        return list(history)
 
804
 
 
805
    def revno(self):
 
806
        """Return current revision number for this branch.
 
807
 
 
808
        That is equivalent to the number of revisions committed to
 
809
        this branch.
 
810
        """
 
811
        return len(self.revision_history())
 
812
 
 
813
    def last_revision(self):
 
814
        """Return last patch hash, or None if no history.
 
815
        """
 
816
        ph = self.revision_history()
 
817
        if ph:
 
818
            return ph[-1]
 
819
        else:
 
820
            return None
 
821
 
 
822
    def missing_revisions(self, other, stop_revision=None, diverged_ok=False):
 
823
        """Return a list of new revisions that would perfectly fit.
 
824
        
 
825
        If self and other have not diverged, return a list of the revisions
 
826
        present in other, but missing from self.
 
827
 
 
828
        >>> from bzrlib.commit import commit
 
829
        >>> bzrlib.trace.silent = True
 
830
        >>> br1 = ScratchBranch()
 
831
        >>> br2 = ScratchBranch()
 
832
        >>> br1.missing_revisions(br2)
 
833
        []
 
834
        >>> commit(br2, "lala!", rev_id="REVISION-ID-1")
 
835
        >>> br1.missing_revisions(br2)
 
836
        [u'REVISION-ID-1']
 
837
        >>> br2.missing_revisions(br1)
 
838
        []
 
839
        >>> commit(br1, "lala!", rev_id="REVISION-ID-1")
 
840
        >>> br1.missing_revisions(br2)
 
841
        []
 
842
        >>> commit(br2, "lala!", rev_id="REVISION-ID-2A")
 
843
        >>> br1.missing_revisions(br2)
 
844
        [u'REVISION-ID-2A']
 
845
        >>> commit(br1, "lala!", rev_id="REVISION-ID-2B")
 
846
        >>> br1.missing_revisions(br2)
 
847
        Traceback (most recent call last):
 
848
        DivergedBranches: These branches have diverged.
 
849
        """
 
850
        self_history = self.revision_history()
 
851
        self_len = len(self_history)
 
852
        other_history = other.revision_history()
 
853
        other_len = len(other_history)
 
854
        common_index = min(self_len, other_len) -1
 
855
        if common_index >= 0 and \
 
856
            self_history[common_index] != other_history[common_index]:
 
857
            raise DivergedBranches(self, other)
 
858
 
 
859
        if stop_revision is None:
 
860
            stop_revision = other_len
 
861
        else:
 
862
            assert isinstance(stop_revision, int)
 
863
            if stop_revision > other_len:
 
864
                raise bzrlib.errors.NoSuchRevision(self, stop_revision)
 
865
        return other_history[self_len:stop_revision]
 
866
 
 
867
    def update_revisions(self, other, stop_revision=None):
 
868
        """Pull in new perfect-fit revisions."""
 
869
        from bzrlib.fetch import greedy_fetch
 
870
        if stop_revision is None:
 
871
            stop_revision = other.last_revision()
 
872
        ### Should this be checking is_ancestor instead of revision_history?
 
873
        if (stop_revision is not None and 
 
874
            stop_revision in self.revision_history()):
 
875
            return
 
876
        greedy_fetch(to_branch=self, from_branch=other,
 
877
                     revision=stop_revision)
 
878
        pullable_revs = self.pullable_revisions(other, stop_revision)
 
879
        if len(pullable_revs) > 0:
 
880
            self.append_revision(*pullable_revs)
 
881
 
 
882
    def pullable_revisions(self, other, stop_revision):
 
883
        other_revno = other.revision_id_to_revno(stop_revision)
 
884
        try:
 
885
            return self.missing_revisions(other, other_revno)
 
886
        except DivergedBranches, e:
 
887
            try:
 
888
                pullable_revs = get_intervening_revisions(self.last_revision(),
 
889
                                                          stop_revision, self)
 
890
                assert self.last_revision() not in pullable_revs
 
891
                return pullable_revs
 
892
            except bzrlib.errors.NotAncestor:
 
893
                if is_ancestor(self.last_revision(), stop_revision, self):
 
894
                    return []
 
895
                else:
 
896
                    raise e
 
897
        
 
898
    def commit(self, *args, **kw):
 
899
        from bzrlib.commit import Commit
 
900
        Commit().commit(self, *args, **kw)
 
901
    
 
902
    def revision_id_to_revno(self, revision_id):
 
903
        """Given a revision id, return its revno"""
 
904
        if revision_id is None:
 
905
            return 0
 
906
        history = self.revision_history()
 
907
        try:
 
908
            return history.index(revision_id) + 1
 
909
        except ValueError:
 
910
            raise bzrlib.errors.NoSuchRevision(self, revision_id)
 
911
 
 
912
    def get_rev_id(self, revno, history=None):
 
913
        """Find the revision id of the specified revno."""
 
914
        if revno == 0:
 
915
            return None
 
916
        if history is None:
 
917
            history = self.revision_history()
 
918
        elif revno <= 0 or revno > len(history):
 
919
            raise bzrlib.errors.NoSuchRevision(self, revno)
 
920
        return history[revno - 1]
 
921
 
 
922
    def revision_tree(self, revision_id):
 
923
        """Return Tree for a revision on this branch.
 
924
 
 
925
        `revision_id` may be None for the null revision, in which case
 
926
        an `EmptyTree` is returned."""
 
927
        # TODO: refactor this to use an existing revision object
 
928
        # so we don't need to read it in twice.
 
929
        if revision_id == None or revision_id == NULL_REVISION:
 
930
            return EmptyTree()
 
931
        else:
 
932
            inv = self.get_revision_inventory(revision_id)
 
933
            return RevisionTree(self.weave_store, inv, revision_id)
 
934
 
 
935
    def working_tree(self):
 
936
        """Return a `Tree` for the working copy."""
 
937
        from bzrlib.workingtree import WorkingTree
 
938
        # TODO: In the future, perhaps WorkingTree should utilize Transport
 
939
        # RobertCollins 20051003 - I don't think it should - working trees are
 
940
        # much more complex to keep consistent than our careful .bzr subset.
 
941
        # instead, we should say that working trees are local only, and optimise
 
942
        # for that.
 
943
        if self._transport.base.find('://') != -1:
 
944
            raise NoWorkingTree(self.base)
 
945
        return WorkingTree(self.base, branch=self)
 
946
 
 
947
    @needs_write_lock
 
948
    def pull(self, source, overwrite=False):
 
949
        source.lock_read()
 
950
        try:
 
951
            try:
 
952
                self.update_revisions(source)
 
953
            except DivergedBranches:
 
954
                if not overwrite:
 
955
                    raise
 
956
                self.set_revision_history(source.revision_history())
 
957
        finally:
 
958
            source.unlock()
 
959
 
 
960
    def basis_tree(self):
 
961
        """Return `Tree` object for last revision.
 
962
 
 
963
        If there are no revisions yet, return an `EmptyTree`.
 
964
        """
 
965
        return self.revision_tree(self.last_revision())
 
966
 
 
967
    @needs_write_lock
 
968
    def rename_one(self, from_rel, to_rel):
 
969
        """Rename one file.
 
970
 
 
971
        This can change the directory or the filename or both.
 
972
        """
 
973
        tree = self.working_tree()
 
974
        inv = tree.inventory
 
975
        if not tree.has_filename(from_rel):
 
976
            raise BzrError("can't rename: old working file %r does not exist" % from_rel)
 
977
        if tree.has_filename(to_rel):
 
978
            raise BzrError("can't rename: new working file %r already exists" % to_rel)
 
979
 
 
980
        file_id = inv.path2id(from_rel)
 
981
        if file_id == None:
 
982
            raise BzrError("can't rename: old name %r is not versioned" % from_rel)
 
983
 
 
984
        if inv.path2id(to_rel):
 
985
            raise BzrError("can't rename: new name %r is already versioned" % to_rel)
 
986
 
 
987
        to_dir, to_tail = os.path.split(to_rel)
 
988
        to_dir_id = inv.path2id(to_dir)
 
989
        if to_dir_id == None and to_dir != '':
 
990
            raise BzrError("can't determine destination directory id for %r" % to_dir)
 
991
 
 
992
        mutter("rename_one:")
 
993
        mutter("  file_id    {%s}" % file_id)
 
994
        mutter("  from_rel   %r" % from_rel)
 
995
        mutter("  to_rel     %r" % to_rel)
 
996
        mutter("  to_dir     %r" % to_dir)
 
997
        mutter("  to_dir_id  {%s}" % to_dir_id)
 
998
 
 
999
        inv.rename(file_id, to_dir_id, to_tail)
 
1000
 
 
1001
        from_abs = self.abspath(from_rel)
 
1002
        to_abs = self.abspath(to_rel)
 
1003
        try:
 
1004
            rename(from_abs, to_abs)
 
1005
        except OSError, e:
 
1006
            raise BzrError("failed to rename %r to %r: %s"
 
1007
                    % (from_abs, to_abs, e[1]),
 
1008
                    ["rename rolled back"])
 
1009
 
 
1010
        self._write_inventory(inv)
 
1011
 
 
1012
    @needs_write_lock
 
1013
    def move(self, from_paths, to_name):
 
1014
        """Rename files.
 
1015
 
 
1016
        to_name must exist as a versioned directory.
 
1017
 
 
1018
        If to_name exists and is a directory, the files are moved into
 
1019
        it, keeping their old names.  If it is a directory, 
 
1020
 
 
1021
        Note that to_name is only the last component of the new name;
 
1022
        this doesn't change the directory.
 
1023
 
 
1024
        This returns a list of (from_path, to_path) pairs for each
 
1025
        entry that is moved.
 
1026
        """
 
1027
        result = []
 
1028
        ## TODO: Option to move IDs only
 
1029
        assert not isinstance(from_paths, basestring)
 
1030
        tree = self.working_tree()
 
1031
        inv = tree.inventory
 
1032
        to_abs = self.abspath(to_name)
 
1033
        if not isdir(to_abs):
 
1034
            raise BzrError("destination %r is not a directory" % to_abs)
 
1035
        if not tree.has_filename(to_name):
 
1036
            raise BzrError("destination %r not in working directory" % to_abs)
 
1037
        to_dir_id = inv.path2id(to_name)
 
1038
        if to_dir_id == None and to_name != '':
 
1039
            raise BzrError("destination %r is not a versioned directory" % to_name)
 
1040
        to_dir_ie = inv[to_dir_id]
 
1041
        if to_dir_ie.kind not in ('directory', 'root_directory'):
 
1042
            raise BzrError("destination %r is not a directory" % to_abs)
 
1043
 
 
1044
        to_idpath = inv.get_idpath(to_dir_id)
 
1045
 
 
1046
        for f in from_paths:
 
1047
            if not tree.has_filename(f):
 
1048
                raise BzrError("%r does not exist in working tree" % f)
 
1049
            f_id = inv.path2id(f)
 
1050
            if f_id == None:
 
1051
                raise BzrError("%r is not versioned" % f)
 
1052
            name_tail = splitpath(f)[-1]
 
1053
            dest_path = appendpath(to_name, name_tail)
 
1054
            if tree.has_filename(dest_path):
 
1055
                raise BzrError("destination %r already exists" % dest_path)
 
1056
            if f_id in to_idpath:
 
1057
                raise BzrError("can't move %r to a subdirectory of itself" % f)
 
1058
 
 
1059
        # OK, so there's a race here, it's possible that someone will
 
1060
        # create a file in this interval and then the rename might be
 
1061
        # left half-done.  But we should have caught most problems.
 
1062
 
 
1063
        for f in from_paths:
 
1064
            name_tail = splitpath(f)[-1]
 
1065
            dest_path = appendpath(to_name, name_tail)
 
1066
            result.append((f, dest_path))
 
1067
            inv.rename(inv.path2id(f), to_dir_id, name_tail)
 
1068
            try:
 
1069
                rename(self.abspath(f), self.abspath(dest_path))
 
1070
            except OSError, e:
 
1071
                raise BzrError("failed to rename %r to %r: %s" % (f, dest_path, e[1]),
 
1072
                        ["rename rolled back"])
 
1073
 
 
1074
        self._write_inventory(inv)
 
1075
        return result
 
1076
 
 
1077
 
 
1078
    def revert(self, filenames, old_tree=None, backups=True):
 
1079
        """Restore selected files to the versions from a previous tree.
 
1080
 
 
1081
        backups
 
1082
            If true (default) backups are made of files before
 
1083
            they're renamed.
 
1084
        """
 
1085
        from bzrlib.atomicfile import AtomicFile
 
1086
        from bzrlib.osutils import backup_file
 
1087
        
 
1088
        inv = self.working_tree().read_working_inventory()
 
1089
        if old_tree is None:
 
1090
            old_tree = self.basis_tree()
 
1091
        old_inv = old_tree.inventory
 
1092
 
 
1093
        nids = []
 
1094
        for fn in filenames:
 
1095
            file_id = inv.path2id(fn)
 
1096
            if not file_id:
 
1097
                raise NotVersionedError(path=fn)
 
1098
            if not old_inv.has_id(file_id):
 
1099
                raise BzrError("file not present in old tree", fn, file_id)
 
1100
            nids.append((fn, file_id))
 
1101
            
 
1102
        # TODO: Rename back if it was previously at a different location
 
1103
 
 
1104
        # TODO: If given a directory, restore the entire contents from
 
1105
        # the previous version.
 
1106
 
 
1107
        # TODO: Make a backup to a temporary file.
 
1108
 
 
1109
        # TODO: If the file previously didn't exist, delete it?
 
1110
        for fn, file_id in nids:
 
1111
            backup_file(fn)
 
1112
            
 
1113
            f = AtomicFile(fn, 'wb')
 
1114
            try:
 
1115
                f.write(old_tree.get_file(file_id).read())
 
1116
                f.commit()
 
1117
            finally:
 
1118
                f.close()
 
1119
 
 
1120
 
 
1121
    def pending_merges(self):
 
1122
        """Return a list of pending merges.
 
1123
 
 
1124
        These are revisions that have been merged into the working
 
1125
        directory but not yet committed.
 
1126
        """
 
1127
        cfn = self._rel_controlfilename('pending-merges')
 
1128
        if not self._transport.has(cfn):
 
1129
            return []
 
1130
        p = []
 
1131
        for l in self.controlfile('pending-merges', 'r').readlines():
 
1132
            p.append(l.rstrip('\n'))
 
1133
        return p
 
1134
 
 
1135
 
 
1136
    def add_pending_merge(self, *revision_ids):
 
1137
        # TODO: Perhaps should check at this point that the
 
1138
        # history of the revision is actually present?
 
1139
        p = self.pending_merges()
 
1140
        updated = False
 
1141
        for rev_id in revision_ids:
 
1142
            if rev_id in p:
 
1143
                continue
 
1144
            p.append(rev_id)
 
1145
            updated = True
 
1146
        if updated:
 
1147
            self.set_pending_merges(p)
 
1148
 
 
1149
    @needs_write_lock
 
1150
    def set_pending_merges(self, rev_list):
 
1151
        self.put_controlfile('pending-merges', '\n'.join(rev_list))
 
1152
 
 
1153
    def get_parent(self):
 
1154
        """Return the parent location of the branch.
 
1155
 
 
1156
        This is the default location for push/pull/missing.  The usual
 
1157
        pattern is that the user can override it by specifying a
 
1158
        location.
 
1159
        """
 
1160
        import errno
 
1161
        _locs = ['parent', 'pull', 'x-pull']
 
1162
        for l in _locs:
 
1163
            try:
 
1164
                return self.controlfile(l, 'r').read().strip('\n')
 
1165
            except IOError, e:
 
1166
                if e.errno != errno.ENOENT:
 
1167
                    raise
 
1168
        return None
 
1169
 
 
1170
    def get_push_location(self):
 
1171
        """Return the None or the location to push this branch to."""
 
1172
        config = bzrlib.config.BranchConfig(self)
 
1173
        push_loc = config.get_user_option('push_location')
 
1174
        return push_loc
 
1175
 
 
1176
    def set_push_location(self, location):
 
1177
        """Set a new push location for this branch."""
 
1178
        config = bzrlib.config.LocationConfig(self.base)
 
1179
        config.set_user_option('push_location', location)
 
1180
 
 
1181
    @needs_write_lock
 
1182
    def set_parent(self, url):
 
1183
        # TODO: Maybe delete old location files?
 
1184
        from bzrlib.atomicfile import AtomicFile
 
1185
        f = AtomicFile(self.controlfilename('parent'))
 
1186
        try:
 
1187
            f.write(url + '\n')
 
1188
            f.commit()
 
1189
        finally:
 
1190
            f.close()
 
1191
 
 
1192
    def tree_config(self):
 
1193
        return TreeConfig(self)
 
1194
 
 
1195
    def check_revno(self, revno):
 
1196
        """\
 
1197
        Check whether a revno corresponds to any revision.
 
1198
        Zero (the NULL revision) is considered valid.
 
1199
        """
 
1200
        if revno != 0:
 
1201
            self.check_real_revno(revno)
 
1202
            
 
1203
    def check_real_revno(self, revno):
 
1204
        """\
 
1205
        Check whether a revno corresponds to a real revision.
 
1206
        Zero (the NULL revision) is considered invalid
 
1207
        """
 
1208
        if revno < 1 or revno > self.revno():
 
1209
            raise InvalidRevisionNumber(revno)
 
1210
        
 
1211
    def sign_revision(self, revision_id, gpg_strategy):
 
1212
        plaintext = Testament.from_revision(self, revision_id).as_short_text()
 
1213
        self.store_revision_signature(gpg_strategy, plaintext, revision_id)
 
1214
 
 
1215
    @needs_write_lock
 
1216
    def store_revision_signature(self, gpg_strategy, plaintext, revision_id):
 
1217
        self.revision_store.add(StringIO(gpg_strategy.sign(plaintext)), 
 
1218
                                revision_id, "sig")
 
1219
 
 
1220
 
 
1221
 
 
1222
class ScratchBranch(_Branch):
 
1223
    """Special test class: a branch that cleans up after itself.
 
1224
 
 
1225
    >>> b = ScratchBranch()
 
1226
    >>> isdir(b.base)
 
1227
    True
 
1228
    >>> bd = b.base
 
1229
    >>> b._transport.__del__()
 
1230
    >>> isdir(bd)
 
1231
    False
 
1232
    """
 
1233
 
 
1234
    def __init__(self, files=[], dirs=[], transport=None):
 
1235
        """Make a test branch.
 
1236
 
 
1237
        This creates a temporary directory and runs init-tree in it.
 
1238
 
 
1239
        If any files are listed, they are created in the working copy.
 
1240
        """
 
1241
        if transport is None:
 
1242
            transport = bzrlib.transport.local.ScratchTransport()
 
1243
            super(ScratchBranch, self).__init__(transport, init=True)
 
1244
        else:
 
1245
            super(ScratchBranch, self).__init__(transport)
 
1246
 
 
1247
        for d in dirs:
 
1248
            self._transport.mkdir(d)
 
1249
            
 
1250
        for f in files:
 
1251
            self._transport.put(f, 'content of %s' % f)
 
1252
 
 
1253
 
 
1254
    def clone(self):
 
1255
        """
 
1256
        >>> orig = ScratchBranch(files=["file1", "file2"])
 
1257
        >>> clone = orig.clone()
 
1258
        >>> if os.name != 'nt':
 
1259
        ...   os.path.samefile(orig.base, clone.base)
 
1260
        ... else:
 
1261
        ...   orig.base == clone.base
 
1262
        ...
 
1263
        False
 
1264
        >>> os.path.isfile(os.path.join(clone.base, "file1"))
 
1265
        True
 
1266
        """
 
1267
        from shutil import copytree
 
1268
        from tempfile import mkdtemp
 
1269
        base = mkdtemp()
 
1270
        os.rmdir(base)
 
1271
        copytree(self.base, base, symlinks=True)
 
1272
        return ScratchBranch(
 
1273
            transport=bzrlib.transport.local.ScratchTransport(base))
 
1274
    
 
1275
 
 
1276
######################################################################
 
1277
# predicates
 
1278
 
 
1279
 
 
1280
def is_control_file(filename):
 
1281
    ## FIXME: better check
 
1282
    filename = os.path.normpath(filename)
 
1283
    while filename != '':
 
1284
        head, tail = os.path.split(filename)
 
1285
        ## mutter('check %r for control file' % ((head, tail), ))
 
1286
        if tail == bzrlib.BZRDIR:
 
1287
            return True
 
1288
        if filename == head:
 
1289
            break
 
1290
        filename = head
 
1291
    return False
 
1292
 
 
1293
 
 
1294
 
 
1295
def gen_file_id(name):
 
1296
    """Return new file id.
 
1297
 
 
1298
    This should probably generate proper UUIDs, but for the moment we
 
1299
    cope with just randomness because running uuidgen every time is
 
1300
    slow."""
 
1301
    import re
 
1302
    from binascii import hexlify
 
1303
    from time import time
 
1304
 
 
1305
    # get last component
 
1306
    idx = name.rfind('/')
 
1307
    if idx != -1:
 
1308
        name = name[idx+1 : ]
 
1309
    idx = name.rfind('\\')
 
1310
    if idx != -1:
 
1311
        name = name[idx+1 : ]
 
1312
 
 
1313
    # make it not a hidden file
 
1314
    name = name.lstrip('.')
 
1315
 
 
1316
    # remove any wierd characters; we don't escape them but rather
 
1317
    # just pull them out
 
1318
    name = re.sub(r'[^\w.]', '', name)
 
1319
 
 
1320
    s = hexlify(rand_bytes(8))
 
1321
    return '-'.join((name, compact_date(time()), s))
 
1322
 
 
1323
 
 
1324
def gen_root_id():
 
1325
    """Return a new tree-root file id."""
 
1326
    return gen_file_id('TREE_ROOT')
 
1327
 
 
1328