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