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