/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
1
# Copyright (C) 2005 Canonical Ltd
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
2
#
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
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.
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
7
#
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
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.
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
12
#
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
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
1948.4.1 by John Arbash Meinel
Update number parsers to raise InvalidRevisionSpec. Update revno: itself so it supports negative numbers
18
import bisect
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
19
import datetime
20
import re
1948.4.1 by John Arbash Meinel
Update number parsers to raise InvalidRevisionSpec. Update revno: itself so it supports negative numbers
21
22
from bzrlib import (
23
    errors,
24
    )
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
25
from bzrlib.errors import BzrError, NoSuchRevision, NoCommits
26
27
_marker = []
28
29
class RevisionInfo(object):
30
    """The results of applying a revision specification to a branch.
31
32
    An instance has two useful attributes: revno, and rev_id.
33
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.
38
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.
42
    """
43
44
    def __init__(self, branch, revno, rev_id=_marker):
45
        self.branch = branch
46
        self.revno = revno
47
        if rev_id is _marker:
48
            # allow caller to be lazy
49
            if self.revno is None:
50
                self.rev_id = None
51
            else:
52
                self.rev_id = branch.get_rev_id(self.revno)
53
        else:
54
            self.rev_id = rev_id
55
56
    def __nonzero__(self):
57
        # first the easy ones...
58
        if self.rev_id is None:
59
            return False
60
        if self.revno is not None:
61
            return True
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
1185.67.2 by Aaron Bentley
Renamed Branch.storage to Branch.repository
65
        return self.branch.repository.has_revision(self.rev_id)
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
66
67
    def __len__(self):
68
        return 2
69
70
    def __getitem__(self, index):
71
        if index == 0: return self.revno
72
        if index == 1: return self.rev_id
73
        raise IndexError(index)
74
75
    def get(self):
1185.67.2 by Aaron Bentley
Renamed Branch.storage to Branch.repository
76
        return self.branch.repository.get_revision(self.rev_id)
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
77
78
    def __eq__(self, other):
79
        if type(other) not in (tuple, list, type(self)):
80
            return False
81
        if type(other) is type(self) and self.branch is not other.branch:
82
            return False
83
        return tuple(self) == tuple(other)
84
85
    def __repr__(self):
86
        return '<bzrlib.revisionspec.RevisionInfo object %s, %s for %r>' % (
87
            self.revno, self.rev_id, self.branch)
88
89
# classes in this list should have a "prefix" attribute, against which
90
# string specs are matched
91
SPEC_TYPES = []
92
93
class RevisionSpec(object):
94
    """A parsed revision specification.
95
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.
100
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.
106
107
    (Equivalent to the old Branch method get_revision_info())
108
    """
109
110
    prefix = None
111
112
    def __new__(cls, spec, foo=_marker):
113
        """Parse a revision specifier.
114
        """
115
        if spec is None:
116
            return object.__new__(RevisionSpec, spec)
117
118
        try:
119
            spec = int(spec)
120
        except ValueError:
121
            pass
122
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)
129
            else:
130
                raise BzrError('No namespace registered for string: %r' %
131
                               spec)
132
        else:
133
            raise TypeError('Unhandled revision type %s' % spec)
134
135
    def __init__(self, spec):
136
        if self.prefix and spec.startswith(self.prefix):
137
            spec = spec[len(self.prefix):]
138
        self.spec = spec
139
140
    def _match_on(self, branch, revs):
141
        return RevisionInfo(branch, 0, None)
142
143
    def _match_on_and_check(self, branch, revs):
144
        info = self._match_on(branch, revs)
145
        if info:
146
            return info
147
        elif info == (0, None):
148
            # special case - the empty tree
149
            return info
150
        elif self.prefix:
1948.4.2 by John Arbash Meinel
Update _match_on_and_check to raise the right error
151
            raise errors.InvalidRevisionSpec(self.prefix + self.spec, branch)
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
152
        else:
1948.4.2 by John Arbash Meinel
Update _match_on_and_check to raise the right error
153
            raise errors.InvalidRevisionSpec(self.spec, branch)
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
154
155
    def in_history(self, branch):
1732.3.1 by Matthieu Moy
Implementation of -r revno:N:/path/to/branch
156
        if branch:
157
            revs = branch.revision_history()
158
        else:
159
            revs = None
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
160
        return self._match_on_and_check(branch, revs)
161
1432 by Robert Collins
branch: namespace
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
170
    in_branch = in_store
171
        
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
172
    def __repr__(self):
173
        # this is mostly for helping with testing
174
        return '<%s %s%s>' % (self.__class__.__name__,
175
                              self.prefix or '',
176
                              self.spec)
1881.1.1 by Matthieu Moy
Fixed and tested "bzr diff" outside a working tree.
177
    
1881.1.4 by Matthieu Moy
needs_tree -> needs_branch
178
    def needs_branch(self):
179
        """Whether this revision spec needs a branch.
180
1711.2.99 by John Arbash Meinel
minor typo fix
181
        Set this to False the branch argument of _match_on is not used.
182
        """
1881.1.1 by Matthieu Moy
Fixed and tested "bzr diff" outside a working tree.
183
        return True
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
184
185
# private API
186
187
class RevisionSpec_int(RevisionSpec):
188
    """Spec is a number.  Special case."""
1948.4.1 by John Arbash Meinel
Update number parsers to raise InvalidRevisionSpec. Update revno: itself so it supports negative numbers
189
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
190
    def __init__(self, spec):
191
        self.spec = int(spec)
192
193
    def _match_on(self, branch, revs):
194
        if self.spec < 0:
195
            revno = len(revs) + self.spec + 1
196
        else:
197
            revno = self.spec
1948.4.1 by John Arbash Meinel
Update number parsers to raise InvalidRevisionSpec. Update revno: itself so it supports negative numbers
198
        try:
199
            rev_id = branch.get_rev_id(revno, revs)
200
        except NoSuchRevision:
201
            raise errors.InvalidRevisionSpec(self.spec, branch)
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
202
        return RevisionInfo(branch, revno, rev_id)
203
204
205
class RevisionSpec_revno(RevisionSpec):
206
    prefix = 'revno:'
207
208
    def _match_on(self, branch, revs):
209
        """Lookup a revision by revision number"""
1948.4.1 by John Arbash Meinel
Update number parsers to raise InvalidRevisionSpec. Update revno: itself so it supports negative numbers
210
        loc = self.spec.find(':')
211
        if loc == -1:
212
            revno_spec = self.spec
213
            branch_spec = None
214
        else:
215
            revno_spec = self.spec[:loc]
216
            branch_spec = self.spec[loc+1:]
217
218
        if revno_spec == '':
219
            if branch_spec is None:
220
                raise errors.InvalidRevisionSpec(branch, self.spec,
221
                        'cannot have an empty revno and no branch')
222
            revno = None
223
        else:
224
            try:
225
                revno = int(revno_spec)
226
            except ValueError, e:
227
                raise errors.InvalidRevisionSpec(branch, self.spec, e)
228
229
            if revno < 0:
230
                revno = len(revs) + revno + 1
231
232
        if branch_spec is not None:
233
            from bzrlib.branch import Branch
234
            branch = Branch.open(branch_spec)
235
236
        try:
237
            revid = branch.get_rev_id(revno)
238
        except NoSuchRevision:
239
            raise errors.InvalidRevisionSpec(branch, self.spec)
240
241
        return RevisionInfo(branch, revno)
1881.1.1 by Matthieu Moy
Fixed and tested "bzr diff" outside a working tree.
242
        
1881.1.4 by Matthieu Moy
needs_tree -> needs_branch
243
    def needs_branch(self):
1881.1.1 by Matthieu Moy
Fixed and tested "bzr diff" outside a working tree.
244
        return self.spec.find(':') == -1
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
245
246
SPEC_TYPES.append(RevisionSpec_revno)
247
248
249
class RevisionSpec_revid(RevisionSpec):
250
    prefix = 'revid:'
251
252
    def _match_on(self, branch, revs):
253
        try:
1948.4.2 by John Arbash Meinel
Update _match_on_and_check to raise the right error
254
            revno = revs.index(self.spec) + 1
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
255
        except ValueError:
1948.4.2 by John Arbash Meinel
Update _match_on_and_check to raise the right error
256
            revno = None
257
        return RevisionInfo(branch, revno, self.spec)
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
258
259
SPEC_TYPES.append(RevisionSpec_revid)
260
261
262
class RevisionSpec_last(RevisionSpec):
1185.1.39 by Robert Collins
Robey Pointers before: namespace to clear up usage of dates in revision parameters
263
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
264
    prefix = 'last:'
265
266
    def _match_on(self, branch, revs):
267
        try:
268
            offset = int(self.spec)
269
        except ValueError:
270
            return RevisionInfo(branch, None)
271
        else:
272
            if offset <= 0:
273
                raise BzrError('You must supply a positive value for --revision last:XXX')
274
            return RevisionInfo(branch, len(revs) - offset + 1)
275
276
SPEC_TYPES.append(RevisionSpec_last)
277
278
1185.1.39 by Robert Collins
Robey Pointers before: namespace to clear up usage of dates in revision parameters
279
class RevisionSpec_before(RevisionSpec):
280
281
    prefix = 'before:'
282
    
283
    def _match_on(self, branch, revs):
284
        r = RevisionSpec(self.spec)._match_on(branch, revs)
285
        if (r.revno is None) or (r.revno == 0):
286
            return r
287
        return RevisionInfo(branch, r.revno - 1)
288
289
SPEC_TYPES.append(RevisionSpec_before)
290
291
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
292
class RevisionSpec_tag(RevisionSpec):
293
    prefix = 'tag:'
294
295
    def _match_on(self, branch, revs):
296
        raise BzrError('tag: namespace registered, but not implemented.')
297
298
SPEC_TYPES.append(RevisionSpec_tag)
299
300
1688.2.2 by Guillaume Pinot
Binary search for 'date:' revision.
301
class RevisionSpec_revs:
302
    def __init__(self, revs, branch):
303
        self.revs = revs
304
        self.branch = branch
305
    def __getitem__(self, index):
306
        r = self.branch.repository.get_revision(self.revs[index])
307
        # TODO: Handle timezone.
308
        return datetime.datetime.fromtimestamp(r.timestamp)
309
    def __len__(self):
310
        return len(self.revs)
311
312
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
313
class RevisionSpec_date(RevisionSpec):
314
    prefix = 'date:'
315
    _date_re = re.compile(
316
            r'(?P<date>(?P<year>\d\d\d\d)-(?P<month>\d\d)-(?P<day>\d\d))?'
317
            r'(,|T)?\s*'
318
            r'(?P<time>(?P<hour>\d\d):(?P<minute>\d\d)(:(?P<second>\d\d))?)?'
319
        )
320
321
    def _match_on(self, branch, revs):
322
        """
323
        Spec for date revisions:
324
          date:value
325
          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
326
          matches the first entry after a given date (either at midnight or
327
          at a specified time).
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
328
329
          So the proper way of saying 'give me all entries for today' is:
1711.2.90 by John Arbash Meinel
Fix the docstring of RevisionSpec_date (bug #31276)
330
              -r date:yesterday..date:today
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
331
        """
1185.1.39 by Robert Collins
Robey Pointers before: namespace to clear up usage of dates in revision parameters
332
        today = datetime.datetime.fromordinal(datetime.date.today().toordinal())
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
333
        if self.spec.lower() == 'yesterday':
334
            dt = today - datetime.timedelta(days=1)
335
        elif self.spec.lower() == 'today':
336
            dt = today
337
        elif self.spec.lower() == 'tomorrow':
338
            dt = today + datetime.timedelta(days=1)
339
        else:
340
            m = self._date_re.match(self.spec)
341
            if not m or (not m.group('date') and not m.group('time')):
342
                raise BzrError('Invalid revision date %r' % self.spec)
343
344
            if m.group('date'):
345
                year, month, day = int(m.group('year')), int(m.group('month')), int(m.group('day'))
346
            else:
347
                year, month, day = today.year, today.month, today.day
348
            if m.group('time'):
349
                hour = int(m.group('hour'))
350
                minute = int(m.group('minute'))
351
                if m.group('second'):
352
                    second = int(m.group('second'))
353
                else:
354
                    second = 0
355
            else:
356
                hour, minute, second = 0,0,0
357
358
            dt = datetime.datetime(year=year, month=month, day=day,
359
                    hour=hour, minute=minute, second=second)
1704.2.27 by Martin Pool
Run bisection search for revision date with lock held. (Robert Widhopf-Frenk)
360
        branch.lock_read()
361
        try:
362
            rev = bisect.bisect(RevisionSpec_revs(revs, branch), dt)
363
        finally:
364
            branch.unlock()
1688.2.2 by Guillaume Pinot
Binary search for 'date:' revision.
365
        if rev == len(revs):
366
            return RevisionInfo(branch, None)
367
        else:
368
            return RevisionInfo(branch, rev + 1)
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
369
370
SPEC_TYPES.append(RevisionSpec_date)
371
372
373
class RevisionSpec_ancestor(RevisionSpec):
374
    prefix = 'ancestor:'
375
376
    def _match_on(self, branch, revs):
377
        from branch import Branch
378
        from revision import common_ancestor, MultipleRevisionSources
1442.1.64 by Robert Collins
Branch.open_containing now returns a tuple (Branch, relative-path).
379
        other_branch = Branch.open_containing(self.spec)[0]
1390 by Robert Collins
pair programming worx... merge integration and weave
380
        revision_a = branch.last_revision()
381
        revision_b = other_branch.last_revision()
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
382
        for r, b in ((revision_a, branch), (revision_b, other_branch)):
383
            if r is None:
384
                raise NoCommits(b)
1185.67.2 by Aaron Bentley
Renamed Branch.storage to Branch.repository
385
        revision_source = MultipleRevisionSources(branch.repository,
386
                                                  other_branch.repository)
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
387
        rev_id = common_ancestor(revision_a, revision_b, revision_source)
388
        try:
389
            revno = branch.revision_id_to_revno(rev_id)
390
        except NoSuchRevision:
391
            revno = None
392
        return RevisionInfo(branch, revno, rev_id)
393
        
394
SPEC_TYPES.append(RevisionSpec_ancestor)
1432 by Robert Collins
branch: namespace
395
396
class RevisionSpec_branch(RevisionSpec):
397
    """A branch: revision specifier.
398
399
    This takes the path to a branch and returns its tip revision id.
400
    """
401
    prefix = 'branch:'
402
403
    def _match_on(self, branch, revs):
404
        from branch import Branch
1442.1.64 by Robert Collins
Branch.open_containing now returns a tuple (Branch, relative-path).
405
        other_branch = Branch.open_containing(self.spec)[0]
1432 by Robert Collins
branch: namespace
406
        revision_b = other_branch.last_revision()
407
        if revision_b is None:
408
            raise NoCommits(other_branch)
409
        # 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.
410
        branch.fetch(other_branch, revision_b)
1432 by Robert Collins
branch: namespace
411
        try:
412
            revno = branch.revision_id_to_revno(revision_b)
413
        except NoSuchRevision:
414
            revno = None
415
        return RevisionInfo(branch, revno, revision_b)
416
        
417
SPEC_TYPES.append(RevisionSpec_branch)