/brz/remove-bazaar

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

« back to all changes in this revision

Viewing changes to bzrlib/branch.py

  • Committer: Robert Collins
  • Date: 2005-09-30 02:54:51 UTC
  • mfrom: (1395)
  • mto: This revision was merged to the branch mainline in revision 1397.
  • Revision ID: robertc@robertcollins.net-20050930025451-47b9e412202be44b
symlink and weaves, whaddya know

Show diffs side-by-side

added added

removed removed

Lines of Context:
17
17
 
18
18
import sys
19
19
import os
 
20
import errno
 
21
from warnings import warn
 
22
 
20
23
 
21
24
import bzrlib
22
25
from bzrlib.trace import mutter, note
23
 
from bzrlib.osutils import isdir, quotefn, compact_date, rand_bytes, \
24
 
     splitpath, \
25
 
     sha_file, appendpath, file_kind
26
 
from bzrlib.errors import BzrError, InvalidRevisionNumber, InvalidRevisionId
27
 
import bzrlib.errors
 
26
from bzrlib.osutils import (isdir, quotefn, compact_date, rand_bytes, 
 
27
                            rename, splitpath, sha_file, appendpath, 
 
28
                            file_kind)
 
29
from bzrlib.errors import (BzrError, InvalidRevisionNumber, InvalidRevisionId,
 
30
                           NoSuchRevision, HistoryMissing, NotBranchError,
 
31
                           DivergedBranches, LockError, UnlistableStore,
 
32
                           UnlistableBranch)
28
33
from bzrlib.textui import show_status
29
 
from bzrlib.revision import Revision
30
 
from bzrlib.xml import unpack_xml
 
34
from bzrlib.revision import Revision, validate_revision_id, is_ancestor
31
35
from bzrlib.delta import compare_trees
32
36
from bzrlib.tree import EmptyTree, RevisionTree
33
 
        
34
 
BZR_BRANCH_FORMAT = "Bazaar-NG branch, format 0.0.4\n"
 
37
from bzrlib.inventory import Inventory
 
38
from bzrlib.weavestore import WeaveStore
 
39
from bzrlib.store import copy_all, ImmutableStore
 
40
import bzrlib.xml5
 
41
import bzrlib.ui
 
42
 
 
43
 
 
44
BZR_BRANCH_FORMAT_4 = "Bazaar-NG branch, format 0.0.4\n"
 
45
BZR_BRANCH_FORMAT_5 = "Bazaar-NG branch, format 5\n"
35
46
## TODO: Maybe include checks for common corruption of newlines, etc?
36
47
 
37
48
 
38
49
# TODO: Some operations like log might retrieve the same revisions
39
50
# repeatedly to calculate deltas.  We could perhaps have a weakref
40
 
# cache in memory to make this faster.
41
 
 
42
 
 
43
 
def find_branch(f, **args):
44
 
    if f and (f.startswith('http://') or f.startswith('https://')):
45
 
        import remotebranch 
46
 
        return remotebranch.RemoteBranch(f, **args)
47
 
    else:
48
 
        return Branch(f, **args)
49
 
 
50
 
 
51
 
def find_cached_branch(f, cache_root, **args):
52
 
    from remotebranch import RemoteBranch
53
 
    br = find_branch(f, **args)
54
 
    def cacheify(br, store_name):
55
 
        from meta_store import CachedStore
56
 
        cache_path = os.path.join(cache_root, store_name)
57
 
        os.mkdir(cache_path)
58
 
        new_store = CachedStore(getattr(br, store_name), cache_path)
59
 
        setattr(br, store_name, new_store)
60
 
 
61
 
    if isinstance(br, RemoteBranch):
62
 
        cacheify(br, 'inventory_store')
63
 
        cacheify(br, 'text_store')
64
 
        cacheify(br, 'revision_store')
65
 
    return br
66
 
 
 
51
# cache in memory to make this faster.  In general anything can be
 
52
# cached in memory between lock and unlock operations.
 
53
 
 
54
def find_branch(*ignored, **ignored_too):
 
55
    # XXX: leave this here for about one release, then remove it
 
56
    raise NotImplementedError('find_branch() is not supported anymore, '
 
57
                              'please use one of the new branch constructors')
67
58
 
68
59
def _relpath(base, path):
69
60
    """Return path relative to base, or raise exception.
87
78
        if tail:
88
79
            s.insert(0, tail)
89
80
    else:
90
 
        from errors import NotBranchError
91
81
        raise NotBranchError("path %r is not within branch %r" % (rp, base))
92
82
 
93
83
    return os.sep.join(s)
101
91
    It is not necessary that f exists.
102
92
 
103
93
    Basically we keep looking up until we find the control directory or
104
 
    run into the root."""
 
94
    run into the root.  If there isn't one, raises NotBranchError.
 
95
    """
105
96
    if f == None:
106
97
        f = os.getcwd()
107
 
    elif hasattr(os.path, 'realpath'):
108
 
        f = os.path.realpath(f)
109
98
    else:
110
 
        f = os.path.abspath(f)
111
 
    if not os.path.exists(f):
 
99
        f = bzrlib.osutils.normalizepath(f)
 
100
    if not bzrlib.osutils.lexists(f):
112
101
        raise BzrError('%r does not exist' % f)
113
 
        
114
102
 
115
103
    orig_f = f
116
104
 
120
108
        head, tail = os.path.split(f)
121
109
        if head == f:
122
110
            # reached the root, whatever that may be
123
 
            raise BzrError('%r is not in a branch' % orig_f)
 
111
            raise NotBranchError('%s is not in a branch' % orig_f)
124
112
        f = head
125
 
    
126
 
class DivergedBranches(Exception):
127
 
    def __init__(self, branch1, branch2):
128
 
        self.branch1 = branch1
129
 
        self.branch2 = branch2
130
 
        Exception.__init__(self, "These branches have diverged.")
 
113
 
 
114
 
131
115
 
132
116
 
133
117
######################################################################
137
121
    """Branch holding a history of revisions.
138
122
 
139
123
    base
140
 
        Base directory of the branch.
 
124
        Base directory/url of the branch.
 
125
    """
 
126
    base = None
 
127
 
 
128
    def __init__(self, *ignored, **ignored_too):
 
129
        raise NotImplementedError('The Branch class is abstract')
 
130
 
 
131
    @staticmethod
 
132
    def open(base):
 
133
        """Open an existing branch, rooted at 'base' (url)"""
 
134
        if base and (base.startswith('http://') or base.startswith('https://')):
 
135
            from bzrlib.remotebranch import RemoteBranch
 
136
            return RemoteBranch(base, find_root=False)
 
137
        else:
 
138
            return LocalBranch(base, find_root=False)
 
139
 
 
140
    @staticmethod
 
141
    def open_containing(url):
 
142
        """Open an existing branch which contains url.
 
143
        
 
144
        This probes for a branch at url, and searches upwards from there.
 
145
        """
 
146
        if url and (url.startswith('http://') or url.startswith('https://')):
 
147
            from bzrlib.remotebranch import RemoteBranch
 
148
            return RemoteBranch(url)
 
149
        else:
 
150
            return LocalBranch(url)
 
151
 
 
152
    @staticmethod
 
153
    def initialize(base):
 
154
        """Create a new branch, rooted at 'base' (url)"""
 
155
        if base and (base.startswith('http://') or base.startswith('https://')):
 
156
            from bzrlib.remotebranch import RemoteBranch
 
157
            return RemoteBranch(base, init=True)
 
158
        else:
 
159
            return LocalBranch(base, init=True)
 
160
 
 
161
    def setup_caching(self, cache_root):
 
162
        """Subclasses that care about caching should override this, and set
 
163
        up cached stores located under cache_root.
 
164
        """
 
165
 
 
166
 
 
167
class LocalBranch(Branch):
 
168
    """A branch stored in the actual filesystem.
 
169
 
 
170
    Note that it's "local" in the context of the filesystem; it doesn't
 
171
    really matter if it's on an nfs/smb/afs/coda/... share, as long as
 
172
    it's writable, and can be accessed via the normal filesystem API.
141
173
 
142
174
    _lock_mode
143
175
        None, or 'r' or 'w'
149
181
    _lock
150
182
        Lock object from bzrlib.lock.
151
183
    """
152
 
    base = None
 
184
    # We actually expect this class to be somewhat short-lived; part of its
 
185
    # purpose is to try to isolate what bits of the branch logic are tied to
 
186
    # filesystem access, so that in a later step, we can extricate them to
 
187
    # a separarte ("storage") class.
153
188
    _lock_mode = None
154
189
    _lock_count = None
155
190
    _lock = None
 
191
    _inventory_weave = None
156
192
    
157
193
    # Map some sort of prefix into a namespace
158
194
    # stuff like "revno:10", "revid:", etc.
159
195
    # This should match a prefix with a function which accepts
160
196
    REVISION_NAMESPACES = {}
161
197
 
162
 
    def __init__(self, base, init=False, find_root=True):
 
198
    def push_stores(self, branch_to):
 
199
        """Copy the content of this branches store to branch_to."""
 
200
        if (self._branch_format != branch_to._branch_format
 
201
            or self._branch_format != 4):
 
202
            from bzrlib.fetch import greedy_fetch
 
203
            mutter("falling back to fetch logic to push between %s(%s) and %s(%s)",
 
204
                   self, self._branch_format, branch_to, branch_to._branch_format)
 
205
            greedy_fetch(to_branch=branch_to, from_branch=self,
 
206
                         revision=self.last_revision())
 
207
            return
 
208
 
 
209
        store_pairs = ((self.text_store,      branch_to.text_store),
 
210
                       (self.inventory_store, branch_to.inventory_store),
 
211
                       (self.revision_store,  branch_to.revision_store))
 
212
        try:
 
213
            for from_store, to_store in store_pairs: 
 
214
                copy_all(from_store, to_store)
 
215
        except UnlistableStore:
 
216
            raise UnlistableBranch(from_store)
 
217
 
 
218
    def __init__(self, base, init=False, find_root=True,
 
219
                 relax_version_check=False):
163
220
        """Create new branch object at a particular location.
164
221
 
165
 
        base -- Base directory for the branch.
 
222
        base -- Base directory for the branch. May be a file:// url.
166
223
        
167
224
        init -- If True, create new control files in a previously
168
225
             unversioned directory.  If False, the branch must already
171
228
        find_root -- If true and init is false, find the root of the
172
229
             existing branch containing base.
173
230
 
 
231
        relax_version_check -- If true, the usual check for the branch
 
232
            version is not applied.  This is intended only for
 
233
            upgrade/recovery type use; it's not guaranteed that
 
234
            all operations will work on old format branches.
 
235
 
174
236
        In the test suite, creation of new trees is tested using the
175
237
        `ScratchBranch` class.
176
238
        """
177
 
        from bzrlib.store import ImmutableStore
178
239
        if init:
179
240
            self.base = os.path.realpath(base)
180
241
            self._make_control()
181
242
        elif find_root:
182
243
            self.base = find_branch_root(base)
183
244
        else:
 
245
            if base.startswith("file://"):
 
246
                base = base[7:]
184
247
            self.base = os.path.realpath(base)
185
248
            if not isdir(self.controlfilename('.')):
186
 
                from errors import NotBranchError
187
 
                raise NotBranchError("not a bzr branch: %s" % quotefn(base),
188
 
                                     ['use "bzr init" to initialize a new working tree',
189
 
                                      'current bzr can only operate from top-of-tree'])
190
 
        self._check_format()
191
 
 
192
 
        self.text_store = ImmutableStore(self.controlfilename('text-store'))
193
 
        self.revision_store = ImmutableStore(self.controlfilename('revision-store'))
194
 
        self.inventory_store = ImmutableStore(self.controlfilename('inventory-store'))
 
249
                raise NotBranchError('not a bzr branch: %s' % quotefn(base),
 
250
                                     ['use "bzr init" to initialize a '
 
251
                                      'new working tree'])
 
252
        self._check_format(relax_version_check)
 
253
        cfn = self.controlfilename
 
254
        if self._branch_format == 4:
 
255
            self.inventory_store = ImmutableStore(cfn('inventory-store'))
 
256
            self.text_store = ImmutableStore(cfn('text-store'))
 
257
        elif self._branch_format == 5:
 
258
            self.control_weaves = WeaveStore(cfn([]))
 
259
            self.weave_store = WeaveStore(cfn('weaves'))
 
260
            if init:
 
261
                # FIXME: Unify with make_control_files
 
262
                self.control_weaves.put_empty_weave('inventory')
 
263
                self.control_weaves.put_empty_weave('ancestry')
 
264
        self.revision_store = ImmutableStore(cfn('revision-store'))
195
265
 
196
266
 
197
267
    def __str__(self):
203
273
 
204
274
    def __del__(self):
205
275
        if self._lock_mode or self._lock:
206
 
            from warnings import warn
 
276
            # XXX: This should show something every time, and be suitable for
 
277
            # headless operation and embedding
207
278
            warn("branch %r was not explicitly unlocked" % self)
208
279
            self._lock.unlock()
209
280
 
210
 
 
211
 
 
212
281
    def lock_write(self):
213
282
        if self._lock_mode:
214
283
            if self._lock_mode != 'w':
215
 
                from errors import LockError
216
284
                raise LockError("can't upgrade to a write lock from %r" %
217
285
                                self._lock_mode)
218
286
            self._lock_count += 1
224
292
            self._lock_count = 1
225
293
 
226
294
 
227
 
 
228
295
    def lock_read(self):
229
296
        if self._lock_mode:
230
297
            assert self._lock_mode in ('r', 'w'), \
237
304
            self._lock_mode = 'r'
238
305
            self._lock_count = 1
239
306
                        
240
 
 
241
 
            
242
307
    def unlock(self):
243
308
        if not self._lock_mode:
244
 
            from errors import LockError
245
309
            raise LockError('branch %r is not locked' % (self))
246
310
 
247
311
        if self._lock_count > 1:
251
315
            self._lock = None
252
316
            self._lock_mode = self._lock_count = None
253
317
 
254
 
 
255
318
    def abspath(self, name):
256
319
        """Return absolute filename for something in the branch"""
257
320
        return os.path.join(self.base, name)
258
321
 
259
 
 
260
322
    def relpath(self, path):
261
323
        """Return path relative to this branch of something inside it.
262
324
 
263
325
        Raises an error if path is not in this branch."""
264
326
        return _relpath(self.base, path)
265
327
 
266
 
 
267
328
    def controlfilename(self, file_or_path):
268
329
        """Return location relative to branch."""
269
330
        if isinstance(file_or_path, basestring):
296
357
        else:
297
358
            raise BzrError("invalid controlfile mode %r" % mode)
298
359
 
299
 
 
300
 
 
301
360
    def _make_control(self):
302
 
        from bzrlib.inventory import Inventory
303
 
        from bzrlib.xml import pack_xml
304
 
        
305
361
        os.mkdir(self.controlfilename([]))
306
362
        self.controlfile('README', 'w').write(
307
363
            "This is a Bazaar-NG control directory.\n"
308
364
            "Do not change any files in this directory.\n")
309
 
        self.controlfile('branch-format', 'w').write(BZR_BRANCH_FORMAT)
310
 
        for d in ('text-store', 'inventory-store', 'revision-store'):
 
365
        self.controlfile('branch-format', 'w').write(BZR_BRANCH_FORMAT_5)
 
366
        for d in ('text-store', 'revision-store',
 
367
                  'weaves'):
311
368
            os.mkdir(self.controlfilename(d))
312
 
        for f in ('revision-history', 'merged-patches',
313
 
                  'pending-merged-patches', 'branch-name',
 
369
        for f in ('revision-history',
 
370
                  'branch-name',
314
371
                  'branch-lock',
315
372
                  'pending-merges'):
316
373
            self.controlfile(f, 'w').write('')
317
374
        mutter('created control directory in ' + self.base)
318
375
 
319
 
        pack_xml(Inventory(gen_root_id()), self.controlfile('inventory','w'))
320
 
 
321
 
 
322
 
    def _check_format(self):
 
376
        # if we want per-tree root ids then this is the place to set
 
377
        # them; they're not needed for now and so ommitted for
 
378
        # simplicity.
 
379
        f = self.controlfile('inventory','w')
 
380
        bzrlib.xml5.serializer_v5.write_inventory(Inventory(), f)
 
381
 
 
382
 
 
383
    def _check_format(self, relax_version_check):
323
384
        """Check this branch format is supported.
324
385
 
325
 
        The current tool only supports the current unstable format.
 
386
        The format level is stored, as an integer, in
 
387
        self._branch_format for code that needs to check it later.
326
388
 
327
389
        In the future, we might need different in-memory Branch
328
390
        classes to support downlevel branches.  But not yet.
329
391
        """
330
 
        # This ignores newlines so that we can open branches created
331
 
        # on Windows from Linux and so on.  I think it might be better
332
 
        # to always make all internal files in unix format.
333
 
        fmt = self.controlfile('branch-format', 'r').read()
334
 
        fmt.replace('\r\n', '')
335
 
        if fmt != BZR_BRANCH_FORMAT:
 
392
        try:
 
393
            fmt = self.controlfile('branch-format', 'r').read()
 
394
        except IOError, e:
 
395
            if hasattr(e, 'errno'):
 
396
                if e.errno == errno.ENOENT:
 
397
                    raise NotBranchError(self.base)
 
398
                else:
 
399
                    raise
 
400
            else:
 
401
                raise
 
402
 
 
403
        if fmt == BZR_BRANCH_FORMAT_5:
 
404
            self._branch_format = 5
 
405
        elif fmt == BZR_BRANCH_FORMAT_4:
 
406
            self._branch_format = 4
 
407
 
 
408
        if (not relax_version_check
 
409
            and self._branch_format != 5):
336
410
            raise BzrError('sorry, branch format %r not supported' % fmt,
337
411
                           ['use a different bzr version',
338
412
                            'or remove the .bzr directory and "bzr init" again'])
356
430
 
357
431
    def read_working_inventory(self):
358
432
        """Read the working inventory."""
359
 
        from bzrlib.inventory import Inventory
360
 
        from bzrlib.xml import unpack_xml
361
 
        from time import time
362
 
        before = time()
363
433
        self.lock_read()
364
434
        try:
365
435
            # ElementTree does its own conversion from UTF-8, so open in
366
436
            # binary.
367
 
            inv = unpack_xml(Inventory,
368
 
                             self.controlfile('inventory', 'rb'))
369
 
            mutter("loaded inventory of %d items in %f"
370
 
                   % (len(inv), time() - before))
371
 
            return inv
 
437
            f = self.controlfile('inventory', 'rb')
 
438
            return bzrlib.xml5.serializer_v5.read_inventory(f)
372
439
        finally:
373
440
            self.unlock()
374
441
            
380
447
        will be committed to the next revision.
381
448
        """
382
449
        from bzrlib.atomicfile import AtomicFile
383
 
        from bzrlib.xml import pack_xml
384
450
        
385
451
        self.lock_write()
386
452
        try:
387
453
            f = AtomicFile(self.controlfilename('inventory'), 'wb')
388
454
            try:
389
 
                pack_xml(inv, f)
 
455
                bzrlib.xml5.serializer_v5.write_inventory(inv, f)
390
456
                f.commit()
391
457
            finally:
392
458
                f.close()
395
461
        
396
462
        mutter('wrote working inventory')
397
463
            
398
 
 
399
464
    inventory = property(read_working_inventory, _write_inventory, None,
400
465
                         """Inventory for the working copy.""")
401
466
 
402
 
 
403
 
    def add(self, files, verbose=False, ids=None):
 
467
    def add(self, files, ids=None):
404
468
        """Make files versioned.
405
469
 
406
 
        Note that the command line normally calls smart_add instead.
 
470
        Note that the command line normally calls smart_add instead,
 
471
        which can automatically recurse.
407
472
 
408
473
        This puts the files in the Added state, so that they will be
409
474
        recorded by the next commit.
419
484
        TODO: Perhaps have an option to add the ids even if the files do
420
485
              not (yet) exist.
421
486
 
422
 
        TODO: Perhaps return the ids of the files?  But then again it
423
 
              is easy to retrieve them if they're needed.
424
 
 
425
 
        TODO: Adding a directory should optionally recurse down and
426
 
              add all non-ignored children.  Perhaps do that in a
427
 
              higher-level method.
 
487
        TODO: Perhaps yield the ids and paths as they're added.
428
488
        """
429
489
        # TODO: Re-adding a file that is removed in the working copy
430
490
        # should probably put it back with the previous ID.
457
517
                    kind = file_kind(fullpath)
458
518
                except OSError:
459
519
                    # maybe something better?
460
 
                    raise BzrError('cannot add: not a regular file or directory: %s' % quotefn(f))
 
520
                    raise BzrError('cannot add: not a regular file, symlink or directory: %s' % quotefn(f))
461
521
 
462
 
                if kind != 'file' and kind != 'directory':
463
 
                    raise BzrError('cannot add: not a regular file or directory: %s' % quotefn(f))
 
522
                if kind not in ('file', 'directory', 'symlink'):
 
523
                    raise BzrError('cannot add: not a regular file, symlink or directory: %s' % quotefn(f))
464
524
 
465
525
                if file_id is None:
466
526
                    file_id = gen_file_id(f)
467
527
                inv.add_path(f, kind=kind, file_id=file_id)
468
528
 
469
 
                if verbose:
470
 
                    print 'added', quotefn(f)
471
 
 
472
529
                mutter("add file %s file_id:{%s} kind=%r" % (f, file_id, kind))
473
530
 
474
531
            self._write_inventory(inv)
480
537
        """Print `file` to stdout."""
481
538
        self.lock_read()
482
539
        try:
483
 
            tree = self.revision_tree(self.lookup_revision(revno))
 
540
            tree = self.revision_tree(self.get_rev_id(revno))
484
541
            # use inventory as it was in that revision
485
542
            file_id = tree.inventory.path2id(file)
486
543
            if not file_id:
534
591
        finally:
535
592
            self.unlock()
536
593
 
537
 
 
538
594
    # FIXME: this doesn't need to be a branch method
539
595
    def set_inventory(self, new_inventory_list):
540
596
        from bzrlib.inventory import Inventory, InventoryEntry
546
602
            inv.add(InventoryEntry(file_id, name, kind, parent))
547
603
        self._write_inventory(inv)
548
604
 
549
 
 
550
605
    def unknowns(self):
551
606
        """Return all unknown files.
552
607
 
583
638
        finally:
584
639
            f.close()
585
640
 
586
 
 
587
 
    def get_revision_xml(self, revision_id):
 
641
    def has_revision(self, revision_id):
 
642
        """True if this branch has a copy of the revision.
 
643
 
 
644
        This does not necessarily imply the revision is merge
 
645
        or on the mainline."""
 
646
        return (revision_id is None
 
647
                or revision_id in self.revision_store)
 
648
 
 
649
    def get_revision_xml_file(self, revision_id):
588
650
        """Return XML file object for revision object."""
589
651
        if not revision_id or not isinstance(revision_id, basestring):
590
652
            raise InvalidRevisionId(revision_id)
593
655
        try:
594
656
            try:
595
657
                return self.revision_store[revision_id]
596
 
            except IndexError:
597
 
                raise bzrlib.errors.NoSuchRevision(revision_id)
 
658
            except (IndexError, KeyError):
 
659
                raise bzrlib.errors.NoSuchRevision(self, revision_id)
598
660
        finally:
599
661
            self.unlock()
600
662
 
 
663
    #deprecated
 
664
    get_revision_xml = get_revision_xml_file
 
665
 
 
666
    def get_revision_xml(self, revision_id):
 
667
        return self.get_revision_xml_file(revision_id).read()
 
668
 
601
669
 
602
670
    def get_revision(self, revision_id):
603
671
        """Return the Revision object for a named revision"""
604
 
        xml_file = self.get_revision_xml(revision_id)
 
672
        xml_file = self.get_revision_xml_file(revision_id)
605
673
 
606
674
        try:
607
 
            r = unpack_xml(Revision, xml_file)
 
675
            r = bzrlib.xml5.serializer_v5.read_revision(xml_file)
608
676
        except SyntaxError, e:
609
677
            raise bzrlib.errors.BzrError('failed to unpack revision_xml',
610
678
                                         [revision_id,
613
681
        assert r.revision_id == revision_id
614
682
        return r
615
683
 
616
 
 
617
684
    def get_revision_delta(self, revno):
618
685
        """Return the delta for one revision.
619
686
 
635
702
 
636
703
        return compare_trees(old_tree, new_tree)
637
704
 
638
 
        
639
 
 
640
705
    def get_revision_sha1(self, revision_id):
641
706
        """Hash the stored value of a revision, and return it."""
642
707
        # In the future, revision entries will be signed. At that
645
710
        # the revision, (add signatures/remove signatures) and still
646
711
        # have all hash pointers stay consistent.
647
712
        # But for now, just hash the contents.
648
 
        return bzrlib.osutils.sha_file(self.get_revision_xml(revision_id))
649
 
 
650
 
 
651
 
    def get_inventory(self, inventory_id):
652
 
        """Get Inventory object by hash.
653
 
 
654
 
        TODO: Perhaps for this and similar methods, take a revision
655
 
               parameter which can be either an integer revno or a
656
 
               string hash."""
657
 
        from bzrlib.inventory import Inventory
658
 
        from bzrlib.xml import unpack_xml
659
 
 
660
 
        return unpack_xml(Inventory, self.inventory_store[inventory_id])
661
 
            
662
 
 
663
 
    def get_inventory_sha1(self, inventory_id):
 
713
        return bzrlib.osutils.sha_file(self.get_revision_xml_file(revision_id))
 
714
 
 
715
    def _get_ancestry_weave(self):
 
716
        return self.control_weaves.get_weave('ancestry')
 
717
 
 
718
    def get_ancestry(self, revision_id):
 
719
        """Return a list of revision-ids integrated by a revision.
 
720
        """
 
721
        # strip newlines
 
722
        if revision_id is None:
 
723
            return [None]
 
724
        w = self._get_ancestry_weave()
 
725
        return [None] + [l[:-1] for l in w.get_iter(w.lookup(revision_id))]
 
726
 
 
727
    def get_inventory_weave(self):
 
728
        return self.control_weaves.get_weave('inventory')
 
729
 
 
730
    def get_inventory(self, revision_id):
 
731
        """Get Inventory object by hash."""
 
732
        xml = self.get_inventory_xml(revision_id)
 
733
        return bzrlib.xml5.serializer_v5.read_inventory_from_string(xml)
 
734
 
 
735
    def get_inventory_xml(self, revision_id):
 
736
        """Get inventory XML as a file object."""
 
737
        try:
 
738
            assert isinstance(revision_id, basestring), type(revision_id)
 
739
            iw = self.get_inventory_weave()
 
740
            return iw.get_text(iw.lookup(revision_id))
 
741
        except IndexError:
 
742
            raise bzrlib.errors.HistoryMissing(self, 'inventory', revision_id)
 
743
 
 
744
    def get_inventory_sha1(self, revision_id):
664
745
        """Return the sha1 hash of the inventory entry
665
746
        """
666
 
        return sha_file(self.inventory_store[inventory_id])
667
 
 
 
747
        return self.get_revision(revision_id).inventory_sha1
668
748
 
669
749
    def get_revision_inventory(self, revision_id):
670
750
        """Return inventory of a past revision."""
671
 
        # bzr 0.0.6 imposes the constraint that the inventory_id
 
751
        # TODO: Unify this with get_inventory()
 
752
        # bzr 0.0.6 and later imposes the constraint that the inventory_id
672
753
        # must be the same as its revision, so this is trivial.
673
754
        if revision_id == None:
674
 
            from bzrlib.inventory import Inventory
675
755
            return Inventory(self.get_root_id())
676
756
        else:
677
757
            return self.get_inventory(revision_id)
678
758
 
679
 
 
680
759
    def revision_history(self):
681
 
        """Return sequence of revision hashes on to this branch.
682
 
 
683
 
        >>> ScratchBranch().revision_history()
684
 
        []
685
 
        """
 
760
        """Return sequence of revision hashes on to this branch."""
686
761
        self.lock_read()
687
762
        try:
688
763
            return [l.rstrip('\r\n') for l in
690
765
        finally:
691
766
            self.unlock()
692
767
 
693
 
 
694
768
    def common_ancestor(self, other, self_revno=None, other_revno=None):
695
769
        """
696
 
        >>> import commit
 
770
        >>> from bzrlib.commit import commit
697
771
        >>> sb = ScratchBranch(files=['foo', 'foo~'])
698
772
        >>> sb.common_ancestor(sb) == (None, None)
699
773
        True
700
 
        >>> commit.commit(sb, "Committing first revision", verbose=False)
 
774
        >>> commit(sb, "Committing first revision", verbose=False)
701
775
        >>> sb.common_ancestor(sb)[0]
702
776
        1
703
777
        >>> clone = sb.clone()
704
 
        >>> commit.commit(sb, "Committing second revision", verbose=False)
 
778
        >>> commit(sb, "Committing second revision", verbose=False)
705
779
        >>> sb.common_ancestor(sb)[0]
706
780
        2
707
781
        >>> sb.common_ancestor(clone)[0]
708
782
        1
709
 
        >>> commit.commit(clone, "Committing divergent second revision", 
 
783
        >>> commit(clone, "Committing divergent second revision", 
710
784
        ...               verbose=False)
711
785
        >>> sb.common_ancestor(clone)[0]
712
786
        1
745
819
        return len(self.revision_history())
746
820
 
747
821
 
748
 
    def last_patch(self):
 
822
    def last_revision(self):
749
823
        """Return last patch hash, or None if no history.
750
824
        """
751
825
        ph = self.revision_history()
755
829
            return None
756
830
 
757
831
 
758
 
    def missing_revisions(self, other, stop_revision=None):
759
 
        """
 
832
    def missing_revisions(self, other, stop_revision=None, diverged_ok=False):
 
833
        """Return a list of new revisions that would perfectly fit.
 
834
        
760
835
        If self and other have not diverged, return a list of the revisions
761
836
        present in other, but missing from self.
762
837
 
782
857
        Traceback (most recent call last):
783
858
        DivergedBranches: These branches have diverged.
784
859
        """
 
860
        # FIXME: If the branches have diverged, but the latest
 
861
        # revision in this branch is completely merged into the other,
 
862
        # then we should still be able to pull.
785
863
        self_history = self.revision_history()
786
864
        self_len = len(self_history)
787
865
        other_history = other.revision_history()
793
871
 
794
872
        if stop_revision is None:
795
873
            stop_revision = other_len
796
 
        elif stop_revision > other_len:
797
 
            raise NoSuchRevision(self, stop_revision)
798
 
        
 
874
        else:
 
875
            assert isinstance(stop_revision, int)
 
876
            if stop_revision > other_len:
 
877
                raise bzrlib.errors.NoSuchRevision(self, stop_revision)
799
878
        return other_history[self_len:stop_revision]
800
879
 
801
 
 
802
880
    def update_revisions(self, other, stop_revision=None):
803
 
        """Pull in all new revisions from other branch.
804
 
        
805
 
        >>> from bzrlib.commit import commit
806
 
        >>> bzrlib.trace.silent = True
807
 
        >>> br1 = ScratchBranch(files=['foo', 'bar'])
808
 
        >>> br1.add('foo')
809
 
        >>> br1.add('bar')
810
 
        >>> commit(br1, "lala!", rev_id="REVISION-ID-1", verbose=False)
811
 
        >>> br2 = ScratchBranch()
812
 
        >>> br2.update_revisions(br1)
813
 
        Added 2 texts.
814
 
        Added 1 inventories.
815
 
        Added 1 revisions.
816
 
        >>> br2.revision_history()
817
 
        [u'REVISION-ID-1']
818
 
        >>> br2.update_revisions(br1)
819
 
        Added 0 texts.
820
 
        Added 0 inventories.
821
 
        Added 0 revisions.
822
 
        >>> br1.text_store.total_size() == br2.text_store.total_size()
823
 
        True
824
 
        """
825
 
        from bzrlib.progress import ProgressBar
826
 
 
827
 
        pb = ProgressBar()
828
 
 
829
 
        pb.update('comparing histories')
830
 
        revision_ids = self.missing_revisions(other, stop_revision)
831
 
 
832
 
        if hasattr(other.revision_store, "prefetch"):
833
 
            other.revision_store.prefetch(revision_ids)
834
 
        if hasattr(other.inventory_store, "prefetch"):
835
 
            inventory_ids = [other.get_revision(r).inventory_id
836
 
                             for r in revision_ids]
837
 
            other.inventory_store.prefetch(inventory_ids)
838
 
                
839
 
        revisions = []
840
 
        needed_texts = set()
841
 
        i = 0
842
 
        for rev_id in revision_ids:
843
 
            i += 1
844
 
            pb.update('fetching revision', i, len(revision_ids))
845
 
            rev = other.get_revision(rev_id)
846
 
            revisions.append(rev)
847
 
            inv = other.get_inventory(str(rev.inventory_id))
848
 
            for key, entry in inv.iter_entries():
849
 
                if entry.text_id is None:
850
 
                    continue
851
 
                if entry.text_id not in self.text_store:
852
 
                    needed_texts.add(entry.text_id)
853
 
 
854
 
        pb.clear()
855
 
                    
856
 
        count = self.text_store.copy_multi(other.text_store, needed_texts)
857
 
        print "Added %d texts." % count 
858
 
        inventory_ids = [ f.inventory_id for f in revisions ]
859
 
        count = self.inventory_store.copy_multi(other.inventory_store, 
860
 
                                                inventory_ids)
861
 
        print "Added %d inventories." % count 
862
 
        revision_ids = [ f.revision_id for f in revisions]
863
 
        count = self.revision_store.copy_multi(other.revision_store, 
864
 
                                               revision_ids)
865
 
        for revision_id in revision_ids:
866
 
            self.append_revision(revision_id)
867
 
        print "Added %d revisions." % count
868
 
                    
869
 
        
 
881
        """Pull in new perfect-fit revisions."""
 
882
        from bzrlib.fetch import greedy_fetch
 
883
        from bzrlib.revision import get_intervening_revisions
 
884
        if stop_revision is None:
 
885
            stop_revision = other.last_revision()
 
886
        greedy_fetch(to_branch=self, from_branch=other,
 
887
                     revision=stop_revision)
 
888
        pullable_revs = self.missing_revisions(
 
889
            other, other.revision_id_to_revno(stop_revision))
 
890
        if pullable_revs:
 
891
            greedy_fetch(to_branch=self,
 
892
                         from_branch=other,
 
893
                         revision=pullable_revs[-1])
 
894
            self.append_revision(*pullable_revs)
 
895
    
 
896
 
870
897
    def commit(self, *args, **kw):
871
 
        from bzrlib.commit import commit
872
 
        commit(self, *args, **kw)
873
 
        
874
 
 
875
 
    def lookup_revision(self, revision):
876
 
        """Return the revision identifier for a given revision information."""
877
 
        revno, info = self.get_revision_info(revision)
878
 
        return info
879
 
 
880
 
    def get_revision_info(self, revision):
881
 
        """Return (revno, revision id) for revision identifier.
882
 
 
883
 
        revision can be an integer, in which case it is assumed to be revno (though
884
 
            this will translate negative values into positive ones)
885
 
        revision can also be a string, in which case it is parsed for something like
886
 
            'date:' or 'revid:' etc.
887
 
        """
888
 
        if revision is None:
889
 
            return 0, None
890
 
        revno = None
891
 
        try:# Convert to int if possible
892
 
            revision = int(revision)
893
 
        except ValueError:
894
 
            pass
895
 
        revs = self.revision_history()
896
 
        if isinstance(revision, int):
897
 
            if revision == 0:
898
 
                return 0, None
899
 
            # Mabye we should do this first, but we don't need it if revision == 0
900
 
            if revision < 0:
901
 
                revno = len(revs) + revision + 1
902
 
            else:
903
 
                revno = revision
904
 
        elif isinstance(revision, basestring):
905
 
            for prefix, func in Branch.REVISION_NAMESPACES.iteritems():
906
 
                if revision.startswith(prefix):
907
 
                    revno = func(self, revs, revision)
908
 
                    break
909
 
            else:
910
 
                raise BzrError('No namespace registered for string: %r' % revision)
911
 
 
912
 
        if revno is None or revno <= 0 or revno > len(revs):
913
 
            raise BzrError("no such revision %s" % revision)
914
 
        return revno, revs[revno-1]
915
 
 
916
 
    def _namespace_revno(self, revs, revision):
917
 
        """Lookup a revision by revision number"""
918
 
        assert revision.startswith('revno:')
919
 
        try:
920
 
            return int(revision[6:])
921
 
        except ValueError:
922
 
            return None
923
 
    REVISION_NAMESPACES['revno:'] = _namespace_revno
924
 
 
925
 
    def _namespace_revid(self, revs, revision):
926
 
        assert revision.startswith('revid:')
927
 
        try:
928
 
            return revs.index(revision[6:]) + 1
929
 
        except ValueError:
930
 
            return None
931
 
    REVISION_NAMESPACES['revid:'] = _namespace_revid
932
 
 
933
 
    def _namespace_last(self, revs, revision):
934
 
        assert revision.startswith('last:')
935
 
        try:
936
 
            offset = int(revision[5:])
937
 
        except ValueError:
938
 
            return None
939
 
        else:
940
 
            if offset <= 0:
941
 
                raise BzrError('You must supply a positive value for --revision last:XXX')
942
 
            return len(revs) - offset + 1
943
 
    REVISION_NAMESPACES['last:'] = _namespace_last
944
 
 
945
 
    def _namespace_tag(self, revs, revision):
946
 
        assert revision.startswith('tag:')
947
 
        raise BzrError('tag: namespace registered, but not implemented.')
948
 
    REVISION_NAMESPACES['tag:'] = _namespace_tag
949
 
 
950
 
    def _namespace_date(self, revs, revision):
951
 
        assert revision.startswith('date:')
952
 
        import datetime
953
 
        # Spec for date revisions:
954
 
        #   date:value
955
 
        #   value can be 'yesterday', 'today', 'tomorrow' or a YYYY-MM-DD string.
956
 
        #   it can also start with a '+/-/='. '+' says match the first
957
 
        #   entry after the given date. '-' is match the first entry before the date
958
 
        #   '=' is match the first entry after, but still on the given date.
959
 
        #
960
 
        #   +2005-05-12 says find the first matching entry after May 12th, 2005 at 0:00
961
 
        #   -2005-05-12 says find the first matching entry before May 12th, 2005 at 0:00
962
 
        #   =2005-05-12 says find the first match after May 12th, 2005 at 0:00 but before
963
 
        #       May 13th, 2005 at 0:00
964
 
        #
965
 
        #   So the proper way of saying 'give me all entries for today' is:
966
 
        #       -r {date:+today}:{date:-tomorrow}
967
 
        #   The default is '=' when not supplied
968
 
        val = revision[5:]
969
 
        match_style = '='
970
 
        if val[:1] in ('+', '-', '='):
971
 
            match_style = val[:1]
972
 
            val = val[1:]
973
 
 
974
 
        today = datetime.datetime.today().replace(hour=0,minute=0,second=0,microsecond=0)
975
 
        if val.lower() == 'yesterday':
976
 
            dt = today - datetime.timedelta(days=1)
977
 
        elif val.lower() == 'today':
978
 
            dt = today
979
 
        elif val.lower() == 'tomorrow':
980
 
            dt = today + datetime.timedelta(days=1)
981
 
        else:
982
 
            import re
983
 
            # This should be done outside the function to avoid recompiling it.
984
 
            _date_re = re.compile(
985
 
                    r'(?P<date>(?P<year>\d\d\d\d)-(?P<month>\d\d)-(?P<day>\d\d))?'
986
 
                    r'(,|T)?\s*'
987
 
                    r'(?P<time>(?P<hour>\d\d):(?P<minute>\d\d)(:(?P<second>\d\d))?)?'
988
 
                )
989
 
            m = _date_re.match(val)
990
 
            if not m or (not m.group('date') and not m.group('time')):
991
 
                raise BzrError('Invalid revision date %r' % revision)
992
 
 
993
 
            if m.group('date'):
994
 
                year, month, day = int(m.group('year')), int(m.group('month')), int(m.group('day'))
995
 
            else:
996
 
                year, month, day = today.year, today.month, today.day
997
 
            if m.group('time'):
998
 
                hour = int(m.group('hour'))
999
 
                minute = int(m.group('minute'))
1000
 
                if m.group('second'):
1001
 
                    second = int(m.group('second'))
1002
 
                else:
1003
 
                    second = 0
1004
 
            else:
1005
 
                hour, minute, second = 0,0,0
1006
 
 
1007
 
            dt = datetime.datetime(year=year, month=month, day=day,
1008
 
                    hour=hour, minute=minute, second=second)
1009
 
        first = dt
1010
 
        last = None
1011
 
        reversed = False
1012
 
        if match_style == '-':
1013
 
            reversed = True
1014
 
        elif match_style == '=':
1015
 
            last = dt + datetime.timedelta(days=1)
1016
 
 
1017
 
        if reversed:
1018
 
            for i in range(len(revs)-1, -1, -1):
1019
 
                r = self.get_revision(revs[i])
1020
 
                # TODO: Handle timezone.
1021
 
                dt = datetime.datetime.fromtimestamp(r.timestamp)
1022
 
                if first >= dt and (last is None or dt >= last):
1023
 
                    return i+1
1024
 
        else:
1025
 
            for i in range(len(revs)):
1026
 
                r = self.get_revision(revs[i])
1027
 
                # TODO: Handle timezone.
1028
 
                dt = datetime.datetime.fromtimestamp(r.timestamp)
1029
 
                if first <= dt and (last is None or dt <= last):
1030
 
                    return i+1
1031
 
    REVISION_NAMESPACES['date:'] = _namespace_date
 
898
        from bzrlib.commit import Commit
 
899
        Commit().commit(self, *args, **kw)
 
900
    
 
901
    def revision_id_to_revno(self, revision_id):
 
902
        """Given a revision id, return its revno"""
 
903
        if revision_id is None:
 
904
            return 0
 
905
        history = self.revision_history()
 
906
        try:
 
907
            return history.index(revision_id) + 1
 
908
        except ValueError:
 
909
            raise bzrlib.errors.NoSuchRevision(self, revision_id)
 
910
 
 
911
    def get_rev_id(self, revno, history=None):
 
912
        """Find the revision id of the specified revno."""
 
913
        if revno == 0:
 
914
            return None
 
915
        if history is None:
 
916
            history = self.revision_history()
 
917
        elif revno <= 0 or revno > len(history):
 
918
            raise bzrlib.errors.NoSuchRevision(self, revno)
 
919
        return history[revno - 1]
1032
920
 
1033
921
    def revision_tree(self, revision_id):
1034
922
        """Return Tree for a revision on this branch.
1041
929
            return EmptyTree()
1042
930
        else:
1043
931
            inv = self.get_revision_inventory(revision_id)
1044
 
            return RevisionTree(self.text_store, inv)
 
932
            return RevisionTree(self.weave_store, inv, revision_id)
1045
933
 
1046
934
 
1047
935
    def working_tree(self):
1048
936
        """Return a `Tree` for the working copy."""
1049
 
        from workingtree import WorkingTree
 
937
        from bzrlib.workingtree import WorkingTree
1050
938
        return WorkingTree(self.base, self.read_working_inventory())
1051
939
 
1052
940
 
1055
943
 
1056
944
        If there are no revisions yet, return an `EmptyTree`.
1057
945
        """
1058
 
        r = self.last_patch()
1059
 
        if r == None:
1060
 
            return EmptyTree()
1061
 
        else:
1062
 
            return RevisionTree(self.text_store, self.get_revision_inventory(r))
1063
 
 
 
946
        return self.revision_tree(self.last_revision())
1064
947
 
1065
948
 
1066
949
    def rename_one(self, from_rel, to_rel):
1098
981
 
1099
982
            inv.rename(file_id, to_dir_id, to_tail)
1100
983
 
1101
 
            print "%s => %s" % (from_rel, to_rel)
1102
 
 
1103
984
            from_abs = self.abspath(from_rel)
1104
985
            to_abs = self.abspath(to_rel)
1105
986
            try:
1106
 
                os.rename(from_abs, to_abs)
 
987
                rename(from_abs, to_abs)
1107
988
            except OSError, e:
1108
989
                raise BzrError("failed to rename %r to %r: %s"
1109
990
                        % (from_abs, to_abs, e[1]),
1124
1005
 
1125
1006
        Note that to_name is only the last component of the new name;
1126
1007
        this doesn't change the directory.
 
1008
 
 
1009
        This returns a list of (from_path, to_path) pairs for each
 
1010
        entry that is moved.
1127
1011
        """
 
1012
        result = []
1128
1013
        self.lock_write()
1129
1014
        try:
1130
1015
            ## TODO: Option to move IDs only
1165
1050
            for f in from_paths:
1166
1051
                name_tail = splitpath(f)[-1]
1167
1052
                dest_path = appendpath(to_name, name_tail)
1168
 
                print "%s => %s" % (f, dest_path)
 
1053
                result.append((f, dest_path))
1169
1054
                inv.rename(inv.path2id(f), to_dir_id, name_tail)
1170
1055
                try:
1171
 
                    os.rename(self.abspath(f), self.abspath(dest_path))
 
1056
                    rename(self.abspath(f), self.abspath(dest_path))
1172
1057
                except OSError, e:
1173
1058
                    raise BzrError("failed to rename %r to %r: %s" % (f, dest_path, e[1]),
1174
1059
                            ["rename rolled back"])
1177
1062
        finally:
1178
1063
            self.unlock()
1179
1064
 
 
1065
        return result
 
1066
 
1180
1067
 
1181
1068
    def revert(self, filenames, old_tree=None, backups=True):
1182
1069
        """Restore selected files to the versions from a previous tree.
1238
1125
 
1239
1126
 
1240
1127
    def add_pending_merge(self, revision_id):
1241
 
        from bzrlib.revision import validate_revision_id
1242
 
 
1243
1128
        validate_revision_id(revision_id)
1244
 
 
 
1129
        # TODO: Perhaps should check at this point that the
 
1130
        # history of the revision is actually present?
1245
1131
        p = self.pending_merges()
1246
1132
        if revision_id in p:
1247
1133
            return
1264
1150
            self.unlock()
1265
1151
 
1266
1152
 
1267
 
 
1268
 
class ScratchBranch(Branch):
 
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
 
 
1171
    def set_parent(self, url):
 
1172
        # TODO: Maybe delete old location files?
 
1173
        from bzrlib.atomicfile import AtomicFile
 
1174
        self.lock_write()
 
1175
        try:
 
1176
            f = AtomicFile(self.controlfilename('parent'))
 
1177
            try:
 
1178
                f.write(url + '\n')
 
1179
                f.commit()
 
1180
            finally:
 
1181
                f.close()
 
1182
        finally:
 
1183
            self.unlock()
 
1184
 
 
1185
    def check_revno(self, revno):
 
1186
        """\
 
1187
        Check whether a revno corresponds to any revision.
 
1188
        Zero (the NULL revision) is considered valid.
 
1189
        """
 
1190
        if revno != 0:
 
1191
            self.check_real_revno(revno)
 
1192
            
 
1193
    def check_real_revno(self, revno):
 
1194
        """\
 
1195
        Check whether a revno corresponds to a real revision.
 
1196
        Zero (the NULL revision) is considered invalid
 
1197
        """
 
1198
        if revno < 1 or revno > self.revno():
 
1199
            raise InvalidRevisionNumber(revno)
 
1200
        
 
1201
        
 
1202
        
 
1203
 
 
1204
 
 
1205
class ScratchBranch(LocalBranch):
1269
1206
    """Special test class: a branch that cleans up after itself.
1270
1207
 
1271
1208
    >>> b = ScratchBranch()
1288
1225
        if base is None:
1289
1226
            base = mkdtemp()
1290
1227
            init = True
1291
 
        Branch.__init__(self, base, init=init)
 
1228
        LocalBranch.__init__(self, base, init=init)
1292
1229
        for d in dirs:
1293
1230
            os.mkdir(self.abspath(d))
1294
1231
            
1300
1237
        """
1301
1238
        >>> orig = ScratchBranch(files=["file1", "file2"])
1302
1239
        >>> clone = orig.clone()
1303
 
        >>> os.path.samefile(orig.base, clone.base)
 
1240
        >>> if os.name != 'nt':
 
1241
        ...   os.path.samefile(orig.base, clone.base)
 
1242
        ... else:
 
1243
        ...   orig.base == clone.base
 
1244
        ...
1304
1245
        False
1305
1246
        >>> os.path.isfile(os.path.join(clone.base, "file1"))
1306
1247
        True
1311
1252
        os.rmdir(base)
1312
1253
        copytree(self.base, base, symlinks=True)
1313
1254
        return ScratchBranch(base=base)
1314
 
        
 
1255
 
1315
1256
    def __del__(self):
1316
1257
        self.destroy()
1317
1258
 
1386
1327
    """Return a new tree-root file id."""
1387
1328
    return gen_file_id('TREE_ROOT')
1388
1329
 
 
1330
 
 
1331
def copy_branch(branch_from, to_location, revision=None, basis_branch=None):
 
1332
    """Copy branch_from into the existing directory to_location.
 
1333
 
 
1334
    revision
 
1335
        If not None, only revisions up to this point will be copied.
 
1336
        The head of the new branch will be that revision.  Must be a
 
1337
        revid or None.
 
1338
 
 
1339
    to_location
 
1340
        The name of a local directory that exists but is empty.
 
1341
 
 
1342
    revno
 
1343
        The revision to copy up to
 
1344
 
 
1345
    basis_branch
 
1346
        A local branch to copy revisions from, related to branch_from
 
1347
    """
 
1348
    # TODO: This could be done *much* more efficiently by just copying
 
1349
    # all the whole weaves and revisions, rather than getting one
 
1350
    # revision at a time.
 
1351
    from bzrlib.merge import merge
 
1352
 
 
1353
    assert isinstance(branch_from, Branch)
 
1354
    assert isinstance(to_location, basestring)
 
1355
    
 
1356
    br_to = Branch.initialize(to_location)
 
1357
    mutter("copy branch from %s to %s", branch_from, br_to)
 
1358
    if basis_branch is not None:
 
1359
        basis_branch.push_stores(br_to)
 
1360
    br_to.set_root_id(branch_from.get_root_id())
 
1361
    if revision is None:
 
1362
        revision = branch_from.last_revision()
 
1363
    br_to.update_revisions(branch_from, stop_revision=revision)
 
1364
    merge((to_location, -1), (to_location, 0), this_dir=to_location,
 
1365
          check_clean=False, ignore_zero=True)
 
1366
    br_to.set_parent(branch_from.base)
 
1367
    mutter("copied")
 
1368
    return br_to