~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/branch.py

  • Committer: Martin Pool
  • Date: 2005-07-06 05:32:32 UTC
  • Revision ID: mbp@sourcefrog.net-20050706053232-3cc703228805ed79
- clean up imports of statcache

Show diffs side-by-side

added added

removed removed

Lines of Context:
15
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
16
 
17
17
 
18
 
import sys
19
 
import os
 
18
import sys, os
20
19
 
21
20
import bzrlib
22
21
from bzrlib.trace import mutter, note
23
 
from bzrlib.osutils import isdir, quotefn, compact_date, rand_bytes, \
24
 
     splitpath, \
 
22
from bzrlib.osutils import isdir, quotefn, compact_date, rand_bytes, splitpath, \
25
23
     sha_file, appendpath, file_kind
26
 
 
27
 
from bzrlib.errors import BzrError, InvalidRevisionNumber, InvalidRevisionId
28
 
import bzrlib.errors
29
 
from bzrlib.textui import show_status
30
 
from bzrlib.revision import Revision
31
 
from bzrlib.xml import unpack_xml
32
 
from bzrlib.delta import compare_trees
33
 
from bzrlib.tree import EmptyTree, RevisionTree
34
 
import bzrlib.ui
35
 
 
36
 
 
 
24
from bzrlib.errors import BzrError
37
25
 
38
26
BZR_BRANCH_FORMAT = "Bazaar-NG branch, format 0.0.4\n"
39
27
## TODO: Maybe include checks for common corruption of newlines, etc?
40
28
 
41
29
 
42
 
# TODO: Some operations like log might retrieve the same revisions
43
 
# repeatedly to calculate deltas.  We could perhaps have a weakref
44
 
# cache in memory to make this faster.
45
 
 
46
 
# TODO: please move the revision-string syntax stuff out of the branch
47
 
# object; it's clutter
48
 
 
49
30
 
50
31
def find_branch(f, **args):
51
32
    if f and (f.startswith('http://') or f.startswith('https://')):
108
89
    It is not necessary that f exists.
109
90
 
110
91
    Basically we keep looking up until we find the control directory or
111
 
    run into the root.  If there isn't one, raises NotBranchError.
112
 
    """
 
92
    run into the root."""
113
93
    if f == None:
114
94
        f = os.getcwd()
115
95
    elif hasattr(os.path, 'realpath'):
128
108
        head, tail = os.path.split(f)
129
109
        if head == f:
130
110
            # reached the root, whatever that may be
131
 
            raise bzrlib.errors.NotBranchError('%s is not in a branch' % orig_f)
 
111
            raise BzrError('%r is not in a branch' % orig_f)
132
112
        f = head
133
 
 
134
 
 
135
 
 
136
 
# XXX: move into bzrlib.errors; subclass BzrError    
 
113
    
137
114
class DivergedBranches(Exception):
138
115
    def __init__(self, branch1, branch2):
139
116
        self.branch1 = branch1
141
118
        Exception.__init__(self, "These branches have diverged.")
142
119
 
143
120
 
 
121
class NoSuchRevision(BzrError):
 
122
    def __init__(self, branch, revision):
 
123
        self.branch = branch
 
124
        self.revision = revision
 
125
        msg = "Branch %s has no revision %d" % (branch, revision)
 
126
        BzrError.__init__(self, msg)
 
127
 
 
128
 
144
129
######################################################################
145
130
# branch objects
146
131
 
165
150
    _lock_count = None
166
151
    _lock = None
167
152
    
168
 
    # Map some sort of prefix into a namespace
169
 
    # stuff like "revno:10", "revid:", etc.
170
 
    # This should match a prefix with a function which accepts
171
 
    REVISION_NAMESPACES = {}
172
 
 
173
153
    def __init__(self, base, init=False, find_root=True):
174
154
        """Create new branch object at a particular location.
175
155
 
327
307
            self.controlfile(f, 'w').write('')
328
308
        mutter('created control directory in ' + self.base)
329
309
 
330
 
        # if we want per-tree root ids then this is the place to set
331
 
        # them; they're not needed for now and so ommitted for
332
 
        # simplicity.
333
310
        pack_xml(Inventory(), self.controlfile('inventory','w'))
334
311
 
335
312
 
351
328
                           ['use a different bzr version',
352
329
                            'or remove the .bzr directory and "bzr init" again'])
353
330
 
354
 
    def get_root_id(self):
355
 
        """Return the id of this branches root"""
356
 
        inv = self.read_working_inventory()
357
 
        return inv.root.file_id
358
331
 
359
 
    def set_root_id(self, file_id):
360
 
        inv = self.read_working_inventory()
361
 
        orig_root_id = inv.root.file_id
362
 
        del inv._byid[inv.root.file_id]
363
 
        inv.root.file_id = file_id
364
 
        inv._byid[inv.root.file_id] = inv.root
365
 
        for fid in inv:
366
 
            entry = inv[fid]
367
 
            if entry.parent_id in (None, orig_root_id):
368
 
                entry.parent_id = inv.root.file_id
369
 
        self._write_inventory(inv)
370
332
 
371
333
    def read_working_inventory(self):
372
334
        """Read the working inventory."""
379
341
            # ElementTree does its own conversion from UTF-8, so open in
380
342
            # binary.
381
343
            inv = unpack_xml(Inventory,
382
 
                             self.controlfile('inventory', 'rb'))
 
344
                                  self.controlfile('inventory', 'rb'))
383
345
            mutter("loaded inventory of %d items in %f"
384
346
                   % (len(inv), time() - before))
385
347
            return inv
440
402
              add all non-ignored children.  Perhaps do that in a
441
403
              higher-level method.
442
404
        """
 
405
        from bzrlib.textui import show_status
443
406
        # TODO: Re-adding a file that is removed in the working copy
444
407
        # should probably put it back with the previous ID.
445
408
        if isinstance(files, basestring):
498
461
            # use inventory as it was in that revision
499
462
            file_id = tree.inventory.path2id(file)
500
463
            if not file_id:
501
 
                raise BzrError("%r is not present in revision %s" % (file, revno))
 
464
                raise BzrError("%r is not present in revision %d" % (file, revno))
502
465
            tree.print_file(file_id)
503
466
        finally:
504
467
            self.unlock()
518
481
        is the opposite of add.  Removing it is consistent with most
519
482
        other tools.  Maybe an option.
520
483
        """
 
484
        from bzrlib.textui import show_status
521
485
        ## TODO: Normalize names
522
486
        ## TODO: Remove nested loops; better scalability
523
487
        if isinstance(files, basestring):
552
516
    # FIXME: this doesn't need to be a branch method
553
517
    def set_inventory(self, new_inventory_list):
554
518
        from bzrlib.inventory import Inventory, InventoryEntry
555
 
        inv = Inventory(self.get_root_id())
 
519
        inv = Inventory()
556
520
        for path, file_id, parent, kind in new_inventory_list:
557
521
            name = os.path.basename(path)
558
522
            if name == "":
580
544
        return self.working_tree().unknowns()
581
545
 
582
546
 
583
 
    def append_revision(self, *revision_ids):
 
547
    def append_revision(self, revision_id):
584
548
        from bzrlib.atomicfile import AtomicFile
585
549
 
586
 
        for revision_id in revision_ids:
587
 
            mutter("add {%s} to revision-history" % revision_id)
588
 
 
589
 
        rev_history = self.revision_history()
590
 
        rev_history.extend(revision_ids)
 
550
        mutter("add {%s} to revision-history" % revision_id)
 
551
        rev_history = self.revision_history() + [revision_id]
591
552
 
592
553
        f = AtomicFile(self.controlfilename('revision-history'))
593
554
        try:
598
559
            f.close()
599
560
 
600
561
 
601
 
    def get_revision_xml(self, revision_id):
602
 
        """Return XML file object for revision object."""
603
 
        if not revision_id or not isinstance(revision_id, basestring):
604
 
            raise InvalidRevisionId(revision_id)
605
 
 
606
 
        self.lock_read()
607
 
        try:
608
 
            try:
609
 
                return self.revision_store[revision_id]
610
 
            except IndexError:
611
 
                raise bzrlib.errors.NoSuchRevision(self, revision_id)
612
 
        finally:
613
 
            self.unlock()
614
 
 
615
 
 
616
562
    def get_revision(self, revision_id):
617
563
        """Return the Revision object for a named revision"""
618
 
        xml_file = self.get_revision_xml(revision_id)
 
564
        from bzrlib.revision import Revision
 
565
        from bzrlib.xml import unpack_xml
619
566
 
 
567
        self.lock_read()
620
568
        try:
621
 
            r = unpack_xml(Revision, xml_file)
622
 
        except SyntaxError, e:
623
 
            raise bzrlib.errors.BzrError('failed to unpack revision_xml',
624
 
                                         [revision_id,
625
 
                                          str(e)])
 
569
            if not revision_id or not isinstance(revision_id, basestring):
 
570
                raise ValueError('invalid revision-id: %r' % revision_id)
 
571
            r = unpack_xml(Revision, self.revision_store[revision_id])
 
572
        finally:
 
573
            self.unlock()
626
574
            
627
575
        assert r.revision_id == revision_id
628
576
        return r
629
 
 
630
 
 
631
 
    def get_revision_delta(self, revno):
632
 
        """Return the delta for one revision.
633
 
 
634
 
        The delta is relative to its mainline predecessor, or the
635
 
        empty tree for revision 1.
636
 
        """
637
 
        assert isinstance(revno, int)
638
 
        rh = self.revision_history()
639
 
        if not (1 <= revno <= len(rh)):
640
 
            raise InvalidRevisionNumber(revno)
641
 
 
642
 
        # revno is 1-based; list is 0-based
643
 
 
644
 
        new_tree = self.revision_tree(rh[revno-1])
645
 
        if revno == 1:
646
 
            old_tree = EmptyTree()
647
 
        else:
648
 
            old_tree = self.revision_tree(rh[revno-2])
649
 
 
650
 
        return compare_trees(old_tree, new_tree)
651
 
 
652
577
        
653
578
 
654
579
    def get_revision_sha1(self, revision_id):
659
584
        # the revision, (add signatures/remove signatures) and still
660
585
        # have all hash pointers stay consistent.
661
586
        # But for now, just hash the contents.
662
 
        return bzrlib.osutils.sha_file(self.get_revision_xml(revision_id))
 
587
        return sha_file(self.revision_store[revision_id])
663
588
 
664
589
 
665
590
    def get_inventory(self, inventory_id):
671
596
        from bzrlib.inventory import Inventory
672
597
        from bzrlib.xml import unpack_xml
673
598
 
674
 
        return unpack_xml(Inventory, self.get_inventory_xml(inventory_id))
675
 
 
676
 
 
677
 
    def get_inventory_xml(self, inventory_id):
678
 
        """Get inventory XML as a file object."""
679
 
        return self.inventory_store[inventory_id]
 
599
        return unpack_xml(Inventory, self.inventory_store[inventory_id])
680
600
            
681
601
 
682
602
    def get_inventory_sha1(self, inventory_id):
683
603
        """Return the sha1 hash of the inventory entry
684
604
        """
685
 
        return sha_file(self.get_inventory_xml(inventory_id))
 
605
        return sha_file(self.inventory_store[inventory_id])
686
606
 
687
607
 
688
608
    def get_revision_inventory(self, revision_id):
691
611
        # must be the same as its revision, so this is trivial.
692
612
        if revision_id == None:
693
613
            from bzrlib.inventory import Inventory
694
 
            return Inventory(self.get_root_id())
 
614
            return Inventory()
695
615
        else:
696
616
            return self.get_inventory(revision_id)
697
617
 
754
674
                return r+1, my_history[r]
755
675
        return None, None
756
676
 
 
677
    def enum_history(self, direction):
 
678
        """Return (revno, revision_id) for history of branch.
 
679
 
 
680
        direction
 
681
            'forward' is from earliest to latest
 
682
            'reverse' is from latest to earliest
 
683
        """
 
684
        rh = self.revision_history()
 
685
        if direction == 'forward':
 
686
            i = 1
 
687
            for rid in rh:
 
688
                yield i, rid
 
689
                i += 1
 
690
        elif direction == 'reverse':
 
691
            i = len(rh)
 
692
            while i > 0:
 
693
                yield i, rh[i-1]
 
694
                i -= 1
 
695
        else:
 
696
            raise ValueError('invalid history direction', direction)
 
697
 
757
698
 
758
699
    def revno(self):
759
700
        """Return current revision number for this branch.
774
715
            return None
775
716
 
776
717
 
777
 
    def missing_revisions(self, other, stop_revision=None, diverged_ok=False):
 
718
    def missing_revisions(self, other, stop_revision=None):
778
719
        """
779
720
        If self and other have not diverged, return a list of the revisions
780
721
        present in other, but missing from self.
813
754
        if stop_revision is None:
814
755
            stop_revision = other_len
815
756
        elif stop_revision > other_len:
816
 
            raise bzrlib.errors.NoSuchRevision(self, stop_revision)
 
757
            raise NoSuchRevision(self, stop_revision)
817
758
        
818
759
        return other_history[self_len:stop_revision]
819
760
 
820
761
 
821
762
    def update_revisions(self, other, stop_revision=None):
822
763
        """Pull in all new revisions from other branch.
 
764
        
 
765
        >>> from bzrlib.commit import commit
 
766
        >>> bzrlib.trace.silent = True
 
767
        >>> br1 = ScratchBranch(files=['foo', 'bar'])
 
768
        >>> br1.add('foo')
 
769
        >>> br1.add('bar')
 
770
        >>> commit(br1, "lala!", rev_id="REVISION-ID-1", verbose=False)
 
771
        >>> br2 = ScratchBranch()
 
772
        >>> br2.update_revisions(br1)
 
773
        Added 2 texts.
 
774
        Added 1 inventories.
 
775
        Added 1 revisions.
 
776
        >>> br2.revision_history()
 
777
        [u'REVISION-ID-1']
 
778
        >>> br2.update_revisions(br1)
 
779
        Added 0 texts.
 
780
        Added 0 inventories.
 
781
        Added 0 revisions.
 
782
        >>> br1.text_store.total_size() == br2.text_store.total_size()
 
783
        True
823
784
        """
824
 
        from bzrlib.fetch import greedy_fetch
825
 
 
826
 
        pb = bzrlib.ui.ui_factory.progress_bar()
 
785
        from bzrlib.progress import ProgressBar
 
786
        try:
 
787
            set
 
788
        except NameError:
 
789
            from sets import Set as set
 
790
 
 
791
        pb = ProgressBar()
 
792
 
827
793
        pb.update('comparing histories')
828
 
 
829
794
        revision_ids = self.missing_revisions(other, stop_revision)
830
795
 
831
 
        if len(revision_ids) > 0:
832
 
            count = greedy_fetch(self, other, revision_ids[-1], pb)[0]
833
 
        else:
834
 
            count = 0
835
 
        self.append_revision(*revision_ids)
836
 
        ## note("Added %d revisions." % count)
837
 
 
838
 
        
839
 
    def install_revisions(self, other, revision_ids, pb):
840
796
        if hasattr(other.revision_store, "prefetch"):
841
797
            other.revision_store.prefetch(revision_ids)
842
798
        if hasattr(other.inventory_store, "prefetch"):
843
799
            inventory_ids = [other.get_revision(r).inventory_id
844
800
                             for r in revision_ids]
845
801
            other.inventory_store.prefetch(inventory_ids)
846
 
 
847
 
        if pb is None:
848
 
            pb = bzrlib.ui.ui_factory.progress_bar()
849
802
                
850
803
        revisions = []
851
804
        needed_texts = set()
852
805
        i = 0
853
 
 
854
 
        failures = set()
855
 
        for i, rev_id in enumerate(revision_ids):
856
 
            pb.update('fetching revision', i+1, len(revision_ids))
857
 
            try:
858
 
                rev = other.get_revision(rev_id)
859
 
            except bzrlib.errors.NoSuchRevision:
860
 
                failures.add(rev_id)
861
 
                continue
862
 
 
 
806
        for rev_id in revision_ids:
 
807
            i += 1
 
808
            pb.update('fetching revision', i, len(revision_ids))
 
809
            rev = other.get_revision(rev_id)
863
810
            revisions.append(rev)
864
811
            inv = other.get_inventory(str(rev.inventory_id))
865
812
            for key, entry in inv.iter_entries():
870
817
 
871
818
        pb.clear()
872
819
                    
873
 
        count, cp_fail = self.text_store.copy_multi(other.text_store, 
874
 
                                                    needed_texts)
 
820
        count = self.text_store.copy_multi(other.text_store, needed_texts)
875
821
        print "Added %d texts." % count 
876
822
        inventory_ids = [ f.inventory_id for f in revisions ]
877
 
        count, cp_fail = self.inventory_store.copy_multi(other.inventory_store, 
878
 
                                                         inventory_ids)
 
823
        count = self.inventory_store.copy_multi(other.inventory_store, 
 
824
                                                inventory_ids)
879
825
        print "Added %d inventories." % count 
880
826
        revision_ids = [ f.revision_id for f in revisions]
881
 
 
882
 
        count, cp_fail = self.revision_store.copy_multi(other.revision_store, 
883
 
                                                          revision_ids,
884
 
                                                          permit_failure=True)
885
 
        assert len(cp_fail) == 0 
886
 
        return count, failures
887
 
       
888
 
 
 
827
        count = self.revision_store.copy_multi(other.revision_store, 
 
828
                                               revision_ids)
 
829
        for revision_id in revision_ids:
 
830
            self.append_revision(revision_id)
 
831
        print "Added %d revisions." % count
 
832
                    
 
833
        
889
834
    def commit(self, *args, **kw):
890
835
        from bzrlib.commit import commit
891
836
        commit(self, *args, **kw)
892
837
        
893
838
 
894
 
    def lookup_revision(self, revision):
895
 
        """Return the revision identifier for a given revision information."""
896
 
        revno, info = self.get_revision_info(revision)
897
 
        return info
898
 
 
899
 
 
900
 
    def revision_id_to_revno(self, revision_id):
901
 
        """Given a revision id, return its revno"""
902
 
        history = self.revision_history()
903
 
        try:
904
 
            return history.index(revision_id) + 1
905
 
        except ValueError:
906
 
            raise bzrlib.errors.NoSuchRevision(self, revision_id)
907
 
 
908
 
 
909
 
    def get_revision_info(self, revision):
910
 
        """Return (revno, revision id) for revision identifier.
911
 
 
912
 
        revision can be an integer, in which case it is assumed to be revno (though
913
 
            this will translate negative values into positive ones)
914
 
        revision can also be a string, in which case it is parsed for something like
915
 
            'date:' or 'revid:' etc.
916
 
        """
917
 
        if revision is None:
918
 
            return 0, None
919
 
        revno = None
920
 
        try:# Convert to int if possible
921
 
            revision = int(revision)
922
 
        except ValueError:
923
 
            pass
924
 
        revs = self.revision_history()
925
 
        if isinstance(revision, int):
926
 
            if revision == 0:
927
 
                return 0, None
928
 
            # Mabye we should do this first, but we don't need it if revision == 0
929
 
            if revision < 0:
930
 
                revno = len(revs) + revision + 1
931
 
            else:
932
 
                revno = revision
933
 
        elif isinstance(revision, basestring):
934
 
            for prefix, func in Branch.REVISION_NAMESPACES.iteritems():
935
 
                if revision.startswith(prefix):
936
 
                    revno = func(self, revs, revision)
937
 
                    break
938
 
            else:
939
 
                raise BzrError('No namespace registered for string: %r' % revision)
940
 
 
941
 
        if revno is None or revno <= 0 or revno > len(revs):
942
 
            raise BzrError("no such revision %s" % revision)
943
 
        return revno, revs[revno-1]
944
 
 
945
 
    def _namespace_revno(self, revs, revision):
946
 
        """Lookup a revision by revision number"""
947
 
        assert revision.startswith('revno:')
948
 
        try:
949
 
            return int(revision[6:])
950
 
        except ValueError:
951
 
            return None
952
 
    REVISION_NAMESPACES['revno:'] = _namespace_revno
953
 
 
954
 
    def _namespace_revid(self, revs, revision):
955
 
        assert revision.startswith('revid:')
956
 
        try:
957
 
            return revs.index(revision[6:]) + 1
958
 
        except ValueError:
959
 
            return None
960
 
    REVISION_NAMESPACES['revid:'] = _namespace_revid
961
 
 
962
 
    def _namespace_last(self, revs, revision):
963
 
        assert revision.startswith('last:')
964
 
        try:
965
 
            offset = int(revision[5:])
966
 
        except ValueError:
967
 
            return None
968
 
        else:
969
 
            if offset <= 0:
970
 
                raise BzrError('You must supply a positive value for --revision last:XXX')
971
 
            return len(revs) - offset + 1
972
 
    REVISION_NAMESPACES['last:'] = _namespace_last
973
 
 
974
 
    def _namespace_tag(self, revs, revision):
975
 
        assert revision.startswith('tag:')
976
 
        raise BzrError('tag: namespace registered, but not implemented.')
977
 
    REVISION_NAMESPACES['tag:'] = _namespace_tag
978
 
 
979
 
    def _namespace_date(self, revs, revision):
980
 
        assert revision.startswith('date:')
981
 
        import datetime
982
 
        # Spec for date revisions:
983
 
        #   date:value
984
 
        #   value can be 'yesterday', 'today', 'tomorrow' or a YYYY-MM-DD string.
985
 
        #   it can also start with a '+/-/='. '+' says match the first
986
 
        #   entry after the given date. '-' is match the first entry before the date
987
 
        #   '=' is match the first entry after, but still on the given date.
988
 
        #
989
 
        #   +2005-05-12 says find the first matching entry after May 12th, 2005 at 0:00
990
 
        #   -2005-05-12 says find the first matching entry before May 12th, 2005 at 0:00
991
 
        #   =2005-05-12 says find the first match after May 12th, 2005 at 0:00 but before
992
 
        #       May 13th, 2005 at 0:00
993
 
        #
994
 
        #   So the proper way of saying 'give me all entries for today' is:
995
 
        #       -r {date:+today}:{date:-tomorrow}
996
 
        #   The default is '=' when not supplied
997
 
        val = revision[5:]
998
 
        match_style = '='
999
 
        if val[:1] in ('+', '-', '='):
1000
 
            match_style = val[:1]
1001
 
            val = val[1:]
1002
 
 
1003
 
        today = datetime.datetime.today().replace(hour=0,minute=0,second=0,microsecond=0)
1004
 
        if val.lower() == 'yesterday':
1005
 
            dt = today - datetime.timedelta(days=1)
1006
 
        elif val.lower() == 'today':
1007
 
            dt = today
1008
 
        elif val.lower() == 'tomorrow':
1009
 
            dt = today + datetime.timedelta(days=1)
1010
 
        else:
1011
 
            import re
1012
 
            # This should be done outside the function to avoid recompiling it.
1013
 
            _date_re = re.compile(
1014
 
                    r'(?P<date>(?P<year>\d\d\d\d)-(?P<month>\d\d)-(?P<day>\d\d))?'
1015
 
                    r'(,|T)?\s*'
1016
 
                    r'(?P<time>(?P<hour>\d\d):(?P<minute>\d\d)(:(?P<second>\d\d))?)?'
1017
 
                )
1018
 
            m = _date_re.match(val)
1019
 
            if not m or (not m.group('date') and not m.group('time')):
1020
 
                raise BzrError('Invalid revision date %r' % revision)
1021
 
 
1022
 
            if m.group('date'):
1023
 
                year, month, day = int(m.group('year')), int(m.group('month')), int(m.group('day'))
1024
 
            else:
1025
 
                year, month, day = today.year, today.month, today.day
1026
 
            if m.group('time'):
1027
 
                hour = int(m.group('hour'))
1028
 
                minute = int(m.group('minute'))
1029
 
                if m.group('second'):
1030
 
                    second = int(m.group('second'))
1031
 
                else:
1032
 
                    second = 0
1033
 
            else:
1034
 
                hour, minute, second = 0,0,0
1035
 
 
1036
 
            dt = datetime.datetime(year=year, month=month, day=day,
1037
 
                    hour=hour, minute=minute, second=second)
1038
 
        first = dt
1039
 
        last = None
1040
 
        reversed = False
1041
 
        if match_style == '-':
1042
 
            reversed = True
1043
 
        elif match_style == '=':
1044
 
            last = dt + datetime.timedelta(days=1)
1045
 
 
1046
 
        if reversed:
1047
 
            for i in range(len(revs)-1, -1, -1):
1048
 
                r = self.get_revision(revs[i])
1049
 
                # TODO: Handle timezone.
1050
 
                dt = datetime.datetime.fromtimestamp(r.timestamp)
1051
 
                if first >= dt and (last is None or dt >= last):
1052
 
                    return i+1
1053
 
        else:
1054
 
            for i in range(len(revs)):
1055
 
                r = self.get_revision(revs[i])
1056
 
                # TODO: Handle timezone.
1057
 
                dt = datetime.datetime.fromtimestamp(r.timestamp)
1058
 
                if first <= dt and (last is None or dt <= last):
1059
 
                    return i+1
1060
 
    REVISION_NAMESPACES['date:'] = _namespace_date
 
839
    def lookup_revision(self, revno):
 
840
        """Return revision hash for revision number."""
 
841
        if revno == 0:
 
842
            return None
 
843
 
 
844
        try:
 
845
            # list is 0-based; revisions are 1-based
 
846
            return self.revision_history()[revno-1]
 
847
        except IndexError:
 
848
            raise BzrError("no such revision %s" % revno)
 
849
 
1061
850
 
1062
851
    def revision_tree(self, revision_id):
1063
852
        """Return Tree for a revision on this branch.
1064
853
 
1065
854
        `revision_id` may be None for the null revision, in which case
1066
855
        an `EmptyTree` is returned."""
 
856
        from bzrlib.tree import EmptyTree, RevisionTree
1067
857
        # TODO: refactor this to use an existing revision object
1068
858
        # so we don't need to read it in twice.
1069
859
        if revision_id == None:
1084
874
 
1085
875
        If there are no revisions yet, return an `EmptyTree`.
1086
876
        """
 
877
        from bzrlib.tree import EmptyTree, RevisionTree
1087
878
        r = self.last_patch()
1088
879
        if r == None:
1089
880
            return EmptyTree()
1409
1200
 
1410
1201
    s = hexlify(rand_bytes(8))
1411
1202
    return '-'.join((name, compact_date(time()), s))
1412
 
 
1413
 
 
1414
 
def gen_root_id():
1415
 
    """Return a new tree-root file id."""
1416
 
    return gen_file_id('TREE_ROOT')
1417