/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 12:12:53 UTC
  • Revision ID: mbp@sourcefrog.net-20050922121253-eae2a3240ea5e493
- upgrade can no longer be done in current version branches
  so don't test it

Show diffs side-by-side

added added

removed removed

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