~bzr-pqm/bzr/bzr.dev

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