~bzr-pqm/bzr/bzr.dev

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
4183.7.1 by Sabin Iacob
update FSF mailing address
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
16
17
3224.5.31 by Andrew Bennetts
A couple more lazy imports, helps 'bzr log --line -r -1' a little.
18
import re
19
20
from bzrlib.lazy_import import lazy_import
21
lazy_import(globals(), """
1948.4.1 by John Arbash Meinel
Update number parsers to raise InvalidRevisionSpec. Update revno: itself so it supports negative numbers
22
import bisect
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
23
import datetime
3224.5.31 by Andrew Bennetts
A couple more lazy imports, helps 'bzr log --line -r -1' a little.
24
""")
1948.4.1 by John Arbash Meinel
Update number parsers to raise InvalidRevisionSpec. Update revno: itself so it supports negative numbers
25
26
from bzrlib import (
27
    errors,
2325.2.5 by Marien Zwart
Call osutils.safe_revision_id instead of duplicating it.
28
    osutils,
3966.2.1 by Jelmer Vernooij
Register revision specifiers in a registry.
29
    registry,
1948.4.18 by John Arbash Meinel
Update branch: spec and tests
30
    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
31
    symbol_versioning,
32
    trace,
1948.4.1 by John Arbash Meinel
Update number parsers to raise InvalidRevisionSpec. Update revno: itself so it supports negative numbers
33
    )
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
34
1948.4.16 by John Arbash Meinel
Move the tests into the associated tester, remove redundant tests, some small PEP8 changes
35
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
36
_marker = []
37
1948.4.16 by John Arbash Meinel
Move the tests into the associated tester, remove redundant tests, some small PEP8 changes
38
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
39
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
40
    """The results of applying a revision specification to a branch."""
41
42
    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.
43
44
    An instance has two useful attributes: revno, and rev_id.
45
46
    They can also be accessed as spec[0] and spec[1] respectively,
47
    so that you can write code like:
48
    revno, rev_id = RevisionSpec(branch, spec)
49
    although this is probably going to be deprecated later.
50
51
    This class exists mostly to be the return value of a RevisionSpec,
52
    so that you can access the member you're interested in (number or id)
53
    or treat the result as a tuple.
54
    """
55
56
    def __init__(self, branch, revno, rev_id=_marker):
57
        self.branch = branch
58
        self.revno = revno
59
        if rev_id is _marker:
60
            # allow caller to be lazy
61
            if self.revno is None:
3872.2.5 by Marius Kruger
return null revid again for null revno
62
                self.rev_id = None
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
63
            else:
64
                self.rev_id = branch.get_rev_id(self.revno)
65
        else:
66
            self.rev_id = rev_id
67
68
    def __nonzero__(self):
69
        # first the easy ones...
70
        if self.rev_id is None:
71
            return False
72
        if self.revno is not None:
73
            return True
74
        # TODO: otherwise, it should depend on how I was built -
75
        # if it's in_history(branch), then check revision_history(),
76
        # if it's in_store(branch), do the check below
1185.67.2 by Aaron Bentley
Renamed Branch.storage to Branch.repository
77
        return self.branch.repository.has_revision(self.rev_id)
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
78
79
    def __len__(self):
80
        return 2
81
82
    def __getitem__(self, index):
83
        if index == 0: return self.revno
84
        if index == 1: return self.rev_id
85
        raise IndexError(index)
86
87
    def get(self):
1185.67.2 by Aaron Bentley
Renamed Branch.storage to Branch.repository
88
        return self.branch.repository.get_revision(self.rev_id)
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
89
90
    def __eq__(self, other):
91
        if type(other) not in (tuple, list, type(self)):
92
            return False
93
        if type(other) is type(self) and self.branch is not other.branch:
94
            return False
95
        return tuple(self) == tuple(other)
96
97
    def __repr__(self):
98
        return '<bzrlib.revisionspec.RevisionInfo object %s, %s for %r>' % (
99
            self.revno, self.rev_id, self.branch)
100
2220.2.3 by Martin Pool
Add tag: revision namespace.
101
    @staticmethod
102
    def from_revision_id(branch, revision_id, revs):
103
        """Construct a RevisionInfo given just the id.
104
105
        Use this if you don't know or care what the revno is.
106
        """
3298.2.11 by Aaron Bentley
Update tests for null:, clea up slightly
107
        if revision_id == revision.NULL_REVISION:
108
            return RevisionInfo(branch, 0, revision_id)
2220.2.3 by Martin Pool
Add tag: revision namespace.
109
        try:
110
            revno = revs.index(revision_id) + 1
111
        except ValueError:
112
            revno = None
113
        return RevisionInfo(branch, revno, revision_id)
114
1948.4.16 by John Arbash Meinel
Move the tests into the associated tester, remove redundant tests, some small PEP8 changes
115
1948.4.35 by John Arbash Meinel
Move the _revno_regex to a more logical location
116
_revno_regex = None
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
117
1948.4.16 by John Arbash Meinel
Move the tests into the associated tester, remove redundant tests, some small PEP8 changes
118
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
119
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
120
    """A parsed revision specification."""
121
122
    help_txt = """A parsed revision specification.
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
123
4569.2.3 by Matthew Fuller
Adjust the help test for the RevisionSpec class a bit to describe the
124
    A revision specification is a string, which may be unambiguous about
125
    what it represents by giving a prefix like 'date:' or 'revid:' etc,
126
    or it may have no prefix, in which case it's tried against several
127
    specifier types in sequence to determine what the user meant.
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
128
129
    Revision specs are an UI element, and they have been moved out
130
    of the branch class to leave "back-end" classes unaware of such
131
    details.  Code that gets a revno or rev_id from other code should
132
    not be using revision specs - revnos and revision ids are the
133
    accepted ways to refer to revisions internally.
134
135
    (Equivalent to the old Branch method get_revision_info())
136
    """
137
138
    prefix = None
3460.1.1 by John Arbash Meinel
Change the RevisionSpec_revno so that it doesn't need to grab the revision_history first.
139
    wants_revision_history = True
4569.2.18 by Vincent Ladeuil
Small refactoring to unblock the submission.
140
    dwim_catchable_exceptions = (errors.InvalidRevisionSpec,)
4569.2.21 by Vincent Ladeuil
Fix some typos.
141
    """Exceptions that RevisionSpec_dwim._match_on will catch.
4569.2.18 by Vincent Ladeuil
Small refactoring to unblock the submission.
142
4569.2.21 by Vincent Ladeuil
Fix some typos.
143
    If the revspec is part of ``dwim_revspecs``, it may be tried with an
144
    invalid revspec and raises some exception. The exceptions mentioned here
145
    will not be reported to the user but simply ignored without stopping the
146
    dwim processing.
4569.2.18 by Vincent Ladeuil
Small refactoring to unblock the submission.
147
    """
1948.4.33 by John Arbash Meinel
Switch from get_revision_spec() to RevisionSpec.from_string() (as advised by Martin)
148
149
    @staticmethod
150
    def from_string(spec):
151
        """Parse a revision spec string into a RevisionSpec object.
152
153
        :param spec: A string specified by the user
154
        :return: A RevisionSpec object that understands how to parse the
155
            supplied notation.
156
        """
157
        if not isinstance(spec, (type(None), basestring)):
158
            raise TypeError('error')
159
160
        if spec is None:
161
            return RevisionSpec(None, _internal=True)
3966.2.1 by Jelmer Vernooij
Register revision specifiers in a registry.
162
        match = revspec_registry.get_prefix(spec)
163
        if match is not None:
164
            spectype, specsuffix = match
165
            trace.mutter('Returning RevisionSpec %s for %s',
166
                         spectype.__name__, spec)
167
            return spectype(spec, _internal=True)
1948.4.33 by John Arbash Meinel
Switch from get_revision_spec() to RevisionSpec.from_string() (as advised by Martin)
168
        else:
3966.2.2 by Jelmer Vernooij
Add backwards compatibility copy of SPEC_TYPES.
169
            for spectype in SPEC_TYPES:
170
                if spec.startswith(spectype.prefix):
4557.4.1 by Matthew Fuller
Move a mutter so that it triggers when the thing it describes happens,
171
                    trace.mutter('Returning RevisionSpec %s for %s',
172
                                 spectype.__name__, spec)
3966.2.2 by Jelmer Vernooij
Add backwards compatibility copy of SPEC_TYPES.
173
                    return spectype(spec, _internal=True)
4569.2.18 by Vincent Ladeuil
Small refactoring to unblock the submission.
174
            # Otherwise treat it as a DWIM, build the RevisionSpec object and
175
            # wait for _match_on to be called.
4569.2.1 by Matthew Fuller
Implement a DWIM revspec type and use it to allow simpler user
176
            return RevisionSpec_dwim(spec, _internal=True)
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
177
178
    def __init__(self, spec, _internal=False):
179
        """Create a RevisionSpec referring to the Null revision.
180
181
        :param spec: The original spec supplied by the user
182
        :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)
183
            called directly. Only from RevisionSpec.from_string()
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
184
        """
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
185
        if not _internal:
186
            symbol_versioning.warn('Creating a RevisionSpec directly has'
187
                                   ' 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)
188
                                   ' 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
189
                                   ' instead.',
190
                                   DeprecationWarning, stacklevel=2)
191
        self.user_spec = spec
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
192
        if self.prefix and spec.startswith(self.prefix):
193
            spec = spec[len(self.prefix):]
194
        self.spec = spec
195
196
    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
197
        trace.mutter('Returning RevisionSpec._match_on: None')
3298.2.11 by Aaron Bentley
Update tests for null:, clea up slightly
198
        return RevisionInfo(branch, None, None)
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
199
200
    def _match_on_and_check(self, branch, revs):
201
        info = self._match_on(branch, revs)
202
        if info:
203
            return info
3298.2.11 by Aaron Bentley
Update tests for null:, clea up slightly
204
        elif info == (None, None):
205
            # special case - nothing supplied
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
206
            return info
207
        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
208
            raise errors.InvalidRevisionSpec(self.user_spec, branch)
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
209
        else:
1948.4.2 by John Arbash Meinel
Update _match_on_and_check to raise the right error
210
            raise errors.InvalidRevisionSpec(self.spec, branch)
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
211
212
    def in_history(self, branch):
1732.3.1 by Matthieu Moy
Implementation of -r revno:N:/path/to/branch
213
        if branch:
3460.1.1 by John Arbash Meinel
Change the RevisionSpec_revno so that it doesn't need to grab the revision_history first.
214
            if self.wants_revision_history:
215
                revs = branch.revision_history()
216
            else:
217
                revs = None
1732.3.1 by Matthieu Moy
Implementation of -r revno:N:/path/to/branch
218
        else:
1988.4.5 by Robert Collins
revisions can now be specified using dotted-decimal revision numbers.
219
            # this should never trigger.
220
            # TODO: make it a deprecated code path. RBC 20060928
1732.3.1 by Matthieu Moy
Implementation of -r revno:N:/path/to/branch
221
            revs = None
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
222
        return self._match_on_and_check(branch, revs)
223
1432 by Robert Collins
branch: namespace
224
        # FIXME: in_history is somewhat broken,
225
        # it will return non-history revisions in many
226
        # circumstances. The expected facility is that
227
        # in_history only returns revision-history revs,
228
        # in_store returns any rev. RBC 20051010
229
    # aliases for now, when we fix the core logic, then they
230
    # will do what you expect.
231
    in_store = in_history
3298.2.8 by John Arbash Meinel
Get rid of .in_branch(need_revno=False) in favor of simpler .as_revision_id()
232
    in_branch = in_store
3060.3.2 by Lukáš Lalinský
Make RevisionSpec_last not load the whole history.
233
3298.2.4 by John Arbash Meinel
Introduce as_revision_id() as a function instead of in_branch(need_revno=False)
234
    def as_revision_id(self, context_branch):
235
        """Return just the revision_id for this revisions spec.
236
237
        Some revision specs require a context_branch to be able to determine
238
        their value. Not all specs will make use of it.
239
        """
240
        return self._as_revision_id(context_branch)
241
242
    def _as_revision_id(self, context_branch):
243
        """Implementation of as_revision_id()
244
245
        Classes should override this function to provide appropriate
246
        functionality. The default is to just call '.in_history().rev_id'
247
        """
248
        return self.in_history(context_branch).rev_id
249
3655.3.1 by Lukáš Lalinský
Fix `bzr st -rbranch:PATH_TO_BRANCH`
250
    def as_tree(self, context_branch):
251
        """Return the tree object for this revisions spec.
252
253
        Some revision specs require a context_branch to be able to determine
254
        the revision id and access the repository. Not all specs will make
255
        use of it.
256
        """
257
        return self._as_tree(context_branch)
258
259
    def _as_tree(self, context_branch):
3732.1.1 by Ian Clatworthy
fix bzr st -rbranch:path-to-branch (Lukas Lalinsky)
260
        """Implementation of as_tree().
3655.3.1 by Lukáš Lalinský
Fix `bzr st -rbranch:PATH_TO_BRANCH`
261
262
        Classes should override this function to provide appropriate
263
        functionality. The default is to just call '.as_revision_id()'
264
        and get the revision tree from context_branch's repository.
265
        """
266
        revision_id = self.as_revision_id(context_branch)
267
        return context_branch.repository.revision_tree(revision_id)
268
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
269
    def __repr__(self):
270
        # 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/
271
        return '<%s %s>' % (self.__class__.__name__,
272
                              self.user_spec)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
273
1881.1.4 by Matthieu Moy
needs_tree -> needs_branch
274
    def needs_branch(self):
275
        """Whether this revision spec needs a branch.
276
1711.2.99 by John Arbash Meinel
minor typo fix
277
        Set this to False the branch argument of _match_on is not used.
278
        """
1881.1.1 by Matthieu Moy
Fixed and tested "bzr diff" outside a working tree.
279
        return True
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
280
1907.4.1 by Matthieu Moy
Fixed merge to work nicely with -r revno:N:path
281
    def get_branch(self):
282
        """When the revision specifier contains a branch location, return it.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
283
1907.4.1 by Matthieu Moy
Fixed merge to work nicely with -r revno:N:path
284
        Otherwise, return None.
285
        """
286
        return None
287
1907.4.9 by Matthieu Moy
missing newline
288
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
289
# private API
290
4569.2.1 by Matthew Fuller
Implement a DWIM revspec type and use it to allow simpler user
291
class RevisionSpec_dwim(RevisionSpec):
292
    """Provides a DWIMish revision specifier lookup.
293
4569.2.18 by Vincent Ladeuil
Small refactoring to unblock the submission.
294
    Note that this does not go in the revspec_registry because by definition
295
    there is no prefix to identify it.  It's solely called from
296
    RevisionSpec.from_string() because the DWIMification happen when _match_on
297
    is called so the string describing the revision is kept here until needed.
4569.2.1 by Matthew Fuller
Implement a DWIM revspec type and use it to allow simpler user
298
    """
299
300
    help_txt = None
4569.2.20 by Vincent Ladeuil
All tests passing for the dwim revspec.
301
    # We don't need to build the revision history ourself, that's delegated to
302
    # each revspec we try.
303
    wants_revision_history = False
4569.2.1 by Matthew Fuller
Implement a DWIM revspec type and use it to allow simpler user
304
4569.2.19 by Vincent Ladeuil
A bit more tweaks.
305
    def _try_spectype(self, rstype, branch):
306
        rs = rstype(self.spec, _internal=True)
4569.2.1 by Matthew Fuller
Implement a DWIM revspec type and use it to allow simpler user
307
        # Hit in_history to find out if it exists, or we need to try the
308
        # next type.
309
        return rs.in_history(branch)
310
311
    def _match_on(self, branch, revs):
312
        """Run the lookup and see what we can get."""
313
314
        # First, see if it's a revno
315
        global _revno_regex
316
        if _revno_regex is None:
317
            _revno_regex = re.compile(r'^(?:(\d+(\.\d+)*)|-\d+)(:.*)?$')
4569.2.19 by Vincent Ladeuil
A bit more tweaks.
318
        if _revno_regex.match(self.spec) is not None:
4569.2.1 by Matthew Fuller
Implement a DWIM revspec type and use it to allow simpler user
319
            try:
4569.2.19 by Vincent Ladeuil
A bit more tweaks.
320
                return self._try_spectype(RevisionSpec_revno, branch)
4569.2.18 by Vincent Ladeuil
Small refactoring to unblock the submission.
321
            except RevisionSpec_revno.dwim_catchable_exceptions:
322
                pass
323
324
        # Next see what has been registered
325
        for rs_class in dwim_revspecs:
326
            try:
4569.2.19 by Vincent Ladeuil
A bit more tweaks.
327
                return self._try_spectype(rs_class, branch)
4569.2.18 by Vincent Ladeuil
Small refactoring to unblock the submission.
328
            except rs_class.dwim_catchable_exceptions:
329
                pass
330
331
        # Well, I dunno what it is. Note that we don't try to keep track of the
332
        # first of last exception raised during the DWIM tries as none seems
333
        # really relevant.
4569.2.1 by Matthew Fuller
Implement a DWIM revspec type and use it to allow simpler user
334
        raise errors.InvalidRevisionSpec(self.spec, branch)
335
336
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
337
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
338
    """Selects a revision using a number."""
339
340
    help_txt = """Selects a revision using a number.
2023.1.1 by ghigo
add topics help
341
342
    Use an integer to specify a revision in the history of the branch.
4569.2.5 by Matthew Fuller
Update online documentation to match new DWIM behavior.
343
    Optionally a branch can be specified.  A negative number will count
344
    from the end of the branch (-1 is the last revision, -2 the previous
345
    one). If the negative number is larger than the branch's history, the
346
    first revision is returned.
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
347
    Examples::
348
3651.2.1 by Daniel Clemente
Clarify that you don't have to write a path if you mean the current branch
349
      revno:1                   -> return the first revision of this branch
2023.1.1 by ghigo
add topics help
350
      revno:3:/path/to/branch   -> return the 3rd revision of
351
                                   the branch '/path/to/branch'
352
      revno:-1                  -> The last revision in a branch.
353
      -2:http://other/branch    -> The second to last revision in the
354
                                   remote branch.
355
      -1000000                  -> Most likely the first revision, unless
356
                                   your history is very long.
357
    """
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
358
    prefix = 'revno:'
3460.1.1 by John Arbash Meinel
Change the RevisionSpec_revno so that it doesn't need to grab the revision_history first.
359
    wants_revision_history = False
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
360
361
    def _match_on(self, branch, revs):
362
        """Lookup a revision by revision number"""
3298.2.6 by John Arbash Meinel
Don't abstract through RevisionInfo for RevisionSpec_revno.as_revision_id()
363
        branch, revno, revision_id = self._lookup(branch, revs)
364
        return RevisionInfo(branch, revno, revision_id)
365
366
    def _lookup(self, branch, revs_or_none):
1948.4.1 by John Arbash Meinel
Update number parsers to raise InvalidRevisionSpec. Update revno: itself so it supports negative numbers
367
        loc = self.spec.find(':')
368
        if loc == -1:
369
            revno_spec = self.spec
370
            branch_spec = None
371
        else:
372
            revno_spec = self.spec[:loc]
373
            branch_spec = self.spec[loc+1:]
374
375
        if revno_spec == '':
1948.4.6 by John Arbash Meinel
A small bugfix, and more tests for revno:
376
            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
377
                raise errors.InvalidRevisionSpec(self.user_spec,
1948.4.5 by John Arbash Meinel
Fix tests for negative entries, and add tests for revno:
378
                        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
379
            revno = None
380
        else:
381
            try:
382
                revno = int(revno_spec)
1988.4.5 by Robert Collins
revisions can now be specified using dotted-decimal revision numbers.
383
                dotted = False
384
            except ValueError:
385
                # dotted decimal. This arguably should not be here
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
386
                # but the from_string method is a little primitive
1988.4.5 by Robert Collins
revisions can now be specified using dotted-decimal revision numbers.
387
                # right now - RBC 20060928
388
                try:
389
                    match_revno = tuple((int(number) for number in revno_spec.split('.')))
390
                except ValueError, e:
391
                    raise errors.InvalidRevisionSpec(self.user_spec, branch, e)
392
393
                dotted = True
1948.4.1 by John Arbash Meinel
Update number parsers to raise InvalidRevisionSpec. Update revno: itself so it supports negative numbers
394
1948.4.6 by John Arbash Meinel
A small bugfix, and more tests for revno:
395
        if branch_spec:
1988.4.5 by Robert Collins
revisions can now be specified using dotted-decimal revision numbers.
396
            # the user has override the branch to look in.
397
            # we need to refresh the revision_history map and
398
            # the branch object.
1948.4.1 by John Arbash Meinel
Update number parsers to raise InvalidRevisionSpec. Update revno: itself so it supports negative numbers
399
            from bzrlib.branch import Branch
400
            branch = Branch.open(branch_spec)
3298.2.6 by John Arbash Meinel
Don't abstract through RevisionInfo for RevisionSpec_revno.as_revision_id()
401
            revs_or_none = None
1948.4.22 by John Arbash Meinel
Refactor common code from integer revno handlers
402
1988.4.5 by Robert Collins
revisions can now be specified using dotted-decimal revision numbers.
403
        if dotted:
404
            try:
3949.2.6 by Ian Clatworthy
review feedback from jam
405
                revision_id = branch.dotted_revno_to_revision_id(match_revno,
406
                    _cache_reverse=True)
3949.2.1 by Ian Clatworthy
Branch.dotted_revno_to_revision_id API
407
            except errors.NoSuchRevision:
3872.2.2 by Marius Kruger
* use NULL_REVISION in stead of None for rev_id
408
                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
409
            else:
1988.4.5 by Robert Collins
revisions can now be specified using dotted-decimal revision numbers.
410
                # there is no traditional 'revno' for dotted-decimal revnos.
411
                # so for  API compatability we return None.
3949.2.6 by Ian Clatworthy
review feedback from jam
412
                return branch, None, revision_id
1988.4.5 by Robert Collins
revisions can now be specified using dotted-decimal revision numbers.
413
        else:
3060.3.3 by Lukáš Lalinský
Make RevisionSpec_revid and RevisionSpec_revno not load the whole revision history.
414
            last_revno, last_revision_id = branch.last_revision_info()
1988.4.5 by Robert Collins
revisions can now be specified using dotted-decimal revision numbers.
415
            if revno < 0:
2249.4.2 by Wouter van Heyst
Convert callers of Branch.revision_history() to Branch.last_revision_info() where sensible.
416
                # if get_rev_id supported negative revnos, there would not be a
417
                # need for this special case.
3060.3.3 by Lukáš Lalinský
Make RevisionSpec_revid and RevisionSpec_revno not load the whole revision history.
418
                if (-revno) >= last_revno:
1988.4.5 by Robert Collins
revisions can now be specified using dotted-decimal revision numbers.
419
                    revno = 1
420
                else:
3060.3.3 by Lukáš Lalinský
Make RevisionSpec_revid and RevisionSpec_revno not load the whole revision history.
421
                    revno = last_revno + revno + 1
1988.4.5 by Robert Collins
revisions can now be specified using dotted-decimal revision numbers.
422
            try:
3298.2.6 by John Arbash Meinel
Don't abstract through RevisionInfo for RevisionSpec_revno.as_revision_id()
423
                revision_id = branch.get_rev_id(revno, revs_or_none)
1988.4.5 by Robert Collins
revisions can now be specified using dotted-decimal revision numbers.
424
            except errors.NoSuchRevision:
425
                raise errors.InvalidRevisionSpec(self.user_spec, branch)
3298.2.6 by John Arbash Meinel
Don't abstract through RevisionInfo for RevisionSpec_revno.as_revision_id()
426
        return branch, revno, revision_id
3060.3.2 by Lukáš Lalinský
Make RevisionSpec_last not load the whole history.
427
3298.2.5 by John Arbash Meinel
Start implementing everything in terms of cheaper _as_revision_id lookups.
428
    def _as_revision_id(self, context_branch):
429
        # We would have the revno here, but we don't really care
3298.2.6 by John Arbash Meinel
Don't abstract through RevisionInfo for RevisionSpec_revno.as_revision_id()
430
        branch, revno, revision_id = self._lookup(context_branch, None)
431
        return revision_id
3060.3.3 by Lukáš Lalinský
Make RevisionSpec_revid and RevisionSpec_revno not load the whole revision history.
432
1881.1.4 by Matthieu Moy
needs_tree -> needs_branch
433
    def needs_branch(self):
1881.1.1 by Matthieu Moy
Fixed and tested "bzr diff" outside a working tree.
434
        return self.spec.find(':') == -1
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
435
1907.4.1 by Matthieu Moy
Fixed merge to work nicely with -r revno:N:path
436
    def get_branch(self):
437
        if self.spec.find(':') == -1:
438
            return None
439
        else:
440
            return self.spec[self.spec.find(':')+1:]
441
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
442
# Old compatibility
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
443
RevisionSpec_int = RevisionSpec_revno
444
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
445
446
447
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
448
    """Selects a revision using the revision id."""
449
450
    help_txt = """Selects a revision using the revision id.
2023.1.1 by ghigo
add topics help
451
452
    Supply a specific revision id, that can be used to specify any
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
453
    revision id in the ancestry of the branch.
2023.1.1 by ghigo
add topics help
454
    Including merges, and pending merges.
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
455
    Examples::
456
2070.4.7 by ghigo
Updates on the basis of the Richard Wilbur suggestions
457
      revid:aaaa@bbbb-123456789 -> Select revision 'aaaa@bbbb-123456789'
3060.3.3 by Lukáš Lalinský
Make RevisionSpec_revid and RevisionSpec_revno not load the whole revision history.
458
    """
459
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
460
    prefix = 'revid:'
461
3298.2.5 by John Arbash Meinel
Start implementing everything in terms of cheaper _as_revision_id lookups.
462
    def _match_on(self, branch, revs):
2325.2.5 by Marien Zwart
Call osutils.safe_revision_id instead of duplicating it.
463
        # self.spec comes straight from parsing the command line arguments,
464
        # so we expect it to be a Unicode string. Switch it to the internal
465
        # representation.
466
        revision_id = osutils.safe_revision_id(self.spec, warn=False)
3298.2.5 by John Arbash Meinel
Start implementing everything in terms of cheaper _as_revision_id lookups.
467
        return RevisionInfo.from_revision_id(branch, revision_id, revs)
3060.3.3 by Lukáš Lalinský
Make RevisionSpec_revid and RevisionSpec_revno not load the whole revision history.
468
3298.2.5 by John Arbash Meinel
Start implementing everything in terms of cheaper _as_revision_id lookups.
469
    def _as_revision_id(self, context_branch):
470
        return osutils.safe_revision_id(self.spec, warn=False)
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
471
472
473
474
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
475
    """Selects the nth revision from the end."""
476
477
    help_txt = """Selects the nth revision from the end.
2023.1.1 by ghigo
add topics help
478
479
    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
480
    This is the same as supplying negative numbers to the 'revno:' spec.
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
481
    Examples::
482
2023.1.1 by ghigo
add topics help
483
      last:1        -> return the last revision
484
      last:3        -> return the revision 2 before the end.
3060.3.2 by Lukáš Lalinský
Make RevisionSpec_last not load the whole history.
485
    """
1185.1.39 by Robert Collins
Robey Pointers before: namespace to clear up usage of dates in revision parameters
486
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
487
    prefix = 'last:'
488
489
    def _match_on(self, branch, revs):
3298.2.5 by John Arbash Meinel
Start implementing everything in terms of cheaper _as_revision_id lookups.
490
        revno, revision_id = self._revno_and_revision_id(branch, revs)
491
        return RevisionInfo(branch, revno, revision_id)
492
493
    def _revno_and_revision_id(self, context_branch, revs_or_none):
494
        last_revno, last_revision_id = context_branch.last_revision_info()
3060.3.2 by Lukáš Lalinský
Make RevisionSpec_last not load the whole history.
495
1948.4.9 by John Arbash Meinel
Cleanup and test last:
496
        if self.spec == '':
3060.3.2 by Lukáš Lalinský
Make RevisionSpec_last not load the whole history.
497
            if not last_revno:
3298.2.5 by John Arbash Meinel
Start implementing everything in terms of cheaper _as_revision_id lookups.
498
                raise errors.NoCommits(context_branch)
499
            return last_revno, last_revision_id
1948.4.9 by John Arbash Meinel
Cleanup and test last:
500
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
501
        try:
502
            offset = int(self.spec)
1948.4.9 by John Arbash Meinel
Cleanup and test last:
503
        except ValueError, e:
3298.2.5 by John Arbash Meinel
Start implementing everything in terms of cheaper _as_revision_id lookups.
504
            raise errors.InvalidRevisionSpec(self.user_spec, context_branch, e)
1948.4.9 by John Arbash Meinel
Cleanup and test last:
505
506
        if offset <= 0:
3298.2.5 by John Arbash Meinel
Start implementing everything in terms of cheaper _as_revision_id lookups.
507
            raise errors.InvalidRevisionSpec(self.user_spec, context_branch,
1948.4.9 by John Arbash Meinel
Cleanup and test last:
508
                                             'you must supply a positive value')
3060.3.2 by Lukáš Lalinský
Make RevisionSpec_last not load the whole history.
509
510
        revno = last_revno - offset + 1
1948.4.9 by John Arbash Meinel
Cleanup and test last:
511
        try:
3298.2.5 by John Arbash Meinel
Start implementing everything in terms of cheaper _as_revision_id lookups.
512
            revision_id = context_branch.get_rev_id(revno, revs_or_none)
1948.4.9 by John Arbash Meinel
Cleanup and test last:
513
        except errors.NoSuchRevision:
3298.2.5 by John Arbash Meinel
Start implementing everything in terms of cheaper _as_revision_id lookups.
514
            raise errors.InvalidRevisionSpec(self.user_spec, context_branch)
515
        return revno, revision_id
516
517
    def _as_revision_id(self, context_branch):
518
        # We compute the revno as part of the process, but we don't really care
519
        # about it.
520
        revno, revision_id = self._revno_and_revision_id(context_branch, None)
521
        return revision_id
3060.3.2 by Lukáš Lalinský
Make RevisionSpec_last not load the whole history.
522
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
523
524
1185.1.39 by Robert Collins
Robey Pointers before: namespace to clear up usage of dates in revision parameters
525
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
526
    """Selects the parent of the revision specified."""
527
528
    help_txt = """Selects the parent of the revision specified.
2023.1.1 by ghigo
add topics help
529
3651.2.4 by Daniel Clemente
Reordered to put explanation first and exceptions after
530
    Supply any revision spec to return the parent of that revision.  This is
531
    mostly useful when inspecting revisions that are not in the revision history
532
    of a branch.
533
2023.1.1 by ghigo
add topics help
534
    It is an error to request the parent of the null revision (before:0).
535
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
536
    Examples::
537
2023.1.1 by ghigo
add topics help
538
      before:1913    -> Return the parent of revno 1913 (revno 1912)
539
      before:revid:aaaa@bbbb-1234567890  -> return the parent of revision
2070.4.7 by ghigo
Updates on the basis of the Richard Wilbur suggestions
540
                                            aaaa@bbbb-1234567890
3651.2.5 by Daniel Clemente
Wrote specifical and simpler example for 'before:', and referred to 'bzr diff -c'
541
      bzr diff -r before:1913..1913
542
            -> Find the changes between revision 1913 and its parent (1912).
543
               (What changes did revision 1913 introduce).
544
               This is equivalent to:  bzr diff -c 1913
2023.1.1 by ghigo
add topics help
545
    """
1185.1.39 by Robert Collins
Robey Pointers before: namespace to clear up usage of dates in revision parameters
546
547
    prefix = 'before:'
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
548
3298.2.5 by John Arbash Meinel
Start implementing everything in terms of cheaper _as_revision_id lookups.
549
    def _match_on(self, branch, revs):
550
        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
551
        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
552
            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
553
                                         'cannot go before the null: revision')
554
        if r.revno is None:
555
            # We need to use the repository history here
556
            rev = branch.repository.get_revision(r.rev_id)
557
            if not rev.parent_ids:
558
                revno = 0
2598.5.10 by Aaron Bentley
Return NULL_REVISION instead of None for the null revision
559
                revision_id = revision.NULL_REVISION
1948.4.13 by John Arbash Meinel
Going before:0 is an error, and if you are on another history, use the leftmost parent
560
            else:
561
                revision_id = rev.parent_ids[0]
3298.2.5 by John Arbash Meinel
Start implementing everything in terms of cheaper _as_revision_id lookups.
562
                try:
563
                    revno = revs.index(revision_id) + 1
564
                except ValueError:
1948.4.13 by John Arbash Meinel
Going before:0 is an error, and if you are on another history, use the leftmost parent
565
                    revno = None
566
        else:
567
            revno = r.revno - 1
568
            try:
569
                revision_id = branch.get_rev_id(revno, revs)
1948.4.26 by John Arbash Meinel
Get rid of direct imports of exceptions
570
            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
571
                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
572
                                                 branch)
573
        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
574
3298.2.5 by John Arbash Meinel
Start implementing everything in terms of cheaper _as_revision_id lookups.
575
    def _as_revision_id(self, context_branch):
576
        base_revspec = RevisionSpec.from_string(self.spec)
577
        base_revision_id = base_revspec.as_revision_id(context_branch)
578
        if base_revision_id == revision.NULL_REVISION:
3495.1.1 by John Arbash Meinel
Fix bug #239933, use the right exception for -c0
579
            raise errors.InvalidRevisionSpec(self.user_spec, context_branch,
3298.2.5 by John Arbash Meinel
Start implementing everything in terms of cheaper _as_revision_id lookups.
580
                                         'cannot go before the null: revision')
3298.2.10 by Aaron Bentley
Refactor partial history code
581
        context_repo = context_branch.repository
582
        context_repo.lock_read()
583
        try:
584
            parent_map = context_repo.get_parent_map([base_revision_id])
585
        finally:
586
            context_repo.unlock()
3298.2.5 by John Arbash Meinel
Start implementing everything in terms of cheaper _as_revision_id lookups.
587
        if base_revision_id not in parent_map:
588
            # Ghost, or unknown revision id
589
            raise errors.InvalidRevisionSpec(self.user_spec, context_branch,
590
                'cannot find the matching revision')
591
        parents = parent_map[base_revision_id]
592
        if len(parents) < 1:
593
            raise errors.InvalidRevisionSpec(self.user_spec, context_branch,
594
                'No parents for revision.')
595
        return parents[0]
3060.3.5 by Lukáš Lalinský
Add support for in_branch for the remaining RevisionSpec subclasses.
596
1185.1.39 by Robert Collins
Robey Pointers before: namespace to clear up usage of dates in revision parameters
597
598
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
599
class RevisionSpec_tag(RevisionSpec):
2220.2.3 by Martin Pool
Add tag: revision namespace.
600
    """Select a revision identified by tag name"""
601
602
    help_txt = """Selects a revision identified by a tag name.
603
1551.10.34 by Aaron Bentley
Fix tag: help
604
    Tags are stored in the branch and created by the 'tag' command.
2220.2.3 by Martin Pool
Add tag: revision namespace.
605
    """
2070.4.14 by John Arbash Meinel
Switch revisionspec to use the help defined as help_txt rather than the doc string
606
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
607
    prefix = 'tag:'
4569.2.18 by Vincent Ladeuil
Small refactoring to unblock the submission.
608
    dwim_catchable_exceptions = (errors.NoSuchTag, errors.TagsNotSupported)
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
609
3298.2.5 by John Arbash Meinel
Start implementing everything in terms of cheaper _as_revision_id lookups.
610
    def _match_on(self, branch, revs):
2220.2.3 by Martin Pool
Add tag: revision namespace.
611
        # Can raise tags not supported, NoSuchTag, etc
3298.2.5 by John Arbash Meinel
Start implementing everything in terms of cheaper _as_revision_id lookups.
612
        return RevisionInfo.from_revision_id(branch,
613
            branch.tags.lookup_tag(self.spec),
614
            revs)
3060.3.5 by Lukáš Lalinský
Add support for in_branch for the remaining RevisionSpec subclasses.
615
3298.2.5 by John Arbash Meinel
Start implementing everything in terms of cheaper _as_revision_id lookups.
616
    def _as_revision_id(self, context_branch):
617
        return context_branch.tags.lookup_tag(self.spec)
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
618
619
620
1948.4.12 by John Arbash Meinel
Some tests for the date: spec
621
class _RevListToTimestamps(object):
622
    """This takes a list of revisions, and allows you to bisect by date"""
623
624
    __slots__ = ['revs', 'branch']
625
1688.2.2 by Guillaume Pinot
Binary search for 'date:' revision.
626
    def __init__(self, revs, branch):
627
        self.revs = revs
628
        self.branch = branch
1948.4.12 by John Arbash Meinel
Some tests for the date: spec
629
1688.2.2 by Guillaume Pinot
Binary search for 'date:' revision.
630
    def __getitem__(self, index):
1948.4.12 by John Arbash Meinel
Some tests for the date: spec
631
        """Get the date of the index'd item"""
1688.2.2 by Guillaume Pinot
Binary search for 'date:' revision.
632
        r = self.branch.repository.get_revision(self.revs[index])
633
        # TODO: Handle timezone.
634
        return datetime.datetime.fromtimestamp(r.timestamp)
1948.4.12 by John Arbash Meinel
Some tests for the date: spec
635
1688.2.2 by Guillaume Pinot
Binary search for 'date:' revision.
636
    def __len__(self):
637
        return len(self.revs)
638
639
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
640
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
641
    """Selects a revision on the basis of a datestamp."""
642
643
    help_txt = """Selects a revision on the basis of a datestamp.
2023.1.1 by ghigo
add topics help
644
645
    Supply a datestamp to select the first revision that matches the date.
646
    Date can be 'yesterday', 'today', 'tomorrow' or a YYYY-MM-DD string.
647
    Matches the first entry after a given date (either at midnight or
648
    at a specified time).
649
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
650
    One way to display all the changes since yesterday would be::
2666.1.5 by Ian Clatworthy
Incorporate feedback from Alex B. & James W.
651
3565.2.1 by Christophe Troestler
(trivial) Corrected typos.
652
        bzr log -r date:yesterday..
2023.1.1 by ghigo
add topics help
653
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
654
    Examples::
655
2023.1.1 by ghigo
add topics help
656
      date:yesterday            -> select the first revision since yesterday
657
      date:2006-08-14,17:10:14  -> select the first revision after
658
                                   August 14th, 2006 at 5:10pm.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
659
    """
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
660
    prefix = 'date:'
661
    _date_re = re.compile(
662
            r'(?P<date>(?P<year>\d\d\d\d)-(?P<month>\d\d)-(?P<day>\d\d))?'
663
            r'(,|T)?\s*'
664
            r'(?P<time>(?P<hour>\d\d):(?P<minute>\d\d)(:(?P<second>\d\d))?)?'
665
        )
666
667
    def _match_on(self, branch, revs):
2023.1.1 by ghigo
add topics help
668
        """Spec for date revisions:
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
669
          date:value
670
          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
671
          matches the first entry after a given date (either at midnight or
672
          at a specified time).
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
673
        """
2070.4.3 by John Arbash Meinel
code and doc cleanup
674
        #  XXX: This doesn't actually work
675
        #  So the proper way of saying 'give me all entries for today' is:
676
        #      -r date:yesterday..date:today
1185.1.39 by Robert Collins
Robey Pointers before: namespace to clear up usage of dates in revision parameters
677
        today = datetime.datetime.fromordinal(datetime.date.today().toordinal())
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
678
        if self.spec.lower() == 'yesterday':
679
            dt = today - datetime.timedelta(days=1)
680
        elif self.spec.lower() == 'today':
681
            dt = today
682
        elif self.spec.lower() == 'tomorrow':
683
            dt = today + datetime.timedelta(days=1)
684
        else:
685
            m = self._date_re.match(self.spec)
686
            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
687
                raise errors.InvalidRevisionSpec(self.user_spec,
1948.4.12 by John Arbash Meinel
Some tests for the date: spec
688
                                                 branch, 'invalid date')
689
690
            try:
691
                if m.group('date'):
692
                    year = int(m.group('year'))
693
                    month = int(m.group('month'))
694
                    day = int(m.group('day'))
695
                else:
696
                    year = today.year
697
                    month = today.month
698
                    day = today.day
699
700
                if m.group('time'):
701
                    hour = int(m.group('hour'))
702
                    minute = int(m.group('minute'))
703
                    if m.group('second'):
704
                        second = int(m.group('second'))
705
                    else:
706
                        second = 0
707
                else:
708
                    hour, minute, second = 0,0,0
709
            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
710
                raise errors.InvalidRevisionSpec(self.user_spec,
1948.4.12 by John Arbash Meinel
Some tests for the date: spec
711
                                                 branch, 'invalid date')
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
712
713
            dt = datetime.datetime(year=year, month=month, day=day,
714
                    hour=hour, minute=minute, second=second)
1704.2.27 by Martin Pool
Run bisection search for revision date with lock held. (Robert Widhopf-Frenk)
715
        branch.lock_read()
716
        try:
1948.4.12 by John Arbash Meinel
Some tests for the date: spec
717
            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)
718
        finally:
719
            branch.unlock()
1688.2.2 by Guillaume Pinot
Binary search for 'date:' revision.
720
        if rev == len(revs):
3298.2.11 by Aaron Bentley
Update tests for null:, clea up slightly
721
            raise errors.InvalidRevisionSpec(self.user_spec, branch)
1688.2.2 by Guillaume Pinot
Binary search for 'date:' revision.
722
        else:
723
            return RevisionInfo(branch, rev + 1)
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
724
725
726
727
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
728
    """Selects a common ancestor with a second branch."""
729
730
    help_txt = """Selects a common ancestor with a second branch.
2023.1.1 by ghigo
add topics help
731
732
    Supply the path to a branch to select the common ancestor.
733
734
    The common ancestor is the last revision that existed in both
735
    branches. Usually this is the branch point, but it could also be
736
    a revision that was merged.
737
738
    This is frequently used with 'diff' to return all of the changes
739
    that your branch introduces, while excluding the changes that you
740
    have not merged from the remote branch.
741
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
742
    Examples::
743
2023.1.1 by ghigo
add topics help
744
      ancestor:/path/to/branch
2070.4.7 by ghigo
Updates on the basis of the Richard Wilbur suggestions
745
      $ bzr diff -r ancestor:../../mainline/branch
2023.1.1 by ghigo
add topics help
746
    """
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
747
    prefix = 'ancestor:'
748
749
    def _match_on(self, branch, revs):
1551.10.33 by Aaron Bentley
Updates from review
750
        trace.mutter('matching ancestor: on: %s, %s', self.spec, branch)
751
        return self._find_revision_info(branch, self.spec)
752
3298.2.5 by John Arbash Meinel
Start implementing everything in terms of cheaper _as_revision_id lookups.
753
    def _as_revision_id(self, context_branch):
754
        return self._find_revision_id(context_branch, self.spec)
755
1551.10.33 by Aaron Bentley
Updates from review
756
    @staticmethod
757
    def _find_revision_info(branch, other_location):
3298.2.5 by John Arbash Meinel
Start implementing everything in terms of cheaper _as_revision_id lookups.
758
        revision_id = RevisionSpec_ancestor._find_revision_id(branch,
759
                                                              other_location)
760
        try:
761
            revno = branch.revision_id_to_revno(revision_id)
762
        except errors.NoSuchRevision:
763
            revno = None
764
        return RevisionInfo(branch, revno, revision_id)
765
766
    @staticmethod
767
    def _find_revision_id(branch, other_location):
1948.4.16 by John Arbash Meinel
Move the tests into the associated tester, remove redundant tests, some small PEP8 changes
768
        from bzrlib.branch import Branch
1948.4.18 by John Arbash Meinel
Update branch: spec and tests
769
3010.1.12 by Robert Collins
Lock branches while doing revision specification lookups.
770
        branch.lock_read()
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
771
        try:
3298.2.5 by John Arbash Meinel
Start implementing everything in terms of cheaper _as_revision_id lookups.
772
            revision_a = revision.ensure_null(branch.last_revision())
773
            if revision_a == revision.NULL_REVISION:
774
                raise errors.NoCommits(branch)
3984.1.2 by Daniel Watkins
Added fix.
775
            if other_location == '':
776
                other_location = branch.get_parent()
3298.2.5 by John Arbash Meinel
Start implementing everything in terms of cheaper _as_revision_id lookups.
777
            other_branch = Branch.open(other_location)
778
            other_branch.lock_read()
779
            try:
780
                revision_b = revision.ensure_null(other_branch.last_revision())
781
                if revision_b == revision.NULL_REVISION:
782
                    raise errors.NoCommits(other_branch)
783
                graph = branch.repository.get_graph(other_branch.repository)
3010.1.12 by Robert Collins
Lock branches while doing revision specification lookups.
784
                rev_id = graph.find_unique_lca(revision_a, revision_b)
3298.2.5 by John Arbash Meinel
Start implementing everything in terms of cheaper _as_revision_id lookups.
785
            finally:
786
                other_branch.unlock()
787
            if rev_id == revision.NULL_REVISION:
788
                raise errors.NoCommonAncestor(revision_a, revision_b)
789
            return rev_id
3010.1.12 by Robert Collins
Lock branches while doing revision specification lookups.
790
        finally:
791
            branch.unlock()
1551.10.33 by Aaron Bentley
Updates from review
792
793
1432 by Robert Collins
branch: namespace
794
1948.4.16 by John Arbash Meinel
Move the tests into the associated tester, remove redundant tests, some small PEP8 changes
795
1432 by Robert Collins
branch: namespace
796
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
797
    """Selects the last revision of a specified branch."""
798
799
    help_txt = """Selects the last revision of a specified branch.
2023.1.1 by ghigo
add topics help
800
801
    Supply the path to a branch to select its last revision.
802
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
803
    Examples::
804
2023.1.1 by ghigo
add topics help
805
      branch:/path/to/branch
1432 by Robert Collins
branch: namespace
806
    """
807
    prefix = 'branch:'
4569.2.18 by Vincent Ladeuil
Small refactoring to unblock the submission.
808
    dwim_catchable_exceptions = (errors.NotBranchError,)
1432 by Robert Collins
branch: namespace
809
810
    def _match_on(self, branch, revs):
1948.4.18 by John Arbash Meinel
Update branch: spec and tests
811
        from bzrlib.branch import Branch
812
        other_branch = Branch.open(self.spec)
1432 by Robert Collins
branch: namespace
813
        revision_b = other_branch.last_revision()
1948.4.18 by John Arbash Meinel
Update branch: spec and tests
814
        if revision_b in (None, revision.NULL_REVISION):
1948.4.26 by John Arbash Meinel
Get rid of direct imports of exceptions
815
            raise errors.NoCommits(other_branch)
1432 by Robert Collins
branch: namespace
816
        # 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.
817
        branch.fetch(other_branch, revision_b)
1432 by Robert Collins
branch: namespace
818
        try:
819
            revno = branch.revision_id_to_revno(revision_b)
1948.4.26 by John Arbash Meinel
Get rid of direct imports of exceptions
820
        except errors.NoSuchRevision:
1432 by Robert Collins
branch: namespace
821
            revno = None
822
        return RevisionInfo(branch, revno, revision_b)
3298.2.5 by John Arbash Meinel
Start implementing everything in terms of cheaper _as_revision_id lookups.
823
824
    def _as_revision_id(self, context_branch):
825
        from bzrlib.branch import Branch
826
        other_branch = Branch.open(self.spec)
827
        last_revision = other_branch.last_revision()
828
        last_revision = revision.ensure_null(last_revision)
1551.19.33 by Aaron Bentley
Use as_revision_id for diff
829
        context_branch.fetch(other_branch, last_revision)
3298.2.5 by John Arbash Meinel
Start implementing everything in terms of cheaper _as_revision_id lookups.
830
        if last_revision == revision.NULL_REVISION:
831
            raise errors.NoCommits(other_branch)
832
        return last_revision
833
3655.3.1 by Lukáš Lalinský
Fix `bzr st -rbranch:PATH_TO_BRANCH`
834
    def _as_tree(self, context_branch):
835
        from bzrlib.branch import Branch
836
        other_branch = Branch.open(self.spec)
837
        last_revision = other_branch.last_revision()
838
        last_revision = revision.ensure_null(last_revision)
839
        if last_revision == revision.NULL_REVISION:
840
            raise errors.NoCommits(other_branch)
841
        return other_branch.repository.revision_tree(last_revision)
842
1551.10.32 by Aaron Bentley
Add submit: specifier, for merge-directive-like diffs
843
844
1551.10.33 by Aaron Bentley
Updates from review
845
class RevisionSpec_submit(RevisionSpec_ancestor):
1551.10.32 by Aaron Bentley
Add submit: specifier, for merge-directive-like diffs
846
    """Selects a common ancestor with a submit branch."""
847
848
    help_txt = """Selects a common ancestor with the submit branch.
849
850
    Diffing against this shows all the changes that were made in this branch,
851
    and is a good predictor of what merge will do.  The submit branch is
3565.2.1 by Christophe Troestler
(trivial) Corrected typos.
852
    used by the bundle and merge directive commands.  If no submit branch
1551.10.32 by Aaron Bentley
Add submit: specifier, for merge-directive-like diffs
853
    is specified, the parent branch is used instead.
854
855
    The common ancestor is the last revision that existed in both
856
    branches. Usually this is the branch point, but it could also be
857
    a revision that was merged.
858
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
859
    Examples::
860
1551.10.32 by Aaron Bentley
Add submit: specifier, for merge-directive-like diffs
861
      $ bzr diff -r submit:
862
    """
1551.10.33 by Aaron Bentley
Updates from review
863
1551.10.32 by Aaron Bentley
Add submit: specifier, for merge-directive-like diffs
864
    prefix = 'submit:'
865
3298.2.5 by John Arbash Meinel
Start implementing everything in terms of cheaper _as_revision_id lookups.
866
    def _get_submit_location(self, branch):
1551.10.32 by Aaron Bentley
Add submit: specifier, for merge-directive-like diffs
867
        submit_location = branch.get_submit_branch()
1551.10.35 by Aaron Bentley
Add note about which branch is selected by submit:
868
        location_type = 'submit branch'
1551.10.32 by Aaron Bentley
Add submit: specifier, for merge-directive-like diffs
869
        if submit_location is None:
870
            submit_location = branch.get_parent()
1551.10.35 by Aaron Bentley
Add note about which branch is selected by submit:
871
            location_type = 'parent branch'
1551.10.32 by Aaron Bentley
Add submit: specifier, for merge-directive-like diffs
872
        if submit_location is None:
873
            raise errors.NoSubmitBranch(branch)
1551.10.35 by Aaron Bentley
Add note about which branch is selected by submit:
874
        trace.note('Using %s %s', location_type, submit_location)
3298.2.5 by John Arbash Meinel
Start implementing everything in terms of cheaper _as_revision_id lookups.
875
        return submit_location
876
877
    def _match_on(self, branch, revs):
878
        trace.mutter('matching ancestor: on: %s, %s', self.spec, branch)
879
        return self._find_revision_info(branch,
880
            self._get_submit_location(branch))
881
882
    def _as_revision_id(self, context_branch):
883
        return self._find_revision_id(context_branch,
884
            self._get_submit_location(context_branch))
1551.10.33 by Aaron Bentley
Updates from review
885
1551.10.35 by Aaron Bentley
Add note about which branch is selected by submit:
886
4569.2.18 by Vincent Ladeuil
Small refactoring to unblock the submission.
887
# The order in which we want to DWIM a revision spec without any prefix.
888
# revno is always tried first and isn't listed here, this is used by
889
# RevisionSpec_dwim._match_on
890
dwim_revspecs = [
891
    RevisionSpec_tag, # Let's try for a tag
892
    RevisionSpec_revid, # Maybe it's a revid?
893
    RevisionSpec_date, # Perhaps a date?
894
    RevisionSpec_branch, # OK, last try, maybe it's a branch
895
    ]
896
897
3966.2.1 by Jelmer Vernooij
Register revision specifiers in a registry.
898
revspec_registry = registry.Registry()
899
def _register_revspec(revspec):
900
    revspec_registry.register(revspec.prefix, revspec)
901
902
_register_revspec(RevisionSpec_revno)
903
_register_revspec(RevisionSpec_revid)
904
_register_revspec(RevisionSpec_last)
905
_register_revspec(RevisionSpec_before)
906
_register_revspec(RevisionSpec_tag)
907
_register_revspec(RevisionSpec_date)
908
_register_revspec(RevisionSpec_ancestor)
909
_register_revspec(RevisionSpec_branch)
910
_register_revspec(RevisionSpec_submit)
3966.2.2 by Jelmer Vernooij
Add backwards compatibility copy of SPEC_TYPES.
911
4569.2.17 by Vincent Ladeuil
Cleanup.
912
# classes in this list should have a "prefix" attribute, against which
913
# string specs are matched
3966.2.2 by Jelmer Vernooij
Add backwards compatibility copy of SPEC_TYPES.
914
SPEC_TYPES = symbol_versioning.deprecated_list(
915
    symbol_versioning.deprecated_in((1, 12, 0)), "SPEC_TYPES", [])