/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

Merge from mpool.

Show diffs side-by-side

added added

removed removed

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