1
# Copyright (C) 2005 Canonical Ltd
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.
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.
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
25
from bzrlib.errors import BzrError, NoSuchRevision, NoCommits
29
class RevisionInfo(object):
30
"""The results of applying a revision specification to a branch.
32
An instance has two useful attributes: revno, and rev_id.
34
They can also be accessed as spec[0] and spec[1] respectively,
35
so that you can write code like:
36
revno, rev_id = RevisionSpec(branch, spec)
37
although this is probably going to be deprecated later.
39
This class exists mostly to be the return value of a RevisionSpec,
40
so that you can access the member you're interested in (number or id)
41
or treat the result as a tuple.
44
def __init__(self, branch, revno, rev_id=_marker):
48
# allow caller to be lazy
49
if self.revno is None:
52
self.rev_id = branch.get_rev_id(self.revno)
56
def __nonzero__(self):
57
# first the easy ones...
58
if self.rev_id is None:
60
if self.revno is not None:
62
# TODO: otherwise, it should depend on how I was built -
63
# if it's in_history(branch), then check revision_history(),
64
# if it's in_store(branch), do the check below
65
return self.branch.repository.has_revision(self.rev_id)
70
def __getitem__(self, index):
71
if index == 0: return self.revno
72
if index == 1: return self.rev_id
73
raise IndexError(index)
76
return self.branch.repository.get_revision(self.rev_id)
78
def __eq__(self, other):
79
if type(other) not in (tuple, list, type(self)):
81
if type(other) is type(self) and self.branch is not other.branch:
83
return tuple(self) == tuple(other)
86
return '<bzrlib.revisionspec.RevisionInfo object %s, %s for %r>' % (
87
self.revno, self.rev_id, self.branch)
89
# classes in this list should have a "prefix" attribute, against which
90
# string specs are matched
93
class RevisionSpec(object):
94
"""A parsed revision specification.
96
A revision specification can be an integer, in which case it is
97
assumed to be a revno (though this will translate negative values
98
into positive ones); or it can be a string, in which case it is
99
parsed for something like 'date:' or 'revid:' etc.
101
Revision specs are an UI element, and they have been moved out
102
of the branch class to leave "back-end" classes unaware of such
103
details. Code that gets a revno or rev_id from other code should
104
not be using revision specs - revnos and revision ids are the
105
accepted ways to refer to revisions internally.
107
(Equivalent to the old Branch method get_revision_info())
112
def __new__(cls, spec, foo=_marker):
113
"""Parse a revision specifier.
116
return object.__new__(RevisionSpec, spec)
123
if isinstance(spec, int):
124
return object.__new__(RevisionSpec_int, spec)
125
elif isinstance(spec, basestring):
126
for spectype in SPEC_TYPES:
127
if spec.startswith(spectype.prefix):
128
return object.__new__(spectype, spec)
130
raise BzrError('No namespace registered for string: %r' %
133
raise TypeError('Unhandled revision type %s' % spec)
135
def __init__(self, spec):
136
if self.prefix and spec.startswith(self.prefix):
137
spec = spec[len(self.prefix):]
140
def _match_on(self, branch, revs):
141
return RevisionInfo(branch, 0, None)
143
def _match_on_and_check(self, branch, revs):
144
info = self._match_on(branch, revs)
147
elif info == (0, None):
148
# special case - the empty tree
151
raise errors.InvalidRevisionSpec(self.prefix + self.spec, branch)
153
raise errors.InvalidRevisionSpec(self.spec, branch)
155
def in_history(self, branch):
157
revs = branch.revision_history()
160
return self._match_on_and_check(branch, revs)
162
# FIXME: in_history is somewhat broken,
163
# it will return non-history revisions in many
164
# circumstances. The expected facility is that
165
# in_history only returns revision-history revs,
166
# in_store returns any rev. RBC 20051010
167
# aliases for now, when we fix the core logic, then they
168
# will do what you expect.
169
in_store = in_history
173
# this is mostly for helping with testing
174
return '<%s %s%s>' % (self.__class__.__name__,
178
def needs_branch(self):
179
"""Whether this revision spec needs a branch.
181
Set this to False the branch argument of _match_on is not used.
187
class RevisionSpec_int(RevisionSpec):
188
"""Spec is a number. Special case."""
190
def __init__(self, spec):
191
self.spec = int(spec)
193
def _match_on(self, branch, revs):
195
revno = len(revs) + self.spec + 1
199
rev_id = branch.get_rev_id(revno, revs)
200
except NoSuchRevision:
201
raise errors.InvalidRevisionSpec(self.spec, branch)
202
return RevisionInfo(branch, revno, rev_id)
205
class RevisionSpec_revno(RevisionSpec):
208
def _match_on(self, branch, revs):
209
"""Lookup a revision by revision number"""
210
loc = self.spec.find(':')
212
revno_spec = self.spec
215
revno_spec = self.spec[:loc]
216
branch_spec = self.spec[loc+1:]
220
raise errors.InvalidRevisionSpec(self.prefix + self.spec,
221
branch, 'cannot have an empty revno and no branch')
225
revno = int(revno_spec)
226
except ValueError, e:
227
raise errors.InvalidRevisionSpec(self.prefix + self.spec,
231
revno = len(revs) + revno + 1
234
from bzrlib.branch import Branch
235
branch = Branch.open(branch_spec)
238
revid = branch.get_rev_id(revno)
239
except NoSuchRevision:
240
raise errors.InvalidRevisionSpec(self.prefix + self.spec, branch)
242
return RevisionInfo(branch, revno)
244
def needs_branch(self):
245
return self.spec.find(':') == -1
247
SPEC_TYPES.append(RevisionSpec_revno)
250
class RevisionSpec_revid(RevisionSpec):
253
def _match_on(self, branch, revs):
255
revno = revs.index(self.spec) + 1
258
return RevisionInfo(branch, revno, self.spec)
260
SPEC_TYPES.append(RevisionSpec_revid)
263
class RevisionSpec_last(RevisionSpec):
267
def _match_on(self, branch, revs):
270
raise NoCommits(branch)
271
return RevisionInfo(branch, len(revs), revs[-1])
274
offset = int(self.spec)
275
except ValueError, e:
276
raise errors.InvalidRevisionSpec(self.prefix + self.spec, branch, e)
279
raise errors.InvalidRevisionSpec(self.prefix + self.spec, branch,
280
'you must supply a positive value')
281
revno = len(revs) - offset + 1
283
revision_id = branch.get_rev_id(revno, revs)
284
except errors.NoSuchRevision:
285
raise errors.InvalidRevisionSpec(self.prefix + self.spec, branch)
286
return RevisionInfo(branch, revno, revision_id)
288
SPEC_TYPES.append(RevisionSpec_last)
291
class RevisionSpec_before(RevisionSpec):
295
def _match_on(self, branch, revs):
296
r = RevisionSpec(self.spec)._match_on(branch, revs)
297
if (r.revno is None) or (r.revno == 0):
299
return RevisionInfo(branch, r.revno - 1)
301
SPEC_TYPES.append(RevisionSpec_before)
304
class RevisionSpec_tag(RevisionSpec):
307
def _match_on(self, branch, revs):
308
raise errors.InvalidRevisionSpec(self.prefix + self.spec, branch,
309
'tag: namespace registered,'
310
' but not implemented')
312
SPEC_TYPES.append(RevisionSpec_tag)
315
class RevisionSpec_revs:
316
def __init__(self, revs, branch):
319
def __getitem__(self, index):
320
r = self.branch.repository.get_revision(self.revs[index])
321
# TODO: Handle timezone.
322
return datetime.datetime.fromtimestamp(r.timestamp)
324
return len(self.revs)
327
class RevisionSpec_date(RevisionSpec):
329
_date_re = re.compile(
330
r'(?P<date>(?P<year>\d\d\d\d)-(?P<month>\d\d)-(?P<day>\d\d))?'
332
r'(?P<time>(?P<hour>\d\d):(?P<minute>\d\d)(:(?P<second>\d\d))?)?'
335
def _match_on(self, branch, revs):
337
Spec for date revisions:
339
value can be 'yesterday', 'today', 'tomorrow' or a YYYY-MM-DD string.
340
matches the first entry after a given date (either at midnight or
341
at a specified time).
343
So the proper way of saying 'give me all entries for today' is:
344
-r date:yesterday..date:today
346
today = datetime.datetime.fromordinal(datetime.date.today().toordinal())
347
if self.spec.lower() == 'yesterday':
348
dt = today - datetime.timedelta(days=1)
349
elif self.spec.lower() == 'today':
351
elif self.spec.lower() == 'tomorrow':
352
dt = today + datetime.timedelta(days=1)
354
m = self._date_re.match(self.spec)
355
if not m or (not m.group('date') and not m.group('time')):
356
raise BzrError('Invalid revision date %r' % self.spec)
359
year, month, day = int(m.group('year')), int(m.group('month')), int(m.group('day'))
361
year, month, day = today.year, today.month, today.day
363
hour = int(m.group('hour'))
364
minute = int(m.group('minute'))
365
if m.group('second'):
366
second = int(m.group('second'))
370
hour, minute, second = 0,0,0
372
dt = datetime.datetime(year=year, month=month, day=day,
373
hour=hour, minute=minute, second=second)
376
rev = bisect.bisect(RevisionSpec_revs(revs, branch), dt)
380
return RevisionInfo(branch, None)
382
return RevisionInfo(branch, rev + 1)
384
SPEC_TYPES.append(RevisionSpec_date)
387
class RevisionSpec_ancestor(RevisionSpec):
390
def _match_on(self, branch, revs):
391
from branch import Branch
392
from revision import common_ancestor, MultipleRevisionSources
393
other_branch = Branch.open_containing(self.spec)[0]
394
revision_a = branch.last_revision()
395
revision_b = other_branch.last_revision()
396
for r, b in ((revision_a, branch), (revision_b, other_branch)):
399
revision_source = MultipleRevisionSources(branch.repository,
400
other_branch.repository)
401
rev_id = common_ancestor(revision_a, revision_b, revision_source)
403
revno = branch.revision_id_to_revno(rev_id)
404
except NoSuchRevision:
406
return RevisionInfo(branch, revno, rev_id)
408
SPEC_TYPES.append(RevisionSpec_ancestor)
410
class RevisionSpec_branch(RevisionSpec):
411
"""A branch: revision specifier.
413
This takes the path to a branch and returns its tip revision id.
417
def _match_on(self, branch, revs):
418
from branch import Branch
419
other_branch = Branch.open_containing(self.spec)[0]
420
revision_b = other_branch.last_revision()
421
if revision_b is None:
422
raise NoCommits(other_branch)
423
# pull in the remote revisions so we can diff
424
branch.fetch(other_branch, revision_b)
426
revno = branch.revision_id_to_revno(revision_b)
427
except NoSuchRevision:
429
return RevisionInfo(branch, revno, revision_b)
431
SPEC_TYPES.append(RevisionSpec_branch)