/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: John Arbash Meinel
  • Date: 2005-09-15 21:35:53 UTC
  • mfrom: (907.1.57)
  • mto: (1393.2.1)
  • mto: This revision was merged to the branch mainline in revision 1396.
  • Revision ID: john@arbash-meinel.com-20050915213552-a6c83a5ef1e20897
(broken) Transport work is merged in. Tests do not pass yet.

Show diffs side-by-side

added added

removed removed

Lines of Context:
23
23
from bzrlib.osutils import isdir, quotefn, compact_date, rand_bytes, \
24
24
     splitpath, \
25
25
     sha_file, appendpath, file_kind
26
 
from bzrlib.errors import BzrError, InvalidRevisionNumber, InvalidRevisionId
27
 
import bzrlib.errors
 
26
 
 
27
from bzrlib.errors import BzrError, InvalidRevisionNumber, InvalidRevisionId, \
 
28
     DivergedBranches, NotBranchError
28
29
from bzrlib.textui import show_status
29
30
from bzrlib.revision import Revision
30
 
from bzrlib.xml import unpack_xml
31
31
from bzrlib.delta import compare_trees
32
32
from bzrlib.tree import EmptyTree, RevisionTree
33
 
        
 
33
import bzrlib.xml
 
34
import bzrlib.ui
 
35
 
 
36
 
 
37
 
34
38
BZR_BRANCH_FORMAT = "Bazaar-NG branch, format 0.0.4\n"
35
39
## TODO: Maybe include checks for common corruption of newlines, etc?
36
40
 
39
43
# repeatedly to calculate deltas.  We could perhaps have a weakref
40
44
# cache in memory to make this faster.
41
45
 
 
46
# TODO: please move the revision-string syntax stuff out of the branch
 
47
# object; it's clutter
 
48
 
42
49
 
43
50
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
    from bzrlib.transport import transport
 
52
    from bzrlib.local_transport import LocalTransport
 
53
    t = transport(f)
 
54
    # FIXME: This is a hack around transport so that
 
55
    #        We can search the local directories for
 
56
    #        a branch root.
 
57
    if args.has_key('init') and args['init']:
 
58
        # Don't search if we are init-ing
 
59
        return Branch(t, **args)
 
60
    if isinstance(t, LocalTransport):
 
61
        root = find_branch_root(f)
 
62
        if root != f:
 
63
            t = transport(root)
 
64
    return Branch(t, **args)
67
65
 
68
66
def _relpath(base, path):
69
67
    """Return path relative to base, or raise exception.
87
85
        if tail:
88
86
            s.insert(0, tail)
89
87
    else:
90
 
        from errors import NotBranchError
91
88
        raise NotBranchError("path %r is not within branch %r" % (rp, base))
92
89
 
93
90
    return os.sep.join(s)
101
98
    It is not necessary that f exists.
102
99
 
103
100
    Basically we keep looking up until we find the control directory or
104
 
    run into the root."""
 
101
    run into the root.  If there isn't one, raises NotBranchError.
 
102
    """
105
103
    if f == None:
106
104
        f = os.getcwd()
107
 
    elif hasattr(os.path, 'realpath'):
 
105
    else:
108
106
        f = os.path.realpath(f)
109
 
    else:
110
 
        f = os.path.abspath(f)
111
107
    if not os.path.exists(f):
112
108
        raise BzrError('%r does not exist' % f)
113
109
        
120
116
        head, tail = os.path.split(f)
121
117
        if head == f:
122
118
            # reached the root, whatever that may be
123
 
            raise BzrError('%r is not in a branch' % orig_f)
 
119
            raise NotBranchError('%s is not in a branch' % orig_f)
124
120
        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.")
 
121
 
 
122
 
131
123
 
132
124
 
133
125
######################################################################
153
145
    _lock_mode = None
154
146
    _lock_count = None
155
147
    _lock = None
 
148
    cache_root = None
156
149
    
157
150
    # Map some sort of prefix into a namespace
158
151
    # stuff like "revno:10", "revid:", etc.
159
152
    # This should match a prefix with a function which accepts
160
153
    REVISION_NAMESPACES = {}
161
154
 
162
 
    def __init__(self, base, init=False, find_root=True):
 
155
    def __init__(self, transport, init=False):
163
156
        """Create new branch object at a particular location.
164
157
 
165
 
        base -- Base directory for the branch.
 
158
        transport -- A Transport object, defining how to access files.
 
159
                (If a string, transport.transport() will be used to
 
160
                create a Transport object)
166
161
        
167
162
        init -- If True, create new control files in a previously
168
163
             unversioned directory.  If False, the branch must already
169
164
             be versioned.
170
165
 
171
 
        find_root -- If true and init is false, find the root of the
172
 
             existing branch containing base.
173
 
 
174
166
        In the test suite, creation of new trees is tested using the
175
167
        `ScratchBranch` class.
176
168
        """
177
 
        from bzrlib.store import ImmutableStore
 
169
        if isinstance(transport, basestring):
 
170
            from transport import transport as get_transport
 
171
            transport = get_transport(transport)
 
172
 
 
173
        self._transport = transport
178
174
        if init:
179
 
            self.base = os.path.realpath(base)
180
175
            self._make_control()
181
 
        elif find_root:
182
 
            self.base = find_branch_root(base)
183
 
        else:
184
 
            self.base = os.path.realpath(base)
185
 
            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
176
        self._check_format()
191
177
 
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'))
195
 
 
196
178
 
197
179
    def __str__(self):
198
 
        return '%s(%r)' % (self.__class__.__name__, self.base)
 
180
        return '%s(%r)' % (self.__class__.__name__, self._transport.base)
199
181
 
200
182
 
201
183
    __repr__ = __str__
203
185
 
204
186
    def __del__(self):
205
187
        if self._lock_mode or self._lock:
206
 
            from warnings import warn
 
188
            from bzrlib.warnings import warn
207
189
            warn("branch %r was not explicitly unlocked" % self)
208
190
            self._lock.unlock()
209
191
 
 
192
        # TODO: It might be best to do this somewhere else,
 
193
        # but it is nice for a Branch object to automatically
 
194
        # cache it's information.
 
195
        # Alternatively, we could have the Transport objects cache requests
 
196
        # See the earlier discussion about how major objects (like Branch)
 
197
        # should never expect their __del__ function to run.
 
198
        if self.cache_root is not None:
 
199
            #from warnings import warn
 
200
            #warn("branch %r auto-cleanup of cache files" % self)
 
201
            try:
 
202
                import shutil
 
203
                shutil.rmtree(self.cache_root)
 
204
            except:
 
205
                pass
 
206
            self.cache_root = None
 
207
 
 
208
    def _get_base(self):
 
209
        if self._transport:
 
210
            return self._transport.base
 
211
        return None
 
212
 
 
213
    base = property(_get_base)
210
214
 
211
215
 
212
216
    def lock_write(self):
 
217
        # TODO: Upgrade locking to support using a Transport,
 
218
        # and potentially a remote locking protocol
213
219
        if self._lock_mode:
214
220
            if self._lock_mode != 'w':
215
 
                from errors import LockError
 
221
                from bzrlib.errors import LockError
216
222
                raise LockError("can't upgrade to a write lock from %r" %
217
223
                                self._lock_mode)
218
224
            self._lock_count += 1
219
225
        else:
220
 
            from bzrlib.lock import WriteLock
221
 
 
222
 
            self._lock = WriteLock(self.controlfilename('branch-lock'))
 
226
            self._lock = self._transport.lock_write(
 
227
                    self._rel_controlfilename('branch-lock'))
223
228
            self._lock_mode = 'w'
224
229
            self._lock_count = 1
225
230
 
226
231
 
227
 
 
228
232
    def lock_read(self):
229
233
        if self._lock_mode:
230
234
            assert self._lock_mode in ('r', 'w'), \
231
235
                   "invalid lock mode %r" % self._lock_mode
232
236
            self._lock_count += 1
233
237
        else:
234
 
            from bzrlib.lock import ReadLock
235
 
 
236
 
            self._lock = ReadLock(self.controlfilename('branch-lock'))
 
238
            self._lock = self._transport.lock_read(
 
239
                    self._rel_controlfilename('branch-lock'))
237
240
            self._lock_mode = 'r'
238
241
            self._lock_count = 1
239
242
                        
240
 
 
241
 
            
242
243
    def unlock(self):
243
244
        if not self._lock_mode:
244
 
            from errors import LockError
 
245
            from bzrlib.errors import LockError
245
246
            raise LockError('branch %r is not locked' % (self))
246
247
 
247
248
        if self._lock_count > 1:
251
252
            self._lock = None
252
253
            self._lock_mode = self._lock_count = None
253
254
 
254
 
 
255
255
    def abspath(self, name):
256
256
        """Return absolute filename for something in the branch"""
257
 
        return os.path.join(self.base, name)
258
 
 
 
257
        return self._transport.abspath(name)
259
258
 
260
259
    def relpath(self, path):
261
260
        """Return path relative to this branch of something inside it.
262
261
 
263
262
        Raises an error if path is not in this branch."""
264
 
        return _relpath(self.base, path)
265
 
 
 
263
        return self._transport.relpath(path)
 
264
 
 
265
 
 
266
    def _rel_controlfilename(self, file_or_path):
 
267
        if isinstance(file_or_path, basestring):
 
268
            file_or_path = [file_or_path]
 
269
        return [bzrlib.BZRDIR] + file_or_path
266
270
 
267
271
    def controlfilename(self, file_or_path):
268
272
        """Return location relative to branch."""
269
 
        if isinstance(file_or_path, basestring):
270
 
            file_or_path = [file_or_path]
271
 
        return os.path.join(self.base, bzrlib.BZRDIR, *file_or_path)
 
273
        return self._transport.abspath(self._rel_controlfilename(file_or_path))
272
274
 
273
275
 
274
276
    def controlfile(self, file_or_path, mode='r'):
282
284
        Controlfiles should almost never be opened in write mode but
283
285
        rather should be atomically copied and replaced using atomicfile.
284
286
        """
285
 
 
286
 
        fn = self.controlfilename(file_or_path)
287
 
 
288
 
        if mode == 'rb' or mode == 'wb':
289
 
            return file(fn, mode)
290
 
        elif mode == 'r' or mode == 'w':
291
 
            # open in binary mode anyhow so there's no newline translation;
292
 
            # codecs uses line buffering by default; don't want that.
293
 
            import codecs
294
 
            return codecs.open(fn, mode + 'b', 'utf-8',
295
 
                               buffering=60000)
 
287
        import codecs
 
288
 
 
289
        relpath = self._rel_controlfilename(file_or_path)
 
290
        #TODO: codecs.open() buffers linewise, so it was overloaded with
 
291
        # a much larger buffer, do we need to do the same for getreader/getwriter?
 
292
        if mode == 'rb': 
 
293
            return self._transport.get(relpath)
 
294
        elif mode == 'wb':
 
295
            raise BzrError("Branch.controlfile(mode='wb') is not supported, use put_controlfiles")
 
296
        elif mode == 'r':
 
297
            return codecs.getreader('utf-8')(self._transport.get(relpath), errors='replace')
 
298
        elif mode == 'w':
 
299
            raise BzrError("Branch.controlfile(mode='w') is not supported, use put_controlfiles")
296
300
        else:
297
301
            raise BzrError("invalid controlfile mode %r" % mode)
298
302
 
299
 
 
 
303
    def put_controlfile(self, path, f, encode=True):
 
304
        """Write an entry as a controlfile.
 
305
 
 
306
        :param path: The path to put the file, relative to the .bzr control
 
307
                     directory
 
308
        :param f: A file-like or string object whose contents should be copied.
 
309
        :param encode:  If true, encode the contents as utf-8
 
310
        """
 
311
        self.put_controlfiles([(path, f)], encode=encode)
 
312
 
 
313
    def put_controlfiles(self, files, encode=True):
 
314
        """Write several entries as controlfiles.
 
315
 
 
316
        :param files: A list of [(path, file)] pairs, where the path is the directory
 
317
                      underneath the bzr control directory
 
318
        :param encode:  If true, encode the contents as utf-8
 
319
        """
 
320
        import codecs
 
321
        ctrl_files = []
 
322
        for path, f in files:
 
323
            if encode:
 
324
                if isinstance(f, basestring):
 
325
                    f = f.encode('utf-8', 'replace')
 
326
                else:
 
327
                    f = codecs.getwriter('utf-8')(f, errors='replace')
 
328
            path = self._rel_controlfilename(path)
 
329
            ctrl_files.append((path, f))
 
330
        self._transport.put_multi(ctrl_files)
300
331
 
301
332
    def _make_control(self):
302
333
        from bzrlib.inventory import Inventory
303
 
        from bzrlib.xml import pack_xml
 
334
        from cStringIO import StringIO
304
335
        
305
 
        os.mkdir(self.controlfilename([]))
306
 
        self.controlfile('README', 'w').write(
 
336
        # Create an empty inventory
 
337
        sio = StringIO()
 
338
        # if we want per-tree root ids then this is the place to set
 
339
        # them; they're not needed for now and so ommitted for
 
340
        # simplicity.
 
341
        bzrlib.xml.serializer_v4.write_inventory(Inventory(), sio)
 
342
 
 
343
        dirs = [[], 'text-store', 'inventory-store', 'revision-store']
 
344
        files = [('README', 
307
345
            "This is a Bazaar-NG control directory.\n"
308
 
            "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'):
311
 
            os.mkdir(self.controlfilename(d))
312
 
        for f in ('revision-history', 'merged-patches',
313
 
                  'pending-merged-patches', 'branch-name',
314
 
                  'branch-lock',
315
 
                  'pending-merges'):
316
 
            self.controlfile(f, 'w').write('')
317
 
        mutter('created control directory in ' + self.base)
318
 
 
319
 
        pack_xml(Inventory(gen_root_id()), self.controlfile('inventory','w'))
320
 
 
 
346
            "Do not change any files in this directory.\n"),
 
347
            ('branch-format', BZR_BRANCH_FORMAT),
 
348
            ('revision-history', ''),
 
349
            ('merged-patches', ''),
 
350
            ('pending-merged-patches', ''),
 
351
            ('branch-name', ''),
 
352
            ('branch-lock', ''),
 
353
            ('pending-merges', ''),
 
354
            ('inventory', sio.getvalue())
 
355
        ]
 
356
        self._transport.mkdir_multi([self._rel_controlfilename(d) for d in dirs])
 
357
        self.put_controlfiles(files)
 
358
        mutter('created control directory in ' + self._transport.base)
321
359
 
322
360
    def _check_format(self):
323
361
        """Check this branch format is supported.
331
369
        # on Windows from Linux and so on.  I think it might be better
332
370
        # to always make all internal files in unix format.
333
371
        fmt = self.controlfile('branch-format', 'r').read()
334
 
        fmt.replace('\r\n', '')
 
372
        fmt = fmt.replace('\r\n', '\n')
335
373
        if fmt != BZR_BRANCH_FORMAT:
336
374
            raise BzrError('sorry, branch format %r not supported' % fmt,
337
375
                           ['use a different bzr version',
338
376
                            'or remove the .bzr directory and "bzr init" again'])
339
377
 
 
378
        # We know that the format is the currently supported one.
 
379
        # So create the rest of the entries.
 
380
        from bzrlib.store.compressed_text import CompressedTextStore
 
381
 
 
382
        if self._transport.should_cache():
 
383
            import tempfile
 
384
            self.cache_root = tempfile.mkdtemp(prefix='bzr-cache')
 
385
            mutter('Branch %r using caching in %r' % (self, self.cache_root))
 
386
        else:
 
387
            self.cache_root = None
 
388
 
 
389
        def get_store(name):
 
390
            relpath = self._rel_controlfilename(name)
 
391
            store = CompressedTextStore(self._transport.clone(relpath))
 
392
            if self._transport.should_cache():
 
393
                from meta_store import CachedStore
 
394
                cache_path = os.path.join(self.cache_root, name)
 
395
                os.mkdir(cache_path)
 
396
                store = CachedStore(store, cache_path)
 
397
            return store
 
398
 
 
399
        self.text_store = get_store('text-store')
 
400
        self.revision_store = get_store('revision-store')
 
401
        self.inventory_store = get_store('inventory-store')
 
402
 
340
403
    def get_root_id(self):
341
404
        """Return the id of this branches root"""
342
405
        inv = self.read_working_inventory()
357
420
    def read_working_inventory(self):
358
421
        """Read the working inventory."""
359
422
        from bzrlib.inventory import Inventory
360
 
        from bzrlib.xml import unpack_xml
361
 
        from time import time
362
 
        before = time()
363
423
        self.lock_read()
364
424
        try:
365
425
            # ElementTree does its own conversion from UTF-8, so open in
366
426
            # 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
 
427
            f = self.controlfile('inventory', 'rb')
 
428
            return bzrlib.xml.serializer_v4.read_inventory(f)
372
429
        finally:
373
430
            self.unlock()
374
431
            
379
436
        That is to say, the inventory describing changes underway, that
380
437
        will be committed to the next revision.
381
438
        """
382
 
        from bzrlib.atomicfile import AtomicFile
383
 
        from bzrlib.xml import pack_xml
384
 
        
 
439
        from cStringIO import StringIO
385
440
        self.lock_write()
386
441
        try:
387
 
            f = AtomicFile(self.controlfilename('inventory'), 'wb')
388
 
            try:
389
 
                pack_xml(inv, f)
390
 
                f.commit()
391
 
            finally:
392
 
                f.close()
 
442
            sio = StringIO()
 
443
            bzrlib.xml.serializer_v4.write_inventory(inv, sio)
 
444
            sio.seek(0)
 
445
            # Transport handles atomicity
 
446
            self.put_controlfile('inventory', sio)
393
447
        finally:
394
448
            self.unlock()
395
449
        
400
454
                         """Inventory for the working copy.""")
401
455
 
402
456
 
403
 
    def add(self, files, verbose=False, ids=None):
 
457
    def add(self, files, ids=None):
404
458
        """Make files versioned.
405
459
 
406
 
        Note that the command line normally calls smart_add instead.
 
460
        Note that the command line normally calls smart_add instead,
 
461
        which can automatically recurse.
407
462
 
408
463
        This puts the files in the Added state, so that they will be
409
464
        recorded by the next commit.
419
474
        TODO: Perhaps have an option to add the ids even if the files do
420
475
              not (yet) exist.
421
476
 
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.
 
477
        TODO: Perhaps yield the ids and paths as they're added.
428
478
        """
429
479
        # TODO: Re-adding a file that is removed in the working copy
430
480
        # should probably put it back with the previous ID.
466
516
                    file_id = gen_file_id(f)
467
517
                inv.add_path(f, kind=kind, file_id=file_id)
468
518
 
469
 
                if verbose:
470
 
                    print 'added', quotefn(f)
471
 
 
472
519
                mutter("add file %s file_id:{%s} kind=%r" % (f, file_id, kind))
473
520
 
474
521
            self._write_inventory(inv)
567
614
 
568
615
 
569
616
    def append_revision(self, *revision_ids):
570
 
        from bzrlib.atomicfile import AtomicFile
571
 
 
572
617
        for revision_id in revision_ids:
573
618
            mutter("add {%s} to revision-history" % revision_id)
574
619
 
575
620
        rev_history = self.revision_history()
576
621
        rev_history.extend(revision_ids)
577
622
 
578
 
        f = AtomicFile(self.controlfilename('revision-history'))
 
623
        self.lock_write()
579
624
        try:
580
 
            for rev_id in rev_history:
581
 
                print >>f, rev_id
582
 
            f.commit()
 
625
            self.put_controlfile('revision-history', '\n'.join(rev_history))
583
626
        finally:
584
 
            f.close()
585
 
 
586
 
 
587
 
    def get_revision_xml(self, revision_id):
 
627
            self.unlock()
 
628
 
 
629
 
 
630
    def get_revision_xml_file(self, revision_id):
588
631
        """Return XML file object for revision object."""
589
632
        if not revision_id or not isinstance(revision_id, basestring):
590
633
            raise InvalidRevisionId(revision_id)
593
636
        try:
594
637
            try:
595
638
                return self.revision_store[revision_id]
596
 
            except IndexError:
597
 
                raise bzrlib.errors.NoSuchRevision(revision_id)
 
639
            except (IndexError, KeyError):
 
640
                raise bzrlib.errors.NoSuchRevision(self, revision_id)
598
641
        finally:
599
642
            self.unlock()
600
643
 
601
644
 
 
645
    #deprecated
 
646
    get_revision_xml = get_revision_xml_file
 
647
 
 
648
 
602
649
    def get_revision(self, revision_id):
603
650
        """Return the Revision object for a named revision"""
604
 
        xml_file = self.get_revision_xml(revision_id)
 
651
        xml_file = self.get_revision_xml_file(revision_id)
605
652
 
606
653
        try:
607
 
            r = unpack_xml(Revision, xml_file)
 
654
            r = bzrlib.xml.serializer_v4.read_revision(xml_file)
608
655
        except SyntaxError, e:
609
656
            raise bzrlib.errors.BzrError('failed to unpack revision_xml',
610
657
                                         [revision_id,
636
683
        return compare_trees(old_tree, new_tree)
637
684
 
638
685
        
 
686
    def get_revisions(self, revision_ids, pb=None):
 
687
        """Return the Revision object for a set of named revisions"""
 
688
        from bzrlib.revision import Revision
 
689
        from bzrlib.xml import unpack_xml
639
690
 
 
691
        # TODO: We need to decide what to do here
 
692
        # we cannot use a generator with a try/finally, because
 
693
        # you cannot guarantee that the caller will iterate through
 
694
        # all entries.
 
695
        # in the past, get_inventory wasn't even wrapped in a
 
696
        # try/finally locking block.
 
697
        # We could either lock without the try/finally, or just
 
698
        # not lock at all. We are reading entries that should
 
699
        # never be updated.
 
700
        # I prefer locking with no finally, so that if someone
 
701
        # asks for a list of revisions, but doesn't consume them,
 
702
        # that is their problem, and they will suffer the consequences
 
703
        self.lock_read()
 
704
        for xml_file in self.revision_store.get(revision_ids, pb=pb):
 
705
            try:
 
706
                r = bzrlib.xml.serializer_v4.read_revision(xml_file)
 
707
            except SyntaxError, e:
 
708
                raise bzrlib.errors.BzrError('failed to unpack revision_xml',
 
709
                                             [revision_id,
 
710
                                              str(e)])
 
711
            yield r
 
712
        self.unlock()
 
713
            
640
714
    def get_revision_sha1(self, revision_id):
641
715
        """Hash the stored value of a revision, and return it."""
642
716
        # In the future, revision entries will be signed. At that
653
727
 
654
728
        TODO: Perhaps for this and similar methods, take a revision
655
729
               parameter which can be either an integer revno or a
656
 
               string hash."""
 
730
               string hash.
 
731
        """
 
732
        f = self.get_inventory_xml_file(inventory_id)
 
733
        return bzrlib.xml.serializer_v4.read_inventory(f)
 
734
 
 
735
 
 
736
    def get_inventory_xml(self, inventory_id):
 
737
        """Get inventory XML as a file object."""
 
738
        # Shouldn't this have a read-lock around it?
 
739
        # As well as some sort of trap for missing ids?
 
740
        return self.inventory_store[inventory_id]
 
741
 
 
742
    get_inventory_xml_file = get_inventory_xml
 
743
            
 
744
    def get_inventories(self, inventory_ids, pb=None, ignore_missing=False):
 
745
        """Get Inventory objects by id
 
746
        """
657
747
        from bzrlib.inventory import Inventory
658
 
        from bzrlib.xml import unpack_xml
659
748
 
660
 
        return unpack_xml(Inventory, self.inventory_store[inventory_id])
661
 
            
 
749
        # See the discussion in get_revisions for why
 
750
        # we don't use a try/finally block here
 
751
        self.lock_read()
 
752
        for f in self.inventory_store.get(inventory_ids, pb=pb, ignore_missing=ignore_missing):
 
753
            if f is not None:
 
754
                # TODO: Possibly put a try/except around this to handle
 
755
                # read serialization errors
 
756
                r = bzrlib.xml.serializer_v4.read_inventory(f)
 
757
                yield r
 
758
            elif ignore_missing:
 
759
                yield None
 
760
            else:
 
761
                raise bzrlib.errors.NoSuchRevision(self, revision_id)
 
762
        self.unlock()
662
763
 
663
764
    def get_inventory_sha1(self, inventory_id):
664
765
        """Return the sha1 hash of the inventory entry
665
766
        """
666
 
        return sha_file(self.inventory_store[inventory_id])
 
767
        return sha_file(self.get_inventory_xml(inventory_id))
667
768
 
668
769
 
669
770
    def get_revision_inventory(self, revision_id):
693
794
 
694
795
    def common_ancestor(self, other, self_revno=None, other_revno=None):
695
796
        """
696
 
        >>> import commit
 
797
        >>> from bzrlib.commit import commit
697
798
        >>> sb = ScratchBranch(files=['foo', 'foo~'])
698
799
        >>> sb.common_ancestor(sb) == (None, None)
699
800
        True
700
 
        >>> commit.commit(sb, "Committing first revision", verbose=False)
 
801
        >>> commit(sb, "Committing first revision", verbose=False)
701
802
        >>> sb.common_ancestor(sb)[0]
702
803
        1
703
804
        >>> clone = sb.clone()
704
 
        >>> commit.commit(sb, "Committing second revision", verbose=False)
 
805
        >>> commit(sb, "Committing second revision", verbose=False)
705
806
        >>> sb.common_ancestor(sb)[0]
706
807
        2
707
808
        >>> sb.common_ancestor(clone)[0]
708
809
        1
709
 
        >>> commit.commit(clone, "Committing divergent second revision", 
 
810
        >>> commit(clone, "Committing divergent second revision", 
710
811
        ...               verbose=False)
711
812
        >>> sb.common_ancestor(clone)[0]
712
813
        1
755
856
            return None
756
857
 
757
858
 
758
 
    def missing_revisions(self, other, stop_revision=None):
 
859
    def missing_revisions(self, other, stop_revision=None, diverged_ok=False):
759
860
        """
760
861
        If self and other have not diverged, return a list of the revisions
761
862
        present in other, but missing from self.
794
895
        if stop_revision is None:
795
896
            stop_revision = other_len
796
897
        elif stop_revision > other_len:
797
 
            raise NoSuchRevision(self, stop_revision)
 
898
            raise bzrlib.errors.NoSuchRevision(self, stop_revision)
798
899
        
799
900
        return other_history[self_len:stop_revision]
800
901
 
801
902
 
802
903
    def update_revisions(self, other, stop_revision=None):
803
904
        """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
905
        """
825
 
        from bzrlib.progress import ProgressBar
826
 
 
827
 
        pb = ProgressBar()
828
 
 
 
906
        from bzrlib.fetch import greedy_fetch
 
907
        from bzrlib.revision import get_intervening_revisions
 
908
 
 
909
        pb = bzrlib.ui.ui_factory.progress_bar()
829
910
        pb.update('comparing histories')
830
 
        revision_ids = self.missing_revisions(other, stop_revision)
831
 
 
 
911
        if stop_revision is None:
 
912
            other_revision = other.last_patch()
 
913
        else:
 
914
            other_revision = other.lookup_revision(stop_revision)
 
915
        count = greedy_fetch(self, other, other_revision, pb)[0]
 
916
        try:
 
917
            revision_ids = self.missing_revisions(other, stop_revision)
 
918
        except DivergedBranches, e:
 
919
            try:
 
920
                revision_ids = get_intervening_revisions(self.last_patch(), 
 
921
                                                         other_revision, self)
 
922
                assert self.last_patch() not in revision_ids
 
923
            except bzrlib.errors.NotAncestor:
 
924
                raise e
 
925
 
 
926
        self.append_revision(*revision_ids)
 
927
        pb.clear()
 
928
 
 
929
    def install_revisions(self, other, revision_ids, pb):
 
930
        # We are going to iterate this many times, so make sure
 
931
        # that it is a list, and not a generator
 
932
        revision_ids = list(revision_ids)
832
933
        if hasattr(other.revision_store, "prefetch"):
833
934
            other.revision_store.prefetch(revision_ids)
834
935
        if hasattr(other.inventory_store, "prefetch"):
835
 
            inventory_ids = [other.get_revision(r).inventory_id
836
 
                             for r in revision_ids]
837
936
            other.inventory_store.prefetch(inventory_ids)
 
937
 
 
938
        if pb is None:
 
939
            pb = bzrlib.ui.ui_factory.progress_bar()
838
940
                
839
 
        revisions = []
 
941
        # This entire next section is generally done
 
942
        # with either generators, or bulk updates
 
943
        inventories = other.get_inventories(revision_ids, ignore_missing=True)
840
944
        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))
 
945
 
 
946
        failures = set()
 
947
        good_revisions = set()
 
948
        for i, (inv, rev_id) in enumerate(zip(inventories, revision_ids)):
 
949
            pb.update('fetching revision', i+1, len(revision_ids))
 
950
 
 
951
            # We don't really need to get the revision here, because
 
952
            # the only thing we needed was the inventory_id, which now
 
953
            # is (by design) identical to the revision_id
 
954
            # try:
 
955
            #     rev = other.get_revision(rev_id)
 
956
            # except bzrlib.errors.NoSuchRevision:
 
957
            #     failures.add(rev_id)
 
958
            #     continue
 
959
 
 
960
            if inv is None:
 
961
                failures.add(rev_id)
 
962
                continue
 
963
            else:
 
964
                good_revisions.add(rev_id)
 
965
 
 
966
            text_ids = []
848
967
            for key, entry in inv.iter_entries():
849
968
                if entry.text_id is None:
850
969
                    continue
851
 
                if entry.text_id not in self.text_store:
852
 
                    needed_texts.add(entry.text_id)
 
970
                text_ids.append(entry.text_id)
 
971
 
 
972
            has_ids = self.text_store.has(text_ids)
 
973
            for has, text_id in zip(has_ids, text_ids):
 
974
                if not has:
 
975
                    needed_texts.add(text_id)
853
976
 
854
977
        pb.clear()
855
978
                    
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
 
        
 
979
        count, cp_fail = self.text_store.copy_multi(other.text_store, 
 
980
                                                    needed_texts)
 
981
        #print "Added %d texts." % count 
 
982
        count, cp_fail = self.inventory_store.copy_multi(other.inventory_store,
 
983
                                                         good_revisions)
 
984
        #print "Added %d inventories." % count 
 
985
        count, cp_fail = self.revision_store.copy_multi(other.revision_store, 
 
986
                                                          good_revisions,
 
987
                                                          permit_failure=True)
 
988
        assert len(cp_fail) == 0 
 
989
        return count, failures
 
990
       
 
991
 
870
992
    def commit(self, *args, **kw):
871
993
        from bzrlib.commit import commit
872
994
        commit(self, *args, **kw)
874
996
 
875
997
    def lookup_revision(self, revision):
876
998
        """Return the revision identifier for a given revision information."""
877
 
        revno, info = self.get_revision_info(revision)
 
999
        revno, info = self._get_revision_info(revision)
878
1000
        return info
879
1001
 
 
1002
 
 
1003
    def revision_id_to_revno(self, revision_id):
 
1004
        """Given a revision id, return its revno"""
 
1005
        history = self.revision_history()
 
1006
        try:
 
1007
            return history.index(revision_id) + 1
 
1008
        except ValueError:
 
1009
            raise bzrlib.errors.NoSuchRevision(self, revision_id)
 
1010
 
 
1011
 
880
1012
    def get_revision_info(self, revision):
881
1013
        """Return (revno, revision id) for revision identifier.
882
1014
 
885
1017
        revision can also be a string, in which case it is parsed for something like
886
1018
            'date:' or 'revid:' etc.
887
1019
        """
 
1020
        revno, rev_id = self._get_revision_info(revision)
 
1021
        if revno is None:
 
1022
            raise bzrlib.errors.NoSuchRevision(self, revision)
 
1023
        return revno, rev_id
 
1024
 
 
1025
    def get_rev_id(self, revno, history=None):
 
1026
        """Find the revision id of the specified revno."""
 
1027
        if revno == 0:
 
1028
            return None
 
1029
        if history is None:
 
1030
            history = self.revision_history()
 
1031
        elif revno <= 0 or revno > len(history):
 
1032
            raise bzrlib.errors.NoSuchRevision(self, revno)
 
1033
        return history[revno - 1]
 
1034
 
 
1035
    def _get_revision_info(self, revision):
 
1036
        """Return (revno, revision id) for revision specifier.
 
1037
 
 
1038
        revision can be an integer, in which case it is assumed to be revno
 
1039
        (though this will translate negative values into positive ones)
 
1040
        revision can also be a string, in which case it is parsed for something
 
1041
        like 'date:' or 'revid:' etc.
 
1042
 
 
1043
        A revid is always returned.  If it is None, the specifier referred to
 
1044
        the null revision.  If the revid does not occur in the revision
 
1045
        history, revno will be None.
 
1046
        """
 
1047
        
888
1048
        if revision is None:
889
1049
            return 0, None
890
1050
        revno = None
894
1054
            pass
895
1055
        revs = self.revision_history()
896
1056
        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
1057
            if revision < 0:
901
1058
                revno = len(revs) + revision + 1
902
1059
            else:
903
1060
                revno = revision
 
1061
            rev_id = self.get_rev_id(revno, revs)
904
1062
        elif isinstance(revision, basestring):
905
1063
            for prefix, func in Branch.REVISION_NAMESPACES.iteritems():
906
1064
                if revision.startswith(prefix):
907
 
                    revno = func(self, revs, revision)
 
1065
                    result = func(self, revs, revision)
 
1066
                    if len(result) > 1:
 
1067
                        revno, rev_id = result
 
1068
                    else:
 
1069
                        revno = result[0]
 
1070
                        rev_id = self.get_rev_id(revno, revs)
908
1071
                    break
909
1072
            else:
910
 
                raise BzrError('No namespace registered for string: %r' % revision)
 
1073
                raise BzrError('No namespace registered for string: %r' %
 
1074
                               revision)
 
1075
        else:
 
1076
            raise TypeError('Unhandled revision type %s' % revision)
911
1077
 
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]
 
1078
        if revno is None:
 
1079
            if rev_id is None:
 
1080
                raise bzrlib.errors.NoSuchRevision(self, revision)
 
1081
        return revno, rev_id
915
1082
 
916
1083
    def _namespace_revno(self, revs, revision):
917
1084
        """Lookup a revision by revision number"""
918
1085
        assert revision.startswith('revno:')
919
1086
        try:
920
 
            return int(revision[6:])
 
1087
            return (int(revision[6:]),)
921
1088
        except ValueError:
922
1089
            return None
923
1090
    REVISION_NAMESPACES['revno:'] = _namespace_revno
924
1091
 
925
1092
    def _namespace_revid(self, revs, revision):
926
1093
        assert revision.startswith('revid:')
 
1094
        rev_id = revision[len('revid:'):]
927
1095
        try:
928
 
            return revs.index(revision[6:]) + 1
 
1096
            return revs.index(rev_id) + 1, rev_id
929
1097
        except ValueError:
930
 
            return None
 
1098
            return None, rev_id
931
1099
    REVISION_NAMESPACES['revid:'] = _namespace_revid
932
1100
 
933
1101
    def _namespace_last(self, revs, revision):
935
1103
        try:
936
1104
            offset = int(revision[5:])
937
1105
        except ValueError:
938
 
            return None
 
1106
            return (None,)
939
1107
        else:
940
1108
            if offset <= 0:
941
1109
                raise BzrError('You must supply a positive value for --revision last:XXX')
942
 
            return len(revs) - offset + 1
 
1110
            return (len(revs) - offset + 1,)
943
1111
    REVISION_NAMESPACES['last:'] = _namespace_last
944
1112
 
945
1113
    def _namespace_tag(self, revs, revision):
1020
1188
                # TODO: Handle timezone.
1021
1189
                dt = datetime.datetime.fromtimestamp(r.timestamp)
1022
1190
                if first >= dt and (last is None or dt >= last):
1023
 
                    return i+1
 
1191
                    return (i+1,)
1024
1192
        else:
1025
1193
            for i in range(len(revs)):
1026
1194
                r = self.get_revision(revs[i])
1027
1195
                # TODO: Handle timezone.
1028
1196
                dt = datetime.datetime.fromtimestamp(r.timestamp)
1029
1197
                if first <= dt and (last is None or dt <= last):
1030
 
                    return i+1
 
1198
                    return (i+1,)
1031
1199
    REVISION_NAMESPACES['date:'] = _namespace_date
1032
1200
 
 
1201
 
 
1202
    def _namespace_ancestor(self, revs, revision):
 
1203
        from revision import common_ancestor, MultipleRevisionSources
 
1204
        other_branch = find_branch(_trim_namespace('ancestor', revision))
 
1205
        revision_a = self.last_patch()
 
1206
        revision_b = other_branch.last_patch()
 
1207
        for r, b in ((revision_a, self), (revision_b, other_branch)):
 
1208
            if r is None:
 
1209
                raise bzrlib.errors.NoCommits(b)
 
1210
        revision_source = MultipleRevisionSources(self, other_branch)
 
1211
        result = common_ancestor(revision_a, revision_b, revision_source)
 
1212
        try:
 
1213
            revno = self.revision_id_to_revno(result)
 
1214
        except bzrlib.errors.NoSuchRevision:
 
1215
            revno = None
 
1216
        return revno,result
 
1217
        
 
1218
 
 
1219
    REVISION_NAMESPACES['ancestor:'] = _namespace_ancestor
 
1220
 
1033
1221
    def revision_tree(self, revision_id):
1034
1222
        """Return Tree for a revision on this branch.
1035
1223
 
1046
1234
 
1047
1235
    def working_tree(self):
1048
1236
        """Return a `Tree` for the working copy."""
1049
 
        from workingtree import WorkingTree
1050
 
        return WorkingTree(self.base, self.read_working_inventory())
 
1237
        from bzrlib.workingtree import WorkingTree
 
1238
        # TODO: In the future, WorkingTree should utilize Transport
 
1239
        return WorkingTree(self._transport.base, self.read_working_inventory())
1051
1240
 
1052
1241
 
1053
1242
    def basis_tree(self):
1098
1287
 
1099
1288
            inv.rename(file_id, to_dir_id, to_tail)
1100
1289
 
1101
 
            print "%s => %s" % (from_rel, to_rel)
1102
 
 
1103
1290
            from_abs = self.abspath(from_rel)
1104
1291
            to_abs = self.abspath(to_rel)
1105
1292
            try:
1124
1311
 
1125
1312
        Note that to_name is only the last component of the new name;
1126
1313
        this doesn't change the directory.
 
1314
 
 
1315
        This returns a list of (from_path, to_path) pairs for each
 
1316
        entry that is moved.
1127
1317
        """
 
1318
        result = []
1128
1319
        self.lock_write()
1129
1320
        try:
1130
1321
            ## TODO: Option to move IDs only
1165
1356
            for f in from_paths:
1166
1357
                name_tail = splitpath(f)[-1]
1167
1358
                dest_path = appendpath(to_name, name_tail)
1168
 
                print "%s => %s" % (f, dest_path)
 
1359
                result.append((f, dest_path))
1169
1360
                inv.rename(inv.path2id(f), to_dir_id, name_tail)
1170
1361
                try:
1171
1362
                    os.rename(self.abspath(f), self.abspath(dest_path))
1177
1368
        finally:
1178
1369
            self.unlock()
1179
1370
 
 
1371
        return result
 
1372
 
1180
1373
 
1181
1374
    def revert(self, filenames, old_tree=None, backups=True):
1182
1375
        """Restore selected files to the versions from a previous tree.
1228
1421
        These are revisions that have been merged into the working
1229
1422
        directory but not yet committed.
1230
1423
        """
1231
 
        cfn = self.controlfilename('pending-merges')
1232
 
        if not os.path.exists(cfn):
 
1424
        cfn = self._rel_controlfilename('pending-merges')
 
1425
        if not self._transport.has(cfn):
1233
1426
            return []
1234
1427
        p = []
1235
1428
        for l in self.controlfile('pending-merges', 'r').readlines():
1237
1430
        return p
1238
1431
 
1239
1432
 
1240
 
    def add_pending_merge(self, revision_id):
 
1433
    def add_pending_merge(self, *revision_ids):
1241
1434
        from bzrlib.revision import validate_revision_id
1242
1435
 
1243
 
        validate_revision_id(revision_id)
 
1436
        for rev_id in revision_ids:
 
1437
            validate_revision_id(rev_id)
1244
1438
 
1245
1439
        p = self.pending_merges()
1246
 
        if revision_id in p:
1247
 
            return
1248
 
        p.append(revision_id)
1249
 
        self.set_pending_merges(p)
1250
 
 
 
1440
        updated = False
 
1441
        for rev_id in revision_ids:
 
1442
            if rev_id in p:
 
1443
                continue
 
1444
            p.append(rev_id)
 
1445
            updated = True
 
1446
        if updated:
 
1447
            self.set_pending_merges(p)
1251
1448
 
1252
1449
    def set_pending_merges(self, rev_list):
 
1450
        self.lock_write()
 
1451
        try:
 
1452
            self.put_controlfile('pending-merges', '\n'.join(rev_list))
 
1453
        finally:
 
1454
            self.unlock()
 
1455
 
 
1456
 
 
1457
    def get_parent(self):
 
1458
        """Return the parent location of the branch.
 
1459
 
 
1460
        This is the default location for push/pull/missing.  The usual
 
1461
        pattern is that the user can override it by specifying a
 
1462
        location.
 
1463
        """
 
1464
        import errno
 
1465
        _locs = ['parent', 'pull', 'x-pull']
 
1466
        for l in _locs:
 
1467
            try:
 
1468
                return self.controlfile(l, 'r').read().strip('\n')
 
1469
            except IOError, e:
 
1470
                if e.errno != errno.ENOENT:
 
1471
                    raise
 
1472
        return None
 
1473
 
 
1474
 
 
1475
    def set_parent(self, url):
 
1476
        # TODO: Maybe delete old location files?
1253
1477
        from bzrlib.atomicfile import AtomicFile
1254
1478
        self.lock_write()
1255
1479
        try:
1256
 
            f = AtomicFile(self.controlfilename('pending-merges'))
 
1480
            f = AtomicFile(self.controlfilename('parent'))
1257
1481
            try:
1258
 
                for l in rev_list:
1259
 
                    print >>f, l
 
1482
                f.write(url + '\n')
1260
1483
                f.commit()
1261
1484
            finally:
1262
1485
                f.close()
1263
1486
        finally:
1264
1487
            self.unlock()
1265
1488
 
 
1489
    def check_revno(self, revno):
 
1490
        """\
 
1491
        Check whether a revno corresponds to any revision.
 
1492
        Zero (the NULL revision) is considered valid.
 
1493
        """
 
1494
        if revno != 0:
 
1495
            self.check_real_revno(revno)
 
1496
            
 
1497
    def check_real_revno(self, revno):
 
1498
        """\
 
1499
        Check whether a revno corresponds to a real revision.
 
1500
        Zero (the NULL revision) is considered invalid
 
1501
        """
 
1502
        if revno < 1 or revno > self.revno():
 
1503
            raise InvalidRevisionNumber(revno)
 
1504
        
 
1505
        
1266
1506
 
1267
1507
 
1268
1508
class ScratchBranch(Branch):
1290
1530
            init = True
1291
1531
        Branch.__init__(self, base, init=init)
1292
1532
        for d in dirs:
1293
 
            os.mkdir(self.abspath(d))
 
1533
            self._transport.mkdir(d)
1294
1534
            
1295
1535
        for f in files:
1296
 
            file(os.path.join(self.base, f), 'w').write('content of %s' % f)
 
1536
            self._transport.put(f, 'content of %s' % f)
1297
1537
 
1298
1538
 
1299
1539
    def clone(self):
1311
1551
        os.rmdir(base)
1312
1552
        copytree(self.base, base, symlinks=True)
1313
1553
        return ScratchBranch(base=base)
 
1554
 
 
1555
 
1314
1556
        
1315
1557
    def __del__(self):
1316
1558
        self.destroy()
1330
1572
                for name in files:
1331
1573
                    os.chmod(os.path.join(root, name), 0700)
1332
1574
            rmtree(self.base)
1333
 
        self.base = None
 
1575
        self._transport = None
1334
1576
 
1335
1577
    
1336
1578
 
1386
1628
    """Return a new tree-root file id."""
1387
1629
    return gen_file_id('TREE_ROOT')
1388
1630
 
 
1631
 
 
1632
def copy_branch(branch_from, to_location, revision=None):
 
1633
    """Copy branch_from into the existing directory to_location.
 
1634
 
 
1635
    revision
 
1636
        If not None, only revisions up to this point will be copied.
 
1637
        The head of the new branch will be that revision.
 
1638
 
 
1639
    to_location
 
1640
        The name of a local directory that exists but is empty.
 
1641
    """
 
1642
    from bzrlib.merge import merge
 
1643
 
 
1644
    assert isinstance(branch_from, Branch)
 
1645
    assert isinstance(to_location, basestring)
 
1646
    
 
1647
    br_to = Branch(to_location, init=True)
 
1648
    br_to.set_root_id(branch_from.get_root_id())
 
1649
    if revision is None:
 
1650
        revno = branch_from.revno()
 
1651
    else:
 
1652
        revno, rev_id = branch_from.get_revision_info(revision)
 
1653
    br_to.update_revisions(branch_from, stop_revision=revno)
 
1654
    merge((to_location, -1), (to_location, 0), this_dir=to_location,
 
1655
          check_clean=False, ignore_zero=True)
 
1656
    br_to.set_parent(branch_from.base)
 
1657
    return br_to
 
1658
 
 
1659
def _trim_namespace(namespace, spec):
 
1660
    full_namespace = namespace + ':'
 
1661
    assert spec.startswith(full_namespace)
 
1662
    return spec[len(full_namespace):]