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
100
class RevisionSpec(object):
101
"""A parsed revision specification.
103
A revision specification can be an integer, in which case it is
104
assumed to be a revno (though this will translate negative values
105
into positive ones); or it can be a string, in which case it is
106
parsed for something like 'date:' or 'revid:' etc.
108
Revision specs are an UI element, and they have been moved out
109
of the branch class to leave "back-end" classes unaware of such
110
details. Code that gets a revno or rev_id from other code should
111
not be using revision specs - revnos and revision ids are the
112
accepted ways to refer to revisions internally.
114
(Equivalent to the old Branch method get_revision_info())
119
def __new__(cls, spec, _internal=False):
121
return object.__new__(cls, spec, _internal=_internal)
123
symbol_versioning.warn('Creating a RevisionSpec directly has'
124
' been deprecated in version 0.11. Use'
125
' RevisionSpec.from_string()'
127
DeprecationWarning, stacklevel=2)
128
return RevisionSpec.from_string(spec)
131
def from_string(spec):
132
"""Parse a revision spec string into a RevisionSpec object.
134
:param spec: A string specified by the user
135
:return: A RevisionSpec object that understands how to parse the
138
if not isinstance(spec, (type(None), basestring)):
139
raise TypeError('error')
142
return RevisionSpec(None, _internal=True)
144
assert isinstance(spec, basestring), \
145
"You should only supply strings not %s" % (type(spec),)
147
for spectype in SPEC_TYPES:
148
if spec.startswith(spectype.prefix):
149
trace.mutter('Returning RevisionSpec %s for %s',
150
spectype.__name__, spec)
151
return spectype(spec, _internal=True)
153
# RevisionSpec_revno is special cased, because it is the only
154
# one that directly handles plain integers
156
if _revno_regex is None:
157
_revno_regex = re.compile(r'-?\d+(:.*)?$')
158
if _revno_regex.match(spec) is not None:
159
return RevisionSpec_revno(spec, _internal=True)
161
raise errors.NoSuchRevisionSpec(spec)
163
def __init__(self, spec, _internal=False):
164
"""Create a RevisionSpec referring to the Null revision.
166
:param spec: The original spec supplied by the user
167
:param _internal: Used to ensure that RevisionSpec is not being
168
called directly. Only from RevisionSpec.from_string()
171
# XXX: Update this after 0.10 is released
172
symbol_versioning.warn('Creating a RevisionSpec directly has'
173
' been deprecated in version 0.11. Use'
174
' RevisionSpec.from_string()'
176
DeprecationWarning, stacklevel=2)
177
self.user_spec = spec
178
if self.prefix and spec.startswith(self.prefix):
179
spec = spec[len(self.prefix):]
182
def _match_on(self, branch, revs):
183
trace.mutter('Returning RevisionSpec._match_on: None')
184
return RevisionInfo(branch, 0, None)
186
def _match_on_and_check(self, branch, revs):
187
info = self._match_on(branch, revs)
190
elif info == (0, None):
191
# special case - the empty tree
194
raise errors.InvalidRevisionSpec(self.user_spec, branch)
196
raise errors.InvalidRevisionSpec(self.spec, branch)
198
def in_history(self, branch):
200
revs = branch.revision_history()
203
return self._match_on_and_check(branch, revs)
205
# FIXME: in_history is somewhat broken,
206
# it will return non-history revisions in many
207
# circumstances. The expected facility is that
208
# in_history only returns revision-history revs,
209
# in_store returns any rev. RBC 20051010
210
# aliases for now, when we fix the core logic, then they
211
# will do what you expect.
212
in_store = in_history
216
# this is mostly for helping with testing
217
return '<%s %s>' % (self.__class__.__name__,
220
def needs_branch(self):
221
"""Whether this revision spec needs a branch.
223
Set this to False the branch argument of _match_on is not used.
227
def get_branch(self):
228
"""When the revision specifier contains a branch location, return it.
230
Otherwise, return None.
237
class RevisionSpec_revno(RevisionSpec):
240
def _match_on(self, branch, revs):
241
"""Lookup a revision by revision number"""
242
loc = self.spec.find(':')
244
revno_spec = self.spec
247
revno_spec = self.spec[:loc]
248
branch_spec = self.spec[loc+1:]
252
raise errors.InvalidRevisionSpec(self.user_spec,
253
branch, 'cannot have an empty revno and no branch')
257
revno = int(revno_spec)
258
except ValueError, e:
259
raise errors.InvalidRevisionSpec(self.user_spec,
263
from bzrlib.branch import Branch
264
branch = Branch.open(branch_spec)
265
# Need to use a new revision history
266
# because we are using a specific branch
267
revs = branch.revision_history()
270
if (-revno) >= len(revs):
273
revno = len(revs) + revno + 1
275
revision_id = branch.get_rev_id(revno, revs)
276
except errors.NoSuchRevision:
277
raise errors.InvalidRevisionSpec(self.user_spec, branch)
278
return RevisionInfo(branch, revno, revision_id)
280
def needs_branch(self):
281
return self.spec.find(':') == -1
283
def get_branch(self):
284
if self.spec.find(':') == -1:
287
return self.spec[self.spec.find(':')+1:]
290
RevisionSpec_int = RevisionSpec_revno
292
SPEC_TYPES.append(RevisionSpec_revno)
295
class RevisionSpec_revid(RevisionSpec):
298
def _match_on(self, branch, revs):
300
revno = revs.index(self.spec) + 1
303
return RevisionInfo(branch, revno, self.spec)
305
SPEC_TYPES.append(RevisionSpec_revid)
308
class RevisionSpec_last(RevisionSpec):
312
def _match_on(self, branch, revs):
315
raise errors.NoCommits(branch)
316
return RevisionInfo(branch, len(revs), revs[-1])
319
offset = int(self.spec)
320
except ValueError, e:
321
raise errors.InvalidRevisionSpec(self.user_spec, branch, e)
324
raise errors.InvalidRevisionSpec(self.user_spec, branch,
325
'you must supply a positive value')
326
revno = len(revs) - offset + 1
328
revision_id = branch.get_rev_id(revno, revs)
329
except errors.NoSuchRevision:
330
raise errors.InvalidRevisionSpec(self.user_spec, branch)
331
return RevisionInfo(branch, revno, revision_id)
333
SPEC_TYPES.append(RevisionSpec_last)
336
class RevisionSpec_before(RevisionSpec):
340
def _match_on(self, branch, revs):
341
r = RevisionSpec.from_string(self.spec)._match_on(branch, revs)
343
raise errors.InvalidRevisionSpec(self.user_spec, branch,
344
'cannot go before the null: revision')
346
# We need to use the repository history here
347
rev = branch.repository.get_revision(r.rev_id)
348
if not rev.parent_ids:
352
revision_id = rev.parent_ids[0]
354
revno = revs.index(revision_id) + 1
360
revision_id = branch.get_rev_id(revno, revs)
361
except errors.NoSuchRevision:
362
raise errors.InvalidRevisionSpec(self.user_spec,
364
return RevisionInfo(branch, revno, revision_id)
366
SPEC_TYPES.append(RevisionSpec_before)
369
class RevisionSpec_tag(RevisionSpec):
372
def _match_on(self, branch, revs):
373
raise errors.InvalidRevisionSpec(self.user_spec, branch,
374
'tag: namespace registered,'
375
' but not implemented')
377
SPEC_TYPES.append(RevisionSpec_tag)
380
class _RevListToTimestamps(object):
381
"""This takes a list of revisions, and allows you to bisect by date"""
383
__slots__ = ['revs', 'branch']
385
def __init__(self, revs, branch):
389
def __getitem__(self, index):
390
"""Get the date of the index'd item"""
391
r = self.branch.repository.get_revision(self.revs[index])
392
# TODO: Handle timezone.
393
return datetime.datetime.fromtimestamp(r.timestamp)
396
return len(self.revs)
399
class RevisionSpec_date(RevisionSpec):
401
_date_re = re.compile(
402
r'(?P<date>(?P<year>\d\d\d\d)-(?P<month>\d\d)-(?P<day>\d\d))?'
404
r'(?P<time>(?P<hour>\d\d):(?P<minute>\d\d)(:(?P<second>\d\d))?)?'
407
def _match_on(self, branch, revs):
409
Spec for date revisions:
411
value can be 'yesterday', 'today', 'tomorrow' or a YYYY-MM-DD string.
412
matches the first entry after a given date (either at midnight or
413
at a specified time).
415
So the proper way of saying 'give me all entries for today' is:
416
-r date:yesterday..date:today
418
today = datetime.datetime.fromordinal(datetime.date.today().toordinal())
419
if self.spec.lower() == 'yesterday':
420
dt = today - datetime.timedelta(days=1)
421
elif self.spec.lower() == 'today':
423
elif self.spec.lower() == 'tomorrow':
424
dt = today + datetime.timedelta(days=1)
426
m = self._date_re.match(self.spec)
427
if not m or (not m.group('date') and not m.group('time')):
428
raise errors.InvalidRevisionSpec(self.user_spec,
429
branch, 'invalid date')
433
year = int(m.group('year'))
434
month = int(m.group('month'))
435
day = int(m.group('day'))
442
hour = int(m.group('hour'))
443
minute = int(m.group('minute'))
444
if m.group('second'):
445
second = int(m.group('second'))
449
hour, minute, second = 0,0,0
451
raise errors.InvalidRevisionSpec(self.user_spec,
452
branch, 'invalid date')
454
dt = datetime.datetime(year=year, month=month, day=day,
455
hour=hour, minute=minute, second=second)
458
rev = bisect.bisect(_RevListToTimestamps(revs, branch), dt)
462
return RevisionInfo(branch, None)
464
return RevisionInfo(branch, rev + 1)
466
SPEC_TYPES.append(RevisionSpec_date)
469
class RevisionSpec_ancestor(RevisionSpec):
472
def _match_on(self, branch, revs):
473
from bzrlib.branch import Branch
475
trace.mutter('matching ancestor: on: %s, %s', self.spec, branch)
476
other_branch = Branch.open(self.spec)
477
revision_a = branch.last_revision()
478
revision_b = other_branch.last_revision()
479
for r, b in ((revision_a, branch), (revision_b, other_branch)):
480
if r in (None, revision.NULL_REVISION):
481
raise errors.NoCommits(b)
482
revision_source = revision.MultipleRevisionSources(
483
branch.repository, other_branch.repository)
484
rev_id = revision.common_ancestor(revision_a, revision_b,
487
revno = branch.revision_id_to_revno(rev_id)
488
except errors.NoSuchRevision:
490
return RevisionInfo(branch, revno, rev_id)
492
SPEC_TYPES.append(RevisionSpec_ancestor)
495
class RevisionSpec_branch(RevisionSpec):
496
"""A branch: revision specifier.
498
This takes the path to a branch and returns its tip revision id.
502
def _match_on(self, branch, revs):
503
from bzrlib.branch import Branch
504
other_branch = Branch.open(self.spec)
505
revision_b = other_branch.last_revision()
506
if revision_b in (None, revision.NULL_REVISION):
507
raise errors.NoCommits(other_branch)
508
# pull in the remote revisions so we can diff
509
branch.fetch(other_branch, revision_b)
511
revno = branch.revision_id_to_revno(revision_b)
512
except errors.NoSuchRevision:
514
return RevisionInfo(branch, revno, revision_b)
516
SPEC_TYPES.append(RevisionSpec_branch)