~bzr-pqm/bzr/bzr.dev

1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
1
# Copyright (C) 2005 Canonical Ltd
2
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
7
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
# GNU General Public License for more details.
12
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
17
18
import datetime
19
import re
1688.2.2 by Guillaume Pinot
Binary search for 'date:' revision.
20
import bisect
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
21
from bzrlib.errors import BzrError, NoSuchRevision, NoCommits
22
23
_marker = []
24
25
class RevisionInfo(object):
26
    """The results of applying a revision specification to a branch.
27
28
    An instance has two useful attributes: revno, and rev_id.
29
30
    They can also be accessed as spec[0] and spec[1] respectively,
31
    so that you can write code like:
32
    revno, rev_id = RevisionSpec(branch, spec)
33
    although this is probably going to be deprecated later.
34
35
    This class exists mostly to be the return value of a RevisionSpec,
36
    so that you can access the member you're interested in (number or id)
37
    or treat the result as a tuple.
38
    """
39
40
    def __init__(self, branch, revno, rev_id=_marker):
41
        self.branch = branch
42
        self.revno = revno
43
        if rev_id is _marker:
44
            # allow caller to be lazy
45
            if self.revno is None:
46
                self.rev_id = None
47
            else:
48
                self.rev_id = branch.get_rev_id(self.revno)
49
        else:
50
            self.rev_id = rev_id
51
52
    def __nonzero__(self):
53
        # first the easy ones...
54
        if self.rev_id is None:
55
            return False
56
        if self.revno is not None:
57
            return True
58
        # TODO: otherwise, it should depend on how I was built -
59
        # if it's in_history(branch), then check revision_history(),
60
        # if it's in_store(branch), do the check below
1185.67.2 by Aaron Bentley
Renamed Branch.storage to Branch.repository
61
        return self.branch.repository.has_revision(self.rev_id)
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
62
63
    def __len__(self):
64
        return 2
65
66
    def __getitem__(self, index):
67
        if index == 0: return self.revno
68
        if index == 1: return self.rev_id
69
        raise IndexError(index)
70
71
    def get(self):
1185.67.2 by Aaron Bentley
Renamed Branch.storage to Branch.repository
72
        return self.branch.repository.get_revision(self.rev_id)
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
73
74
    def __eq__(self, other):
75
        if type(other) not in (tuple, list, type(self)):
76
            return False
77
        if type(other) is type(self) and self.branch is not other.branch:
78
            return False
79
        return tuple(self) == tuple(other)
80
81
    def __repr__(self):
82
        return '<bzrlib.revisionspec.RevisionInfo object %s, %s for %r>' % (
83
            self.revno, self.rev_id, self.branch)
84
85
# classes in this list should have a "prefix" attribute, against which
86
# string specs are matched
87
SPEC_TYPES = []
88
89
class RevisionSpec(object):
90
    """A parsed revision specification.
91
92
    A revision specification can be an integer, in which case it is
93
    assumed to be a revno (though this will translate negative values
94
    into positive ones); or it can be a string, in which case it is
95
    parsed for something like 'date:' or 'revid:' etc.
96
97
    Revision specs are an UI element, and they have been moved out
98
    of the branch class to leave "back-end" classes unaware of such
99
    details.  Code that gets a revno or rev_id from other code should
100
    not be using revision specs - revnos and revision ids are the
101
    accepted ways to refer to revisions internally.
102
103
    (Equivalent to the old Branch method get_revision_info())
104
    """
105
106
    prefix = None
107
108
    def __new__(cls, spec, foo=_marker):
109
        """Parse a revision specifier.
110
        """
111
        if spec is None:
112
            return object.__new__(RevisionSpec, spec)
113
114
        try:
115
            spec = int(spec)
116
        except ValueError:
117
            pass
118
119
        if isinstance(spec, int):
120
            return object.__new__(RevisionSpec_int, spec)
121
        elif isinstance(spec, basestring):
122
            for spectype in SPEC_TYPES:
123
                if spec.startswith(spectype.prefix):
124
                    return object.__new__(spectype, spec)
125
            else:
126
                raise BzrError('No namespace registered for string: %r' %
127
                               spec)
128
        else:
129
            raise TypeError('Unhandled revision type %s' % spec)
130
131
    def __init__(self, spec):
132
        if self.prefix and spec.startswith(self.prefix):
133
            spec = spec[len(self.prefix):]
134
        self.spec = spec
135
136
    def _match_on(self, branch, revs):
137
        return RevisionInfo(branch, 0, None)
138
139
    def _match_on_and_check(self, branch, revs):
140
        info = self._match_on(branch, revs)
141
        if info:
142
            return info
143
        elif info == (0, None):
144
            # special case - the empty tree
145
            return info
146
        elif self.prefix:
147
            raise NoSuchRevision(branch, self.prefix + str(self.spec))
148
        else:
149
            raise NoSuchRevision(branch, str(self.spec))
150
151
    def in_history(self, branch):
152
        revs = branch.revision_history()
153
        return self._match_on_and_check(branch, revs)
154
1432 by Robert Collins
branch: namespace
155
        # FIXME: in_history is somewhat broken,
156
        # it will return non-history revisions in many
157
        # circumstances. The expected facility is that
158
        # in_history only returns revision-history revs,
159
        # in_store returns any rev. RBC 20051010
160
    # aliases for now, when we fix the core logic, then they
161
    # will do what you expect.
162
    in_store = in_history
163
    in_branch = in_store
164
        
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
165
    def __repr__(self):
166
        # this is mostly for helping with testing
167
        return '<%s %s%s>' % (self.__class__.__name__,
168
                              self.prefix or '',
169
                              self.spec)
170
171
172
# private API
173
174
class RevisionSpec_int(RevisionSpec):
175
    """Spec is a number.  Special case."""
176
    def __init__(self, spec):
177
        self.spec = int(spec)
178
179
    def _match_on(self, branch, revs):
180
        if self.spec < 0:
181
            revno = len(revs) + self.spec + 1
182
        else:
183
            revno = self.spec
184
        rev_id = branch.get_rev_id(revno, revs)
185
        return RevisionInfo(branch, revno, rev_id)
186
187
188
class RevisionSpec_revno(RevisionSpec):
189
    prefix = 'revno:'
190
191
    def _match_on(self, branch, revs):
192
        """Lookup a revision by revision number"""
193
        try:
194
            return RevisionInfo(branch, int(self.spec))
195
        except ValueError:
196
            return RevisionInfo(branch, None)
197
198
SPEC_TYPES.append(RevisionSpec_revno)
199
200
201
class RevisionSpec_revid(RevisionSpec):
202
    prefix = 'revid:'
203
204
    def _match_on(self, branch, revs):
205
        try:
206
            return RevisionInfo(branch, revs.index(self.spec) + 1, self.spec)
207
        except ValueError:
1185.62.5 by John Arbash Meinel
Updated -r revid:foo so that it can match revisions which aren't in the revision history
208
            return RevisionInfo(branch, None, self.spec)
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
209
210
SPEC_TYPES.append(RevisionSpec_revid)
211
212
213
class RevisionSpec_last(RevisionSpec):
1185.1.39 by Robert Collins
Robey Pointers before: namespace to clear up usage of dates in revision parameters
214
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
215
    prefix = 'last:'
216
217
    def _match_on(self, branch, revs):
218
        try:
219
            offset = int(self.spec)
220
        except ValueError:
221
            return RevisionInfo(branch, None)
222
        else:
223
            if offset <= 0:
224
                raise BzrError('You must supply a positive value for --revision last:XXX')
225
            return RevisionInfo(branch, len(revs) - offset + 1)
226
227
SPEC_TYPES.append(RevisionSpec_last)
228
229
1185.1.39 by Robert Collins
Robey Pointers before: namespace to clear up usage of dates in revision parameters
230
class RevisionSpec_before(RevisionSpec):
231
232
    prefix = 'before:'
233
    
234
    def _match_on(self, branch, revs):
235
        r = RevisionSpec(self.spec)._match_on(branch, revs)
236
        if (r.revno is None) or (r.revno == 0):
237
            return r
238
        return RevisionInfo(branch, r.revno - 1)
239
240
SPEC_TYPES.append(RevisionSpec_before)
241
242
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
243
class RevisionSpec_tag(RevisionSpec):
244
    prefix = 'tag:'
245
246
    def _match_on(self, branch, revs):
247
        raise BzrError('tag: namespace registered, but not implemented.')
248
249
SPEC_TYPES.append(RevisionSpec_tag)
250
251
1688.2.2 by Guillaume Pinot
Binary search for 'date:' revision.
252
class RevisionSpec_revs:
253
    def __init__(self, revs, branch):
254
        self.revs = revs
255
        self.branch = branch
256
    def __getitem__(self, index):
257
        r = self.branch.repository.get_revision(self.revs[index])
258
        # TODO: Handle timezone.
259
        return datetime.datetime.fromtimestamp(r.timestamp)
260
    def __len__(self):
261
        return len(self.revs)
262
263
1704.2.27 by Martin Pool
Run bisection search for revision date with lock held. (Robert Widhopf-Frenk)
264
class RevisionSpec_revs:
265
    def __init__(self, revs, branch):
266
        self.revs = revs
267
        self.branch = branch
268
    def __getitem__(self, index):
269
        r = self.branch.repository.get_revision(self.revs[index])
270
        # TODO: Handle timezone.
271
        return datetime.datetime.fromtimestamp(r.timestamp)
272
    def __len__(self):
273
        return len(self.revs)
274
275
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
276
class RevisionSpec_date(RevisionSpec):
277
    prefix = 'date:'
278
    _date_re = re.compile(
279
            r'(?P<date>(?P<year>\d\d\d\d)-(?P<month>\d\d)-(?P<day>\d\d))?'
280
            r'(,|T)?\s*'
281
            r'(?P<time>(?P<hour>\d\d):(?P<minute>\d\d)(:(?P<second>\d\d))?)?'
282
        )
283
284
    def _match_on(self, branch, revs):
285
        """
286
        Spec for date revisions:
287
          date:value
288
          value can be 'yesterday', 'today', 'tomorrow' or a YYYY-MM-DD string.
1185.1.39 by Robert Collins
Robey Pointers before: namespace to clear up usage of dates in revision parameters
289
          matches the first entry after a given date (either at midnight or
290
          at a specified time).
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
291
292
          So the proper way of saying 'give me all entries for today' is:
1185.1.39 by Robert Collins
Robey Pointers before: namespace to clear up usage of dates in revision parameters
293
              -r date:today..date:tomorrow
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
294
        """
1185.1.39 by Robert Collins
Robey Pointers before: namespace to clear up usage of dates in revision parameters
295
        today = datetime.datetime.fromordinal(datetime.date.today().toordinal())
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
296
        if self.spec.lower() == 'yesterday':
297
            dt = today - datetime.timedelta(days=1)
298
        elif self.spec.lower() == 'today':
299
            dt = today
300
        elif self.spec.lower() == 'tomorrow':
301
            dt = today + datetime.timedelta(days=1)
302
        else:
303
            m = self._date_re.match(self.spec)
304
            if not m or (not m.group('date') and not m.group('time')):
305
                raise BzrError('Invalid revision date %r' % self.spec)
306
307
            if m.group('date'):
308
                year, month, day = int(m.group('year')), int(m.group('month')), int(m.group('day'))
309
            else:
310
                year, month, day = today.year, today.month, today.day
311
            if m.group('time'):
312
                hour = int(m.group('hour'))
313
                minute = int(m.group('minute'))
314
                if m.group('second'):
315
                    second = int(m.group('second'))
316
                else:
317
                    second = 0
318
            else:
319
                hour, minute, second = 0,0,0
320
321
            dt = datetime.datetime(year=year, month=month, day=day,
322
                    hour=hour, minute=minute, second=second)
1704.2.27 by Martin Pool
Run bisection search for revision date with lock held. (Robert Widhopf-Frenk)
323
        branch.lock_read()
324
        try:
325
            rev = bisect.bisect(RevisionSpec_revs(revs, branch), dt)
326
        finally:
327
            branch.unlock()
1688.2.2 by Guillaume Pinot
Binary search for 'date:' revision.
328
        if rev == len(revs):
329
            return RevisionInfo(branch, None)
330
        else:
331
            return RevisionInfo(branch, rev + 1)
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
332
333
SPEC_TYPES.append(RevisionSpec_date)
334
335
336
class RevisionSpec_ancestor(RevisionSpec):
337
    prefix = 'ancestor:'
338
339
    def _match_on(self, branch, revs):
340
        from branch import Branch
341
        from revision import common_ancestor, MultipleRevisionSources
1442.1.64 by Robert Collins
Branch.open_containing now returns a tuple (Branch, relative-path).
342
        other_branch = Branch.open_containing(self.spec)[0]
1390 by Robert Collins
pair programming worx... merge integration and weave
343
        revision_a = branch.last_revision()
344
        revision_b = other_branch.last_revision()
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
345
        for r, b in ((revision_a, branch), (revision_b, other_branch)):
346
            if r is None:
347
                raise NoCommits(b)
1185.67.2 by Aaron Bentley
Renamed Branch.storage to Branch.repository
348
        revision_source = MultipleRevisionSources(branch.repository,
349
                                                  other_branch.repository)
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
350
        rev_id = common_ancestor(revision_a, revision_b, revision_source)
351
        try:
352
            revno = branch.revision_id_to_revno(rev_id)
353
        except NoSuchRevision:
354
            revno = None
355
        return RevisionInfo(branch, revno, rev_id)
356
        
357
SPEC_TYPES.append(RevisionSpec_ancestor)
1432 by Robert Collins
branch: namespace
358
359
class RevisionSpec_branch(RevisionSpec):
360
    """A branch: revision specifier.
361
362
    This takes the path to a branch and returns its tip revision id.
363
    """
364
    prefix = 'branch:'
365
366
    def _match_on(self, branch, revs):
367
        from branch import Branch
1442.1.64 by Robert Collins
Branch.open_containing now returns a tuple (Branch, relative-path).
368
        other_branch = Branch.open_containing(self.spec)[0]
1432 by Robert Collins
branch: namespace
369
        revision_b = other_branch.last_revision()
370
        if revision_b is None:
371
            raise NoCommits(other_branch)
372
        # pull in the remote revisions so we can diff
1534.1.31 by Robert Collins
Deprecated fetch.fetch and fetch.greedy_fetch for branch.fetch, and move the Repository.fetch internals to InterRepo and InterWeaveRepo.
373
        branch.fetch(other_branch, revision_b)
1432 by Robert Collins
branch: namespace
374
        try:
375
            revno = branch.revision_id_to_revno(revision_b)
376
        except NoSuchRevision:
377
            revno = None
378
        return RevisionInfo(branch, revno, revision_b)
379
        
380
SPEC_TYPES.append(RevisionSpec_branch)