~bzr-pqm/bzr/bzr.dev

2220.2.3 by Martin Pool
Add tag: revision namespace.
1
# Copyright (C) 2005, 2006, 2007 Canonical Ltd
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
2
#
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
7
#
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
# GNU General Public License for more details.
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
12
#
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
17
1948.4.1 by John Arbash Meinel
Update number parsers to raise InvalidRevisionSpec. Update revno: itself so it supports negative numbers
18
import bisect
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
19
import datetime
20
import re
1948.4.1 by John Arbash Meinel
Update number parsers to raise InvalidRevisionSpec. Update revno: itself so it supports negative numbers
21
22
from bzrlib import (
23
    errors,
2325.2.5 by Marien Zwart
Call osutils.safe_revision_id instead of duplicating it.
24
    osutils,
1948.4.18 by John Arbash Meinel
Update branch: spec and tests
25
    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
26
    symbol_versioning,
27
    trace,
1988.4.5 by Robert Collins
revisions can now be specified using dotted-decimal revision numbers.
28
    tsort,
1948.4.1 by John Arbash Meinel
Update number parsers to raise InvalidRevisionSpec. Update revno: itself so it supports negative numbers
29
    )
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
30
1948.4.16 by John Arbash Meinel
Move the tests into the associated tester, remove redundant tests, some small PEP8 changes
31
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
32
_marker = []
33
1948.4.16 by John Arbash Meinel
Move the tests into the associated tester, remove redundant tests, some small PEP8 changes
34
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
35
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
36
    """The results of applying a revision specification to a branch."""
37
38
    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.
39
40
    An instance has two useful attributes: revno, and rev_id.
41
42
    They can also be accessed as spec[0] and spec[1] respectively,
43
    so that you can write code like:
44
    revno, rev_id = RevisionSpec(branch, spec)
45
    although this is probably going to be deprecated later.
46
47
    This class exists mostly to be the return value of a RevisionSpec,
48
    so that you can access the member you're interested in (number or id)
49
    or treat the result as a tuple.
50
    """
51
52
    def __init__(self, branch, revno, rev_id=_marker):
53
        self.branch = branch
54
        self.revno = revno
55
        if rev_id is _marker:
56
            # allow caller to be lazy
57
            if self.revno is None:
58
                self.rev_id = None
59
            else:
60
                self.rev_id = branch.get_rev_id(self.revno)
61
        else:
62
            self.rev_id = rev_id
63
64
    def __nonzero__(self):
65
        # first the easy ones...
66
        if self.rev_id is None:
67
            return False
68
        if self.revno is not None:
69
            return True
70
        # TODO: otherwise, it should depend on how I was built -
71
        # if it's in_history(branch), then check revision_history(),
72
        # if it's in_store(branch), do the check below
1185.67.2 by Aaron Bentley
Renamed Branch.storage to Branch.repository
73
        return self.branch.repository.has_revision(self.rev_id)
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
74
75
    def __len__(self):
76
        return 2
77
78
    def __getitem__(self, index):
79
        if index == 0: return self.revno
80
        if index == 1: return self.rev_id
81
        raise IndexError(index)
82
83
    def get(self):
1185.67.2 by Aaron Bentley
Renamed Branch.storage to Branch.repository
84
        return self.branch.repository.get_revision(self.rev_id)
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
85
86
    def __eq__(self, other):
87
        if type(other) not in (tuple, list, type(self)):
88
            return False
89
        if type(other) is type(self) and self.branch is not other.branch:
90
            return False
91
        return tuple(self) == tuple(other)
92
93
    def __repr__(self):
94
        return '<bzrlib.revisionspec.RevisionInfo object %s, %s for %r>' % (
95
            self.revno, self.rev_id, self.branch)
96
2220.2.3 by Martin Pool
Add tag: revision namespace.
97
    @staticmethod
98
    def from_revision_id(branch, revision_id, revs):
99
        """Construct a RevisionInfo given just the id.
100
101
        Use this if you don't know or care what the revno is.
102
        """
3298.2.11 by Aaron Bentley
Update tests for null:, clea up slightly
103
        if revision_id == revision.NULL_REVISION:
104
            return RevisionInfo(branch, 0, revision_id)
2220.2.3 by Martin Pool
Add tag: revision namespace.
105
        try:
106
            revno = revs.index(revision_id) + 1
107
        except ValueError:
108
            revno = None
109
        return RevisionInfo(branch, revno, revision_id)
110
1948.4.16 by John Arbash Meinel
Move the tests into the associated tester, remove redundant tests, some small PEP8 changes
111
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
112
# classes in this list should have a "prefix" attribute, against which
113
# string specs are matched
114
SPEC_TYPES = []
1948.4.35 by John Arbash Meinel
Move the _revno_regex to a more logical location
115
_revno_regex = None
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
116
1948.4.16 by John Arbash Meinel
Move the tests into the associated tester, remove redundant tests, some small PEP8 changes
117
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
118
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
119
    """A parsed revision specification."""
120
121
    help_txt = """A parsed revision specification.
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
122
123
    A revision specification can be an integer, in which case it is
124
    assumed to be a revno (though this will translate negative values
125
    into positive ones); or it can be a string, in which case it is
126
    parsed for something like 'date:' or 'revid:' etc.
127
128
    Revision specs are an UI element, and they have been moved out
129
    of the branch class to leave "back-end" classes unaware of such
130
    details.  Code that gets a revno or rev_id from other code should
131
    not be using revision specs - revnos and revision ids are the
132
    accepted ways to refer to revisions internally.
133
134
    (Equivalent to the old Branch method get_revision_info())
135
    """
136
137
    prefix = None
138
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
139
    def __new__(cls, spec, _internal=False):
140
        if _internal:
141
            return object.__new__(cls, spec, _internal=_internal)
142
143
        symbol_versioning.warn('Creating a RevisionSpec directly has'
144
                               ' 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)
145
                               ' 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
146
                               ' instead.',
147
                               DeprecationWarning, stacklevel=2)
1948.4.33 by John Arbash Meinel
Switch from get_revision_spec() to RevisionSpec.from_string() (as advised by Martin)
148
        return RevisionSpec.from_string(spec)
149
150
    @staticmethod
151
    def from_string(spec):
152
        """Parse a revision spec string into a RevisionSpec object.
153
154
        :param spec: A string specified by the user
155
        :return: A RevisionSpec object that understands how to parse the
156
            supplied notation.
157
        """
158
        if not isinstance(spec, (type(None), basestring)):
159
            raise TypeError('error')
160
161
        if spec is None:
162
            return RevisionSpec(None, _internal=True)
163
164
        assert isinstance(spec, basestring), \
165
            "You should only supply strings not %s" % (type(spec),)
166
167
        for spectype in SPEC_TYPES:
168
            if spec.startswith(spectype.prefix):
169
                trace.mutter('Returning RevisionSpec %s for %s',
170
                             spectype.__name__, spec)
171
                return spectype(spec, _internal=True)
172
        else:
173
            # RevisionSpec_revno is special cased, because it is the only
174
            # one that directly handles plain integers
1988.4.5 by Robert Collins
revisions can now be specified using dotted-decimal revision numbers.
175
            # TODO: This should not be special cased rather it should be
176
            # a method invocation on spectype.canparse()
1948.4.33 by John Arbash Meinel
Switch from get_revision_spec() to RevisionSpec.from_string() (as advised by Martin)
177
            global _revno_regex
178
            if _revno_regex is None:
1988.4.5 by Robert Collins
revisions can now be specified using dotted-decimal revision numbers.
179
                _revno_regex = re.compile(r'^(?:(\d+(\.\d+)*)|-\d+)(:.*)?$')
1948.4.33 by John Arbash Meinel
Switch from get_revision_spec() to RevisionSpec.from_string() (as advised by Martin)
180
            if _revno_regex.match(spec) is not None:
181
                return RevisionSpec_revno(spec, _internal=True)
182
183
            raise errors.NoSuchRevisionSpec(spec)
1948.4.27 by John Arbash Meinel
Deprecate calling RevisionSpec directly, and instead use a helper function. Also merge the old RevisionSpec_int class into RevisionSpec_revno
184
185
    def __init__(self, spec, _internal=False):
186
        """Create a RevisionSpec referring to the Null revision.
187
188
        :param spec: The original spec supplied by the user
189
        :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)
190
            called directly. Only from RevisionSpec.from_string()
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
191
        """
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
192
        if not _internal:
193
            # XXX: Update this after 0.10 is released
194
            symbol_versioning.warn('Creating a RevisionSpec directly has'
195
                                   ' 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)
196
                                   ' 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
197
                                   ' instead.',
198
                                   DeprecationWarning, stacklevel=2)
199
        self.user_spec = spec
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
200
        if self.prefix and spec.startswith(self.prefix):
201
            spec = spec[len(self.prefix):]
202
        self.spec = spec
203
204
    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
205
        trace.mutter('Returning RevisionSpec._match_on: None')
3298.2.11 by Aaron Bentley
Update tests for null:, clea up slightly
206
        return RevisionInfo(branch, None, None)
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
207
208
    def _match_on_and_check(self, branch, revs):
209
        info = self._match_on(branch, revs)
210
        if info:
211
            return info
3298.2.11 by Aaron Bentley
Update tests for null:, clea up slightly
212
        elif info == (None, None):
213
            # special case - nothing supplied
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
214
            return info
215
        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
216
            raise errors.InvalidRevisionSpec(self.user_spec, branch)
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
217
        else:
1948.4.2 by John Arbash Meinel
Update _match_on_and_check to raise the right error
218
            raise errors.InvalidRevisionSpec(self.spec, branch)
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
219
220
    def in_history(self, branch):
1732.3.1 by Matthieu Moy
Implementation of -r revno:N:/path/to/branch
221
        if branch:
222
            revs = branch.revision_history()
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
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
255
    def __repr__(self):
256
        # 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/
257
        return '<%s %s>' % (self.__class__.__name__,
258
                              self.user_spec)
1881.1.1 by Matthieu Moy
Fixed and tested "bzr diff" outside a working tree.
259
    
1881.1.4 by Matthieu Moy
needs_tree -> needs_branch
260
    def needs_branch(self):
261
        """Whether this revision spec needs a branch.
262
1711.2.99 by John Arbash Meinel
minor typo fix
263
        Set this to False the branch argument of _match_on is not used.
264
        """
1881.1.1 by Matthieu Moy
Fixed and tested "bzr diff" outside a working tree.
265
        return True
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
266
1907.4.1 by Matthieu Moy
Fixed merge to work nicely with -r revno:N:path
267
    def get_branch(self):
268
        """When the revision specifier contains a branch location, return it.
269
        
270
        Otherwise, return None.
271
        """
272
        return None
273
1907.4.9 by Matthieu Moy
missing newline
274
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
275
# private API
276
277
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
278
    """Selects a revision using a number."""
279
280
    help_txt = """Selects a revision using a number.
2023.1.1 by ghigo
add topics help
281
282
    Use an integer to specify a revision in the history of the branch.
283
    Optionally a branch can be specified. The 'revno:' prefix is optional.
284
    A negative number will count from the end of the branch (-1 is the
285
    last revision, -2 the previous one). If the negative number is larger
286
    than the branch's history, the first revision is returned.
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
287
    Examples::
288
2023.1.1 by ghigo
add topics help
289
      revno:1                   -> return the first revision
290
      revno:3:/path/to/branch   -> return the 3rd revision of
291
                                   the branch '/path/to/branch'
292
      revno:-1                  -> The last revision in a branch.
293
      -2:http://other/branch    -> The second to last revision in the
294
                                   remote branch.
295
      -1000000                  -> Most likely the first revision, unless
296
                                   your history is very long.
297
    """
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
298
    prefix = 'revno:'
299
300
    def _match_on(self, branch, revs):
301
        """Lookup a revision by revision number"""
3298.2.6 by John Arbash Meinel
Don't abstract through RevisionInfo for RevisionSpec_revno.as_revision_id()
302
        branch, revno, revision_id = self._lookup(branch, revs)
303
        return RevisionInfo(branch, revno, revision_id)
304
305
    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
306
        loc = self.spec.find(':')
307
        if loc == -1:
308
            revno_spec = self.spec
309
            branch_spec = None
310
        else:
311
            revno_spec = self.spec[:loc]
312
            branch_spec = self.spec[loc+1:]
313
314
        if revno_spec == '':
1948.4.6 by John Arbash Meinel
A small bugfix, and more tests for revno:
315
            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
316
                raise errors.InvalidRevisionSpec(self.user_spec,
1948.4.5 by John Arbash Meinel
Fix tests for negative entries, and add tests for revno:
317
                        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
318
            revno = None
319
        else:
320
            try:
321
                revno = int(revno_spec)
1988.4.5 by Robert Collins
revisions can now be specified using dotted-decimal revision numbers.
322
                dotted = False
323
            except ValueError:
324
                # dotted decimal. This arguably should not be here
325
                # but the from_string method is a little primitive 
326
                # right now - RBC 20060928
327
                try:
328
                    match_revno = tuple((int(number) for number in revno_spec.split('.')))
329
                except ValueError, e:
330
                    raise errors.InvalidRevisionSpec(self.user_spec, branch, e)
331
332
                dotted = True
1948.4.1 by John Arbash Meinel
Update number parsers to raise InvalidRevisionSpec. Update revno: itself so it supports negative numbers
333
1948.4.6 by John Arbash Meinel
A small bugfix, and more tests for revno:
334
        if branch_spec:
1988.4.5 by Robert Collins
revisions can now be specified using dotted-decimal revision numbers.
335
            # the user has override the branch to look in.
336
            # we need to refresh the revision_history map and
337
            # the branch object.
1948.4.1 by John Arbash Meinel
Update number parsers to raise InvalidRevisionSpec. Update revno: itself so it supports negative numbers
338
            from bzrlib.branch import Branch
339
            branch = Branch.open(branch_spec)
3298.2.6 by John Arbash Meinel
Don't abstract through RevisionInfo for RevisionSpec_revno.as_revision_id()
340
            revs_or_none = None
1948.4.22 by John Arbash Meinel
Refactor common code from integer revno handlers
341
1988.4.5 by Robert Collins
revisions can now be specified using dotted-decimal revision numbers.
342
        if dotted:
343
            branch.lock_read()
344
            try:
2418.5.9 by John Arbash Meinel
Have RevisionSpec_revno() also use the new helper
345
                revision_id_to_revno = branch.get_revision_id_to_revno_map()
346
                revisions = [revision_id for revision_id, revno
347
                             in revision_id_to_revno.iteritems()
348
                             if revno == match_revno]
1988.4.5 by Robert Collins
revisions can now be specified using dotted-decimal revision numbers.
349
            finally:
350
                branch.unlock()
351
            if len(revisions) != 1:
3298.2.6 by John Arbash Meinel
Don't abstract through RevisionInfo for RevisionSpec_revno.as_revision_id()
352
                return branch, None, None
1948.4.27 by John Arbash Meinel
Deprecate calling RevisionSpec directly, and instead use a helper function. Also merge the old RevisionSpec_int class into RevisionSpec_revno
353
            else:
1988.4.5 by Robert Collins
revisions can now be specified using dotted-decimal revision numbers.
354
                # there is no traditional 'revno' for dotted-decimal revnos.
355
                # so for  API compatability we return None.
3298.2.6 by John Arbash Meinel
Don't abstract through RevisionInfo for RevisionSpec_revno.as_revision_id()
356
                return branch, None, revisions[0]
1988.4.5 by Robert Collins
revisions can now be specified using dotted-decimal revision numbers.
357
        else:
3060.3.3 by Lukáš Lalinský
Make RevisionSpec_revid and RevisionSpec_revno not load the whole revision history.
358
            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.
359
            if revno < 0:
2249.4.2 by Wouter van Heyst
Convert callers of Branch.revision_history() to Branch.last_revision_info() where sensible.
360
                # if get_rev_id supported negative revnos, there would not be a
361
                # need for this special case.
3060.3.3 by Lukáš Lalinský
Make RevisionSpec_revid and RevisionSpec_revno not load the whole revision history.
362
                if (-revno) >= last_revno:
1988.4.5 by Robert Collins
revisions can now be specified using dotted-decimal revision numbers.
363
                    revno = 1
364
                else:
3060.3.3 by Lukáš Lalinský
Make RevisionSpec_revid and RevisionSpec_revno not load the whole revision history.
365
                    revno = last_revno + revno + 1
1988.4.5 by Robert Collins
revisions can now be specified using dotted-decimal revision numbers.
366
            try:
3298.2.6 by John Arbash Meinel
Don't abstract through RevisionInfo for RevisionSpec_revno.as_revision_id()
367
                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.
368
            except errors.NoSuchRevision:
369
                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()
370
        return branch, revno, revision_id
3060.3.2 by Lukáš Lalinský
Make RevisionSpec_last not load the whole history.
371
3298.2.5 by John Arbash Meinel
Start implementing everything in terms of cheaper _as_revision_id lookups.
372
    def _as_revision_id(self, context_branch):
373
        # 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()
374
        branch, revno, revision_id = self._lookup(context_branch, None)
375
        return revision_id
3060.3.3 by Lukáš Lalinský
Make RevisionSpec_revid and RevisionSpec_revno not load the whole revision history.
376
1881.1.4 by Matthieu Moy
needs_tree -> needs_branch
377
    def needs_branch(self):
1881.1.1 by Matthieu Moy
Fixed and tested "bzr diff" outside a working tree.
378
        return self.spec.find(':') == -1
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
379
1907.4.1 by Matthieu Moy
Fixed merge to work nicely with -r revno:N:path
380
    def get_branch(self):
381
        if self.spec.find(':') == -1:
382
            return None
383
        else:
384
            return self.spec[self.spec.find(':')+1:]
385
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
386
# Old compatibility 
387
RevisionSpec_int = RevisionSpec_revno
388
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
389
SPEC_TYPES.append(RevisionSpec_revno)
390
391
392
class RevisionSpec_revid(RevisionSpec):
2070.4.14 by John Arbash Meinel
Switch revisionspec to use the help defined as help_txt rather than the doc string
393
    """Selects a revision using the revision id."""
394
395
    help_txt = """Selects a revision using the revision id.
2023.1.1 by ghigo
add topics help
396
397
    Supply a specific revision id, that can be used to specify any
398
    revision id in the ancestry of the branch. 
399
    Including merges, and pending merges.
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
400
    Examples::
401
2070.4.7 by ghigo
Updates on the basis of the Richard Wilbur suggestions
402
      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.
403
    """
404
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
405
    prefix = 'revid:'
406
3298.2.5 by John Arbash Meinel
Start implementing everything in terms of cheaper _as_revision_id lookups.
407
    def _match_on(self, branch, revs):
2325.2.5 by Marien Zwart
Call osutils.safe_revision_id instead of duplicating it.
408
        # self.spec comes straight from parsing the command line arguments,
409
        # so we expect it to be a Unicode string. Switch it to the internal
410
        # representation.
411
        revision_id = osutils.safe_revision_id(self.spec, warn=False)
3298.2.5 by John Arbash Meinel
Start implementing everything in terms of cheaper _as_revision_id lookups.
412
        return RevisionInfo.from_revision_id(branch, revision_id, revs)
3060.3.3 by Lukáš Lalinský
Make RevisionSpec_revid and RevisionSpec_revno not load the whole revision history.
413
3298.2.5 by John Arbash Meinel
Start implementing everything in terms of cheaper _as_revision_id lookups.
414
    def _as_revision_id(self, context_branch):
415
        return osutils.safe_revision_id(self.spec, warn=False)
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
416
417
SPEC_TYPES.append(RevisionSpec_revid)
418
419
420
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
421
    """Selects the nth revision from the end."""
422
423
    help_txt = """Selects the nth revision from the end.
2023.1.1 by ghigo
add topics help
424
425
    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
426
    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
427
    Examples::
428
2023.1.1 by ghigo
add topics help
429
      last:1        -> return the last revision
430
      last:3        -> return the revision 2 before the end.
3060.3.2 by Lukáš Lalinský
Make RevisionSpec_last not load the whole history.
431
    """
1185.1.39 by Robert Collins
Robey Pointers before: namespace to clear up usage of dates in revision parameters
432
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
433
    prefix = 'last:'
434
435
    def _match_on(self, branch, revs):
3298.2.5 by John Arbash Meinel
Start implementing everything in terms of cheaper _as_revision_id lookups.
436
        revno, revision_id = self._revno_and_revision_id(branch, revs)
437
        return RevisionInfo(branch, revno, revision_id)
438
439
    def _revno_and_revision_id(self, context_branch, revs_or_none):
440
        last_revno, last_revision_id = context_branch.last_revision_info()
3060.3.2 by Lukáš Lalinský
Make RevisionSpec_last not load the whole history.
441
1948.4.9 by John Arbash Meinel
Cleanup and test last:
442
        if self.spec == '':
3060.3.2 by Lukáš Lalinský
Make RevisionSpec_last not load the whole history.
443
            if not last_revno:
3298.2.5 by John Arbash Meinel
Start implementing everything in terms of cheaper _as_revision_id lookups.
444
                raise errors.NoCommits(context_branch)
445
            return last_revno, last_revision_id
1948.4.9 by John Arbash Meinel
Cleanup and test last:
446
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
447
        try:
448
            offset = int(self.spec)
1948.4.9 by John Arbash Meinel
Cleanup and test last:
449
        except ValueError, e:
3298.2.5 by John Arbash Meinel
Start implementing everything in terms of cheaper _as_revision_id lookups.
450
            raise errors.InvalidRevisionSpec(self.user_spec, context_branch, e)
1948.4.9 by John Arbash Meinel
Cleanup and test last:
451
452
        if offset <= 0:
3298.2.5 by John Arbash Meinel
Start implementing everything in terms of cheaper _as_revision_id lookups.
453
            raise errors.InvalidRevisionSpec(self.user_spec, context_branch,
1948.4.9 by John Arbash Meinel
Cleanup and test last:
454
                                             'you must supply a positive value')
3060.3.2 by Lukáš Lalinský
Make RevisionSpec_last not load the whole history.
455
456
        revno = last_revno - offset + 1
1948.4.9 by John Arbash Meinel
Cleanup and test last:
457
        try:
3298.2.5 by John Arbash Meinel
Start implementing everything in terms of cheaper _as_revision_id lookups.
458
            revision_id = context_branch.get_rev_id(revno, revs_or_none)
1948.4.9 by John Arbash Meinel
Cleanup and test last:
459
        except errors.NoSuchRevision:
3298.2.5 by John Arbash Meinel
Start implementing everything in terms of cheaper _as_revision_id lookups.
460
            raise errors.InvalidRevisionSpec(self.user_spec, context_branch)
461
        return revno, revision_id
462
463
    def _as_revision_id(self, context_branch):
464
        # We compute the revno as part of the process, but we don't really care
465
        # about it.
466
        revno, revision_id = self._revno_and_revision_id(context_branch, None)
467
        return revision_id
3060.3.2 by Lukáš Lalinský
Make RevisionSpec_last not load the whole history.
468
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
469
SPEC_TYPES.append(RevisionSpec_last)
470
471
1185.1.39 by Robert Collins
Robey Pointers before: namespace to clear up usage of dates in revision parameters
472
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
473
    """Selects the parent of the revision specified."""
474
475
    help_txt = """Selects the parent of the revision specified.
2023.1.1 by ghigo
add topics help
476
477
    Supply any revision spec to return the parent of that revision.
478
    It is an error to request the parent of the null revision (before:0).
479
    This is mostly useful when inspecting revisions that are not in the
480
    revision history of a branch.
481
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
482
    Examples::
483
2023.1.1 by ghigo
add topics help
484
      before:1913    -> Return the parent of revno 1913 (revno 1912)
485
      before:revid:aaaa@bbbb-1234567890  -> return the parent of revision
2070.4.7 by ghigo
Updates on the basis of the Richard Wilbur suggestions
486
                                            aaaa@bbbb-1234567890
2023.1.1 by ghigo
add topics help
487
      bzr diff -r before:revid:aaaa..revid:aaaa
488
            -> Find the changes between revision 'aaaa' and its parent.
489
               (what changes did 'aaaa' introduce)
490
    """
1185.1.39 by Robert Collins
Robey Pointers before: namespace to clear up usage of dates in revision parameters
491
492
    prefix = 'before:'
493
    
3298.2.5 by John Arbash Meinel
Start implementing everything in terms of cheaper _as_revision_id lookups.
494
    def _match_on(self, branch, revs):
495
        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
496
        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
497
            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
498
                                         'cannot go before the null: revision')
499
        if r.revno is None:
500
            # We need to use the repository history here
501
            rev = branch.repository.get_revision(r.rev_id)
502
            if not rev.parent_ids:
503
                revno = 0
2598.5.10 by Aaron Bentley
Return NULL_REVISION instead of None for the null revision
504
                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
505
            else:
506
                revision_id = rev.parent_ids[0]
3298.2.5 by John Arbash Meinel
Start implementing everything in terms of cheaper _as_revision_id lookups.
507
                try:
508
                    revno = revs.index(revision_id) + 1
509
                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
510
                    revno = None
511
        else:
512
            revno = r.revno - 1
513
            try:
514
                revision_id = branch.get_rev_id(revno, revs)
1948.4.26 by John Arbash Meinel
Get rid of direct imports of exceptions
515
            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
516
                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
517
                                                 branch)
518
        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
519
3298.2.5 by John Arbash Meinel
Start implementing everything in terms of cheaper _as_revision_id lookups.
520
    def _as_revision_id(self, context_branch):
521
        base_revspec = RevisionSpec.from_string(self.spec)
522
        base_revision_id = base_revspec.as_revision_id(context_branch)
523
        if base_revision_id == revision.NULL_REVISION:
524
            raise errors.InvalidRevisionSpec(self.user_spec, branch,
525
                                         'cannot go before the null: revision')
3298.2.10 by Aaron Bentley
Refactor partial history code
526
        context_repo = context_branch.repository
527
        context_repo.lock_read()
528
        try:
529
            parent_map = context_repo.get_parent_map([base_revision_id])
530
        finally:
531
            context_repo.unlock()
3298.2.5 by John Arbash Meinel
Start implementing everything in terms of cheaper _as_revision_id lookups.
532
        if base_revision_id not in parent_map:
533
            # Ghost, or unknown revision id
534
            raise errors.InvalidRevisionSpec(self.user_spec, context_branch,
535
                'cannot find the matching revision')
536
        parents = parent_map[base_revision_id]
537
        if len(parents) < 1:
538
            raise errors.InvalidRevisionSpec(self.user_spec, context_branch,
539
                'No parents for revision.')
540
        return parents[0]
3060.3.5 by Lukáš Lalinský
Add support for in_branch for the remaining RevisionSpec subclasses.
541
1185.1.39 by Robert Collins
Robey Pointers before: namespace to clear up usage of dates in revision parameters
542
SPEC_TYPES.append(RevisionSpec_before)
543
544
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
545
class RevisionSpec_tag(RevisionSpec):
2220.2.3 by Martin Pool
Add tag: revision namespace.
546
    """Select a revision identified by tag name"""
547
548
    help_txt = """Selects a revision identified by a tag name.
549
1551.10.34 by Aaron Bentley
Fix tag: help
550
    Tags are stored in the branch and created by the 'tag' command.
2220.2.3 by Martin Pool
Add tag: revision namespace.
551
    """
2070.4.14 by John Arbash Meinel
Switch revisionspec to use the help defined as help_txt rather than the doc string
552
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
553
    prefix = 'tag:'
554
3298.2.5 by John Arbash Meinel
Start implementing everything in terms of cheaper _as_revision_id lookups.
555
    def _match_on(self, branch, revs):
2220.2.3 by Martin Pool
Add tag: revision namespace.
556
        # 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.
557
        return RevisionInfo.from_revision_id(branch,
558
            branch.tags.lookup_tag(self.spec),
559
            revs)
3060.3.5 by Lukáš Lalinský
Add support for in_branch for the remaining RevisionSpec subclasses.
560
3298.2.5 by John Arbash Meinel
Start implementing everything in terms of cheaper _as_revision_id lookups.
561
    def _as_revision_id(self, context_branch):
562
        return context_branch.tags.lookup_tag(self.spec)
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
563
564
SPEC_TYPES.append(RevisionSpec_tag)
565
566
1948.4.12 by John Arbash Meinel
Some tests for the date: spec
567
class _RevListToTimestamps(object):
568
    """This takes a list of revisions, and allows you to bisect by date"""
569
570
    __slots__ = ['revs', 'branch']
571
1688.2.2 by Guillaume Pinot
Binary search for 'date:' revision.
572
    def __init__(self, revs, branch):
573
        self.revs = revs
574
        self.branch = branch
1948.4.12 by John Arbash Meinel
Some tests for the date: spec
575
1688.2.2 by Guillaume Pinot
Binary search for 'date:' revision.
576
    def __getitem__(self, index):
1948.4.12 by John Arbash Meinel
Some tests for the date: spec
577
        """Get the date of the index'd item"""
1688.2.2 by Guillaume Pinot
Binary search for 'date:' revision.
578
        r = self.branch.repository.get_revision(self.revs[index])
579
        # TODO: Handle timezone.
580
        return datetime.datetime.fromtimestamp(r.timestamp)
1948.4.12 by John Arbash Meinel
Some tests for the date: spec
581
1688.2.2 by Guillaume Pinot
Binary search for 'date:' revision.
582
    def __len__(self):
583
        return len(self.revs)
584
585
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
586
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
587
    """Selects a revision on the basis of a datestamp."""
588
589
    help_txt = """Selects a revision on the basis of a datestamp.
2023.1.1 by ghigo
add topics help
590
591
    Supply a datestamp to select the first revision that matches the date.
592
    Date can be 'yesterday', 'today', 'tomorrow' or a YYYY-MM-DD string.
593
    Matches the first entry after a given date (either at midnight or
594
    at a specified time).
595
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
596
    One way to display all the changes since yesterday would be::
2666.1.5 by Ian Clatworthy
Incorporate feedback from Alex B. & James W.
597
2023.1.1 by ghigo
add topics help
598
        bzr log -r date:yesterday..-1
599
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
600
    Examples::
601
2023.1.1 by ghigo
add topics help
602
      date:yesterday            -> select the first revision since yesterday
603
      date:2006-08-14,17:10:14  -> select the first revision after
604
                                   August 14th, 2006 at 5:10pm.
605
    """    
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
606
    prefix = 'date:'
607
    _date_re = re.compile(
608
            r'(?P<date>(?P<year>\d\d\d\d)-(?P<month>\d\d)-(?P<day>\d\d))?'
609
            r'(,|T)?\s*'
610
            r'(?P<time>(?P<hour>\d\d):(?P<minute>\d\d)(:(?P<second>\d\d))?)?'
611
        )
612
613
    def _match_on(self, branch, revs):
2023.1.1 by ghigo
add topics help
614
        """Spec for date revisions:
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
615
          date:value
616
          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
617
          matches the first entry after a given date (either at midnight or
618
          at a specified time).
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
619
        """
2070.4.3 by John Arbash Meinel
code and doc cleanup
620
        #  XXX: This doesn't actually work
621
        #  So the proper way of saying 'give me all entries for today' is:
622
        #      -r date:yesterday..date:today
1185.1.39 by Robert Collins
Robey Pointers before: namespace to clear up usage of dates in revision parameters
623
        today = datetime.datetime.fromordinal(datetime.date.today().toordinal())
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
624
        if self.spec.lower() == 'yesterday':
625
            dt = today - datetime.timedelta(days=1)
626
        elif self.spec.lower() == 'today':
627
            dt = today
628
        elif self.spec.lower() == 'tomorrow':
629
            dt = today + datetime.timedelta(days=1)
630
        else:
631
            m = self._date_re.match(self.spec)
632
            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
633
                raise errors.InvalidRevisionSpec(self.user_spec,
1948.4.12 by John Arbash Meinel
Some tests for the date: spec
634
                                                 branch, 'invalid date')
635
636
            try:
637
                if m.group('date'):
638
                    year = int(m.group('year'))
639
                    month = int(m.group('month'))
640
                    day = int(m.group('day'))
641
                else:
642
                    year = today.year
643
                    month = today.month
644
                    day = today.day
645
646
                if m.group('time'):
647
                    hour = int(m.group('hour'))
648
                    minute = int(m.group('minute'))
649
                    if m.group('second'):
650
                        second = int(m.group('second'))
651
                    else:
652
                        second = 0
653
                else:
654
                    hour, minute, second = 0,0,0
655
            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
656
                raise errors.InvalidRevisionSpec(self.user_spec,
1948.4.12 by John Arbash Meinel
Some tests for the date: spec
657
                                                 branch, 'invalid date')
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
658
659
            dt = datetime.datetime(year=year, month=month, day=day,
660
                    hour=hour, minute=minute, second=second)
1704.2.27 by Martin Pool
Run bisection search for revision date with lock held. (Robert Widhopf-Frenk)
661
        branch.lock_read()
662
        try:
1948.4.12 by John Arbash Meinel
Some tests for the date: spec
663
            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)
664
        finally:
665
            branch.unlock()
1688.2.2 by Guillaume Pinot
Binary search for 'date:' revision.
666
        if rev == len(revs):
3298.2.11 by Aaron Bentley
Update tests for null:, clea up slightly
667
            raise errors.InvalidRevisionSpec(self.user_spec, branch)
1688.2.2 by Guillaume Pinot
Binary search for 'date:' revision.
668
        else:
669
            return RevisionInfo(branch, rev + 1)
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
670
671
SPEC_TYPES.append(RevisionSpec_date)
672
673
674
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
675
    """Selects a common ancestor with a second branch."""
676
677
    help_txt = """Selects a common ancestor with a second branch.
2023.1.1 by ghigo
add topics help
678
679
    Supply the path to a branch to select the common ancestor.
680
681
    The common ancestor is the last revision that existed in both
682
    branches. Usually this is the branch point, but it could also be
683
    a revision that was merged.
684
685
    This is frequently used with 'diff' to return all of the changes
686
    that your branch introduces, while excluding the changes that you
687
    have not merged from the remote branch.
688
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
689
    Examples::
690
2023.1.1 by ghigo
add topics help
691
      ancestor:/path/to/branch
2070.4.7 by ghigo
Updates on the basis of the Richard Wilbur suggestions
692
      $ bzr diff -r ancestor:../../mainline/branch
2023.1.1 by ghigo
add topics help
693
    """
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
694
    prefix = 'ancestor:'
695
696
    def _match_on(self, branch, revs):
1551.10.33 by Aaron Bentley
Updates from review
697
        trace.mutter('matching ancestor: on: %s, %s', self.spec, branch)
698
        return self._find_revision_info(branch, self.spec)
699
3298.2.5 by John Arbash Meinel
Start implementing everything in terms of cheaper _as_revision_id lookups.
700
    def _as_revision_id(self, context_branch):
701
        return self._find_revision_id(context_branch, self.spec)
702
1551.10.33 by Aaron Bentley
Updates from review
703
    @staticmethod
704
    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.
705
        revision_id = RevisionSpec_ancestor._find_revision_id(branch,
706
                                                              other_location)
707
        try:
708
            revno = branch.revision_id_to_revno(revision_id)
709
        except errors.NoSuchRevision:
710
            revno = None
711
        return RevisionInfo(branch, revno, revision_id)
712
713
    @staticmethod
714
    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
715
        from bzrlib.branch import Branch
1948.4.18 by John Arbash Meinel
Update branch: spec and tests
716
3010.1.12 by Robert Collins
Lock branches while doing revision specification lookups.
717
        branch.lock_read()
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
718
        try:
3298.2.5 by John Arbash Meinel
Start implementing everything in terms of cheaper _as_revision_id lookups.
719
            revision_a = revision.ensure_null(branch.last_revision())
720
            if revision_a == revision.NULL_REVISION:
721
                raise errors.NoCommits(branch)
722
            other_branch = Branch.open(other_location)
723
            other_branch.lock_read()
724
            try:
725
                revision_b = revision.ensure_null(other_branch.last_revision())
726
                if revision_b == revision.NULL_REVISION:
727
                    raise errors.NoCommits(other_branch)
728
                graph = branch.repository.get_graph(other_branch.repository)
3010.1.12 by Robert Collins
Lock branches while doing revision specification lookups.
729
                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.
730
            finally:
731
                other_branch.unlock()
732
            if rev_id == revision.NULL_REVISION:
733
                raise errors.NoCommonAncestor(revision_a, revision_b)
734
            return rev_id
3010.1.12 by Robert Collins
Lock branches while doing revision specification lookups.
735
        finally:
736
            branch.unlock()
1551.10.33 by Aaron Bentley
Updates from review
737
738
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
739
SPEC_TYPES.append(RevisionSpec_ancestor)
1432 by Robert Collins
branch: namespace
740
1948.4.16 by John Arbash Meinel
Move the tests into the associated tester, remove redundant tests, some small PEP8 changes
741
1432 by Robert Collins
branch: namespace
742
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
743
    """Selects the last revision of a specified branch."""
744
745
    help_txt = """Selects the last revision of a specified branch.
2023.1.1 by ghigo
add topics help
746
747
    Supply the path to a branch to select its last revision.
748
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
749
    Examples::
750
2023.1.1 by ghigo
add topics help
751
      branch:/path/to/branch
1432 by Robert Collins
branch: namespace
752
    """
753
    prefix = 'branch:'
754
755
    def _match_on(self, branch, revs):
1948.4.18 by John Arbash Meinel
Update branch: spec and tests
756
        from bzrlib.branch import Branch
757
        other_branch = Branch.open(self.spec)
1432 by Robert Collins
branch: namespace
758
        revision_b = other_branch.last_revision()
1948.4.18 by John Arbash Meinel
Update branch: spec and tests
759
        if revision_b in (None, revision.NULL_REVISION):
1948.4.26 by John Arbash Meinel
Get rid of direct imports of exceptions
760
            raise errors.NoCommits(other_branch)
1432 by Robert Collins
branch: namespace
761
        # pull in the remote revisions so we can diff
1534.1.31 by Robert Collins
Deprecated fetch.fetch and fetch.greedy_fetch for branch.fetch, and move the Repository.fetch internals to InterRepo and InterWeaveRepo.
762
        branch.fetch(other_branch, revision_b)
1432 by Robert Collins
branch: namespace
763
        try:
764
            revno = branch.revision_id_to_revno(revision_b)
1948.4.26 by John Arbash Meinel
Get rid of direct imports of exceptions
765
        except errors.NoSuchRevision:
1432 by Robert Collins
branch: namespace
766
            revno = None
767
        return RevisionInfo(branch, revno, revision_b)
3298.2.5 by John Arbash Meinel
Start implementing everything in terms of cheaper _as_revision_id lookups.
768
769
    def _as_revision_id(self, context_branch):
770
        from bzrlib.branch import Branch
771
        other_branch = Branch.open(self.spec)
772
        last_revision = other_branch.last_revision()
773
        last_revision = revision.ensure_null(last_revision)
774
        if last_revision == revision.NULL_REVISION:
775
            raise errors.NoCommits(other_branch)
776
        return last_revision
777
1432 by Robert Collins
branch: namespace
778
SPEC_TYPES.append(RevisionSpec_branch)
1551.10.32 by Aaron Bentley
Add submit: specifier, for merge-directive-like diffs
779
780
1551.10.33 by Aaron Bentley
Updates from review
781
class RevisionSpec_submit(RevisionSpec_ancestor):
1551.10.32 by Aaron Bentley
Add submit: specifier, for merge-directive-like diffs
782
    """Selects a common ancestor with a submit branch."""
783
784
    help_txt = """Selects a common ancestor with the submit branch.
785
786
    Diffing against this shows all the changes that were made in this branch,
787
    and is a good predictor of what merge will do.  The submit branch is
788
    used by the bundle and merge directive comands.  If no submit branch
789
    is specified, the parent branch is used instead.
790
791
    The common ancestor is the last revision that existed in both
792
    branches. Usually this is the branch point, but it could also be
793
    a revision that was merged.
794
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
795
    Examples::
796
1551.10.32 by Aaron Bentley
Add submit: specifier, for merge-directive-like diffs
797
      $ bzr diff -r submit:
798
    """
1551.10.33 by Aaron Bentley
Updates from review
799
1551.10.32 by Aaron Bentley
Add submit: specifier, for merge-directive-like diffs
800
    prefix = 'submit:'
801
3298.2.5 by John Arbash Meinel
Start implementing everything in terms of cheaper _as_revision_id lookups.
802
    def _get_submit_location(self, branch):
1551.10.32 by Aaron Bentley
Add submit: specifier, for merge-directive-like diffs
803
        submit_location = branch.get_submit_branch()
1551.10.35 by Aaron Bentley
Add note about which branch is selected by submit:
804
        location_type = 'submit branch'
1551.10.32 by Aaron Bentley
Add submit: specifier, for merge-directive-like diffs
805
        if submit_location is None:
806
            submit_location = branch.get_parent()
1551.10.35 by Aaron Bentley
Add note about which branch is selected by submit:
807
            location_type = 'parent branch'
1551.10.32 by Aaron Bentley
Add submit: specifier, for merge-directive-like diffs
808
        if submit_location is None:
809
            raise errors.NoSubmitBranch(branch)
1551.10.35 by Aaron Bentley
Add note about which branch is selected by submit:
810
        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.
811
        return submit_location
812
813
    def _match_on(self, branch, revs):
814
        trace.mutter('matching ancestor: on: %s, %s', self.spec, branch)
815
        return self._find_revision_info(branch,
816
            self._get_submit_location(branch))
817
818
    def _as_revision_id(self, context_branch):
819
        return self._find_revision_id(context_branch,
820
            self._get_submit_location(context_branch))
1551.10.33 by Aaron Bentley
Updates from review
821
1551.10.35 by Aaron Bentley
Add note about which branch is selected by submit:
822
1551.10.33 by Aaron Bentley
Updates from review
823
SPEC_TYPES.append(RevisionSpec_submit)