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
33
class RevisionInfo(object):
34
"""The results of applying a revision specification to a branch.
36
An instance has two useful attributes: revno, and rev_id.
38
They can also be accessed as spec[0] and spec[1] respectively,
39
so that you can write code like:
40
revno, rev_id = RevisionSpec(branch, spec)
41
although this is probably going to be deprecated later.
43
This class exists mostly to be the return value of a RevisionSpec,
44
so that you can access the member you're interested in (number or id)
45
or treat the result as a tuple.
48
def __init__(self, branch, revno, rev_id=_marker):
52
# allow caller to be lazy
53
if self.revno is None:
56
self.rev_id = branch.get_rev_id(self.revno)
60
def __nonzero__(self):
61
# first the easy ones...
62
if self.rev_id is None:
64
if self.revno is not None:
66
# TODO: otherwise, it should depend on how I was built -
67
# if it's in_history(branch), then check revision_history(),
68
# if it's in_store(branch), do the check below
69
return self.branch.repository.has_revision(self.rev_id)
74
def __getitem__(self, index):
75
if index == 0: return self.revno
76
if index == 1: return self.rev_id
77
raise IndexError(index)
80
return self.branch.repository.get_revision(self.rev_id)
82
def __eq__(self, other):
83
if type(other) not in (tuple, list, type(self)):
85
if type(other) is type(self) and self.branch is not other.branch:
87
return tuple(self) == tuple(other)
90
return '<bzrlib.revisionspec.RevisionInfo object %s, %s for %r>' % (
91
self.revno, self.rev_id, self.branch)
94
# classes in this list should have a "prefix" attribute, against which
95
# string specs are matched
99
class RevisionSpec(object):
100
"""A parsed revision specification.
102
A revision specification can be an integer, in which case it is
103
assumed to be a revno (though this will translate negative values
104
into positive ones); or it can be a string, in which case it is
105
parsed for something like 'date:' or 'revid:' etc.
107
Revision specs are an UI element, and they have been moved out
108
of the branch class to leave "back-end" classes unaware of such
109
details. Code that gets a revno or rev_id from other code should
110
not be using revision specs - revnos and revision ids are the
111
accepted ways to refer to revisions internally.
113
(Equivalent to the old Branch method get_revision_info())
118
def __new__(cls, spec, _internal=False):
120
return object.__new__(cls, spec, _internal=_internal)
122
symbol_versioning.warn('Creating a RevisionSpec directly has'
123
' been deprecated in version 0.11. Use'
124
' RevisionSpec.from_string()'
126
DeprecationWarning, stacklevel=2)
127
return RevisionSpec.from_string(spec)
130
def from_string(spec):
131
"""Parse a revision spec string into a RevisionSpec object.
133
:param spec: A string specified by the user
134
:return: A RevisionSpec object that understands how to parse the
137
if not isinstance(spec, (type(None), basestring)):
138
raise TypeError('error')
141
return RevisionSpec(None, _internal=True)
143
assert isinstance(spec, basestring), \
144
"You should only supply strings not %s" % (type(spec),)
146
for spectype in SPEC_TYPES:
147
if spec.startswith(spectype.prefix):
148
trace.mutter('Returning RevisionSpec %s for %s',
149
spectype.__name__, spec)
150
return spectype(spec, _internal=True)
152
# RevisionSpec_revno is special cased, because it is the only
153
# one that directly handles plain integers
155
if _revno_regex is None:
156
_revno_regex = re.compile(r'-?\d+(:.*)?$')
157
if _revno_regex.match(spec) is not None:
158
return RevisionSpec_revno(spec, _internal=True)
160
raise errors.NoSuchRevisionSpec(spec)
162
def __init__(self, spec, _internal=False):
163
"""Create a RevisionSpec referring to the Null revision.
165
:param spec: The original spec supplied by the user
166
:param _internal: Used to ensure that RevisionSpec is not being
167
called directly. Only from RevisionSpec.from_string()
170
# XXX: Update this after 0.10 is released
171
symbol_versioning.warn('Creating a RevisionSpec directly has'
172
' been deprecated in version 0.11. Use'
173
' RevisionSpec.from_string()'
175
DeprecationWarning, stacklevel=2)
176
self.user_spec = spec
177
if self.prefix and spec.startswith(self.prefix):
178
spec = spec[len(self.prefix):]
181
def _match_on(self, branch, revs):
182
trace.mutter('Returning RevisionSpec._match_on: None')
183
return RevisionInfo(branch, 0, None)
185
def _match_on_and_check(self, branch, revs):
186
info = self._match_on(branch, revs)
189
elif info == (0, None):
190
# special case - the empty tree
193
raise errors.InvalidRevisionSpec(self.user_spec, branch)
195
raise errors.InvalidRevisionSpec(self.spec, branch)
197
def in_history(self, branch):
199
revs = branch.revision_history()
202
return self._match_on_and_check(branch, revs)
204
# FIXME: in_history is somewhat broken,
205
# it will return non-history revisions in many
206
# circumstances. The expected facility is that
207
# in_history only returns revision-history revs,
208
# in_store returns any rev. RBC 20051010
209
# aliases for now, when we fix the core logic, then they
210
# will do what you expect.
211
in_store = in_history
215
# this is mostly for helping with testing
216
return '<%s %s>' % (self.__class__.__name__,
219
def needs_branch(self):
220
"""Whether this revision spec needs a branch.
222
Set this to False the branch argument of _match_on is not used.
232
class RevisionSpec_revno(RevisionSpec):
235
def _match_on(self, branch, revs):
236
"""Lookup a revision by revision number"""
237
loc = self.spec.find(':')
239
revno_spec = self.spec
242
revno_spec = self.spec[:loc]
243
branch_spec = self.spec[loc+1:]
247
raise errors.InvalidRevisionSpec(self.user_spec,
248
branch, 'cannot have an empty revno and no branch')
252
revno = int(revno_spec)
253
except ValueError, e:
254
raise errors.InvalidRevisionSpec(self.user_spec,
258
from bzrlib.branch import Branch
259
branch = Branch.open(branch_spec)
260
# Need to use a new revision history
261
# because we are using a specific branch
262
revs = branch.revision_history()
265
if (-revno) >= len(revs):
268
revno = len(revs) + revno + 1
270
revision_id = branch.get_rev_id(revno, revs)
271
except errors.NoSuchRevision:
272
raise errors.InvalidRevisionSpec(self.user_spec, branch)
273
return RevisionInfo(branch, revno, revision_id)
275
def needs_branch(self):
276
return self.spec.find(':') == -1
279
RevisionSpec_int = RevisionSpec_revno
281
SPEC_TYPES.append(RevisionSpec_revno)
284
class RevisionSpec_revid(RevisionSpec):
287
def _match_on(self, branch, revs):
289
revno = revs.index(self.spec) + 1
292
return RevisionInfo(branch, revno, self.spec)
294
SPEC_TYPES.append(RevisionSpec_revid)
297
class RevisionSpec_last(RevisionSpec):
301
def _match_on(self, branch, revs):
304
raise errors.NoCommits(branch)
305
return RevisionInfo(branch, len(revs), revs[-1])
308
offset = int(self.spec)
309
except ValueError, e:
310
raise errors.InvalidRevisionSpec(self.user_spec, branch, e)
313
raise errors.InvalidRevisionSpec(self.user_spec, branch,
314
'you must supply a positive value')
315
revno = len(revs) - offset + 1
317
revision_id = branch.get_rev_id(revno, revs)
318
except errors.NoSuchRevision:
319
raise errors.InvalidRevisionSpec(self.user_spec, branch)
320
return RevisionInfo(branch, revno, revision_id)
322
SPEC_TYPES.append(RevisionSpec_last)
325
class RevisionSpec_before(RevisionSpec):
329
def _match_on(self, branch, revs):
330
r = RevisionSpec.from_string(self.spec)._match_on(branch, revs)
332
raise errors.InvalidRevisionSpec(self.user_spec, branch,
333
'cannot go before the null: revision')
335
# We need to use the repository history here
336
rev = branch.repository.get_revision(r.rev_id)
337
if not rev.parent_ids:
341
revision_id = rev.parent_ids[0]
343
revno = revs.index(revision_id) + 1
349
revision_id = branch.get_rev_id(revno, revs)
350
except errors.NoSuchRevision:
351
raise errors.InvalidRevisionSpec(self.user_spec,
353
return RevisionInfo(branch, revno, revision_id)
355
SPEC_TYPES.append(RevisionSpec_before)
358
class RevisionSpec_tag(RevisionSpec):
361
def _match_on(self, branch, revs):
362
raise errors.InvalidRevisionSpec(self.user_spec, branch,
363
'tag: namespace registered,'
364
' but not implemented')
366
SPEC_TYPES.append(RevisionSpec_tag)
369
class _RevListToTimestamps(object):
370
"""This takes a list of revisions, and allows you to bisect by date"""
372
__slots__ = ['revs', 'branch']
374
def __init__(self, revs, branch):
378
def __getitem__(self, index):
379
"""Get the date of the index'd item"""
380
r = self.branch.repository.get_revision(self.revs[index])
381
# TODO: Handle timezone.
382
return datetime.datetime.fromtimestamp(r.timestamp)
385
return len(self.revs)
388
class RevisionSpec_date(RevisionSpec):
390
_date_re = re.compile(
391
r'(?P<date>(?P<year>\d\d\d\d)-(?P<month>\d\d)-(?P<day>\d\d))?'
393
r'(?P<time>(?P<hour>\d\d):(?P<minute>\d\d)(:(?P<second>\d\d))?)?'
396
def _match_on(self, branch, revs):
398
Spec for date revisions:
400
value can be 'yesterday', 'today', 'tomorrow' or a YYYY-MM-DD string.
401
matches the first entry after a given date (either at midnight or
402
at a specified time).
404
So the proper way of saying 'give me all entries for today' is:
405
-r date:yesterday..date:today
407
today = datetime.datetime.fromordinal(datetime.date.today().toordinal())
408
if self.spec.lower() == 'yesterday':
409
dt = today - datetime.timedelta(days=1)
410
elif self.spec.lower() == 'today':
412
elif self.spec.lower() == 'tomorrow':
413
dt = today + datetime.timedelta(days=1)
415
m = self._date_re.match(self.spec)
416
if not m or (not m.group('date') and not m.group('time')):
417
raise errors.InvalidRevisionSpec(self.user_spec,
418
branch, 'invalid date')
422
year = int(m.group('year'))
423
month = int(m.group('month'))
424
day = int(m.group('day'))
431
hour = int(m.group('hour'))
432
minute = int(m.group('minute'))
433
if m.group('second'):
434
second = int(m.group('second'))
438
hour, minute, second = 0,0,0
440
raise errors.InvalidRevisionSpec(self.user_spec,
441
branch, 'invalid date')
443
dt = datetime.datetime(year=year, month=month, day=day,
444
hour=hour, minute=minute, second=second)
447
rev = bisect.bisect(_RevListToTimestamps(revs, branch), dt)
451
return RevisionInfo(branch, None)
453
return RevisionInfo(branch, rev + 1)
455
SPEC_TYPES.append(RevisionSpec_date)
458
class RevisionSpec_ancestor(RevisionSpec):
461
def _match_on(self, branch, revs):
462
from bzrlib.branch import Branch
464
trace.mutter('matching ancestor: on: %s, %s', self.spec, branch)
465
other_branch = Branch.open(self.spec)
466
revision_a = branch.last_revision()
467
revision_b = other_branch.last_revision()
468
for r, b in ((revision_a, branch), (revision_b, other_branch)):
469
if r in (None, revision.NULL_REVISION):
470
raise errors.NoCommits(b)
471
revision_source = revision.MultipleRevisionSources(
472
branch.repository, other_branch.repository)
473
rev_id = revision.common_ancestor(revision_a, revision_b,
476
revno = branch.revision_id_to_revno(rev_id)
477
except errors.NoSuchRevision:
479
return RevisionInfo(branch, revno, rev_id)
481
SPEC_TYPES.append(RevisionSpec_ancestor)
484
class RevisionSpec_branch(RevisionSpec):
485
"""A branch: revision specifier.
487
This takes the path to a branch and returns its tip revision id.
491
def _match_on(self, branch, revs):
492
from bzrlib.branch import Branch
493
other_branch = Branch.open(self.spec)
494
revision_b = other_branch.last_revision()
495
if revision_b in (None, revision.NULL_REVISION):
496
raise errors.NoCommits(other_branch)
497
# pull in the remote revisions so we can diff
498
branch.fetch(other_branch, revision_b)
500
revno = branch.revision_id_to_revno(revision_b)
501
except errors.NoSuchRevision:
503
return RevisionInfo(branch, revno, revision_b)
505
SPEC_TYPES.append(RevisionSpec_branch)