/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: Martin Pool
  • Date: 2005-09-22 06:54:01 UTC
  • Revision ID: mbp@sourcefrog.net-20050922065401-6694b0f910701fca
- try to avoid redundant conversion of strings when retrieving from weaves

Show diffs side-by-side

added added

removed removed

Lines of Context:
17
17
 
18
18
import sys
19
19
import os
 
20
from cStringIO import StringIO
20
21
 
21
22
import bzrlib
22
23
from bzrlib.trace import mutter, note
23
24
from bzrlib.osutils import isdir, quotefn, compact_date, rand_bytes, \
24
25
     splitpath, \
25
26
     sha_file, appendpath, file_kind
26
 
from bzrlib.errors import BzrError, InvalidRevisionNumber, InvalidRevisionId
27
 
import bzrlib.errors
 
27
 
 
28
from bzrlib.errors import (BzrError, InvalidRevisionNumber, InvalidRevisionId,
 
29
                           NoSuchRevision, HistoryMissing, NotBranchError,
 
30
                           LockError)
28
31
from bzrlib.textui import show_status
29
 
from bzrlib.revision import Revision
30
 
from bzrlib.xml import unpack_xml
 
32
from bzrlib.revision import Revision, validate_revision_id
31
33
from bzrlib.delta import compare_trees
32
34
from bzrlib.tree import EmptyTree, RevisionTree
33
 
        
34
 
BZR_BRANCH_FORMAT = "Bazaar-NG branch, format 0.0.4\n"
 
35
from bzrlib.inventory import Inventory
 
36
from bzrlib.weavestore import WeaveStore
 
37
from bzrlib.store import ImmutableStore
 
38
import bzrlib.xml5
 
39
import bzrlib.ui
 
40
 
 
41
 
 
42
BZR_BRANCH_FORMAT_4 = "Bazaar-NG branch, format 0.0.4\n"
 
43
BZR_BRANCH_FORMAT_5 = "Bazaar-NG branch, format 5\n"
35
44
## TODO: Maybe include checks for common corruption of newlines, etc?
36
45
 
37
46
 
38
47
# TODO: Some operations like log might retrieve the same revisions
39
48
# repeatedly to calculate deltas.  We could perhaps have a weakref
40
 
# cache in memory to make this faster.
 
49
# cache in memory to make this faster.  In general anything can be
 
50
# cached in memory between lock and unlock operations.
 
51
 
 
52
# TODO: please move the revision-string syntax stuff out of the branch
 
53
# object; it's clutter
41
54
 
42
55
 
43
56
def find_branch(f, **args):
87
100
        if tail:
88
101
            s.insert(0, tail)
89
102
    else:
90
 
        from errors import NotBranchError
91
103
        raise NotBranchError("path %r is not within branch %r" % (rp, base))
92
104
 
93
105
    return os.sep.join(s)
101
113
    It is not necessary that f exists.
102
114
 
103
115
    Basically we keep looking up until we find the control directory or
104
 
    run into the root."""
 
116
    run into the root.  If there isn't one, raises NotBranchError.
 
117
    """
105
118
    if f == None:
106
119
        f = os.getcwd()
107
120
    elif hasattr(os.path, 'realpath'):
120
133
        head, tail = os.path.split(f)
121
134
        if head == f:
122
135
            # reached the root, whatever that may be
123
 
            raise BzrError('%r is not in a branch' % orig_f)
 
136
            raise NotBranchError('%s is not in a branch' % orig_f)
124
137
        f = head
125
 
    
 
138
 
 
139
 
 
140
 
 
141
# XXX: move into bzrlib.errors; subclass BzrError    
126
142
class DivergedBranches(Exception):
127
143
    def __init__(self, branch1, branch2):
128
144
        self.branch1 = branch1
153
169
    _lock_mode = None
154
170
    _lock_count = None
155
171
    _lock = None
 
172
    _inventory_weave = None
156
173
    
157
174
    # Map some sort of prefix into a namespace
158
175
    # stuff like "revno:10", "revid:", etc.
159
176
    # This should match a prefix with a function which accepts
160
177
    REVISION_NAMESPACES = {}
161
178
 
162
 
    def __init__(self, base, init=False, find_root=True):
 
179
    def __init__(self, base, init=False, find_root=True,
 
180
                 relax_version_check=False):
163
181
        """Create new branch object at a particular location.
164
182
 
165
183
        base -- Base directory for the branch.
171
189
        find_root -- If true and init is false, find the root of the
172
190
             existing branch containing base.
173
191
 
 
192
        relax_version_check -- If true, the usual check for the branch
 
193
            version is not applied.  This is intended only for
 
194
            upgrade/recovery type use; it's not guaranteed that
 
195
            all operations will work on old format branches.
 
196
 
174
197
        In the test suite, creation of new trees is tested using the
175
198
        `ScratchBranch` class.
176
199
        """
177
 
        from bzrlib.store import ImmutableStore
178
200
        if init:
179
201
            self.base = os.path.realpath(base)
180
202
            self._make_control()
183
205
        else:
184
206
            self.base = os.path.realpath(base)
185
207
            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'))
 
208
                raise NotBranchError('not a bzr branch: %s' % quotefn(base),
 
209
                                     ['use "bzr init" to initialize a '
 
210
                                      'new working tree'])
 
211
        self._check_format(relax_version_check)
 
212
        cfn = self.controlfilename
 
213
        if self._branch_format == 4:
 
214
            self.inventory_store = ImmutableStore(cfn('inventory-store'))
 
215
            self.text_store = ImmutableStore(cfn('text-store'))
 
216
        elif self._branch_format == 5:
 
217
            self.control_weaves = WeaveStore(cfn([]))
 
218
            self.weave_store = WeaveStore(cfn('weaves'))
 
219
        self.revision_store = ImmutableStore(cfn('revision-store'))
195
220
 
196
221
 
197
222
    def __str__(self):
208
233
            self._lock.unlock()
209
234
 
210
235
 
211
 
 
212
236
    def lock_write(self):
213
237
        if self._lock_mode:
214
238
            if self._lock_mode != 'w':
215
 
                from errors import LockError
216
239
                raise LockError("can't upgrade to a write lock from %r" %
217
240
                                self._lock_mode)
218
241
            self._lock_count += 1
224
247
            self._lock_count = 1
225
248
 
226
249
 
227
 
 
228
250
    def lock_read(self):
229
251
        if self._lock_mode:
230
252
            assert self._lock_mode in ('r', 'w'), \
237
259
            self._lock_mode = 'r'
238
260
            self._lock_count = 1
239
261
                        
240
 
 
241
 
            
242
262
    def unlock(self):
243
263
        if not self._lock_mode:
244
 
            from errors import LockError
245
264
            raise LockError('branch %r is not locked' % (self))
246
265
 
247
266
        if self._lock_count > 1:
251
270
            self._lock = None
252
271
            self._lock_mode = self._lock_count = None
253
272
 
254
 
 
255
273
    def abspath(self, name):
256
274
        """Return absolute filename for something in the branch"""
257
275
        return os.path.join(self.base, name)
258
276
 
259
 
 
260
277
    def relpath(self, path):
261
278
        """Return path relative to this branch of something inside it.
262
279
 
263
280
        Raises an error if path is not in this branch."""
264
281
        return _relpath(self.base, path)
265
282
 
266
 
 
267
283
    def controlfilename(self, file_or_path):
268
284
        """Return location relative to branch."""
269
285
        if isinstance(file_or_path, basestring):
296
312
        else:
297
313
            raise BzrError("invalid controlfile mode %r" % mode)
298
314
 
299
 
 
300
 
 
301
315
    def _make_control(self):
302
 
        from bzrlib.inventory import Inventory
303
 
        from bzrlib.xml import pack_xml
304
 
        
305
316
        os.mkdir(self.controlfilename([]))
306
317
        self.controlfile('README', 'w').write(
307
318
            "This is a Bazaar-NG control directory.\n"
308
319
            "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'):
 
320
        self.controlfile('branch-format', 'w').write(BZR_BRANCH_FORMAT_5)
 
321
        for d in ('text-store', 'revision-store',
 
322
                  'weaves'):
311
323
            os.mkdir(self.controlfilename(d))
312
 
        for f in ('revision-history', 'merged-patches',
313
 
                  'pending-merged-patches', 'branch-name',
 
324
        for f in ('revision-history',
 
325
                  'branch-name',
314
326
                  'branch-lock',
315
327
                  'pending-merges'):
316
328
            self.controlfile(f, 'w').write('')
317
329
        mutter('created control directory in ' + self.base)
318
330
 
319
 
        pack_xml(Inventory(gen_root_id()), self.controlfile('inventory','w'))
320
 
 
321
 
 
322
 
    def _check_format(self):
 
331
        # if we want per-tree root ids then this is the place to set
 
332
        # them; they're not needed for now and so ommitted for
 
333
        # simplicity.
 
334
        f = self.controlfile('inventory','w')
 
335
        bzrlib.xml5.serializer_v5.write_inventory(Inventory(), f)
 
336
        
 
337
 
 
338
 
 
339
    def _check_format(self, relax_version_check):
323
340
        """Check this branch format is supported.
324
341
 
325
 
        The current tool only supports the current unstable format.
 
342
        The format level is stored, as an integer, in
 
343
        self._branch_format for code that needs to check it later.
326
344
 
327
345
        In the future, we might need different in-memory Branch
328
346
        classes to support downlevel branches.  But not yet.
329
347
        """
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
348
        fmt = self.controlfile('branch-format', 'r').read()
334
 
        fmt.replace('\r\n', '')
335
 
        if fmt != BZR_BRANCH_FORMAT:
336
 
            raise BzrError('sorry, branch format %r not supported' % fmt,
337
 
                           ['use a different bzr version',
338
 
                            'or remove the .bzr directory and "bzr init" again'])
 
349
        if fmt == BZR_BRANCH_FORMAT_5:
 
350
            self._branch_format = 5
 
351
        elif fmt == BZR_BRANCH_FORMAT_4:
 
352
            self._branch_format = 4
 
353
 
 
354
        if (not relax_version_check
 
355
            and self._branch_format != 5):
 
356
            raise BzrError('sorry, branch format "%s" not supported; ' 
 
357
                           'use a different bzr version, '
 
358
                           'or run "bzr upgrade"'
 
359
                           % fmt.rstrip('\n\r'))
 
360
        
339
361
 
340
362
    def get_root_id(self):
341
363
        """Return the id of this branches root"""
356
378
 
357
379
    def read_working_inventory(self):
358
380
        """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
381
        self.lock_read()
364
382
        try:
365
383
            # ElementTree does its own conversion from UTF-8, so open in
366
384
            # 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
 
385
            f = self.controlfile('inventory', 'rb')
 
386
            return bzrlib.xml5.serializer_v5.read_inventory(f)
372
387
        finally:
373
388
            self.unlock()
374
389
            
380
395
        will be committed to the next revision.
381
396
        """
382
397
        from bzrlib.atomicfile import AtomicFile
383
 
        from bzrlib.xml import pack_xml
384
398
        
385
399
        self.lock_write()
386
400
        try:
387
401
            f = AtomicFile(self.controlfilename('inventory'), 'wb')
388
402
            try:
389
 
                pack_xml(inv, f)
 
403
                bzrlib.xml5.serializer_v5.write_inventory(inv, f)
390
404
                f.commit()
391
405
            finally:
392
406
                f.close()
400
414
                         """Inventory for the working copy.""")
401
415
 
402
416
 
403
 
    def add(self, files, verbose=False, ids=None):
 
417
    def add(self, files, ids=None):
404
418
        """Make files versioned.
405
419
 
406
 
        Note that the command line normally calls smart_add instead.
 
420
        Note that the command line normally calls smart_add instead,
 
421
        which can automatically recurse.
407
422
 
408
423
        This puts the files in the Added state, so that they will be
409
424
        recorded by the next commit.
419
434
        TODO: Perhaps have an option to add the ids even if the files do
420
435
              not (yet) exist.
421
436
 
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.
 
437
        TODO: Perhaps yield the ids and paths as they're added.
428
438
        """
429
439
        # TODO: Re-adding a file that is removed in the working copy
430
440
        # should probably put it back with the previous ID.
466
476
                    file_id = gen_file_id(f)
467
477
                inv.add_path(f, kind=kind, file_id=file_id)
468
478
 
469
 
                if verbose:
470
 
                    print 'added', quotefn(f)
471
 
 
472
479
                mutter("add file %s file_id:{%s} kind=%r" % (f, file_id, kind))
473
480
 
474
481
            self._write_inventory(inv)
584
591
            f.close()
585
592
 
586
593
 
587
 
    def get_revision_xml(self, revision_id):
 
594
    def has_revision(self, revision_id):
 
595
        """True if this branch has a copy of the revision.
 
596
 
 
597
        This does not necessarily imply the revision is merge
 
598
        or on the mainline."""
 
599
        return revision_id in self.revision_store
 
600
 
 
601
 
 
602
    def get_revision_xml_file(self, revision_id):
588
603
        """Return XML file object for revision object."""
589
604
        if not revision_id or not isinstance(revision_id, basestring):
590
605
            raise InvalidRevisionId(revision_id)
594
609
            try:
595
610
                return self.revision_store[revision_id]
596
611
            except IndexError:
597
 
                raise bzrlib.errors.NoSuchRevision(revision_id)
 
612
                raise bzrlib.errors.NoSuchRevision(self, revision_id)
598
613
        finally:
599
614
            self.unlock()
600
615
 
601
616
 
 
617
    def get_revision_xml(self, revision_id):
 
618
        return self.get_revision_xml_file(revision_id).read()
 
619
 
 
620
 
602
621
    def get_revision(self, revision_id):
603
622
        """Return the Revision object for a named revision"""
604
 
        xml_file = self.get_revision_xml(revision_id)
 
623
        xml_file = self.get_revision_xml_file(revision_id)
605
624
 
606
625
        try:
607
 
            r = unpack_xml(Revision, xml_file)
 
626
            r = bzrlib.xml5.serializer_v5.read_revision(xml_file)
608
627
        except SyntaxError, e:
609
628
            raise bzrlib.errors.BzrError('failed to unpack revision_xml',
610
629
                                         [revision_id,
639
658
 
640
659
    def get_revision_sha1(self, revision_id):
641
660
        """Hash the stored value of a revision, and return it."""
642
 
        # In the future, revision entries will be signed. At that
643
 
        # point, it is probably best *not* to include the signature
644
 
        # in the revision hash. Because that lets you re-sign
645
 
        # the revision, (add signatures/remove signatures) and still
646
 
        # have all hash pointers stay consistent.
647
 
        # 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):
 
661
        return bzrlib.osutils.sha_file(self.get_revision_xml_file(revision_id))
 
662
 
 
663
 
 
664
    def _get_ancestry_weave(self):
 
665
        return self.control_weaves.get_weave('ancestry')
 
666
        
 
667
 
 
668
    def get_ancestry(self, revision_id):
 
669
        """Return a list of revision-ids integrated by a revision.
 
670
        """
 
671
        # strip newlines
 
672
        w = self._get_ancestry_weave()
 
673
        return [l[:-1] for l in w.get_iter(w.lookup(revision_id))]
 
674
 
 
675
 
 
676
    def get_inventory_weave(self):
 
677
        return self.control_weaves.get_weave('inventory')
 
678
 
 
679
 
 
680
    def get_inventory(self, revision_id):
 
681
        """Get Inventory object by hash."""
 
682
        # FIXME: The text gets passed around a lot coming from the weave.
 
683
        f = StringIO(self.get_inventory_xml(revision_id))
 
684
        return bzrlib.xml5.serializer_v5.read_inventory(f)
 
685
 
 
686
 
 
687
    def get_inventory_xml(self, revision_id):
 
688
        """Get inventory XML as a file object."""
 
689
        try:
 
690
            assert isinstance(revision_id, basestring), type(revision_id)
 
691
            iw = self.get_inventory_weave()
 
692
            return iw.get_text(iw.lookup(revision_id))
 
693
        except IndexError:
 
694
            raise bzrlib.errors.HistoryMissing(self, 'inventory', revision_id)
 
695
 
 
696
 
 
697
    def get_inventory_sha1(self, revision_id):
664
698
        """Return the sha1 hash of the inventory entry
665
699
        """
666
 
        return sha_file(self.inventory_store[inventory_id])
 
700
        return self.get_revision(revision_id).inventory_sha1
667
701
 
668
702
 
669
703
    def get_revision_inventory(self, revision_id):
670
704
        """Return inventory of a past revision."""
671
 
        # bzr 0.0.6 imposes the constraint that the inventory_id
 
705
        # bzr 0.0.6 and later imposes the constraint that the inventory_id
672
706
        # must be the same as its revision, so this is trivial.
673
707
        if revision_id == None:
674
 
            from bzrlib.inventory import Inventory
675
708
            return Inventory(self.get_root_id())
676
709
        else:
677
710
            return self.get_inventory(revision_id)
678
711
 
679
712
 
680
713
    def revision_history(self):
681
 
        """Return sequence of revision hashes on to this branch.
682
 
 
683
 
        >>> ScratchBranch().revision_history()
684
 
        []
685
 
        """
 
714
        """Return sequence of revision hashes on to this branch."""
686
715
        self.lock_read()
687
716
        try:
688
717
            return [l.rstrip('\r\n') for l in
697
726
        >>> sb = ScratchBranch(files=['foo', 'foo~'])
698
727
        >>> sb.common_ancestor(sb) == (None, None)
699
728
        True
700
 
        >>> commit.commit(sb, "Committing first revision", verbose=False)
 
729
        >>> commit.commit(sb, "Committing first revision")
701
730
        >>> sb.common_ancestor(sb)[0]
702
731
        1
703
732
        >>> clone = sb.clone()
704
 
        >>> commit.commit(sb, "Committing second revision", verbose=False)
 
733
        >>> commit.commit(sb, "Committing second revision")
705
734
        >>> sb.common_ancestor(sb)[0]
706
735
        2
707
736
        >>> sb.common_ancestor(clone)[0]
708
737
        1
709
 
        >>> commit.commit(clone, "Committing divergent second revision", 
710
 
        ...               verbose=False)
 
738
        >>> commit.commit(clone, "Committing divergent second revision")
711
739
        >>> sb.common_ancestor(clone)[0]
712
740
        1
713
741
        >>> sb.common_ancestor(clone) == clone.common_ancestor(sb)
745
773
        return len(self.revision_history())
746
774
 
747
775
 
748
 
    def last_patch(self):
 
776
    def last_revision(self):
749
777
        """Return last patch hash, or None if no history.
750
778
        """
751
779
        ph = self.revision_history()
755
783
            return None
756
784
 
757
785
 
758
 
    def missing_revisions(self, other, stop_revision=None):
759
 
        """
 
786
    def missing_revisions(self, other, stop_revision=None, diverged_ok=False):
 
787
        """Return a list of new revisions that would perfectly fit.
 
788
        
760
789
        If self and other have not diverged, return a list of the revisions
761
790
        present in other, but missing from self.
762
791
 
782
811
        Traceback (most recent call last):
783
812
        DivergedBranches: These branches have diverged.
784
813
        """
 
814
        # FIXME: If the branches have diverged, but the latest
 
815
        # revision in this branch is completely merged into the other,
 
816
        # then we should still be able to pull.
785
817
        self_history = self.revision_history()
786
818
        self_len = len(self_history)
787
819
        other_history = other.revision_history()
793
825
 
794
826
        if stop_revision is None:
795
827
            stop_revision = other_len
796
 
        elif stop_revision > other_len:
797
 
            raise NoSuchRevision(self, stop_revision)
 
828
        else:
 
829
            assert isinstance(stop_revision, int)
 
830
            if stop_revision > other_len:
 
831
                raise bzrlib.errors.NoSuchRevision(self, stop_revision)
798
832
        
799
833
        return other_history[self_len:stop_revision]
800
834
 
801
835
 
802
 
    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
 
836
    def update_revisions(self, other, stop_revno=None):
 
837
        """Pull in new perfect-fit revisions.
824
838
        """
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
 
        
 
839
        from bzrlib.fetch import greedy_fetch
 
840
 
 
841
        if stop_revno:
 
842
            stop_revision = other.lookup_revision(stop_revno)
 
843
        else:
 
844
            stop_revision = None
 
845
        greedy_fetch(to_branch=self, from_branch=other,
 
846
                     revision=stop_revision)
 
847
 
 
848
        pullable_revs = self.missing_revisions(other, stop_revision)
 
849
 
 
850
        if pullable_revs:
 
851
            greedy_fetch(to_branch=self,
 
852
                         from_branch=other,
 
853
                         revision=pullable_revs[-1])
 
854
            self.append_revision(*pullable_revs)
 
855
 
 
856
 
870
857
    def commit(self, *args, **kw):
871
 
        from bzrlib.commit import commit
872
 
        commit(self, *args, **kw)
 
858
        from bzrlib.commit import Commit
 
859
        Commit().commit(self, *args, **kw)
873
860
        
874
861
 
875
862
    def lookup_revision(self, revision):
876
863
        """Return the revision identifier for a given revision information."""
877
 
        revno, info = self.get_revision_info(revision)
 
864
        revno, info = self._get_revision_info(revision)
878
865
        return info
879
866
 
 
867
 
 
868
    def revision_id_to_revno(self, revision_id):
 
869
        """Given a revision id, return its revno"""
 
870
        history = self.revision_history()
 
871
        try:
 
872
            return history.index(revision_id) + 1
 
873
        except ValueError:
 
874
            raise bzrlib.errors.NoSuchRevision(self, revision_id)
 
875
 
 
876
 
880
877
    def get_revision_info(self, revision):
881
878
        """Return (revno, revision id) for revision identifier.
882
879
 
885
882
        revision can also be a string, in which case it is parsed for something like
886
883
            'date:' or 'revid:' etc.
887
884
        """
 
885
        revno, rev_id = self._get_revision_info(revision)
 
886
        if revno is None:
 
887
            raise bzrlib.errors.NoSuchRevision(self, revision)
 
888
        return revno, rev_id
 
889
 
 
890
    def get_rev_id(self, revno, history=None):
 
891
        """Find the revision id of the specified revno."""
 
892
        if revno == 0:
 
893
            return None
 
894
        if history is None:
 
895
            history = self.revision_history()
 
896
        elif revno <= 0 or revno > len(history):
 
897
            raise bzrlib.errors.NoSuchRevision(self, revno)
 
898
        return history[revno - 1]
 
899
 
 
900
    def _get_revision_info(self, revision):
 
901
        """Return (revno, revision id) for revision specifier.
 
902
 
 
903
        revision can be an integer, in which case it is assumed to be revno
 
904
        (though this will translate negative values into positive ones)
 
905
        revision can also be a string, in which case it is parsed for something
 
906
        like 'date:' or 'revid:' etc.
 
907
 
 
908
        A revid is always returned.  If it is None, the specifier referred to
 
909
        the null revision.  If the revid does not occur in the revision
 
910
        history, revno will be None.
 
911
        """
 
912
        
888
913
        if revision is None:
889
914
            return 0, None
890
915
        revno = None
894
919
            pass
895
920
        revs = self.revision_history()
896
921
        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
922
            if revision < 0:
901
923
                revno = len(revs) + revision + 1
902
924
            else:
903
925
                revno = revision
 
926
            rev_id = self.get_rev_id(revno, revs)
904
927
        elif isinstance(revision, basestring):
905
928
            for prefix, func in Branch.REVISION_NAMESPACES.iteritems():
906
929
                if revision.startswith(prefix):
907
 
                    revno = func(self, revs, revision)
 
930
                    result = func(self, revs, revision)
 
931
                    if len(result) > 1:
 
932
                        revno, rev_id = result
 
933
                    else:
 
934
                        revno = result[0]
 
935
                        rev_id = self.get_rev_id(revno, revs)
908
936
                    break
909
937
            else:
910
 
                raise BzrError('No namespace registered for string: %r' % revision)
 
938
                raise BzrError('No namespace registered for string: %r' %
 
939
                               revision)
 
940
        else:
 
941
            raise TypeError('Unhandled revision type %s' % revision)
911
942
 
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]
 
943
        if revno is None:
 
944
            if rev_id is None:
 
945
                raise bzrlib.errors.NoSuchRevision(self, revision)
 
946
        return revno, rev_id
915
947
 
916
948
    def _namespace_revno(self, revs, revision):
917
949
        """Lookup a revision by revision number"""
918
950
        assert revision.startswith('revno:')
919
951
        try:
920
 
            return int(revision[6:])
 
952
            return (int(revision[6:]),)
921
953
        except ValueError:
922
954
            return None
923
955
    REVISION_NAMESPACES['revno:'] = _namespace_revno
924
956
 
925
957
    def _namespace_revid(self, revs, revision):
926
958
        assert revision.startswith('revid:')
 
959
        rev_id = revision[len('revid:'):]
927
960
        try:
928
 
            return revs.index(revision[6:]) + 1
 
961
            return revs.index(rev_id) + 1, rev_id
929
962
        except ValueError:
930
 
            return None
 
963
            return None, rev_id
931
964
    REVISION_NAMESPACES['revid:'] = _namespace_revid
932
965
 
933
966
    def _namespace_last(self, revs, revision):
935
968
        try:
936
969
            offset = int(revision[5:])
937
970
        except ValueError:
938
 
            return None
 
971
            return (None,)
939
972
        else:
940
973
            if offset <= 0:
941
974
                raise BzrError('You must supply a positive value for --revision last:XXX')
942
 
            return len(revs) - offset + 1
 
975
            return (len(revs) - offset + 1,)
943
976
    REVISION_NAMESPACES['last:'] = _namespace_last
944
977
 
945
978
    def _namespace_tag(self, revs, revision):
1020
1053
                # TODO: Handle timezone.
1021
1054
                dt = datetime.datetime.fromtimestamp(r.timestamp)
1022
1055
                if first >= dt and (last is None or dt >= last):
1023
 
                    return i+1
 
1056
                    return (i+1,)
1024
1057
        else:
1025
1058
            for i in range(len(revs)):
1026
1059
                r = self.get_revision(revs[i])
1027
1060
                # TODO: Handle timezone.
1028
1061
                dt = datetime.datetime.fromtimestamp(r.timestamp)
1029
1062
                if first <= dt and (last is None or dt <= last):
1030
 
                    return i+1
 
1063
                    return (i+1,)
1031
1064
    REVISION_NAMESPACES['date:'] = _namespace_date
1032
1065
 
1033
1066
    def revision_tree(self, revision_id):
1041
1074
            return EmptyTree()
1042
1075
        else:
1043
1076
            inv = self.get_revision_inventory(revision_id)
1044
 
            return RevisionTree(self.text_store, inv)
 
1077
            return RevisionTree(self.weave_store, inv, revision_id)
1045
1078
 
1046
1079
 
1047
1080
    def working_tree(self):
1055
1088
 
1056
1089
        If there are no revisions yet, return an `EmptyTree`.
1057
1090
        """
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
 
 
 
1091
        return self.revision_tree(self.last_revision())
1064
1092
 
1065
1093
 
1066
1094
    def rename_one(self, from_rel, to_rel):
1098
1126
 
1099
1127
            inv.rename(file_id, to_dir_id, to_tail)
1100
1128
 
1101
 
            print "%s => %s" % (from_rel, to_rel)
1102
 
 
1103
1129
            from_abs = self.abspath(from_rel)
1104
1130
            to_abs = self.abspath(to_rel)
1105
1131
            try:
1124
1150
 
1125
1151
        Note that to_name is only the last component of the new name;
1126
1152
        this doesn't change the directory.
 
1153
 
 
1154
        This returns a list of (from_path, to_path) pairs for each
 
1155
        entry that is moved.
1127
1156
        """
 
1157
        result = []
1128
1158
        self.lock_write()
1129
1159
        try:
1130
1160
            ## TODO: Option to move IDs only
1165
1195
            for f in from_paths:
1166
1196
                name_tail = splitpath(f)[-1]
1167
1197
                dest_path = appendpath(to_name, name_tail)
1168
 
                print "%s => %s" % (f, dest_path)
 
1198
                result.append((f, dest_path))
1169
1199
                inv.rename(inv.path2id(f), to_dir_id, name_tail)
1170
1200
                try:
1171
1201
                    os.rename(self.abspath(f), self.abspath(dest_path))
1177
1207
        finally:
1178
1208
            self.unlock()
1179
1209
 
 
1210
        return result
 
1211
 
1180
1212
 
1181
1213
    def revert(self, filenames, old_tree=None, backups=True):
1182
1214
        """Restore selected files to the versions from a previous tree.
1238
1270
 
1239
1271
 
1240
1272
    def add_pending_merge(self, revision_id):
1241
 
        from bzrlib.revision import validate_revision_id
1242
 
 
1243
1273
        validate_revision_id(revision_id)
1244
 
 
 
1274
        # TODO: Perhaps should check at this point that the
 
1275
        # history of the revision is actually present?
1245
1276
        p = self.pending_merges()
1246
1277
        if revision_id in p:
1247
1278
            return
1264
1295
            self.unlock()
1265
1296
 
1266
1297
 
 
1298
    def get_parent(self):
 
1299
        """Return the parent location of the branch.
 
1300
 
 
1301
        This is the default location for push/pull/missing.  The usual
 
1302
        pattern is that the user can override it by specifying a
 
1303
        location.
 
1304
        """
 
1305
        import errno
 
1306
        _locs = ['parent', 'pull', 'x-pull']
 
1307
        for l in _locs:
 
1308
            try:
 
1309
                return self.controlfile(l, 'r').read().strip('\n')
 
1310
            except IOError, e:
 
1311
                if e.errno != errno.ENOENT:
 
1312
                    raise
 
1313
        return None
 
1314
 
 
1315
 
 
1316
    def set_parent(self, url):
 
1317
        # TODO: Maybe delete old location files?
 
1318
        from bzrlib.atomicfile import AtomicFile
 
1319
        self.lock_write()
 
1320
        try:
 
1321
            f = AtomicFile(self.controlfilename('parent'))
 
1322
            try:
 
1323
                f.write(url + '\n')
 
1324
                f.commit()
 
1325
            finally:
 
1326
                f.close()
 
1327
        finally:
 
1328
            self.unlock()
 
1329
 
 
1330
    def check_revno(self, revno):
 
1331
        """\
 
1332
        Check whether a revno corresponds to any revision.
 
1333
        Zero (the NULL revision) is considered valid.
 
1334
        """
 
1335
        if revno != 0:
 
1336
            self.check_real_revno(revno)
 
1337
            
 
1338
    def check_real_revno(self, revno):
 
1339
        """\
 
1340
        Check whether a revno corresponds to a real revision.
 
1341
        Zero (the NULL revision) is considered invalid
 
1342
        """
 
1343
        if revno < 1 or revno > self.revno():
 
1344
            raise InvalidRevisionNumber(revno)
 
1345
        
 
1346
        
 
1347
 
1267
1348
 
1268
1349
class ScratchBranch(Branch):
1269
1350
    """Special test class: a branch that cleans up after itself.
1311
1392
        os.rmdir(base)
1312
1393
        copytree(self.base, base, symlinks=True)
1313
1394
        return ScratchBranch(base=base)
 
1395
 
 
1396
 
1314
1397
        
1315
1398
    def __del__(self):
1316
1399
        self.destroy()
1386
1469
    """Return a new tree-root file id."""
1387
1470
    return gen_file_id('TREE_ROOT')
1388
1471
 
 
1472
 
 
1473
def pull_loc(branch):
 
1474
    # TODO: Should perhaps just make attribute be 'base' in
 
1475
    # RemoteBranch and Branch?
 
1476
    if hasattr(branch, "baseurl"):
 
1477
        return branch.baseurl
 
1478
    else:
 
1479
        return branch.base
 
1480
 
 
1481
 
 
1482
def copy_branch(branch_from, to_location, revision=None):
 
1483
    """Copy branch_from into the existing directory to_location.
 
1484
 
 
1485
    revision
 
1486
        If not None, only revisions up to this point will be copied.
 
1487
        The head of the new branch will be that revision.  Can be a
 
1488
        revno or revid.
 
1489
 
 
1490
    to_location
 
1491
        The name of a local directory that exists but is empty.
 
1492
    """
 
1493
    # TODO: This could be done *much* more efficiently by just copying
 
1494
    # all the whole weaves and revisions, rather than getting one
 
1495
    # revision at a time.
 
1496
    from bzrlib.merge import merge
 
1497
    from bzrlib.branch import Branch
 
1498
 
 
1499
    assert isinstance(branch_from, Branch)
 
1500
    assert isinstance(to_location, basestring)
 
1501
    
 
1502
    br_to = Branch(to_location, init=True)
 
1503
    br_to.set_root_id(branch_from.get_root_id())
 
1504
    if revision is None:
 
1505
        revno = None
 
1506
    else:
 
1507
        revno, rev_id = branch_from.get_revision_info(revision)
 
1508
    br_to.update_revisions(branch_from, stop_revno=revno)
 
1509
    merge((to_location, -1), (to_location, 0), this_dir=to_location,
 
1510
          check_clean=False, ignore_zero=True)
 
1511
    
 
1512
    from_location = pull_loc(branch_from)
 
1513
    br_to.set_parent(pull_loc(branch_from))
 
1514