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