/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
2220.2.3 by Martin Pool
Add tag: revision namespace.
1
# Copyright (C) 2005, 2006, 2007 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,
1948.4.18 by John Arbash Meinel
Update branch: spec and tests
24
    revision,
1948.4.27 by John Arbash Meinel
Deprecate calling RevisionSpec directly, and instead use a helper function. Also merge the old RevisionSpec_int class into RevisionSpec_revno
25
    symbol_versioning,
26
    trace,
1988.4.5 by Robert Collins
revisions can now be specified using dotted-decimal revision numbers.
27
    tsort,
1948.4.1 by John Arbash Meinel
Update number parsers to raise InvalidRevisionSpec. Update revno: itself so it supports negative numbers
28
    )
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
29
1948.4.16 by John Arbash Meinel
Move the tests into the associated tester, remove redundant tests, some small PEP8 changes
30
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
31
_marker = []
32
1948.4.16 by John Arbash Meinel
Move the tests into the associated tester, remove redundant tests, some small PEP8 changes
33
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
34
class RevisionInfo(object):
2070.4.14 by John Arbash Meinel
Switch revisionspec to use the help defined as help_txt rather than the doc string
35
    """The results of applying a revision specification to a branch."""
36
37
    help_txt = """The results of applying a revision specification to a branch.
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
38
39
    An instance has two useful attributes: revno, and rev_id.
40
41
    They can also be accessed as spec[0] and spec[1] respectively,
42
    so that you can write code like:
43
    revno, rev_id = RevisionSpec(branch, spec)
44
    although this is probably going to be deprecated later.
45
46
    This class exists mostly to be the return value of a RevisionSpec,
47
    so that you can access the member you're interested in (number or id)
48
    or treat the result as a tuple.
49
    """
50
51
    def __init__(self, branch, revno, rev_id=_marker):
52
        self.branch = branch
53
        self.revno = revno
54
        if rev_id is _marker:
55
            # allow caller to be lazy
56
            if self.revno is None:
57
                self.rev_id = None
58
            else:
59
                self.rev_id = branch.get_rev_id(self.revno)
60
        else:
61
            self.rev_id = rev_id
62
63
    def __nonzero__(self):
64
        # first the easy ones...
65
        if self.rev_id is None:
66
            return False
67
        if self.revno is not None:
68
            return True
69
        # TODO: otherwise, it should depend on how I was built -
70
        # if it's in_history(branch), then check revision_history(),
71
        # if it's in_store(branch), do the check below
1185.67.2 by Aaron Bentley
Renamed Branch.storage to Branch.repository
72
        return self.branch.repository.has_revision(self.rev_id)
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
73
74
    def __len__(self):
75
        return 2
76
77
    def __getitem__(self, index):
78
        if index == 0: return self.revno
79
        if index == 1: return self.rev_id
80
        raise IndexError(index)
81
82
    def get(self):
1185.67.2 by Aaron Bentley
Renamed Branch.storage to Branch.repository
83
        return self.branch.repository.get_revision(self.rev_id)
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
84
85
    def __eq__(self, other):
86
        if type(other) not in (tuple, list, type(self)):
87
            return False
88
        if type(other) is type(self) and self.branch is not other.branch:
89
            return False
90
        return tuple(self) == tuple(other)
91
92
    def __repr__(self):
93
        return '<bzrlib.revisionspec.RevisionInfo object %s, %s for %r>' % (
94
            self.revno, self.rev_id, self.branch)
95
2220.2.3 by Martin Pool
Add tag: revision namespace.
96
    @staticmethod
97
    def from_revision_id(branch, revision_id, revs):
98
        """Construct a RevisionInfo given just the id.
99
100
        Use this if you don't know or care what the revno is.
101
        """
102
        try:
103
            revno = revs.index(revision_id) + 1
104
        except ValueError:
105
            revno = None
106
        return RevisionInfo(branch, revno, revision_id)
107
1948.4.16 by John Arbash Meinel
Move the tests into the associated tester, remove redundant tests, some small PEP8 changes
108
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
109
# classes in this list should have a "prefix" attribute, against which
110
# string specs are matched
111
SPEC_TYPES = []
1948.4.35 by John Arbash Meinel
Move the _revno_regex to a more logical location
112
_revno_regex = None
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
113
1948.4.16 by John Arbash Meinel
Move the tests into the associated tester, remove redundant tests, some small PEP8 changes
114
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
115
class RevisionSpec(object):
2070.4.14 by John Arbash Meinel
Switch revisionspec to use the help defined as help_txt rather than the doc string
116
    """A parsed revision specification."""
117
118
    help_txt = """A parsed revision specification.
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
119
120
    A revision specification can be an integer, in which case it is
121
    assumed to be a revno (though this will translate negative values
122
    into positive ones); or it can be a string, in which case it is
123
    parsed for something like 'date:' or 'revid:' etc.
124
125
    Revision specs are an UI element, and they have been moved out
126
    of the branch class to leave "back-end" classes unaware of such
127
    details.  Code that gets a revno or rev_id from other code should
128
    not be using revision specs - revnos and revision ids are the
129
    accepted ways to refer to revisions internally.
130
131
    (Equivalent to the old Branch method get_revision_info())
132
    """
133
134
    prefix = None
135
1948.4.27 by John Arbash Meinel
Deprecate calling RevisionSpec directly, and instead use a helper function. Also merge the old RevisionSpec_int class into RevisionSpec_revno
136
    def __new__(cls, spec, _internal=False):
137
        if _internal:
138
            return object.__new__(cls, spec, _internal=_internal)
139
140
        symbol_versioning.warn('Creating a RevisionSpec directly has'
141
                               ' been deprecated in version 0.11. Use'
1948.4.33 by John Arbash Meinel
Switch from get_revision_spec() to RevisionSpec.from_string() (as advised by Martin)
142
                               ' RevisionSpec.from_string()'
1948.4.27 by John Arbash Meinel
Deprecate calling RevisionSpec directly, and instead use a helper function. Also merge the old RevisionSpec_int class into RevisionSpec_revno
143
                               ' instead.',
144
                               DeprecationWarning, stacklevel=2)
1948.4.33 by John Arbash Meinel
Switch from get_revision_spec() to RevisionSpec.from_string() (as advised by Martin)
145
        return RevisionSpec.from_string(spec)
146
147
    @staticmethod
148
    def from_string(spec):
149
        """Parse a revision spec string into a RevisionSpec object.
150
151
        :param spec: A string specified by the user
152
        :return: A RevisionSpec object that understands how to parse the
153
            supplied notation.
154
        """
155
        if not isinstance(spec, (type(None), basestring)):
156
            raise TypeError('error')
157
158
        if spec is None:
159
            return RevisionSpec(None, _internal=True)
160
161
        assert isinstance(spec, basestring), \
162
            "You should only supply strings not %s" % (type(spec),)
163
164
        for spectype in SPEC_TYPES:
165
            if spec.startswith(spectype.prefix):
166
                trace.mutter('Returning RevisionSpec %s for %s',
167
                             spectype.__name__, spec)
168
                return spectype(spec, _internal=True)
169
        else:
170
            # RevisionSpec_revno is special cased, because it is the only
171
            # one that directly handles plain integers
1988.4.5 by Robert Collins
revisions can now be specified using dotted-decimal revision numbers.
172
            # TODO: This should not be special cased rather it should be
173
            # a method invocation on spectype.canparse()
1948.4.33 by John Arbash Meinel
Switch from get_revision_spec() to RevisionSpec.from_string() (as advised by Martin)
174
            global _revno_regex
175
            if _revno_regex is None:
1988.4.5 by Robert Collins
revisions can now be specified using dotted-decimal revision numbers.
176
                _revno_regex = re.compile(r'^(?:(\d+(\.\d+)*)|-\d+)(:.*)?$')
1948.4.33 by John Arbash Meinel
Switch from get_revision_spec() to RevisionSpec.from_string() (as advised by Martin)
177
            if _revno_regex.match(spec) is not None:
178
                return RevisionSpec_revno(spec, _internal=True)
179
180
            raise errors.NoSuchRevisionSpec(spec)
1948.4.27 by John Arbash Meinel
Deprecate calling RevisionSpec directly, and instead use a helper function. Also merge the old RevisionSpec_int class into RevisionSpec_revno
181
182
    def __init__(self, spec, _internal=False):
183
        """Create a RevisionSpec referring to the Null revision.
184
185
        :param spec: The original spec supplied by the user
186
        :param _internal: Used to ensure that RevisionSpec is not being
1948.4.33 by John Arbash Meinel
Switch from get_revision_spec() to RevisionSpec.from_string() (as advised by Martin)
187
            called directly. Only from RevisionSpec.from_string()
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
188
        """
1948.4.27 by John Arbash Meinel
Deprecate calling RevisionSpec directly, and instead use a helper function. Also merge the old RevisionSpec_int class into RevisionSpec_revno
189
        if not _internal:
190
            # XXX: Update this after 0.10 is released
191
            symbol_versioning.warn('Creating a RevisionSpec directly has'
192
                                   ' been deprecated in version 0.11. Use'
1948.4.33 by John Arbash Meinel
Switch from get_revision_spec() to RevisionSpec.from_string() (as advised by Martin)
193
                                   ' RevisionSpec.from_string()'
1948.4.27 by John Arbash Meinel
Deprecate calling RevisionSpec directly, and instead use a helper function. Also merge the old RevisionSpec_int class into RevisionSpec_revno
194
                                   ' instead.',
195
                                   DeprecationWarning, stacklevel=2)
196
        self.user_spec = spec
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
197
        if self.prefix and spec.startswith(self.prefix):
198
            spec = spec[len(self.prefix):]
199
        self.spec = spec
200
201
    def _match_on(self, branch, revs):
1948.4.27 by John Arbash Meinel
Deprecate calling RevisionSpec directly, and instead use a helper function. Also merge the old RevisionSpec_int class into RevisionSpec_revno
202
        trace.mutter('Returning RevisionSpec._match_on: None')
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
203
        return RevisionInfo(branch, 0, None)
204
205
    def _match_on_and_check(self, branch, revs):
206
        info = self._match_on(branch, revs)
207
        if info:
208
            return info
209
        elif info == (0, None):
210
            # special case - the empty tree
211
            return info
212
        elif self.prefix:
1948.4.27 by John Arbash Meinel
Deprecate calling RevisionSpec directly, and instead use a helper function. Also merge the old RevisionSpec_int class into RevisionSpec_revno
213
            raise errors.InvalidRevisionSpec(self.user_spec, branch)
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
214
        else:
1948.4.2 by John Arbash Meinel
Update _match_on_and_check to raise the right error
215
            raise errors.InvalidRevisionSpec(self.spec, branch)
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
216
217
    def in_history(self, branch):
1732.3.1 by Matthieu Moy
Implementation of -r revno:N:/path/to/branch
218
        if branch:
219
            revs = branch.revision_history()
220
        else:
1988.4.5 by Robert Collins
revisions can now be specified using dotted-decimal revision numbers.
221
            # this should never trigger.
222
            # TODO: make it a deprecated code path. RBC 20060928
1732.3.1 by Matthieu Moy
Implementation of -r revno:N:/path/to/branch
223
            revs = None
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
224
        return self._match_on_and_check(branch, revs)
225
1432 by Robert Collins
branch: namespace
226
        # FIXME: in_history is somewhat broken,
227
        # it will return non-history revisions in many
228
        # circumstances. The expected facility is that
229
        # in_history only returns revision-history revs,
230
        # in_store returns any rev. RBC 20051010
231
    # aliases for now, when we fix the core logic, then they
232
    # will do what you expect.
233
    in_store = in_history
234
    in_branch = in_store
235
        
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
236
    def __repr__(self):
237
        # this is mostly for helping with testing
1948.4.32 by John Arbash Meinel
Clean up __repr__, as well as add tests that we can handle -r12:branch/
238
        return '<%s %s>' % (self.__class__.__name__,
239
                              self.user_spec)
1881.1.1 by Matthieu Moy
Fixed and tested "bzr diff" outside a working tree.
240
    
1881.1.4 by Matthieu Moy
needs_tree -> needs_branch
241
    def needs_branch(self):
242
        """Whether this revision spec needs a branch.
243
1711.2.99 by John Arbash Meinel
minor typo fix
244
        Set this to False the branch argument of _match_on is not used.
245
        """
1881.1.1 by Matthieu Moy
Fixed and tested "bzr diff" outside a working tree.
246
        return True
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
247
1907.4.1 by Matthieu Moy
Fixed merge to work nicely with -r revno:N:path
248
    def get_branch(self):
249
        """When the revision specifier contains a branch location, return it.
250
        
251
        Otherwise, return None.
252
        """
253
        return None
254
1907.4.9 by Matthieu Moy
missing newline
255
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
256
# private API
257
258
class RevisionSpec_revno(RevisionSpec):
2070.4.14 by John Arbash Meinel
Switch revisionspec to use the help defined as help_txt rather than the doc string
259
    """Selects a revision using a number."""
260
261
    help_txt = """Selects a revision using a number.
2023.1.1 by ghigo
add topics help
262
263
    Use an integer to specify a revision in the history of the branch.
264
    Optionally a branch can be specified. The 'revno:' prefix is optional.
265
    A negative number will count from the end of the branch (-1 is the
266
    last revision, -2 the previous one). If the negative number is larger
267
    than the branch's history, the first revision is returned.
268
    examples:
269
      revno:1                   -> return the first revision
270
      revno:3:/path/to/branch   -> return the 3rd revision of
271
                                   the branch '/path/to/branch'
272
      revno:-1                  -> The last revision in a branch.
273
      -2:http://other/branch    -> The second to last revision in the
274
                                   remote branch.
275
      -1000000                  -> Most likely the first revision, unless
276
                                   your history is very long.
277
    """
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
278
    prefix = 'revno:'
279
280
    def _match_on(self, branch, revs):
281
        """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
282
        loc = self.spec.find(':')
283
        if loc == -1:
284
            revno_spec = self.spec
285
            branch_spec = None
286
        else:
287
            revno_spec = self.spec[:loc]
288
            branch_spec = self.spec[loc+1:]
289
290
        if revno_spec == '':
1948.4.6 by John Arbash Meinel
A small bugfix, and more tests for revno:
291
            if not branch_spec:
1948.4.27 by John Arbash Meinel
Deprecate calling RevisionSpec directly, and instead use a helper function. Also merge the old RevisionSpec_int class into RevisionSpec_revno
292
                raise errors.InvalidRevisionSpec(self.user_spec,
1948.4.5 by John Arbash Meinel
Fix tests for negative entries, and add tests for revno:
293
                        branch, 'cannot have an empty revno and no branch')
1948.4.1 by John Arbash Meinel
Update number parsers to raise InvalidRevisionSpec. Update revno: itself so it supports negative numbers
294
            revno = None
295
        else:
296
            try:
297
                revno = int(revno_spec)
1988.4.5 by Robert Collins
revisions can now be specified using dotted-decimal revision numbers.
298
                dotted = False
299
            except ValueError:
300
                # dotted decimal. This arguably should not be here
301
                # but the from_string method is a little primitive 
302
                # right now - RBC 20060928
303
                try:
304
                    match_revno = tuple((int(number) for number in revno_spec.split('.')))
305
                except ValueError, e:
306
                    raise errors.InvalidRevisionSpec(self.user_spec, branch, e)
307
308
                dotted = True
1948.4.1 by John Arbash Meinel
Update number parsers to raise InvalidRevisionSpec. Update revno: itself so it supports negative numbers
309
1948.4.6 by John Arbash Meinel
A small bugfix, and more tests for revno:
310
        if branch_spec:
1988.4.5 by Robert Collins
revisions can now be specified using dotted-decimal revision numbers.
311
            # the user has override the branch to look in.
312
            # we need to refresh the revision_history map and
313
            # the branch object.
1948.4.1 by John Arbash Meinel
Update number parsers to raise InvalidRevisionSpec. Update revno: itself so it supports negative numbers
314
            from bzrlib.branch import Branch
315
            branch = Branch.open(branch_spec)
1948.4.22 by John Arbash Meinel
Refactor common code from integer revno handlers
316
            # Need to use a new revision history
317
            # because we are using a specific branch
318
            revs = branch.revision_history()
319
1988.4.5 by Robert Collins
revisions can now be specified using dotted-decimal revision numbers.
320
        if dotted:
321
            branch.lock_read()
322
            try:
323
                last_rev = branch.last_revision()
324
                merge_sorted_revisions = tsort.merge_sort(
325
                    branch.repository.get_revision_graph(last_rev),
326
                    last_rev,
327
                    generate_revno=True)
328
                def match(item):
329
                    return item[3] == match_revno
330
                revisions = filter(match, merge_sorted_revisions)
331
            finally:
332
                branch.unlock()
333
            if len(revisions) != 1:
334
                return RevisionInfo(branch, None, None)
1948.4.27 by John Arbash Meinel
Deprecate calling RevisionSpec directly, and instead use a helper function. Also merge the old RevisionSpec_int class into RevisionSpec_revno
335
            else:
1988.4.5 by Robert Collins
revisions can now be specified using dotted-decimal revision numbers.
336
                # there is no traditional 'revno' for dotted-decimal revnos.
337
                # so for  API compatability we return None.
338
                return RevisionInfo(branch, None, revisions[0][1])
339
        else:
340
            if revno < 0:
341
                if (-revno) >= len(revs):
342
                    revno = 1
343
                else:
344
                    revno = len(revs) + revno + 1
345
            try:
346
                revision_id = branch.get_rev_id(revno, revs)
347
            except errors.NoSuchRevision:
348
                raise errors.InvalidRevisionSpec(self.user_spec, branch)
1948.4.27 by John Arbash Meinel
Deprecate calling RevisionSpec directly, and instead use a helper function. Also merge the old RevisionSpec_int class into RevisionSpec_revno
349
        return RevisionInfo(branch, revno, revision_id)
1881.1.1 by Matthieu Moy
Fixed and tested "bzr diff" outside a working tree.
350
        
1881.1.4 by Matthieu Moy
needs_tree -> needs_branch
351
    def needs_branch(self):
1881.1.1 by Matthieu Moy
Fixed and tested "bzr diff" outside a working tree.
352
        return self.spec.find(':') == -1
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
353
1907.4.1 by Matthieu Moy
Fixed merge to work nicely with -r revno:N:path
354
    def get_branch(self):
355
        if self.spec.find(':') == -1:
356
            return None
357
        else:
358
            return self.spec[self.spec.find(':')+1:]
359
1948.4.27 by John Arbash Meinel
Deprecate calling RevisionSpec directly, and instead use a helper function. Also merge the old RevisionSpec_int class into RevisionSpec_revno
360
# Old compatibility 
361
RevisionSpec_int = RevisionSpec_revno
362
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
363
SPEC_TYPES.append(RevisionSpec_revno)
364
365
366
class RevisionSpec_revid(RevisionSpec):
2070.4.14 by John Arbash Meinel
Switch revisionspec to use the help defined as help_txt rather than the doc string
367
    """Selects a revision using the revision id."""
368
369
    help_txt = """Selects a revision using the revision id.
2023.1.1 by ghigo
add topics help
370
371
    Supply a specific revision id, that can be used to specify any
372
    revision id in the ancestry of the branch. 
373
    Including merges, and pending merges.
374
    examples:
2070.4.7 by ghigo
Updates on the basis of the Richard Wilbur suggestions
375
      revid:aaaa@bbbb-123456789 -> Select revision 'aaaa@bbbb-123456789'
2023.1.1 by ghigo
add topics help
376
    """    
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
377
    prefix = 'revid:'
378
379
    def _match_on(self, branch, revs):
2220.2.3 by Martin Pool
Add tag: revision namespace.
380
        return RevisionInfo.from_revision_id(branch, self.spec, revs)
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
381
382
SPEC_TYPES.append(RevisionSpec_revid)
383
384
385
class RevisionSpec_last(RevisionSpec):
2070.4.14 by John Arbash Meinel
Switch revisionspec to use the help defined as help_txt rather than the doc string
386
    """Selects the nth revision from the end."""
387
388
    help_txt = """Selects the nth revision from the end.
2023.1.1 by ghigo
add topics help
389
390
    Supply a positive number to get the nth revision from the end.
2070.4.7 by ghigo
Updates on the basis of the Richard Wilbur suggestions
391
    This is the same as supplying negative numbers to the 'revno:' spec.
2023.1.1 by ghigo
add topics help
392
    examples:
393
      last:1        -> return the last revision
394
      last:3        -> return the revision 2 before the end.
395
    """    
1185.1.39 by Robert Collins
Robey Pointers before: namespace to clear up usage of dates in revision parameters
396
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
397
    prefix = 'last:'
398
399
    def _match_on(self, branch, revs):
1948.4.9 by John Arbash Meinel
Cleanup and test last:
400
        if self.spec == '':
401
            if not revs:
1948.4.26 by John Arbash Meinel
Get rid of direct imports of exceptions
402
                raise errors.NoCommits(branch)
1948.4.9 by John Arbash Meinel
Cleanup and test last:
403
            return RevisionInfo(branch, len(revs), revs[-1])
404
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
405
        try:
406
            offset = int(self.spec)
1948.4.9 by John Arbash Meinel
Cleanup and test last:
407
        except ValueError, e:
1948.4.27 by John Arbash Meinel
Deprecate calling RevisionSpec directly, and instead use a helper function. Also merge the old RevisionSpec_int class into RevisionSpec_revno
408
            raise errors.InvalidRevisionSpec(self.user_spec, branch, e)
1948.4.9 by John Arbash Meinel
Cleanup and test last:
409
410
        if offset <= 0:
1948.4.27 by John Arbash Meinel
Deprecate calling RevisionSpec directly, and instead use a helper function. Also merge the old RevisionSpec_int class into RevisionSpec_revno
411
            raise errors.InvalidRevisionSpec(self.user_spec, branch,
1948.4.9 by John Arbash Meinel
Cleanup and test last:
412
                                             'you must supply a positive value')
413
        revno = len(revs) - offset + 1
414
        try:
415
            revision_id = branch.get_rev_id(revno, revs)
416
        except errors.NoSuchRevision:
1948.4.27 by John Arbash Meinel
Deprecate calling RevisionSpec directly, and instead use a helper function. Also merge the old RevisionSpec_int class into RevisionSpec_revno
417
            raise errors.InvalidRevisionSpec(self.user_spec, branch)
1948.4.9 by John Arbash Meinel
Cleanup and test last:
418
        return RevisionInfo(branch, revno, revision_id)
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
419
420
SPEC_TYPES.append(RevisionSpec_last)
421
422
1185.1.39 by Robert Collins
Robey Pointers before: namespace to clear up usage of dates in revision parameters
423
class RevisionSpec_before(RevisionSpec):
2070.4.14 by John Arbash Meinel
Switch revisionspec to use the help defined as help_txt rather than the doc string
424
    """Selects the parent of the revision specified."""
425
426
    help_txt = """Selects the parent of the revision specified.
2023.1.1 by ghigo
add topics help
427
428
    Supply any revision spec to return the parent of that revision.
429
    It is an error to request the parent of the null revision (before:0).
430
    This is mostly useful when inspecting revisions that are not in the
431
    revision history of a branch.
432
433
    examples:
434
      before:1913    -> Return the parent of revno 1913 (revno 1912)
435
      before:revid:aaaa@bbbb-1234567890  -> return the parent of revision
2070.4.7 by ghigo
Updates on the basis of the Richard Wilbur suggestions
436
                                            aaaa@bbbb-1234567890
2023.1.1 by ghigo
add topics help
437
      bzr diff -r before:revid:aaaa..revid:aaaa
438
            -> Find the changes between revision 'aaaa' and its parent.
439
               (what changes did 'aaaa' introduce)
440
    """
1185.1.39 by Robert Collins
Robey Pointers before: namespace to clear up usage of dates in revision parameters
441
442
    prefix = 'before:'
443
    
444
    def _match_on(self, branch, revs):
1948.4.33 by John Arbash Meinel
Switch from get_revision_spec() to RevisionSpec.from_string() (as advised by Martin)
445
        r = RevisionSpec.from_string(self.spec)._match_on(branch, revs)
1948.4.13 by John Arbash Meinel
Going before:0 is an error, and if you are on another history, use the leftmost parent
446
        if r.revno == 0:
1948.4.27 by John Arbash Meinel
Deprecate calling RevisionSpec directly, and instead use a helper function. Also merge the old RevisionSpec_int class into RevisionSpec_revno
447
            raise errors.InvalidRevisionSpec(self.user_spec, branch,
1948.4.13 by John Arbash Meinel
Going before:0 is an error, and if you are on another history, use the leftmost parent
448
                                         'cannot go before the null: revision')
449
        if r.revno is None:
450
            # We need to use the repository history here
451
            rev = branch.repository.get_revision(r.rev_id)
452
            if not rev.parent_ids:
453
                revno = 0
454
                revision_id = None
455
            else:
456
                revision_id = rev.parent_ids[0]
457
                try:
458
                    revno = revs.index(revision_id) + 1
459
                except ValueError:
460
                    revno = None
461
        else:
462
            revno = r.revno - 1
463
            try:
464
                revision_id = branch.get_rev_id(revno, revs)
1948.4.26 by John Arbash Meinel
Get rid of direct imports of exceptions
465
            except errors.NoSuchRevision:
1948.4.27 by John Arbash Meinel
Deprecate calling RevisionSpec directly, and instead use a helper function. Also merge the old RevisionSpec_int class into RevisionSpec_revno
466
                raise errors.InvalidRevisionSpec(self.user_spec,
1948.4.13 by John Arbash Meinel
Going before:0 is an error, and if you are on another history, use the leftmost parent
467
                                                 branch)
468
        return RevisionInfo(branch, revno, revision_id)
1185.1.39 by Robert Collins
Robey Pointers before: namespace to clear up usage of dates in revision parameters
469
470
SPEC_TYPES.append(RevisionSpec_before)
471
472
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
473
class RevisionSpec_tag(RevisionSpec):
2220.2.3 by Martin Pool
Add tag: revision namespace.
474
    """Select a revision identified by tag name"""
475
476
    help_txt = """Selects a revision identified by a tag name.
477
478
    Tags are stored in the repository and created by the 'tag'
479
    command.
480
    """
2070.4.14 by John Arbash Meinel
Switch revisionspec to use the help defined as help_txt rather than the doc string
481
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
482
    prefix = 'tag:'
483
484
    def _match_on(self, branch, revs):
2220.2.3 by Martin Pool
Add tag: revision namespace.
485
        # Can raise tags not supported, NoSuchTag, etc
486
        return RevisionInfo.from_revision_id(branch,
487
            branch.repository.lookup_tag(self.spec),
488
            revs)
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
489
490
SPEC_TYPES.append(RevisionSpec_tag)
491
492
1948.4.12 by John Arbash Meinel
Some tests for the date: spec
493
class _RevListToTimestamps(object):
494
    """This takes a list of revisions, and allows you to bisect by date"""
495
496
    __slots__ = ['revs', 'branch']
497
1688.2.2 by Guillaume Pinot
Binary search for 'date:' revision.
498
    def __init__(self, revs, branch):
499
        self.revs = revs
500
        self.branch = branch
1948.4.12 by John Arbash Meinel
Some tests for the date: spec
501
1688.2.2 by Guillaume Pinot
Binary search for 'date:' revision.
502
    def __getitem__(self, index):
1948.4.12 by John Arbash Meinel
Some tests for the date: spec
503
        """Get the date of the index'd item"""
1688.2.2 by Guillaume Pinot
Binary search for 'date:' revision.
504
        r = self.branch.repository.get_revision(self.revs[index])
505
        # TODO: Handle timezone.
506
        return datetime.datetime.fromtimestamp(r.timestamp)
1948.4.12 by John Arbash Meinel
Some tests for the date: spec
507
1688.2.2 by Guillaume Pinot
Binary search for 'date:' revision.
508
    def __len__(self):
509
        return len(self.revs)
510
511
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
512
class RevisionSpec_date(RevisionSpec):
2070.4.14 by John Arbash Meinel
Switch revisionspec to use the help defined as help_txt rather than the doc string
513
    """Selects a revision on the basis of a datestamp."""
514
515
    help_txt = """Selects a revision on the basis of a datestamp.
2023.1.1 by ghigo
add topics help
516
517
    Supply a datestamp to select the first revision that matches the date.
518
    Date can be 'yesterday', 'today', 'tomorrow' or a YYYY-MM-DD string.
519
    Matches the first entry after a given date (either at midnight or
520
    at a specified time).
521
522
    One way to display all the changes since yesterday would be:
523
        bzr log -r date:yesterday..-1
524
525
    examples:
526
      date:yesterday            -> select the first revision since yesterday
527
      date:2006-08-14,17:10:14  -> select the first revision after
528
                                   August 14th, 2006 at 5:10pm.
529
    """    
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
530
    prefix = 'date:'
531
    _date_re = re.compile(
532
            r'(?P<date>(?P<year>\d\d\d\d)-(?P<month>\d\d)-(?P<day>\d\d))?'
533
            r'(,|T)?\s*'
534
            r'(?P<time>(?P<hour>\d\d):(?P<minute>\d\d)(:(?P<second>\d\d))?)?'
535
        )
536
537
    def _match_on(self, branch, revs):
2023.1.1 by ghigo
add topics help
538
        """Spec for date revisions:
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
539
          date:value
540
          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
541
          matches the first entry after a given date (either at midnight or
542
          at a specified time).
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
543
        """
2070.4.3 by John Arbash Meinel
code and doc cleanup
544
        #  XXX: This doesn't actually work
545
        #  So the proper way of saying 'give me all entries for today' is:
546
        #      -r date:yesterday..date:today
1185.1.39 by Robert Collins
Robey Pointers before: namespace to clear up usage of dates in revision parameters
547
        today = datetime.datetime.fromordinal(datetime.date.today().toordinal())
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
548
        if self.spec.lower() == 'yesterday':
549
            dt = today - datetime.timedelta(days=1)
550
        elif self.spec.lower() == 'today':
551
            dt = today
552
        elif self.spec.lower() == 'tomorrow':
553
            dt = today + datetime.timedelta(days=1)
554
        else:
555
            m = self._date_re.match(self.spec)
556
            if not m or (not m.group('date') and not m.group('time')):
1948.4.27 by John Arbash Meinel
Deprecate calling RevisionSpec directly, and instead use a helper function. Also merge the old RevisionSpec_int class into RevisionSpec_revno
557
                raise errors.InvalidRevisionSpec(self.user_spec,
1948.4.12 by John Arbash Meinel
Some tests for the date: spec
558
                                                 branch, 'invalid date')
559
560
            try:
561
                if m.group('date'):
562
                    year = int(m.group('year'))
563
                    month = int(m.group('month'))
564
                    day = int(m.group('day'))
565
                else:
566
                    year = today.year
567
                    month = today.month
568
                    day = today.day
569
570
                if m.group('time'):
571
                    hour = int(m.group('hour'))
572
                    minute = int(m.group('minute'))
573
                    if m.group('second'):
574
                        second = int(m.group('second'))
575
                    else:
576
                        second = 0
577
                else:
578
                    hour, minute, second = 0,0,0
579
            except ValueError:
1948.4.27 by John Arbash Meinel
Deprecate calling RevisionSpec directly, and instead use a helper function. Also merge the old RevisionSpec_int class into RevisionSpec_revno
580
                raise errors.InvalidRevisionSpec(self.user_spec,
1948.4.12 by John Arbash Meinel
Some tests for the date: spec
581
                                                 branch, 'invalid date')
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
582
583
            dt = datetime.datetime(year=year, month=month, day=day,
584
                    hour=hour, minute=minute, second=second)
1704.2.27 by Martin Pool
Run bisection search for revision date with lock held. (Robert Widhopf-Frenk)
585
        branch.lock_read()
586
        try:
1948.4.12 by John Arbash Meinel
Some tests for the date: spec
587
            rev = bisect.bisect(_RevListToTimestamps(revs, branch), dt)
1704.2.27 by Martin Pool
Run bisection search for revision date with lock held. (Robert Widhopf-Frenk)
588
        finally:
589
            branch.unlock()
1688.2.2 by Guillaume Pinot
Binary search for 'date:' revision.
590
        if rev == len(revs):
591
            return RevisionInfo(branch, None)
592
        else:
593
            return RevisionInfo(branch, rev + 1)
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
594
595
SPEC_TYPES.append(RevisionSpec_date)
596
597
598
class RevisionSpec_ancestor(RevisionSpec):
2070.4.14 by John Arbash Meinel
Switch revisionspec to use the help defined as help_txt rather than the doc string
599
    """Selects a common ancestor with a second branch."""
600
601
    help_txt = """Selects a common ancestor with a second branch.
2023.1.1 by ghigo
add topics help
602
603
    Supply the path to a branch to select the common ancestor.
604
605
    The common ancestor is the last revision that existed in both
606
    branches. Usually this is the branch point, but it could also be
607
    a revision that was merged.
608
609
    This is frequently used with 'diff' to return all of the changes
610
    that your branch introduces, while excluding the changes that you
611
    have not merged from the remote branch.
612
613
    examples:
614
      ancestor:/path/to/branch
2070.4.7 by ghigo
Updates on the basis of the Richard Wilbur suggestions
615
      $ bzr diff -r ancestor:../../mainline/branch
2023.1.1 by ghigo
add topics help
616
    """
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
617
    prefix = 'ancestor:'
618
619
    def _match_on(self, branch, revs):
1948.4.16 by John Arbash Meinel
Move the tests into the associated tester, remove redundant tests, some small PEP8 changes
620
        from bzrlib.branch import Branch
1948.4.18 by John Arbash Meinel
Update branch: spec and tests
621
1948.4.27 by John Arbash Meinel
Deprecate calling RevisionSpec directly, and instead use a helper function. Also merge the old RevisionSpec_int class into RevisionSpec_revno
622
        trace.mutter('matching ancestor: on: %s, %s', self.spec, branch)
1948.4.17 by John Arbash Meinel
Update tests for ancestor: spec
623
        other_branch = Branch.open(self.spec)
1390 by Robert Collins
pair programming worx... merge integration and weave
624
        revision_a = branch.last_revision()
625
        revision_b = other_branch.last_revision()
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
626
        for r, b in ((revision_a, branch), (revision_b, other_branch)):
1948.4.18 by John Arbash Meinel
Update branch: spec and tests
627
            if r in (None, revision.NULL_REVISION):
1948.4.26 by John Arbash Meinel
Get rid of direct imports of exceptions
628
                raise errors.NoCommits(b)
1948.4.18 by John Arbash Meinel
Update branch: spec and tests
629
        revision_source = revision.MultipleRevisionSources(
630
                branch.repository, other_branch.repository)
631
        rev_id = revision.common_ancestor(revision_a, revision_b,
632
                                          revision_source)
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
633
        try:
634
            revno = branch.revision_id_to_revno(rev_id)
1948.4.26 by John Arbash Meinel
Get rid of direct imports of exceptions
635
        except errors.NoSuchRevision:
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
636
            revno = None
637
        return RevisionInfo(branch, revno, rev_id)
638
        
639
SPEC_TYPES.append(RevisionSpec_ancestor)
1432 by Robert Collins
branch: namespace
640
1948.4.16 by John Arbash Meinel
Move the tests into the associated tester, remove redundant tests, some small PEP8 changes
641
1432 by Robert Collins
branch: namespace
642
class RevisionSpec_branch(RevisionSpec):
2070.4.14 by John Arbash Meinel
Switch revisionspec to use the help defined as help_txt rather than the doc string
643
    """Selects the last revision of a specified branch."""
644
645
    help_txt = """Selects the last revision of a specified branch.
2023.1.1 by ghigo
add topics help
646
647
    Supply the path to a branch to select its last revision.
648
649
    examples:
650
      branch:/path/to/branch
1432 by Robert Collins
branch: namespace
651
    """
652
    prefix = 'branch:'
653
654
    def _match_on(self, branch, revs):
1948.4.18 by John Arbash Meinel
Update branch: spec and tests
655
        from bzrlib.branch import Branch
656
        other_branch = Branch.open(self.spec)
1432 by Robert Collins
branch: namespace
657
        revision_b = other_branch.last_revision()
1948.4.18 by John Arbash Meinel
Update branch: spec and tests
658
        if revision_b in (None, revision.NULL_REVISION):
1948.4.26 by John Arbash Meinel
Get rid of direct imports of exceptions
659
            raise errors.NoCommits(other_branch)
1432 by Robert Collins
branch: namespace
660
        # 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.
661
        branch.fetch(other_branch, revision_b)
1432 by Robert Collins
branch: namespace
662
        try:
663
            revno = branch.revision_id_to_revno(revision_b)
1948.4.26 by John Arbash Meinel
Get rid of direct imports of exceptions
664
        except errors.NoSuchRevision:
1432 by Robert Collins
branch: namespace
665
            revno = None
666
        return RevisionInfo(branch, revno, revision_b)
667
        
668
SPEC_TYPES.append(RevisionSpec_branch)