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
34
class RevisionInfo(object):
35
"""The results of applying a revision specification to a branch.
37
An instance has two useful attributes: revno, and rev_id.
39
They can also be accessed as spec[0] and spec[1] respectively,
40
so that you can write code like:
41
revno, rev_id = RevisionSpec(branch, spec)
42
although this is probably going to be deprecated later.
44
This class exists mostly to be the return value of a RevisionSpec,
45
so that you can access the member you're interested in (number or id)
46
or treat the result as a tuple.
49
def __init__(self, branch, revno, rev_id=_marker):
53
# allow caller to be lazy
54
if self.revno is None:
57
self.rev_id = branch.get_rev_id(self.revno)
61
def __nonzero__(self):
62
# first the easy ones...
63
if self.rev_id is None:
65
if self.revno is not None:
67
# TODO: otherwise, it should depend on how I was built -
68
# if it's in_history(branch), then check revision_history(),
69
# if it's in_store(branch), do the check below
70
return self.branch.repository.has_revision(self.rev_id)
75
def __getitem__(self, index):
76
if index == 0: return self.revno
77
if index == 1: return self.rev_id
78
raise IndexError(index)
81
return self.branch.repository.get_revision(self.rev_id)
83
def __eq__(self, other):
84
if type(other) not in (tuple, list, type(self)):
86
if type(other) is type(self) and self.branch is not other.branch:
88
return tuple(self) == tuple(other)
91
return '<bzrlib.revisionspec.RevisionInfo object %s, %s for %r>' % (
92
self.revno, self.rev_id, self.branch)
95
# classes in this list should have a "prefix" attribute, against which
96
# string specs are matched
101
class RevisionSpec(object):
102
"""A parsed revision specification.
104
A revision specification can be an integer, in which case it is
105
assumed to be a revno (though this will translate negative values
106
into positive ones); or it can be a string, in which case it is
107
parsed for something like 'date:' or 'revid:' etc.
109
Revision specs are an UI element, and they have been moved out
110
of the branch class to leave "back-end" classes unaware of such
111
details. Code that gets a revno or rev_id from other code should
112
not be using revision specs - revnos and revision ids are the
113
accepted ways to refer to revisions internally.
115
(Equivalent to the old Branch method get_revision_info())
120
def __new__(cls, spec, _internal=False):
122
return object.__new__(cls, spec, _internal=_internal)
124
symbol_versioning.warn('Creating a RevisionSpec directly has'
125
' been deprecated in version 0.11. Use'
126
' RevisionSpec.from_string()'
128
DeprecationWarning, stacklevel=2)
129
return RevisionSpec.from_string(spec)
132
def from_string(spec):
133
"""Parse a revision spec string into a RevisionSpec object.
135
:param spec: A string specified by the user
136
:return: A RevisionSpec object that understands how to parse the
139
if not isinstance(spec, (type(None), basestring)):
140
raise TypeError('error')
143
return RevisionSpec(None, _internal=True)
145
assert isinstance(spec, basestring), \
146
"You should only supply strings not %s" % (type(spec),)
148
for spectype in SPEC_TYPES:
149
if spec.startswith(spectype.prefix):
150
trace.mutter('Returning RevisionSpec %s for %s',
151
spectype.__name__, spec)
152
return spectype(spec, _internal=True)
154
# RevisionSpec_revno is special cased, because it is the only
155
# one that directly handles plain integers
156
# TODO: This should not be special cased rather it should be
157
# a method invocation on spectype.canparse()
159
if _revno_regex is None:
160
_revno_regex = re.compile(r'^(?:(\d+(\.\d+)*)|-\d+)(:.*)?$')
161
if _revno_regex.match(spec) is not None:
162
return RevisionSpec_revno(spec, _internal=True)
164
raise errors.NoSuchRevisionSpec(spec)
166
def __init__(self, spec, _internal=False):
167
"""Create a RevisionSpec referring to the Null revision.
169
:param spec: The original spec supplied by the user
170
:param _internal: Used to ensure that RevisionSpec is not being
171
called directly. Only from RevisionSpec.from_string()
174
# XXX: Update this after 0.10 is released
175
symbol_versioning.warn('Creating a RevisionSpec directly has'
176
' been deprecated in version 0.11. Use'
177
' RevisionSpec.from_string()'
179
DeprecationWarning, stacklevel=2)
180
self.user_spec = spec
181
if self.prefix and spec.startswith(self.prefix):
182
spec = spec[len(self.prefix):]
185
def _match_on(self, branch, revs):
186
trace.mutter('Returning RevisionSpec._match_on: None')
187
return RevisionInfo(branch, 0, None)
189
def _match_on_and_check(self, branch, revs):
190
info = self._match_on(branch, revs)
193
elif info == (0, None):
194
# special case - the empty tree
197
raise errors.InvalidRevisionSpec(self.user_spec, branch)
199
raise errors.InvalidRevisionSpec(self.spec, branch)
201
def in_history(self, branch):
203
revs = branch.revision_history()
205
# this should never trigger.
206
# TODO: make it a deprecated code path. RBC 20060928
208
return self._match_on_and_check(branch, revs)
210
# FIXME: in_history is somewhat broken,
211
# it will return non-history revisions in many
212
# circumstances. The expected facility is that
213
# in_history only returns revision-history revs,
214
# in_store returns any rev. RBC 20051010
215
# aliases for now, when we fix the core logic, then they
216
# will do what you expect.
217
in_store = in_history
221
# this is mostly for helping with testing
222
return '<%s %s>' % (self.__class__.__name__,
225
def needs_branch(self):
226
"""Whether this revision spec needs a branch.
228
Set this to False the branch argument of _match_on is not used.
235
class RevisionSpec_revno(RevisionSpec):
238
def _match_on(self, branch, revs):
239
"""Lookup a revision by revision number"""
240
loc = self.spec.find(':')
242
revno_spec = self.spec
245
revno_spec = self.spec[:loc]
246
branch_spec = self.spec[loc+1:]
250
raise errors.InvalidRevisionSpec(self.user_spec,
251
branch, 'cannot have an empty revno and no branch')
255
revno = int(revno_spec)
258
# dotted decimal. This arguably should not be here
259
# but the from_string method is a little primitive
260
# right now - RBC 20060928
262
match_revno = tuple((int(number) for number in revno_spec.split('.')))
263
except ValueError, e:
264
raise errors.InvalidRevisionSpec(self.user_spec, branch, e)
269
# the user has override the branch to look in.
270
# we need to refresh the revision_history map and
272
from bzrlib.branch import Branch
273
branch = Branch.open(branch_spec)
274
# Need to use a new revision history
275
# because we are using a specific branch
276
revs = branch.revision_history()
281
last_rev = branch.last_revision()
282
merge_sorted_revisions = tsort.merge_sort(
283
branch.repository.get_revision_graph(last_rev),
287
return item[3] == match_revno
288
revisions = filter(match, merge_sorted_revisions)
291
if len(revisions) != 1:
292
return RevisionInfo(branch, None, None)
294
# there is no traditional 'revno' for dotted-decimal revnos.
295
# so for API compatability we return None.
296
return RevisionInfo(branch, None, revisions[0][1])
299
if (-revno) >= len(revs):
302
revno = len(revs) + revno + 1
304
revision_id = branch.get_rev_id(revno, revs)
305
except errors.NoSuchRevision:
306
raise errors.InvalidRevisionSpec(self.user_spec, branch)
307
return RevisionInfo(branch, revno, revision_id)
309
def needs_branch(self):
310
return self.spec.find(':') == -1
313
RevisionSpec_int = RevisionSpec_revno
315
SPEC_TYPES.append(RevisionSpec_revno)
318
class RevisionSpec_revid(RevisionSpec):
321
def _match_on(self, branch, revs):
323
revno = revs.index(self.spec) + 1
326
return RevisionInfo(branch, revno, self.spec)
328
SPEC_TYPES.append(RevisionSpec_revid)
331
class RevisionSpec_last(RevisionSpec):
335
def _match_on(self, branch, revs):
338
raise errors.NoCommits(branch)
339
return RevisionInfo(branch, len(revs), revs[-1])
342
offset = int(self.spec)
343
except ValueError, e:
344
raise errors.InvalidRevisionSpec(self.user_spec, branch, e)
347
raise errors.InvalidRevisionSpec(self.user_spec, branch,
348
'you must supply a positive value')
349
revno = len(revs) - offset + 1
351
revision_id = branch.get_rev_id(revno, revs)
352
except errors.NoSuchRevision:
353
raise errors.InvalidRevisionSpec(self.user_spec, branch)
354
return RevisionInfo(branch, revno, revision_id)
356
SPEC_TYPES.append(RevisionSpec_last)
359
class RevisionSpec_before(RevisionSpec):
363
def _match_on(self, branch, revs):
364
r = RevisionSpec.from_string(self.spec)._match_on(branch, revs)
366
raise errors.InvalidRevisionSpec(self.user_spec, branch,
367
'cannot go before the null: revision')
369
# We need to use the repository history here
370
rev = branch.repository.get_revision(r.rev_id)
371
if not rev.parent_ids:
375
revision_id = rev.parent_ids[0]
377
revno = revs.index(revision_id) + 1
383
revision_id = branch.get_rev_id(revno, revs)
384
except errors.NoSuchRevision:
385
raise errors.InvalidRevisionSpec(self.user_spec,
387
return RevisionInfo(branch, revno, revision_id)
389
SPEC_TYPES.append(RevisionSpec_before)
392
class RevisionSpec_tag(RevisionSpec):
395
def _match_on(self, branch, revs):
396
raise errors.InvalidRevisionSpec(self.user_spec, branch,
397
'tag: namespace registered,'
398
' but not implemented')
400
SPEC_TYPES.append(RevisionSpec_tag)
403
class _RevListToTimestamps(object):
404
"""This takes a list of revisions, and allows you to bisect by date"""
406
__slots__ = ['revs', 'branch']
408
def __init__(self, revs, branch):
412
def __getitem__(self, index):
413
"""Get the date of the index'd item"""
414
r = self.branch.repository.get_revision(self.revs[index])
415
# TODO: Handle timezone.
416
return datetime.datetime.fromtimestamp(r.timestamp)
419
return len(self.revs)
422
class RevisionSpec_date(RevisionSpec):
424
_date_re = re.compile(
425
r'(?P<date>(?P<year>\d\d\d\d)-(?P<month>\d\d)-(?P<day>\d\d))?'
427
r'(?P<time>(?P<hour>\d\d):(?P<minute>\d\d)(:(?P<second>\d\d))?)?'
430
def _match_on(self, branch, revs):
432
Spec for date revisions:
434
value can be 'yesterday', 'today', 'tomorrow' or a YYYY-MM-DD string.
435
matches the first entry after a given date (either at midnight or
436
at a specified time).
438
So the proper way of saying 'give me all entries for today' is:
439
-r date:yesterday..date:today
441
today = datetime.datetime.fromordinal(datetime.date.today().toordinal())
442
if self.spec.lower() == 'yesterday':
443
dt = today - datetime.timedelta(days=1)
444
elif self.spec.lower() == 'today':
446
elif self.spec.lower() == 'tomorrow':
447
dt = today + datetime.timedelta(days=1)
449
m = self._date_re.match(self.spec)
450
if not m or (not m.group('date') and not m.group('time')):
451
raise errors.InvalidRevisionSpec(self.user_spec,
452
branch, 'invalid date')
456
year = int(m.group('year'))
457
month = int(m.group('month'))
458
day = int(m.group('day'))
465
hour = int(m.group('hour'))
466
minute = int(m.group('minute'))
467
if m.group('second'):
468
second = int(m.group('second'))
472
hour, minute, second = 0,0,0
474
raise errors.InvalidRevisionSpec(self.user_spec,
475
branch, 'invalid date')
477
dt = datetime.datetime(year=year, month=month, day=day,
478
hour=hour, minute=minute, second=second)
481
rev = bisect.bisect(_RevListToTimestamps(revs, branch), dt)
485
return RevisionInfo(branch, None)
487
return RevisionInfo(branch, rev + 1)
489
SPEC_TYPES.append(RevisionSpec_date)
492
class RevisionSpec_ancestor(RevisionSpec):
495
def _match_on(self, branch, revs):
496
from bzrlib.branch import Branch
498
trace.mutter('matching ancestor: on: %s, %s', self.spec, branch)
499
other_branch = Branch.open(self.spec)
500
revision_a = branch.last_revision()
501
revision_b = other_branch.last_revision()
502
for r, b in ((revision_a, branch), (revision_b, other_branch)):
503
if r in (None, revision.NULL_REVISION):
504
raise errors.NoCommits(b)
505
revision_source = revision.MultipleRevisionSources(
506
branch.repository, other_branch.repository)
507
rev_id = revision.common_ancestor(revision_a, revision_b,
510
revno = branch.revision_id_to_revno(rev_id)
511
except errors.NoSuchRevision:
513
return RevisionInfo(branch, revno, rev_id)
515
SPEC_TYPES.append(RevisionSpec_ancestor)
518
class RevisionSpec_branch(RevisionSpec):
519
"""A branch: revision specifier.
521
This takes the path to a branch and returns its tip revision id.
525
def _match_on(self, branch, revs):
526
from bzrlib.branch import Branch
527
other_branch = Branch.open(self.spec)
528
revision_b = other_branch.last_revision()
529
if revision_b in (None, revision.NULL_REVISION):
530
raise errors.NoCommits(other_branch)
531
# pull in the remote revisions so we can diff
532
branch.fetch(other_branch, revision_b)
534
revno = branch.revision_id_to_revno(revision_b)
535
except errors.NoSuchRevision:
537
return RevisionInfo(branch, revno, revision_b)
539
SPEC_TYPES.append(RevisionSpec_branch)