/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 06:52:59 UTC
  • Revision ID: mbp@sourcefrog.net-20050916065259-714aeb37c2510699
- remove another test that tries to merge an imaginary parent

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)
28
30
from bzrlib.textui import show_status
29
 
from bzrlib.revision import Revision
30
 
from bzrlib.xml import unpack_xml
 
31
from bzrlib.revision import Revision, validate_revision_id
31
32
from bzrlib.delta import compare_trees
32
33
from bzrlib.tree import EmptyTree, RevisionTree
33
 
        
34
 
BZR_BRANCH_FORMAT = "Bazaar-NG branch, format 0.0.4\n"
 
34
from bzrlib.inventory import Inventory
 
35
from bzrlib.weavestore import WeaveStore
 
36
from bzrlib.store import ImmutableStore
 
37
import bzrlib.xml5
 
38
import bzrlib.ui
 
39
 
 
40
 
 
41
INVENTORY_FILEID = '__inventory'
 
42
ANCESTRY_FILEID = '__ancestry'
 
43
 
 
44
 
 
45
BZR_BRANCH_FORMAT_4 = "Bazaar-NG branch, format 0.0.4\n"
 
46
BZR_BRANCH_FORMAT_5 = "Bazaar-NG branch, format 5\n"
35
47
## TODO: Maybe include checks for common corruption of newlines, etc?
36
48
 
37
49
 
38
50
# TODO: Some operations like log might retrieve the same revisions
39
51
# repeatedly to calculate deltas.  We could perhaps have a weakref
40
 
# cache in memory to make this faster.
 
52
# cache in memory to make this faster.  In general anything can be
 
53
# cached in memory between lock and unlock operations.
 
54
 
 
55
# TODO: please move the revision-string syntax stuff out of the branch
 
56
# object; it's clutter
41
57
 
42
58
 
43
59
def find_branch(f, **args):
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 bzrlib.errors.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.
174
195
        In the test suite, creation of new trees is tested using the
175
196
        `ScratchBranch` class.
176
197
        """
177
 
        from bzrlib.store import ImmutableStore
178
198
        if init:
179
199
            self.base = os.path.realpath(base)
180
200
            self._make_control()
189
209
                                      'current bzr can only operate from top-of-tree'])
190
210
        self._check_format()
191
211
 
192
 
        self.text_store = ImmutableStore(self.controlfilename('text-store'))
 
212
        self.weave_store = WeaveStore(self.controlfilename('weaves'))
193
213
        self.revision_store = ImmutableStore(self.controlfilename('revision-store'))
194
 
        self.inventory_store = ImmutableStore(self.controlfilename('inventory-store'))
195
214
 
196
215
 
197
216
    def __str__(self):
208
227
            self._lock.unlock()
209
228
 
210
229
 
211
 
 
212
230
    def lock_write(self):
213
231
        if self._lock_mode:
214
232
            if self._lock_mode != 'w':
224
242
            self._lock_count = 1
225
243
 
226
244
 
227
 
 
228
245
    def lock_read(self):
229
246
        if self._lock_mode:
230
247
            assert self._lock_mode in ('r', 'w'), \
237
254
            self._lock_mode = 'r'
238
255
            self._lock_count = 1
239
256
                        
240
 
 
241
 
            
242
257
    def unlock(self):
243
258
        if not self._lock_mode:
244
259
            from errors import LockError
251
266
            self._lock = None
252
267
            self._lock_mode = self._lock_count = None
253
268
 
254
 
 
255
269
    def abspath(self, name):
256
270
        """Return absolute filename for something in the branch"""
257
271
        return os.path.join(self.base, name)
258
272
 
259
 
 
260
273
    def relpath(self, path):
261
274
        """Return path relative to this branch of something inside it.
262
275
 
263
276
        Raises an error if path is not in this branch."""
264
277
        return _relpath(self.base, path)
265
278
 
266
 
 
267
279
    def controlfilename(self, file_or_path):
268
280
        """Return location relative to branch."""
269
281
        if isinstance(file_or_path, basestring):
296
308
        else:
297
309
            raise BzrError("invalid controlfile mode %r" % mode)
298
310
 
299
 
 
300
 
 
301
311
    def _make_control(self):
302
 
        from bzrlib.inventory import Inventory
303
 
        from bzrlib.xml import pack_xml
304
 
        
305
312
        os.mkdir(self.controlfilename([]))
306
313
        self.controlfile('README', 'w').write(
307
314
            "This is a Bazaar-NG control directory.\n"
308
315
            "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'):
 
316
        self.controlfile('branch-format', 'w').write(BZR_BRANCH_FORMAT_5)
 
317
        for d in ('text-store', 'revision-store',
 
318
                  'weaves'):
311
319
            os.mkdir(self.controlfilename(d))
312
320
        for f in ('revision-history', 'merged-patches',
313
321
                  'pending-merged-patches', 'branch-name',
316
324
            self.controlfile(f, 'w').write('')
317
325
        mutter('created control directory in ' + self.base)
318
326
 
319
 
        pack_xml(Inventory(gen_root_id()), self.controlfile('inventory','w'))
 
327
        # if we want per-tree root ids then this is the place to set
 
328
        # them; they're not needed for now and so ommitted for
 
329
        # simplicity.
 
330
        f = self.controlfile('inventory','w')
 
331
        bzrlib.xml5.serializer_v5.write_inventory(Inventory(), f)
 
332
        
320
333
 
321
334
 
322
335
    def _check_format(self):
323
336
        """Check this branch format is supported.
324
337
 
325
 
        The current tool only supports the current unstable format.
 
338
        The format level is stored, as an integer, in
 
339
        self._branch_format for code that needs to check it later.
326
340
 
327
341
        In the future, we might need different in-memory Branch
328
342
        classes to support downlevel branches.  But not yet.
329
343
        """
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
344
        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'])
 
345
        if fmt == BZR_BRANCH_FORMAT_5:
 
346
            self._branch_format = 5
 
347
        else:
 
348
            raise BzrError('sorry, branch format "%s" not supported; ' 
 
349
                           'use a different bzr version, '
 
350
                           'or run "bzr upgrade", '
 
351
                           'or remove the .bzr directory and "bzr init" again'
 
352
                           % fmt.rstrip('\n\r'))
339
353
 
340
354
    def get_root_id(self):
341
355
        """Return the id of this branches root"""
356
370
 
357
371
    def read_working_inventory(self):
358
372
        """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
373
        self.lock_read()
364
374
        try:
365
375
            # ElementTree does its own conversion from UTF-8, so open in
366
376
            # 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
 
377
            f = self.controlfile('inventory', 'rb')
 
378
            return bzrlib.xml5.serializer_v5.read_inventory(f)
372
379
        finally:
373
380
            self.unlock()
374
381
            
380
387
        will be committed to the next revision.
381
388
        """
382
389
        from bzrlib.atomicfile import AtomicFile
383
 
        from bzrlib.xml import pack_xml
384
390
        
385
391
        self.lock_write()
386
392
        try:
387
393
            f = AtomicFile(self.controlfilename('inventory'), 'wb')
388
394
            try:
389
 
                pack_xml(inv, f)
 
395
                bzrlib.xml5.serializer_v5.write_inventory(inv, f)
390
396
                f.commit()
391
397
            finally:
392
398
                f.close()
400
406
                         """Inventory for the working copy.""")
401
407
 
402
408
 
403
 
    def add(self, files, verbose=False, ids=None):
 
409
    def add(self, files, ids=None):
404
410
        """Make files versioned.
405
411
 
406
 
        Note that the command line normally calls smart_add instead.
 
412
        Note that the command line normally calls smart_add instead,
 
413
        which can automatically recurse.
407
414
 
408
415
        This puts the files in the Added state, so that they will be
409
416
        recorded by the next commit.
419
426
        TODO: Perhaps have an option to add the ids even if the files do
420
427
              not (yet) exist.
421
428
 
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.
 
429
        TODO: Perhaps yield the ids and paths as they're added.
428
430
        """
429
431
        # TODO: Re-adding a file that is removed in the working copy
430
432
        # should probably put it back with the previous ID.
466
468
                    file_id = gen_file_id(f)
467
469
                inv.add_path(f, kind=kind, file_id=file_id)
468
470
 
469
 
                if verbose:
470
 
                    print 'added', quotefn(f)
471
 
 
472
471
                mutter("add file %s file_id:{%s} kind=%r" % (f, file_id, kind))
473
472
 
474
473
            self._write_inventory(inv)
584
583
            f.close()
585
584
 
586
585
 
587
 
    def get_revision_xml(self, revision_id):
 
586
    def has_revision(self, revision_id):
 
587
        """True if this branch has a copy of the revision.
 
588
 
 
589
        This does not necessarily imply the revision is merge
 
590
        or on the mainline."""
 
591
        return revision_id in self.revision_store
 
592
 
 
593
 
 
594
    def get_revision_xml_file(self, revision_id):
588
595
        """Return XML file object for revision object."""
589
596
        if not revision_id or not isinstance(revision_id, basestring):
590
597
            raise InvalidRevisionId(revision_id)
594
601
            try:
595
602
                return self.revision_store[revision_id]
596
603
            except IndexError:
597
 
                raise bzrlib.errors.NoSuchRevision(revision_id)
 
604
                raise bzrlib.errors.NoSuchRevision(self, revision_id)
598
605
        finally:
599
606
            self.unlock()
600
607
 
601
608
 
 
609
    def get_revision_xml(self, revision_id):
 
610
        return self.get_revision_xml_file(revision_id).read()
 
611
 
 
612
 
602
613
    def get_revision(self, revision_id):
603
614
        """Return the Revision object for a named revision"""
604
 
        xml_file = self.get_revision_xml(revision_id)
 
615
        xml_file = self.get_revision_xml_file(revision_id)
605
616
 
606
617
        try:
607
 
            r = unpack_xml(Revision, xml_file)
 
618
            r = bzrlib.xml5.serializer_v5.read_revision(xml_file)
608
619
        except SyntaxError, e:
609
620
            raise bzrlib.errors.BzrError('failed to unpack revision_xml',
610
621
                                         [revision_id,
639
650
 
640
651
    def get_revision_sha1(self, revision_id):
641
652
        """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):
 
653
        return bzrlib.osutils.sha_file(self.get_revision_xml_file(revision_id))
 
654
 
 
655
 
 
656
    def get_ancestry(self, revision_id):
 
657
        """Return a list of revision-ids integrated by a revision.
 
658
        """
 
659
        w = self.weave_store.get_weave(ANCESTRY_FILEID)
 
660
        # strip newlines
 
661
        return [l[:-1] for l in w.get_iter(w.lookup(revision_id))]
 
662
 
 
663
 
 
664
    def get_inventory_weave(self):
 
665
        return self.weave_store.get_weave(INVENTORY_FILEID)
 
666
 
 
667
 
 
668
    def get_inventory(self, revision_id):
 
669
        """Get Inventory object by hash."""
 
670
        # FIXME: The text gets passed around a lot coming from the weave.
 
671
        f = StringIO(self.get_inventory_xml(revision_id))
 
672
        return bzrlib.xml5.serializer_v5.read_inventory(f)
 
673
 
 
674
 
 
675
    def get_inventory_xml(self, revision_id):
 
676
        """Get inventory XML as a file object."""
 
677
        try:
 
678
            assert isinstance(revision_id, basestring), type(revision_id)
 
679
            iw = self.get_inventory_weave()
 
680
            return iw.get_text(iw.lookup(revision_id))
 
681
        except IndexError:
 
682
            raise bzrlib.errors.HistoryMissing(self, 'inventory', revision_id)
 
683
 
 
684
 
 
685
    def get_inventory_sha1(self, revision_id):
664
686
        """Return the sha1 hash of the inventory entry
665
687
        """
666
 
        return sha_file(self.inventory_store[inventory_id])
 
688
        return self.get_revision(revision_id).inventory_sha1
667
689
 
668
690
 
669
691
    def get_revision_inventory(self, revision_id):
670
692
        """Return inventory of a past revision."""
671
 
        # bzr 0.0.6 imposes the constraint that the inventory_id
 
693
        # bzr 0.0.6 and later imposes the constraint that the inventory_id
672
694
        # must be the same as its revision, so this is trivial.
673
695
        if revision_id == None:
674
 
            from bzrlib.inventory import Inventory
675
696
            return Inventory(self.get_root_id())
676
697
        else:
677
698
            return self.get_inventory(revision_id)
697
718
        >>> sb = ScratchBranch(files=['foo', 'foo~'])
698
719
        >>> sb.common_ancestor(sb) == (None, None)
699
720
        True
700
 
        >>> commit.commit(sb, "Committing first revision", verbose=False)
 
721
        >>> commit.commit(sb, "Committing first revision")
701
722
        >>> sb.common_ancestor(sb)[0]
702
723
        1
703
724
        >>> clone = sb.clone()
704
 
        >>> commit.commit(sb, "Committing second revision", verbose=False)
 
725
        >>> commit.commit(sb, "Committing second revision")
705
726
        >>> sb.common_ancestor(sb)[0]
706
727
        2
707
728
        >>> sb.common_ancestor(clone)[0]
708
729
        1
709
 
        >>> commit.commit(clone, "Committing divergent second revision", 
710
 
        ...               verbose=False)
 
730
        >>> commit.commit(clone, "Committing divergent second revision")
711
731
        >>> sb.common_ancestor(clone)[0]
712
732
        1
713
733
        >>> sb.common_ancestor(clone) == clone.common_ancestor(sb)
745
765
        return len(self.revision_history())
746
766
 
747
767
 
748
 
    def last_patch(self):
 
768
    def last_revision(self):
749
769
        """Return last patch hash, or None if no history.
750
770
        """
751
771
        ph = self.revision_history()
755
775
            return None
756
776
 
757
777
 
758
 
    def missing_revisions(self, other, stop_revision=None):
759
 
        """
 
778
    def missing_revisions(self, other, stop_revision=None, diverged_ok=False):
 
779
        """Return a list of new revisions that would perfectly fit.
 
780
        
760
781
        If self and other have not diverged, return a list of the revisions
761
782
        present in other, but missing from self.
762
783
 
782
803
        Traceback (most recent call last):
783
804
        DivergedBranches: These branches have diverged.
784
805
        """
 
806
        # FIXME: If the branches have diverged, but the latest
 
807
        # revision in this branch is completely merged into the other,
 
808
        # then we should still be able to pull.
785
809
        self_history = self.revision_history()
786
810
        self_len = len(self_history)
787
811
        other_history = other.revision_history()
793
817
 
794
818
        if stop_revision is None:
795
819
            stop_revision = other_len
796
 
        elif stop_revision > other_len:
797
 
            raise NoSuchRevision(self, stop_revision)
 
820
        else:
 
821
            assert isinstance(stop_revision, int)
 
822
            if stop_revision > other_len:
 
823
                raise bzrlib.errors.NoSuchRevision(self, stop_revision)
798
824
        
799
825
        return other_history[self_len:stop_revision]
800
826
 
801
827
 
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
 
828
    def update_revisions(self, other, stop_revno=None):
 
829
        """Pull in new perfect-fit revisions.
824
830
        """
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
 
        
 
831
        from bzrlib.fetch import greedy_fetch
 
832
 
 
833
        if stop_revno:
 
834
            stop_revision = other.lookup_revision(stop_revno)
 
835
        else:
 
836
            stop_revision = None
 
837
        greedy_fetch(to_branch=self, from_branch=other,
 
838
                     revision=stop_revision)
 
839
 
 
840
        pullable_revs = self.missing_revisions(other, stop_revision)
 
841
 
 
842
        if pullable_revs:
 
843
            greedy_fetch(to_branch=self,
 
844
                         from_branch=other,
 
845
                         revision=pullable_revs[-1])
 
846
            self.append_revision(*pullable_revs)
 
847
 
 
848
 
870
849
    def commit(self, *args, **kw):
871
 
        from bzrlib.commit import commit
872
 
        commit(self, *args, **kw)
 
850
        from bzrlib.commit import Commit
 
851
        Commit().commit(self, *args, **kw)
873
852
        
874
853
 
875
854
    def lookup_revision(self, revision):
876
855
        """Return the revision identifier for a given revision information."""
877
 
        revno, info = self.get_revision_info(revision)
 
856
        revno, info = self._get_revision_info(revision)
878
857
        return info
879
858
 
 
859
 
 
860
    def revision_id_to_revno(self, revision_id):
 
861
        """Given a revision id, return its revno"""
 
862
        history = self.revision_history()
 
863
        try:
 
864
            return history.index(revision_id) + 1
 
865
        except ValueError:
 
866
            raise bzrlib.errors.NoSuchRevision(self, revision_id)
 
867
 
 
868
 
880
869
    def get_revision_info(self, revision):
881
870
        """Return (revno, revision id) for revision identifier.
882
871
 
885
874
        revision can also be a string, in which case it is parsed for something like
886
875
            'date:' or 'revid:' etc.
887
876
        """
 
877
        revno, rev_id = self._get_revision_info(revision)
 
878
        if revno is None:
 
879
            raise bzrlib.errors.NoSuchRevision(self, revision)
 
880
        return revno, rev_id
 
881
 
 
882
    def get_rev_id(self, revno, history=None):
 
883
        """Find the revision id of the specified revno."""
 
884
        if revno == 0:
 
885
            return None
 
886
        if history is None:
 
887
            history = self.revision_history()
 
888
        elif revno <= 0 or revno > len(history):
 
889
            raise bzrlib.errors.NoSuchRevision(self, revno)
 
890
        return history[revno - 1]
 
891
 
 
892
    def _get_revision_info(self, revision):
 
893
        """Return (revno, revision id) for revision specifier.
 
894
 
 
895
        revision can be an integer, in which case it is assumed to be revno
 
896
        (though this will translate negative values into positive ones)
 
897
        revision can also be a string, in which case it is parsed for something
 
898
        like 'date:' or 'revid:' etc.
 
899
 
 
900
        A revid is always returned.  If it is None, the specifier referred to
 
901
        the null revision.  If the revid does not occur in the revision
 
902
        history, revno will be None.
 
903
        """
 
904
        
888
905
        if revision is None:
889
906
            return 0, None
890
907
        revno = None
894
911
            pass
895
912
        revs = self.revision_history()
896
913
        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
914
            if revision < 0:
901
915
                revno = len(revs) + revision + 1
902
916
            else:
903
917
                revno = revision
 
918
            rev_id = self.get_rev_id(revno, revs)
904
919
        elif isinstance(revision, basestring):
905
920
            for prefix, func in Branch.REVISION_NAMESPACES.iteritems():
906
921
                if revision.startswith(prefix):
907
 
                    revno = func(self, revs, revision)
 
922
                    result = func(self, revs, revision)
 
923
                    if len(result) > 1:
 
924
                        revno, rev_id = result
 
925
                    else:
 
926
                        revno = result[0]
 
927
                        rev_id = self.get_rev_id(revno, revs)
908
928
                    break
909
929
            else:
910
 
                raise BzrError('No namespace registered for string: %r' % revision)
 
930
                raise BzrError('No namespace registered for string: %r' %
 
931
                               revision)
 
932
        else:
 
933
            raise TypeError('Unhandled revision type %s' % revision)
911
934
 
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]
 
935
        if revno is None:
 
936
            if rev_id is None:
 
937
                raise bzrlib.errors.NoSuchRevision(self, revision)
 
938
        return revno, rev_id
915
939
 
916
940
    def _namespace_revno(self, revs, revision):
917
941
        """Lookup a revision by revision number"""
918
942
        assert revision.startswith('revno:')
919
943
        try:
920
 
            return int(revision[6:])
 
944
            return (int(revision[6:]),)
921
945
        except ValueError:
922
946
            return None
923
947
    REVISION_NAMESPACES['revno:'] = _namespace_revno
924
948
 
925
949
    def _namespace_revid(self, revs, revision):
926
950
        assert revision.startswith('revid:')
 
951
        rev_id = revision[len('revid:'):]
927
952
        try:
928
 
            return revs.index(revision[6:]) + 1
 
953
            return revs.index(rev_id) + 1, rev_id
929
954
        except ValueError:
930
 
            return None
 
955
            return None, rev_id
931
956
    REVISION_NAMESPACES['revid:'] = _namespace_revid
932
957
 
933
958
    def _namespace_last(self, revs, revision):
935
960
        try:
936
961
            offset = int(revision[5:])
937
962
        except ValueError:
938
 
            return None
 
963
            return (None,)
939
964
        else:
940
965
            if offset <= 0:
941
966
                raise BzrError('You must supply a positive value for --revision last:XXX')
942
 
            return len(revs) - offset + 1
 
967
            return (len(revs) - offset + 1,)
943
968
    REVISION_NAMESPACES['last:'] = _namespace_last
944
969
 
945
970
    def _namespace_tag(self, revs, revision):
1020
1045
                # TODO: Handle timezone.
1021
1046
                dt = datetime.datetime.fromtimestamp(r.timestamp)
1022
1047
                if first >= dt and (last is None or dt >= last):
1023
 
                    return i+1
 
1048
                    return (i+1,)
1024
1049
        else:
1025
1050
            for i in range(len(revs)):
1026
1051
                r = self.get_revision(revs[i])
1027
1052
                # TODO: Handle timezone.
1028
1053
                dt = datetime.datetime.fromtimestamp(r.timestamp)
1029
1054
                if first <= dt and (last is None or dt <= last):
1030
 
                    return i+1
 
1055
                    return (i+1,)
1031
1056
    REVISION_NAMESPACES['date:'] = _namespace_date
1032
1057
 
1033
1058
    def revision_tree(self, revision_id):
1041
1066
            return EmptyTree()
1042
1067
        else:
1043
1068
            inv = self.get_revision_inventory(revision_id)
1044
 
            return RevisionTree(self.text_store, inv)
 
1069
            return RevisionTree(self.weave_store, inv, revision_id)
1045
1070
 
1046
1071
 
1047
1072
    def working_tree(self):
1055
1080
 
1056
1081
        If there are no revisions yet, return an `EmptyTree`.
1057
1082
        """
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
 
 
 
1083
        return self.revision_tree(self.last_revision())
1064
1084
 
1065
1085
 
1066
1086
    def rename_one(self, from_rel, to_rel):
1098
1118
 
1099
1119
            inv.rename(file_id, to_dir_id, to_tail)
1100
1120
 
1101
 
            print "%s => %s" % (from_rel, to_rel)
1102
 
 
1103
1121
            from_abs = self.abspath(from_rel)
1104
1122
            to_abs = self.abspath(to_rel)
1105
1123
            try:
1124
1142
 
1125
1143
        Note that to_name is only the last component of the new name;
1126
1144
        this doesn't change the directory.
 
1145
 
 
1146
        This returns a list of (from_path, to_path) pairs for each
 
1147
        entry that is moved.
1127
1148
        """
 
1149
        result = []
1128
1150
        self.lock_write()
1129
1151
        try:
1130
1152
            ## TODO: Option to move IDs only
1165
1187
            for f in from_paths:
1166
1188
                name_tail = splitpath(f)[-1]
1167
1189
                dest_path = appendpath(to_name, name_tail)
1168
 
                print "%s => %s" % (f, dest_path)
 
1190
                result.append((f, dest_path))
1169
1191
                inv.rename(inv.path2id(f), to_dir_id, name_tail)
1170
1192
                try:
1171
1193
                    os.rename(self.abspath(f), self.abspath(dest_path))
1177
1199
        finally:
1178
1200
            self.unlock()
1179
1201
 
 
1202
        return result
 
1203
 
1180
1204
 
1181
1205
    def revert(self, filenames, old_tree=None, backups=True):
1182
1206
        """Restore selected files to the versions from a previous tree.
1238
1262
 
1239
1263
 
1240
1264
    def add_pending_merge(self, revision_id):
1241
 
        from bzrlib.revision import validate_revision_id
1242
 
 
1243
1265
        validate_revision_id(revision_id)
1244
 
 
 
1266
        # TODO: Perhaps should check at this point that the
 
1267
        # history of the revision is actually present?
1245
1268
        p = self.pending_merges()
1246
1269
        if revision_id in p:
1247
1270
            return
1264
1287
            self.unlock()
1265
1288
 
1266
1289
 
 
1290
    def get_parent(self):
 
1291
        """Return the parent location of the branch.
 
1292
 
 
1293
        This is the default location for push/pull/missing.  The usual
 
1294
        pattern is that the user can override it by specifying a
 
1295
        location.
 
1296
        """
 
1297
        import errno
 
1298
        _locs = ['parent', 'pull', 'x-pull']
 
1299
        for l in _locs:
 
1300
            try:
 
1301
                return self.controlfile(l, 'r').read().strip('\n')
 
1302
            except IOError, e:
 
1303
                if e.errno != errno.ENOENT:
 
1304
                    raise
 
1305
        return None
 
1306
 
 
1307
 
 
1308
    def set_parent(self, url):
 
1309
        # TODO: Maybe delete old location files?
 
1310
        from bzrlib.atomicfile import AtomicFile
 
1311
        self.lock_write()
 
1312
        try:
 
1313
            f = AtomicFile(self.controlfilename('parent'))
 
1314
            try:
 
1315
                f.write(url + '\n')
 
1316
                f.commit()
 
1317
            finally:
 
1318
                f.close()
 
1319
        finally:
 
1320
            self.unlock()
 
1321
 
 
1322
    def check_revno(self, revno):
 
1323
        """\
 
1324
        Check whether a revno corresponds to any revision.
 
1325
        Zero (the NULL revision) is considered valid.
 
1326
        """
 
1327
        if revno != 0:
 
1328
            self.check_real_revno(revno)
 
1329
            
 
1330
    def check_real_revno(self, revno):
 
1331
        """\
 
1332
        Check whether a revno corresponds to a real revision.
 
1333
        Zero (the NULL revision) is considered invalid
 
1334
        """
 
1335
        if revno < 1 or revno > self.revno():
 
1336
            raise InvalidRevisionNumber(revno)
 
1337
        
 
1338
        
 
1339
 
1267
1340
 
1268
1341
class ScratchBranch(Branch):
1269
1342
    """Special test class: a branch that cleans up after itself.
1311
1384
        os.rmdir(base)
1312
1385
        copytree(self.base, base, symlinks=True)
1313
1386
        return ScratchBranch(base=base)
 
1387
 
 
1388
 
1314
1389
        
1315
1390
    def __del__(self):
1316
1391
        self.destroy()
1386
1461
    """Return a new tree-root file id."""
1387
1462
    return gen_file_id('TREE_ROOT')
1388
1463
 
 
1464
 
 
1465
def pull_loc(branch):
 
1466
    # TODO: Should perhaps just make attribute be 'base' in
 
1467
    # RemoteBranch and Branch?
 
1468
    if hasattr(branch, "baseurl"):
 
1469
        return branch.baseurl
 
1470
    else:
 
1471
        return branch.base
 
1472
 
 
1473
 
 
1474
def copy_branch(branch_from, to_location, revision=None):
 
1475
    """Copy branch_from into the existing directory to_location.
 
1476
 
 
1477
    revision
 
1478
        If not None, only revisions up to this point will be copied.
 
1479
        The head of the new branch will be that revision.  Can be a
 
1480
        revno or revid.
 
1481
 
 
1482
    to_location
 
1483
        The name of a local directory that exists but is empty.
 
1484
    """
 
1485
    # TODO: This could be done *much* more efficiently by just copying
 
1486
    # all the whole weaves and revisions, rather than getting one
 
1487
    # revision at a time.
 
1488
    from bzrlib.merge import merge
 
1489
    from bzrlib.branch import Branch
 
1490
 
 
1491
    assert isinstance(branch_from, Branch)
 
1492
    assert isinstance(to_location, basestring)
 
1493
    
 
1494
    br_to = Branch(to_location, init=True)
 
1495
    br_to.set_root_id(branch_from.get_root_id())
 
1496
    if revision is None:
 
1497
        revno = None
 
1498
    else:
 
1499
        revno, rev_id = branch_from.get_revision_info(revision)
 
1500
    br_to.update_revisions(branch_from, stop_revno=revno)
 
1501
    merge((to_location, -1), (to_location, 0), this_dir=to_location,
 
1502
          check_clean=False, ignore_zero=True)
 
1503
    
 
1504
    from_location = pull_loc(branch_from)
 
1505
    br_to.set_parent(pull_loc(branch_from))
 
1506