/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

remove more duplicate merged hunks. Bad MERGE3, BAD.

Show diffs side-by-side

added added

removed removed

Lines of Context:
43
43
# repeatedly to calculate deltas.  We could perhaps have a weakref
44
44
# cache in memory to make this faster.
45
45
 
46
 
def find_branch(*ignored, **ignored_too):
47
 
    # XXX: leave this here for about one release, then remove it
48
 
    raise NotImplementedError('find_branch() is not supported anymore, '
49
 
                              'please use one of the new branch constructors')
 
46
# TODO: please move the revision-string syntax stuff out of the branch
 
47
# object; it's clutter
 
48
 
 
49
 
 
50
def find_branch(f, **args):
 
51
    if f and (f.startswith('http://') or f.startswith('https://')):
 
52
        from bzrlib.remotebranch import RemoteBranch
 
53
        return RemoteBranch(f, **args)
 
54
    else:
 
55
        return Branch(f, **args)
 
56
 
 
57
 
 
58
def find_cached_branch(f, cache_root, **args):
 
59
    from bzrlib.remotebranch import RemoteBranch
 
60
    br = find_branch(f, **args)
 
61
    def cacheify(br, store_name):
 
62
        from bzrlib.meta_store import CachedStore
 
63
        cache_path = os.path.join(cache_root, store_name)
 
64
        os.mkdir(cache_path)
 
65
        new_store = CachedStore(getattr(br, store_name), cache_path)
 
66
        setattr(br, store_name, new_store)
 
67
 
 
68
    if isinstance(br, RemoteBranch):
 
69
        cacheify(br, 'inventory_store')
 
70
        cacheify(br, 'text_store')
 
71
        cacheify(br, 'revision_store')
 
72
    return br
 
73
 
50
74
 
51
75
def _relpath(base, path):
52
76
    """Return path relative to base, or raise exception.
116
140
    """Branch holding a history of revisions.
117
141
 
118
142
    base
119
 
        Base directory/url of the branch.
120
 
    """
121
 
    base = None
122
 
 
123
 
    def __init__(self, *ignored, **ignored_too):
124
 
        raise NotImplementedError('The Branch class is abstract')
125
 
 
126
 
    @staticmethod
127
 
    def open(base):
128
 
        """Open an existing branch, rooted at 'base' (url)"""
129
 
        if base and (base.startswith('http://') or base.startswith('https://')):
130
 
            from bzrlib.remotebranch import RemoteBranch
131
 
            return RemoteBranch(base, find_root=False)
132
 
        else:
133
 
            return LocalBranch(base, find_root=False)
134
 
 
135
 
    @staticmethod
136
 
    def open_containing(url):
137
 
        """Open an existing branch, containing url (search upwards for the root)
138
 
        """
139
 
        if url and (url.startswith('http://') or url.startswith('https://')):
140
 
            from bzrlib.remotebranch import RemoteBranch
141
 
            return RemoteBranch(url)
142
 
        else:
143
 
            return LocalBranch(url)
144
 
 
145
 
    @staticmethod
146
 
    def initialize(base):
147
 
        """Create a new branch, rooted at 'base' (url)"""
148
 
        if base and (base.startswith('http://') or base.startswith('https://')):
149
 
            from bzrlib.remotebranch import RemoteBranch
150
 
            return RemoteBranch(base, init=True)
151
 
        else:
152
 
            return LocalBranch(base, init=True)
153
 
 
154
 
    def setup_caching(self, cache_root):
155
 
        """Subclasses that care about caching should override this, and set
156
 
        up cached stores located under cache_root.
157
 
        """
158
 
 
159
 
 
160
 
class LocalBranch(Branch):
161
 
    """A branch stored in the actual filesystem.
162
 
 
163
 
    Note that it's "local" in the context of the filesystem; it doesn't
164
 
    really matter if it's on an nfs/smb/afs/coda/... share, as long as
165
 
    it's writable, and can be accessed via the normal filesystem API.
 
143
        Base directory of the branch.
166
144
 
167
145
    _lock_mode
168
146
        None, or 'r' or 'w'
174
152
    _lock
175
153
        Lock object from bzrlib.lock.
176
154
    """
177
 
    # We actually expect this class to be somewhat short-lived; part of its
178
 
    # purpose is to try to isolate what bits of the branch logic are tied to
179
 
    # filesystem access, so that in a later step, we can extricate them to
180
 
    # a separarte ("storage") class.
 
155
    base = None
181
156
    _lock_mode = None
182
157
    _lock_count = None
183
158
    _lock = None
 
159
    
 
160
    # Map some sort of prefix into a namespace
 
161
    # stuff like "revno:10", "revid:", etc.
 
162
    # This should match a prefix with a function which accepts
 
163
    REVISION_NAMESPACES = {}
184
164
 
185
165
    def __init__(self, base, init=False, find_root=True):
186
166
        """Create new branch object at a particular location.
483
463
        """Print `file` to stdout."""
484
464
        self.lock_read()
485
465
        try:
486
 
            tree = self.revision_tree(self.get_rev_id(revno))
 
466
            tree = self.revision_tree(self.lookup_revision(revno))
487
467
            # use inventory as it was in that revision
488
468
            file_id = tree.inventory.path2id(file)
489
469
            if not file_id:
596
576
        try:
597
577
            try:
598
578
                return self.revision_store[revision_id]
599
 
            except (IndexError, KeyError):
 
579
            except IndexError:
600
580
                raise bzrlib.errors.NoSuchRevision(self, revision_id)
601
581
        finally:
602
582
            self.unlock()
821
801
 
822
802
        pb = bzrlib.ui.ui_factory.progress_bar()
823
803
        pb.update('comparing histories')
824
 
        if stop_revision is None:
825
 
            other_revision = other.last_patch()
826
 
        else:
827
 
            other_revision = other.get_rev_id(stop_revision)
828
 
        count = greedy_fetch(self, other, other_revision, pb)[0]
 
804
 
829
805
        try:
830
806
            revision_ids = self.missing_revisions(other, stop_revision)
831
807
        except DivergedBranches, e:
832
808
            try:
 
809
                if stop_revision is None:
 
810
                    end_revision = other.last_patch()
833
811
                revision_ids = get_intervening_revisions(self.last_patch(), 
834
 
                                                         other_revision, self)
 
812
                                                         end_revision, other)
835
813
                assert self.last_patch() not in revision_ids
836
814
            except bzrlib.errors.NotAncestor:
837
815
                raise e
838
816
 
 
817
        if len(revision_ids) > 0:
 
818
            count = greedy_fetch(self, other, revision_ids[-1], pb)[0]
 
819
        else:
 
820
            count = 0
839
821
        self.append_revision(*revision_ids)
 
822
        ## note("Added %d revisions." % count)
840
823
        pb.clear()
841
824
 
842
825
    def install_revisions(self, other, revision_ids, pb):
843
826
        if hasattr(other.revision_store, "prefetch"):
844
827
            other.revision_store.prefetch(revision_ids)
845
828
        if hasattr(other.inventory_store, "prefetch"):
846
 
            inventory_ids = []
847
 
            for rev_id in revision_ids:
848
 
                try:
849
 
                    revision = other.get_revision(rev_id).inventory_id
850
 
                    inventory_ids.append(revision)
851
 
                except bzrlib.errors.NoSuchRevision:
852
 
                    pass
 
829
            inventory_ids = [other.get_revision(r).inventory_id
 
830
                             for r in revision_ids]
853
831
            other.inventory_store.prefetch(inventory_ids)
854
832
 
855
833
        if pb is None:
898
876
        from bzrlib.commit import commit
899
877
        commit(self, *args, **kw)
900
878
        
 
879
 
 
880
    def lookup_revision(self, revision):
 
881
        """Return the revision identifier for a given revision information."""
 
882
        revno, info = self._get_revision_info(revision)
 
883
        return info
 
884
 
 
885
 
901
886
    def revision_id_to_revno(self, revision_id):
902
887
        """Given a revision id, return its revno"""
903
888
        history = self.revision_history()
906
891
        except ValueError:
907
892
            raise bzrlib.errors.NoSuchRevision(self, revision_id)
908
893
 
 
894
 
 
895
    def get_revision_info(self, revision):
 
896
        """Return (revno, revision id) for revision identifier.
 
897
 
 
898
        revision can be an integer, in which case it is assumed to be revno (though
 
899
            this will translate negative values into positive ones)
 
900
        revision can also be a string, in which case it is parsed for something like
 
901
            'date:' or 'revid:' etc.
 
902
        """
 
903
        revno, rev_id = self._get_revision_info(revision)
 
904
        if revno is None:
 
905
            raise bzrlib.errors.NoSuchRevision(self, revision)
 
906
        return revno, rev_id
 
907
 
909
908
    def get_rev_id(self, revno, history=None):
910
909
        """Find the revision id of the specified revno."""
911
910
        if revno == 0:
916
915
            raise bzrlib.errors.NoSuchRevision(self, revno)
917
916
        return history[revno - 1]
918
917
 
 
918
    def _get_revision_info(self, revision):
 
919
        """Return (revno, revision id) for revision specifier.
 
920
 
 
921
        revision can be an integer, in which case it is assumed to be revno
 
922
        (though this will translate negative values into positive ones)
 
923
        revision can also be a string, in which case it is parsed for something
 
924
        like 'date:' or 'revid:' etc.
 
925
 
 
926
        A revid is always returned.  If it is None, the specifier referred to
 
927
        the null revision.  If the revid does not occur in the revision
 
928
        history, revno will be None.
 
929
        """
 
930
        
 
931
        if revision is None:
 
932
            return 0, None
 
933
        revno = None
 
934
        try:# Convert to int if possible
 
935
            revision = int(revision)
 
936
        except ValueError:
 
937
            pass
 
938
        revs = self.revision_history()
 
939
        if isinstance(revision, int):
 
940
            if revision < 0:
 
941
                revno = len(revs) + revision + 1
 
942
            else:
 
943
                revno = revision
 
944
            rev_id = self.get_rev_id(revno, revs)
 
945
        elif isinstance(revision, basestring):
 
946
            for prefix, func in Branch.REVISION_NAMESPACES.iteritems():
 
947
                if revision.startswith(prefix):
 
948
                    result = func(self, revs, revision)
 
949
                    if len(result) > 1:
 
950
                        revno, rev_id = result
 
951
                    else:
 
952
                        revno = result[0]
 
953
                        rev_id = self.get_rev_id(revno, revs)
 
954
                    break
 
955
            else:
 
956
                raise BzrError('No namespace registered for string: %r' %
 
957
                               revision)
 
958
        else:
 
959
            raise TypeError('Unhandled revision type %s' % revision)
 
960
 
 
961
        if revno is None:
 
962
            if rev_id is None:
 
963
                raise bzrlib.errors.NoSuchRevision(self, revision)
 
964
        return revno, rev_id
 
965
 
 
966
    def _namespace_revno(self, revs, revision):
 
967
        """Lookup a revision by revision number"""
 
968
        assert revision.startswith('revno:')
 
969
        try:
 
970
            return (int(revision[6:]),)
 
971
        except ValueError:
 
972
            return None
 
973
    REVISION_NAMESPACES['revno:'] = _namespace_revno
 
974
 
 
975
    def _namespace_revid(self, revs, revision):
 
976
        assert revision.startswith('revid:')
 
977
        rev_id = revision[len('revid:'):]
 
978
        try:
 
979
            return revs.index(rev_id) + 1, rev_id
 
980
        except ValueError:
 
981
            return None, rev_id
 
982
    REVISION_NAMESPACES['revid:'] = _namespace_revid
 
983
 
 
984
    def _namespace_last(self, revs, revision):
 
985
        assert revision.startswith('last:')
 
986
        try:
 
987
            offset = int(revision[5:])
 
988
        except ValueError:
 
989
            return (None,)
 
990
        else:
 
991
            if offset <= 0:
 
992
                raise BzrError('You must supply a positive value for --revision last:XXX')
 
993
            return (len(revs) - offset + 1,)
 
994
    REVISION_NAMESPACES['last:'] = _namespace_last
 
995
 
 
996
    def _namespace_tag(self, revs, revision):
 
997
        assert revision.startswith('tag:')
 
998
        raise BzrError('tag: namespace registered, but not implemented.')
 
999
    REVISION_NAMESPACES['tag:'] = _namespace_tag
 
1000
 
 
1001
    def _namespace_date(self, revs, revision):
 
1002
        assert revision.startswith('date:')
 
1003
        import datetime
 
1004
        # Spec for date revisions:
 
1005
        #   date:value
 
1006
        #   value can be 'yesterday', 'today', 'tomorrow' or a YYYY-MM-DD string.
 
1007
        #   it can also start with a '+/-/='. '+' says match the first
 
1008
        #   entry after the given date. '-' is match the first entry before the date
 
1009
        #   '=' is match the first entry after, but still on the given date.
 
1010
        #
 
1011
        #   +2005-05-12 says find the first matching entry after May 12th, 2005 at 0:00
 
1012
        #   -2005-05-12 says find the first matching entry before May 12th, 2005 at 0:00
 
1013
        #   =2005-05-12 says find the first match after May 12th, 2005 at 0:00 but before
 
1014
        #       May 13th, 2005 at 0:00
 
1015
        #
 
1016
        #   So the proper way of saying 'give me all entries for today' is:
 
1017
        #       -r {date:+today}:{date:-tomorrow}
 
1018
        #   The default is '=' when not supplied
 
1019
        val = revision[5:]
 
1020
        match_style = '='
 
1021
        if val[:1] in ('+', '-', '='):
 
1022
            match_style = val[:1]
 
1023
            val = val[1:]
 
1024
 
 
1025
        today = datetime.datetime.today().replace(hour=0,minute=0,second=0,microsecond=0)
 
1026
        if val.lower() == 'yesterday':
 
1027
            dt = today - datetime.timedelta(days=1)
 
1028
        elif val.lower() == 'today':
 
1029
            dt = today
 
1030
        elif val.lower() == 'tomorrow':
 
1031
            dt = today + datetime.timedelta(days=1)
 
1032
        else:
 
1033
            import re
 
1034
            # This should be done outside the function to avoid recompiling it.
 
1035
            _date_re = re.compile(
 
1036
                    r'(?P<date>(?P<year>\d\d\d\d)-(?P<month>\d\d)-(?P<day>\d\d))?'
 
1037
                    r'(,|T)?\s*'
 
1038
                    r'(?P<time>(?P<hour>\d\d):(?P<minute>\d\d)(:(?P<second>\d\d))?)?'
 
1039
                )
 
1040
            m = _date_re.match(val)
 
1041
            if not m or (not m.group('date') and not m.group('time')):
 
1042
                raise BzrError('Invalid revision date %r' % revision)
 
1043
 
 
1044
            if m.group('date'):
 
1045
                year, month, day = int(m.group('year')), int(m.group('month')), int(m.group('day'))
 
1046
            else:
 
1047
                year, month, day = today.year, today.month, today.day
 
1048
            if m.group('time'):
 
1049
                hour = int(m.group('hour'))
 
1050
                minute = int(m.group('minute'))
 
1051
                if m.group('second'):
 
1052
                    second = int(m.group('second'))
 
1053
                else:
 
1054
                    second = 0
 
1055
            else:
 
1056
                hour, minute, second = 0,0,0
 
1057
 
 
1058
            dt = datetime.datetime(year=year, month=month, day=day,
 
1059
                    hour=hour, minute=minute, second=second)
 
1060
        first = dt
 
1061
        last = None
 
1062
        reversed = False
 
1063
        if match_style == '-':
 
1064
            reversed = True
 
1065
        elif match_style == '=':
 
1066
            last = dt + datetime.timedelta(days=1)
 
1067
 
 
1068
        if reversed:
 
1069
            for i in range(len(revs)-1, -1, -1):
 
1070
                r = self.get_revision(revs[i])
 
1071
                # TODO: Handle timezone.
 
1072
                dt = datetime.datetime.fromtimestamp(r.timestamp)
 
1073
                if first >= dt and (last is None or dt >= last):
 
1074
                    return (i+1,)
 
1075
        else:
 
1076
            for i in range(len(revs)):
 
1077
                r = self.get_revision(revs[i])
 
1078
                # TODO: Handle timezone.
 
1079
                dt = datetime.datetime.fromtimestamp(r.timestamp)
 
1080
                if first <= dt and (last is None or dt <= last):
 
1081
                    return (i+1,)
 
1082
    REVISION_NAMESPACES['date:'] = _namespace_date
919
1083
 
920
1084
    def revision_tree(self, revision_id):
921
1085
        """Return Tree for a revision on this branch.
1204
1368
            raise InvalidRevisionNumber(revno)
1205
1369
        
1206
1370
        
1207
 
        
1208
 
 
1209
 
 
1210
 
class ScratchBranch(LocalBranch):
 
1371
 
 
1372
 
 
1373
class ScratchBranch(Branch):
1211
1374
    """Special test class: a branch that cleans up after itself.
1212
1375
 
1213
1376
    >>> b = ScratchBranch()
1230
1393
        if base is None:
1231
1394
            base = mkdtemp()
1232
1395
            init = True
1233
 
        LocalBranch.__init__(self, base, init=init)
 
1396
        Branch.__init__(self, base, init=init)
1234
1397
        for d in dirs:
1235
1398
            os.mkdir(self.abspath(d))
1236
1399
            
1342
1505
        The name of a local directory that exists but is empty.
1343
1506
    """
1344
1507
    from bzrlib.merge import merge
1345
 
    from bzrlib.revisionspec import RevisionSpec
1346
1508
 
1347
1509
    assert isinstance(branch_from, Branch)
1348
1510
    assert isinstance(to_location, basestring)
1349
1511
    
1350
 
    br_to = Branch.initialize(to_location)
 
1512
    br_to = Branch(to_location, init=True)
1351
1513
    br_to.set_root_id(branch_from.get_root_id())
1352
1514
    if revision is None:
1353
1515
        revno = branch_from.revno()
1354
1516
    else:
1355
 
        revno, rev_id = RevisionSpec(revision).in_history(branch_from)
 
1517
        revno, rev_id = branch_from.get_revision_info(revision)
1356
1518
    br_to.update_revisions(branch_from, stop_revision=revno)
1357
1519
    merge((to_location, -1), (to_location, 0), this_dir=to_location,
1358
1520
          check_clean=False, ignore_zero=True)
 
1521
    
1359
1522
    br_to.set_parent(branch_from.base)
1360
 
    return br_to