/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
18
import datetime
19
import re
1688.2.2 by Guillaume Pinot
Binary search for 'date:' revision.
20
import bisect
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
21
from bzrlib.errors import BzrError, NoSuchRevision, NoCommits
22
23
_marker = []
24
25
class RevisionInfo(object):
26
    """The results of applying a revision specification to a branch.
27
28
    An instance has two useful attributes: revno, and rev_id.
29
30
    They can also be accessed as spec[0] and spec[1] respectively,
31
    so that you can write code like:
32
    revno, rev_id = RevisionSpec(branch, spec)
33
    although this is probably going to be deprecated later.
34
35
    This class exists mostly to be the return value of a RevisionSpec,
36
    so that you can access the member you're interested in (number or id)
37
    or treat the result as a tuple.
38
    """
39
40
    def __init__(self, branch, revno, rev_id=_marker):
41
        self.branch = branch
42
        self.revno = revno
43
        if rev_id is _marker:
44
            # allow caller to be lazy
45
            if self.revno is None:
46
                self.rev_id = None
47
            else:
48
                self.rev_id = branch.get_rev_id(self.revno)
49
        else:
50
            self.rev_id = rev_id
51
52
    def __nonzero__(self):
53
        # first the easy ones...
54
        if self.rev_id is None:
55
            return False
56
        if self.revno is not None:
57
            return True
58
        # TODO: otherwise, it should depend on how I was built -
59
        # if it's in_history(branch), then check revision_history(),
60
        # if it's in_store(branch), do the check below
1185.67.2 by Aaron Bentley
Renamed Branch.storage to Branch.repository
61
        return self.branch.repository.has_revision(self.rev_id)
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
62
63
    def __len__(self):
64
        return 2
65
66
    def __getitem__(self, index):
67
        if index == 0: return self.revno
68
        if index == 1: return self.rev_id
69
        raise IndexError(index)
70
71
    def get(self):
1185.67.2 by Aaron Bentley
Renamed Branch.storage to Branch.repository
72
        return self.branch.repository.get_revision(self.rev_id)
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
73
74
    def __eq__(self, other):
75
        if type(other) not in (tuple, list, type(self)):
76
            return False
77
        if type(other) is type(self) and self.branch is not other.branch:
78
            return False
79
        return tuple(self) == tuple(other)
80
81
    def __repr__(self):
82
        return '<bzrlib.revisionspec.RevisionInfo object %s, %s for %r>' % (
83
            self.revno, self.rev_id, self.branch)
84
85
# classes in this list should have a "prefix" attribute, against which
86
# string specs are matched
87
SPEC_TYPES = []
88
89
class RevisionSpec(object):
90
    """A parsed revision specification.
91
92
    A revision specification can be an integer, in which case it is
93
    assumed to be a revno (though this will translate negative values
94
    into positive ones); or it can be a string, in which case it is
95
    parsed for something like 'date:' or 'revid:' etc.
96
97
    Revision specs are an UI element, and they have been moved out
98
    of the branch class to leave "back-end" classes unaware of such
99
    details.  Code that gets a revno or rev_id from other code should
100
    not be using revision specs - revnos and revision ids are the
101
    accepted ways to refer to revisions internally.
102
103
    (Equivalent to the old Branch method get_revision_info())
104
    """
105
106
    prefix = None
107
108
    def __new__(cls, spec, foo=_marker):
109
        """Parse a revision specifier.
110
        """
111
        if spec is None:
112
            return object.__new__(RevisionSpec, spec)
113
114
        try:
115
            spec = int(spec)
116
        except ValueError:
117
            pass
118
119
        if isinstance(spec, int):
120
            return object.__new__(RevisionSpec_int, spec)
121
        elif isinstance(spec, basestring):
122
            for spectype in SPEC_TYPES:
123
                if spec.startswith(spectype.prefix):
124
                    return object.__new__(spectype, spec)
125
            else:
126
                raise BzrError('No namespace registered for string: %r' %
127
                               spec)
128
        else:
129
            raise TypeError('Unhandled revision type %s' % spec)
130
131
    def __init__(self, spec):
132
        if self.prefix and spec.startswith(self.prefix):
133
            spec = spec[len(self.prefix):]
134
        self.spec = spec
135
136
    def _match_on(self, branch, revs):
137
        return RevisionInfo(branch, 0, None)
138
139
    def _match_on_and_check(self, branch, revs):
140
        info = self._match_on(branch, revs)
141
        if info:
142
            return info
143
        elif info == (0, None):
144
            # special case - the empty tree
145
            return info
146
        elif self.prefix:
147
            raise NoSuchRevision(branch, self.prefix + str(self.spec))
148
        else:
149
            raise NoSuchRevision(branch, str(self.spec))
150
151
    def in_history(self, branch):
1732.3.1 by Matthieu Moy
Implementation of -r revno:N:/path/to/branch
152
        if branch:
153
            revs = branch.revision_history()
154
        else:
155
            revs = None
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
156
        return self._match_on_and_check(branch, revs)
157
1432 by Robert Collins
branch: namespace
158
        # FIXME: in_history is somewhat broken,
159
        # it will return non-history revisions in many
160
        # circumstances. The expected facility is that
161
        # in_history only returns revision-history revs,
162
        # in_store returns any rev. RBC 20051010
163
    # aliases for now, when we fix the core logic, then they
164
    # will do what you expect.
165
    in_store = in_history
166
    in_branch = in_store
167
        
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
168
    def __repr__(self):
169
        # this is mostly for helping with testing
170
        return '<%s %s%s>' % (self.__class__.__name__,
171
                              self.prefix or '',
172
                              self.spec)
1881.1.1 by Matthieu Moy
Fixed and tested "bzr diff" outside a working tree.
173
    
1881.1.4 by Matthieu Moy
needs_tree -> needs_branch
174
    def needs_branch(self):
175
        """Whether this revision spec needs a branch.
176
1711.2.99 by John Arbash Meinel
minor typo fix
177
        Set this to False the branch argument of _match_on is not used.
178
        """
1881.1.1 by Matthieu Moy
Fixed and tested "bzr diff" outside a working tree.
179
        return True
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
180
1907.4.1 by Matthieu Moy
Fixed merge to work nicely with -r revno:N:path
181
    def get_branch(self):
182
        """When the revision specifier contains a branch location, return it.
183
        
184
        Otherwise, return None.
185
        """
186
        return None
187
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
188
# private API
189
190
class RevisionSpec_int(RevisionSpec):
191
    """Spec is a number.  Special case."""
192
    def __init__(self, spec):
193
        self.spec = int(spec)
194
195
    def _match_on(self, branch, revs):
196
        if self.spec < 0:
197
            revno = len(revs) + self.spec + 1
198
        else:
199
            revno = self.spec
200
        rev_id = branch.get_rev_id(revno, revs)
201
        return RevisionInfo(branch, revno, rev_id)
202
203
204
class RevisionSpec_revno(RevisionSpec):
205
    prefix = 'revno:'
206
207
    def _match_on(self, branch, revs):
208
        """Lookup a revision by revision number"""
1732.3.1 by Matthieu Moy
Implementation of -r revno:N:/path/to/branch
209
        if self.spec.find(':') == -1:
210
            try:
211
                return RevisionInfo(branch, int(self.spec))
212
            except ValueError:
213
                return RevisionInfo(branch, None)
214
        else:
215
            from branch import Branch
216
            revname = self.spec[self.spec.find(':')+1:]
217
            other_branch = Branch.open_containing(revname)[0]
218
            try:
219
                revno = int(self.spec[:self.spec.find(':')])
220
            except ValueError:
221
                return RevisionInfo(other_branch, None)
222
            revid = other_branch.get_rev_id(revno)
223
            return RevisionInfo(other_branch, revno)
1881.1.1 by Matthieu Moy
Fixed and tested "bzr diff" outside a working tree.
224
        
1881.1.4 by Matthieu Moy
needs_tree -> needs_branch
225
    def needs_branch(self):
1881.1.1 by Matthieu Moy
Fixed and tested "bzr diff" outside a working tree.
226
        return self.spec.find(':') == -1
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
227
1907.4.1 by Matthieu Moy
Fixed merge to work nicely with -r revno:N:path
228
    def get_branch(self):
229
        if self.spec.find(':') == -1:
230
            return None
231
        else:
232
            return self.spec[self.spec.find(':')+1:]
233
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
234
SPEC_TYPES.append(RevisionSpec_revno)
235
236
237
class RevisionSpec_revid(RevisionSpec):
238
    prefix = 'revid:'
239
240
    def _match_on(self, branch, revs):
241
        try:
242
            return RevisionInfo(branch, revs.index(self.spec) + 1, self.spec)
243
        except ValueError:
1185.62.5 by John Arbash Meinel
Updated -r revid:foo so that it can match revisions which aren't in the revision history
244
            return RevisionInfo(branch, None, self.spec)
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
245
246
SPEC_TYPES.append(RevisionSpec_revid)
247
248
249
class RevisionSpec_last(RevisionSpec):
1185.1.39 by Robert Collins
Robey Pointers before: namespace to clear up usage of dates in revision parameters
250
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
251
    prefix = 'last:'
252
253
    def _match_on(self, branch, revs):
254
        try:
255
            offset = int(self.spec)
256
        except ValueError:
257
            return RevisionInfo(branch, None)
258
        else:
259
            if offset <= 0:
260
                raise BzrError('You must supply a positive value for --revision last:XXX')
261
            return RevisionInfo(branch, len(revs) - offset + 1)
262
263
SPEC_TYPES.append(RevisionSpec_last)
264
265
1185.1.39 by Robert Collins
Robey Pointers before: namespace to clear up usage of dates in revision parameters
266
class RevisionSpec_before(RevisionSpec):
267
268
    prefix = 'before:'
269
    
270
    def _match_on(self, branch, revs):
271
        r = RevisionSpec(self.spec)._match_on(branch, revs)
272
        if (r.revno is None) or (r.revno == 0):
273
            return r
274
        return RevisionInfo(branch, r.revno - 1)
275
276
SPEC_TYPES.append(RevisionSpec_before)
277
278
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
279
class RevisionSpec_tag(RevisionSpec):
280
    prefix = 'tag:'
281
282
    def _match_on(self, branch, revs):
283
        raise BzrError('tag: namespace registered, but not implemented.')
284
285
SPEC_TYPES.append(RevisionSpec_tag)
286
287
1688.2.2 by Guillaume Pinot
Binary search for 'date:' revision.
288
class RevisionSpec_revs:
289
    def __init__(self, revs, branch):
290
        self.revs = revs
291
        self.branch = branch
292
    def __getitem__(self, index):
293
        r = self.branch.repository.get_revision(self.revs[index])
294
        # TODO: Handle timezone.
295
        return datetime.datetime.fromtimestamp(r.timestamp)
296
    def __len__(self):
297
        return len(self.revs)
298
299
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
300
class RevisionSpec_date(RevisionSpec):
301
    prefix = 'date:'
302
    _date_re = re.compile(
303
            r'(?P<date>(?P<year>\d\d\d\d)-(?P<month>\d\d)-(?P<day>\d\d))?'
304
            r'(,|T)?\s*'
305
            r'(?P<time>(?P<hour>\d\d):(?P<minute>\d\d)(:(?P<second>\d\d))?)?'
306
        )
307
308
    def _match_on(self, branch, revs):
309
        """
310
        Spec for date revisions:
311
          date:value
312
          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
313
          matches the first entry after a given date (either at midnight or
314
          at a specified time).
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
315
316
          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)
317
              -r date:yesterday..date:today
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
318
        """
1185.1.39 by Robert Collins
Robey Pointers before: namespace to clear up usage of dates in revision parameters
319
        today = datetime.datetime.fromordinal(datetime.date.today().toordinal())
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
320
        if self.spec.lower() == 'yesterday':
321
            dt = today - datetime.timedelta(days=1)
322
        elif self.spec.lower() == 'today':
323
            dt = today
324
        elif self.spec.lower() == 'tomorrow':
325
            dt = today + datetime.timedelta(days=1)
326
        else:
327
            m = self._date_re.match(self.spec)
328
            if not m or (not m.group('date') and not m.group('time')):
329
                raise BzrError('Invalid revision date %r' % self.spec)
330
331
            if m.group('date'):
332
                year, month, day = int(m.group('year')), int(m.group('month')), int(m.group('day'))
333
            else:
334
                year, month, day = today.year, today.month, today.day
335
            if m.group('time'):
336
                hour = int(m.group('hour'))
337
                minute = int(m.group('minute'))
338
                if m.group('second'):
339
                    second = int(m.group('second'))
340
                else:
341
                    second = 0
342
            else:
343
                hour, minute, second = 0,0,0
344
345
            dt = datetime.datetime(year=year, month=month, day=day,
346
                    hour=hour, minute=minute, second=second)
1704.2.27 by Martin Pool
Run bisection search for revision date with lock held. (Robert Widhopf-Frenk)
347
        branch.lock_read()
348
        try:
349
            rev = bisect.bisect(RevisionSpec_revs(revs, branch), dt)
350
        finally:
351
            branch.unlock()
1688.2.2 by Guillaume Pinot
Binary search for 'date:' revision.
352
        if rev == len(revs):
353
            return RevisionInfo(branch, None)
354
        else:
355
            return RevisionInfo(branch, rev + 1)
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
356
357
SPEC_TYPES.append(RevisionSpec_date)
358
359
360
class RevisionSpec_ancestor(RevisionSpec):
361
    prefix = 'ancestor:'
362
363
    def _match_on(self, branch, revs):
364
        from branch import Branch
365
        from revision import common_ancestor, MultipleRevisionSources
1442.1.64 by Robert Collins
Branch.open_containing now returns a tuple (Branch, relative-path).
366
        other_branch = Branch.open_containing(self.spec)[0]
1390 by Robert Collins
pair programming worx... merge integration and weave
367
        revision_a = branch.last_revision()
368
        revision_b = other_branch.last_revision()
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
369
        for r, b in ((revision_a, branch), (revision_b, other_branch)):
370
            if r is None:
371
                raise NoCommits(b)
1185.67.2 by Aaron Bentley
Renamed Branch.storage to Branch.repository
372
        revision_source = MultipleRevisionSources(branch.repository,
373
                                                  other_branch.repository)
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
374
        rev_id = common_ancestor(revision_a, revision_b, revision_source)
375
        try:
376
            revno = branch.revision_id_to_revno(rev_id)
377
        except NoSuchRevision:
378
            revno = None
379
        return RevisionInfo(branch, revno, rev_id)
380
        
381
SPEC_TYPES.append(RevisionSpec_ancestor)
1432 by Robert Collins
branch: namespace
382
383
class RevisionSpec_branch(RevisionSpec):
384
    """A branch: revision specifier.
385
386
    This takes the path to a branch and returns its tip revision id.
387
    """
388
    prefix = 'branch:'
389
390
    def _match_on(self, branch, revs):
391
        from branch import Branch
1442.1.64 by Robert Collins
Branch.open_containing now returns a tuple (Branch, relative-path).
392
        other_branch = Branch.open_containing(self.spec)[0]
1432 by Robert Collins
branch: namespace
393
        revision_b = other_branch.last_revision()
394
        if revision_b is None:
395
            raise NoCommits(other_branch)
396
        # 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.
397
        branch.fetch(other_branch, revision_b)
1432 by Robert Collins
branch: namespace
398
        try:
399
            revno = branch.revision_id_to_revno(revision_b)
400
        except NoSuchRevision:
401
            revno = None
402
        return RevisionInfo(branch, revno, revision_b)
403
        
404
SPEC_TYPES.append(RevisionSpec_branch)