~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/branch.py

  • Committer: Martin Pool
  • Date: 2005-07-07 10:31:36 UTC
  • Revision ID: mbp@sourcefrog.net-20050707103135-9b4d911d8df6e880
- fix pwk help

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
414
376
                         """Inventory for the working copy.""")
415
377
 
416
378
 
417
 
    def add(self, files, ids=None):
 
379
    def add(self, files, verbose=False, ids=None):
418
380
        """Make files versioned.
419
381
 
420
 
        Note that the command line normally calls smart_add instead,
421
 
        which can automatically recurse.
 
382
        Note that the command line normally calls smart_add instead.
422
383
 
423
384
        This puts the files in the Added state, so that they will be
424
385
        recorded by the next commit.
434
395
        TODO: Perhaps have an option to add the ids even if the files do
435
396
              not (yet) exist.
436
397
 
437
 
        TODO: Perhaps yield the ids and paths as they're added.
 
398
        TODO: Perhaps return the ids of the files?  But then again it
 
399
              is easy to retrieve them if they're needed.
 
400
 
 
401
        TODO: Adding a directory should optionally recurse down and
 
402
              add all non-ignored children.  Perhaps do that in a
 
403
              higher-level method.
438
404
        """
 
405
        from bzrlib.textui import show_status
439
406
        # TODO: Re-adding a file that is removed in the working copy
440
407
        # should probably put it back with the previous ID.
441
408
        if isinstance(files, basestring):
476
443
                    file_id = gen_file_id(f)
477
444
                inv.add_path(f, kind=kind, file_id=file_id)
478
445
 
 
446
                if verbose:
 
447
                    print 'added', quotefn(f)
 
448
 
479
449
                mutter("add file %s file_id:{%s} kind=%r" % (f, file_id, kind))
480
450
 
481
451
            self._write_inventory(inv)
491
461
            # use inventory as it was in that revision
492
462
            file_id = tree.inventory.path2id(file)
493
463
            if not file_id:
494
 
                raise BzrError("%r is not present in revision %s" % (file, revno))
 
464
                raise BzrError("%r is not present in revision %d" % (file, revno))
495
465
            tree.print_file(file_id)
496
466
        finally:
497
467
            self.unlock()
511
481
        is the opposite of add.  Removing it is consistent with most
512
482
        other tools.  Maybe an option.
513
483
        """
 
484
        from bzrlib.textui import show_status
514
485
        ## TODO: Normalize names
515
486
        ## TODO: Remove nested loops; better scalability
516
487
        if isinstance(files, basestring):
545
516
    # FIXME: this doesn't need to be a branch method
546
517
    def set_inventory(self, new_inventory_list):
547
518
        from bzrlib.inventory import Inventory, InventoryEntry
548
 
        inv = Inventory(self.get_root_id())
 
519
        inv = Inventory()
549
520
        for path, file_id, parent, kind in new_inventory_list:
550
521
            name = os.path.basename(path)
551
522
            if name == "":
573
544
        return self.working_tree().unknowns()
574
545
 
575
546
 
576
 
    def append_revision(self, *revision_ids):
 
547
    def append_revision(self, revision_id):
577
548
        from bzrlib.atomicfile import AtomicFile
578
549
 
579
 
        for revision_id in revision_ids:
580
 
            mutter("add {%s} to revision-history" % revision_id)
581
 
 
582
 
        rev_history = self.revision_history()
583
 
        rev_history.extend(revision_ids)
 
550
        mutter("add {%s} to revision-history" % revision_id)
 
551
        rev_history = self.revision_history() + [revision_id]
584
552
 
585
553
        f = AtomicFile(self.controlfilename('revision-history'))
586
554
        try:
591
559
            f.close()
592
560
 
593
561
 
594
 
    def get_revision_xml(self, revision_id):
595
 
        """Return XML file object for revision object."""
596
 
        if not revision_id or not isinstance(revision_id, basestring):
597
 
            raise InvalidRevisionId(revision_id)
598
 
 
599
 
        self.lock_read()
600
 
        try:
601
 
            try:
602
 
                return self.revision_store[revision_id]
603
 
            except IndexError:
604
 
                raise bzrlib.errors.NoSuchRevision(self, revision_id)
605
 
        finally:
606
 
            self.unlock()
607
 
 
608
 
 
609
562
    def get_revision(self, revision_id):
610
563
        """Return the Revision object for a named revision"""
611
 
        xml_file = self.get_revision_xml(revision_id)
 
564
        from bzrlib.revision import Revision
 
565
        from bzrlib.xml import unpack_xml
612
566
 
 
567
        self.lock_read()
613
568
        try:
614
 
            r = unpack_xml(Revision, xml_file)
615
 
        except SyntaxError, e:
616
 
            raise bzrlib.errors.BzrError('failed to unpack revision_xml',
617
 
                                         [revision_id,
618
 
                                          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()
619
574
            
620
575
        assert r.revision_id == revision_id
621
576
        return r
622
 
 
623
 
 
624
 
    def get_revision_delta(self, revno):
625
 
        """Return the delta for one revision.
626
 
 
627
 
        The delta is relative to its mainline predecessor, or the
628
 
        empty tree for revision 1.
629
 
        """
630
 
        assert isinstance(revno, int)
631
 
        rh = self.revision_history()
632
 
        if not (1 <= revno <= len(rh)):
633
 
            raise InvalidRevisionNumber(revno)
634
 
 
635
 
        # revno is 1-based; list is 0-based
636
 
 
637
 
        new_tree = self.revision_tree(rh[revno-1])
638
 
        if revno == 1:
639
 
            old_tree = EmptyTree()
640
 
        else:
641
 
            old_tree = self.revision_tree(rh[revno-2])
642
 
 
643
 
        return compare_trees(old_tree, new_tree)
644
 
 
645
577
        
646
578
 
647
579
    def get_revision_sha1(self, revision_id):
652
584
        # the revision, (add signatures/remove signatures) and still
653
585
        # have all hash pointers stay consistent.
654
586
        # But for now, just hash the contents.
655
 
        return bzrlib.osutils.sha_file(self.get_revision_xml(revision_id))
 
587
        return sha_file(self.revision_store[revision_id])
656
588
 
657
589
 
658
590
    def get_inventory(self, inventory_id):
664
596
        from bzrlib.inventory import Inventory
665
597
        from bzrlib.xml import unpack_xml
666
598
 
667
 
        return unpack_xml(Inventory, self.get_inventory_xml(inventory_id))
668
 
 
669
 
 
670
 
    def get_inventory_xml(self, inventory_id):
671
 
        """Get inventory XML as a file object."""
672
 
        return self.inventory_store[inventory_id]
 
599
        return unpack_xml(Inventory, self.inventory_store[inventory_id])
673
600
            
674
601
 
675
602
    def get_inventory_sha1(self, inventory_id):
676
603
        """Return the sha1 hash of the inventory entry
677
604
        """
678
 
        return sha_file(self.get_inventory_xml(inventory_id))
 
605
        return sha_file(self.inventory_store[inventory_id])
679
606
 
680
607
 
681
608
    def get_revision_inventory(self, revision_id):
684
611
        # must be the same as its revision, so this is trivial.
685
612
        if revision_id == None:
686
613
            from bzrlib.inventory import Inventory
687
 
            return Inventory(self.get_root_id())
 
614
            return Inventory()
688
615
        else:
689
616
            return self.get_inventory(revision_id)
690
617
 
747
674
                return r+1, my_history[r]
748
675
        return None, None
749
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
 
750
698
 
751
699
    def revno(self):
752
700
        """Return current revision number for this branch.
767
715
            return None
768
716
 
769
717
 
770
 
    def missing_revisions(self, other, stop_revision=None, diverged_ok=False):
 
718
    def missing_revisions(self, other, stop_revision=None):
771
719
        """
772
720
        If self and other have not diverged, return a list of the revisions
773
721
        present in other, but missing from self.
806
754
        if stop_revision is None:
807
755
            stop_revision = other_len
808
756
        elif stop_revision > other_len:
809
 
            raise bzrlib.errors.NoSuchRevision(self, stop_revision)
 
757
            raise NoSuchRevision(self, stop_revision)
810
758
        
811
759
        return other_history[self_len:stop_revision]
812
760
 
813
761
 
814
762
    def update_revisions(self, other, stop_revision=None):
815
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
816
784
        """
817
 
        from bzrlib.fetch import greedy_fetch
818
 
 
819
 
        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
 
820
793
        pb.update('comparing histories')
821
 
 
822
794
        revision_ids = self.missing_revisions(other, stop_revision)
823
795
 
824
 
        if len(revision_ids) > 0:
825
 
            count = greedy_fetch(self, other, revision_ids[-1], pb)[0]
826
 
        else:
827
 
            count = 0
828
 
        self.append_revision(*revision_ids)
829
 
        ## note("Added %d revisions." % count)
830
 
        pb.clear()
831
 
 
832
 
        
833
 
        
834
 
    def install_revisions(self, other, revision_ids, pb):
835
796
        if hasattr(other.revision_store, "prefetch"):
836
797
            other.revision_store.prefetch(revision_ids)
837
798
        if hasattr(other.inventory_store, "prefetch"):
838
799
            inventory_ids = [other.get_revision(r).inventory_id
839
800
                             for r in revision_ids]
840
801
            other.inventory_store.prefetch(inventory_ids)
841
 
 
842
 
        if pb is None:
843
 
            pb = bzrlib.ui.ui_factory.progress_bar()
844
802
                
845
803
        revisions = []
846
804
        needed_texts = set()
847
805
        i = 0
848
 
 
849
 
        failures = set()
850
 
        for i, rev_id in enumerate(revision_ids):
851
 
            pb.update('fetching revision', i+1, len(revision_ids))
852
 
            try:
853
 
                rev = other.get_revision(rev_id)
854
 
            except bzrlib.errors.NoSuchRevision:
855
 
                failures.add(rev_id)
856
 
                continue
857
 
 
 
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)
858
810
            revisions.append(rev)
859
811
            inv = other.get_inventory(str(rev.inventory_id))
860
812
            for key, entry in inv.iter_entries():
865
817
 
866
818
        pb.clear()
867
819
                    
868
 
        count, cp_fail = self.text_store.copy_multi(other.text_store, 
869
 
                                                    needed_texts)
870
 
        #print "Added %d texts." % count 
 
820
        count = self.text_store.copy_multi(other.text_store, needed_texts)
 
821
        print "Added %d texts." % count 
871
822
        inventory_ids = [ f.inventory_id for f in revisions ]
872
 
        count, cp_fail = self.inventory_store.copy_multi(other.inventory_store, 
873
 
                                                         inventory_ids)
874
 
        #print "Added %d inventories." % count 
 
823
        count = self.inventory_store.copy_multi(other.inventory_store, 
 
824
                                                inventory_ids)
 
825
        print "Added %d inventories." % count 
875
826
        revision_ids = [ f.revision_id for f in revisions]
876
 
 
877
 
        count, cp_fail = self.revision_store.copy_multi(other.revision_store, 
878
 
                                                          revision_ids,
879
 
                                                          permit_failure=True)
880
 
        assert len(cp_fail) == 0 
881
 
        return count, failures
882
 
       
883
 
 
 
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
        
884
834
    def commit(self, *args, **kw):
885
835
        from bzrlib.commit import commit
886
836
        commit(self, *args, **kw)
887
837
        
888
838
 
889
 
    def lookup_revision(self, revision):
890
 
        """Return the revision identifier for a given revision information."""
891
 
        revno, info = self.get_revision_info(revision)
892
 
        return info
893
 
 
894
 
 
895
 
    def revision_id_to_revno(self, revision_id):
896
 
        """Given a revision id, return its revno"""
897
 
        history = self.revision_history()
898
 
        try:
899
 
            return history.index(revision_id) + 1
900
 
        except ValueError:
901
 
            raise bzrlib.errors.NoSuchRevision(self, revision_id)
902
 
 
903
 
 
904
 
    def get_revision_info(self, revision):
905
 
        """Return (revno, revision id) for revision identifier.
906
 
 
907
 
        revision can be an integer, in which case it is assumed to be revno (though
908
 
            this will translate negative values into positive ones)
909
 
        revision can also be a string, in which case it is parsed for something like
910
 
            'date:' or 'revid:' etc.
911
 
        """
912
 
        if revision is None:
913
 
            return 0, None
914
 
        revno = None
915
 
        try:# Convert to int if possible
916
 
            revision = int(revision)
917
 
        except ValueError:
918
 
            pass
919
 
        revs = self.revision_history()
920
 
        if isinstance(revision, int):
921
 
            if revision == 0:
922
 
                return 0, None
923
 
            # Mabye we should do this first, but we don't need it if revision == 0
924
 
            if revision < 0:
925
 
                revno = len(revs) + revision + 1
926
 
            else:
927
 
                revno = revision
928
 
        elif isinstance(revision, basestring):
929
 
            for prefix, func in Branch.REVISION_NAMESPACES.iteritems():
930
 
                if revision.startswith(prefix):
931
 
                    revno = func(self, revs, revision)
932
 
                    break
933
 
            else:
934
 
                raise BzrError('No namespace registered for string: %r' % revision)
935
 
 
936
 
        if revno is None or revno <= 0 or revno > len(revs):
937
 
            raise BzrError("no such revision %s" % revision)
938
 
        return revno, revs[revno-1]
939
 
 
940
 
    def _namespace_revno(self, revs, revision):
941
 
        """Lookup a revision by revision number"""
942
 
        assert revision.startswith('revno:')
943
 
        try:
944
 
            return int(revision[6:])
945
 
        except ValueError:
946
 
            return None
947
 
    REVISION_NAMESPACES['revno:'] = _namespace_revno
948
 
 
949
 
    def _namespace_revid(self, revs, revision):
950
 
        assert revision.startswith('revid:')
951
 
        try:
952
 
            return revs.index(revision[6:]) + 1
953
 
        except ValueError:
954
 
            return None
955
 
    REVISION_NAMESPACES['revid:'] = _namespace_revid
956
 
 
957
 
    def _namespace_last(self, revs, revision):
958
 
        assert revision.startswith('last:')
959
 
        try:
960
 
            offset = int(revision[5:])
961
 
        except ValueError:
962
 
            return None
963
 
        else:
964
 
            if offset <= 0:
965
 
                raise BzrError('You must supply a positive value for --revision last:XXX')
966
 
            return len(revs) - offset + 1
967
 
    REVISION_NAMESPACES['last:'] = _namespace_last
968
 
 
969
 
    def _namespace_tag(self, revs, revision):
970
 
        assert revision.startswith('tag:')
971
 
        raise BzrError('tag: namespace registered, but not implemented.')
972
 
    REVISION_NAMESPACES['tag:'] = _namespace_tag
973
 
 
974
 
    def _namespace_date(self, revs, revision):
975
 
        assert revision.startswith('date:')
976
 
        import datetime
977
 
        # Spec for date revisions:
978
 
        #   date:value
979
 
        #   value can be 'yesterday', 'today', 'tomorrow' or a YYYY-MM-DD string.
980
 
        #   it can also start with a '+/-/='. '+' says match the first
981
 
        #   entry after the given date. '-' is match the first entry before the date
982
 
        #   '=' is match the first entry after, but still on the given date.
983
 
        #
984
 
        #   +2005-05-12 says find the first matching entry after May 12th, 2005 at 0:00
985
 
        #   -2005-05-12 says find the first matching entry before May 12th, 2005 at 0:00
986
 
        #   =2005-05-12 says find the first match after May 12th, 2005 at 0:00 but before
987
 
        #       May 13th, 2005 at 0:00
988
 
        #
989
 
        #   So the proper way of saying 'give me all entries for today' is:
990
 
        #       -r {date:+today}:{date:-tomorrow}
991
 
        #   The default is '=' when not supplied
992
 
        val = revision[5:]
993
 
        match_style = '='
994
 
        if val[:1] in ('+', '-', '='):
995
 
            match_style = val[:1]
996
 
            val = val[1:]
997
 
 
998
 
        today = datetime.datetime.today().replace(hour=0,minute=0,second=0,microsecond=0)
999
 
        if val.lower() == 'yesterday':
1000
 
            dt = today - datetime.timedelta(days=1)
1001
 
        elif val.lower() == 'today':
1002
 
            dt = today
1003
 
        elif val.lower() == 'tomorrow':
1004
 
            dt = today + datetime.timedelta(days=1)
1005
 
        else:
1006
 
            import re
1007
 
            # This should be done outside the function to avoid recompiling it.
1008
 
            _date_re = re.compile(
1009
 
                    r'(?P<date>(?P<year>\d\d\d\d)-(?P<month>\d\d)-(?P<day>\d\d))?'
1010
 
                    r'(,|T)?\s*'
1011
 
                    r'(?P<time>(?P<hour>\d\d):(?P<minute>\d\d)(:(?P<second>\d\d))?)?'
1012
 
                )
1013
 
            m = _date_re.match(val)
1014
 
            if not m or (not m.group('date') and not m.group('time')):
1015
 
                raise BzrError('Invalid revision date %r' % revision)
1016
 
 
1017
 
            if m.group('date'):
1018
 
                year, month, day = int(m.group('year')), int(m.group('month')), int(m.group('day'))
1019
 
            else:
1020
 
                year, month, day = today.year, today.month, today.day
1021
 
            if m.group('time'):
1022
 
                hour = int(m.group('hour'))
1023
 
                minute = int(m.group('minute'))
1024
 
                if m.group('second'):
1025
 
                    second = int(m.group('second'))
1026
 
                else:
1027
 
                    second = 0
1028
 
            else:
1029
 
                hour, minute, second = 0,0,0
1030
 
 
1031
 
            dt = datetime.datetime(year=year, month=month, day=day,
1032
 
                    hour=hour, minute=minute, second=second)
1033
 
        first = dt
1034
 
        last = None
1035
 
        reversed = False
1036
 
        if match_style == '-':
1037
 
            reversed = True
1038
 
        elif match_style == '=':
1039
 
            last = dt + datetime.timedelta(days=1)
1040
 
 
1041
 
        if reversed:
1042
 
            for i in range(len(revs)-1, -1, -1):
1043
 
                r = self.get_revision(revs[i])
1044
 
                # TODO: Handle timezone.
1045
 
                dt = datetime.datetime.fromtimestamp(r.timestamp)
1046
 
                if first >= dt and (last is None or dt >= last):
1047
 
                    return i+1
1048
 
        else:
1049
 
            for i in range(len(revs)):
1050
 
                r = self.get_revision(revs[i])
1051
 
                # TODO: Handle timezone.
1052
 
                dt = datetime.datetime.fromtimestamp(r.timestamp)
1053
 
                if first <= dt and (last is None or dt <= last):
1054
 
                    return i+1
1055
 
    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
 
1056
850
 
1057
851
    def revision_tree(self, revision_id):
1058
852
        """Return Tree for a revision on this branch.
1059
853
 
1060
854
        `revision_id` may be None for the null revision, in which case
1061
855
        an `EmptyTree` is returned."""
 
856
        from bzrlib.tree import EmptyTree, RevisionTree
1062
857
        # TODO: refactor this to use an existing revision object
1063
858
        # so we don't need to read it in twice.
1064
859
        if revision_id == None:
1079
874
 
1080
875
        If there are no revisions yet, return an `EmptyTree`.
1081
876
        """
 
877
        from bzrlib.tree import EmptyTree, RevisionTree
1082
878
        r = self.last_patch()
1083
879
        if r == None:
1084
880
            return EmptyTree()
1122
918
 
1123
919
            inv.rename(file_id, to_dir_id, to_tail)
1124
920
 
 
921
            print "%s => %s" % (from_rel, to_rel)
 
922
 
1125
923
            from_abs = self.abspath(from_rel)
1126
924
            to_abs = self.abspath(to_rel)
1127
925
            try:
1146
944
 
1147
945
        Note that to_name is only the last component of the new name;
1148
946
        this doesn't change the directory.
1149
 
 
1150
 
        This returns a list of (from_path, to_path) pairs for each
1151
 
        entry that is moved.
1152
947
        """
1153
 
        result = []
1154
948
        self.lock_write()
1155
949
        try:
1156
950
            ## TODO: Option to move IDs only
1191
985
            for f in from_paths:
1192
986
                name_tail = splitpath(f)[-1]
1193
987
                dest_path = appendpath(to_name, name_tail)
1194
 
                result.append((f, dest_path))
 
988
                print "%s => %s" % (f, dest_path)
1195
989
                inv.rename(inv.path2id(f), to_dir_id, name_tail)
1196
990
                try:
1197
991
                    os.rename(self.abspath(f), self.abspath(dest_path))
1203
997
        finally:
1204
998
            self.unlock()
1205
999
 
1206
 
        return result
1207
 
 
1208
1000
 
1209
1001
    def revert(self, filenames, old_tree=None, backups=True):
1210
1002
        """Restore selected files to the versions from a previous tree.
1408
1200
 
1409
1201
    s = hexlify(rand_bytes(8))
1410
1202
    return '-'.join((name, compact_date(time()), s))
1411
 
 
1412
 
 
1413
 
def gen_root_id():
1414
 
    """Return a new tree-root file id."""
1415
 
    return gen_file_id('TREE_ROOT')
1416