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