/brz/remove-bazaar

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