/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-16 09:43:55 UTC
  • Revision ID: mbp@sourcefrog.net-20050916094355-d1a3d0aebe303f28
- rename entry_version to name_version
  (a better description since it covers the name and path)

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