~bzr-pqm/bzr/bzr.dev

2220.2.3 by Martin Pool
Add tag: revision namespace.
1
# Copyright (C) 2005, 2006, 2007 Canonical Ltd
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
2
#
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
7
#
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
# GNU General Public License for more details.
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
12
#
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
17
1948.4.1 by John Arbash Meinel
Update number parsers to raise InvalidRevisionSpec. Update revno: itself so it supports negative numbers
18
import bisect
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
19
import datetime
20
import re
1948.4.1 by John Arbash Meinel
Update number parsers to raise InvalidRevisionSpec. Update revno: itself so it supports negative numbers
21
22
from bzrlib import (
23
    errors,
2325.2.5 by Marien Zwart
Call osutils.safe_revision_id instead of duplicating it.
24
    osutils,
1948.4.18 by John Arbash Meinel
Update branch: spec and tests
25
    revision,
1948.4.27 by John Arbash Meinel
Deprecate calling RevisionSpec directly, and instead use a helper function. Also merge the old RevisionSpec_int class into RevisionSpec_revno
26
    symbol_versioning,
27
    trace,
1988.4.5 by Robert Collins
revisions can now be specified using dotted-decimal revision numbers.
28
    tsort,
1948.4.1 by John Arbash Meinel
Update number parsers to raise InvalidRevisionSpec. Update revno: itself so it supports negative numbers
29
    )
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
30
1948.4.16 by John Arbash Meinel
Move the tests into the associated tester, remove redundant tests, some small PEP8 changes
31
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
32
_marker = []
33
1948.4.16 by John Arbash Meinel
Move the tests into the associated tester, remove redundant tests, some small PEP8 changes
34
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
35
class RevisionInfo(object):
2070.4.14 by John Arbash Meinel
Switch revisionspec to use the help defined as help_txt rather than the doc string
36
    """The results of applying a revision specification to a branch."""
37
38
    help_txt = """The results of applying a revision specification to a branch.
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
39
40
    An instance has two useful attributes: revno, and rev_id.
41
42
    They can also be accessed as spec[0] and spec[1] respectively,
43
    so that you can write code like:
44
    revno, rev_id = RevisionSpec(branch, spec)
45
    although this is probably going to be deprecated later.
46
47
    This class exists mostly to be the return value of a RevisionSpec,
48
    so that you can access the member you're interested in (number or id)
49
    or treat the result as a tuple.
50
    """
51
52
    def __init__(self, branch, revno, rev_id=_marker):
53
        self.branch = branch
54
        self.revno = revno
55
        if rev_id is _marker:
56
            # allow caller to be lazy
57
            if self.revno is None:
58
                self.rev_id = None
59
            else:
60
                self.rev_id = branch.get_rev_id(self.revno)
61
        else:
62
            self.rev_id = rev_id
63
64
    def __nonzero__(self):
65
        # first the easy ones...
66
        if self.rev_id is None:
67
            return False
68
        if self.revno is not None:
69
            return True
70
        # TODO: otherwise, it should depend on how I was built -
71
        # if it's in_history(branch), then check revision_history(),
72
        # if it's in_store(branch), do the check below
1185.67.2 by Aaron Bentley
Renamed Branch.storage to Branch.repository
73
        return self.branch.repository.has_revision(self.rev_id)
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
74
75
    def __len__(self):
76
        return 2
77
78
    def __getitem__(self, index):
79
        if index == 0: return self.revno
80
        if index == 1: return self.rev_id
81
        raise IndexError(index)
82
83
    def get(self):
1185.67.2 by Aaron Bentley
Renamed Branch.storage to Branch.repository
84
        return self.branch.repository.get_revision(self.rev_id)
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
85
86
    def __eq__(self, other):
87
        if type(other) not in (tuple, list, type(self)):
88
            return False
89
        if type(other) is type(self) and self.branch is not other.branch:
90
            return False
91
        return tuple(self) == tuple(other)
92
93
    def __repr__(self):
94
        return '<bzrlib.revisionspec.RevisionInfo object %s, %s for %r>' % (
95
            self.revno, self.rev_id, self.branch)
96
2220.2.3 by Martin Pool
Add tag: revision namespace.
97
    @staticmethod
98
    def from_revision_id(branch, revision_id, revs):
99
        """Construct a RevisionInfo given just the id.
100
101
        Use this if you don't know or care what the revno is.
102
        """
103
        try:
104
            revno = revs.index(revision_id) + 1
105
        except ValueError:
106
            revno = None
107
        return RevisionInfo(branch, revno, revision_id)
108
1948.4.16 by John Arbash Meinel
Move the tests into the associated tester, remove redundant tests, some small PEP8 changes
109
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
110
# classes in this list should have a "prefix" attribute, against which
111
# string specs are matched
112
SPEC_TYPES = []
1948.4.35 by John Arbash Meinel
Move the _revno_regex to a more logical location
113
_revno_regex = None
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
114
1948.4.16 by John Arbash Meinel
Move the tests into the associated tester, remove redundant tests, some small PEP8 changes
115
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
116
class RevisionSpec(object):
2070.4.14 by John Arbash Meinel
Switch revisionspec to use the help defined as help_txt rather than the doc string
117
    """A parsed revision specification."""
118
119
    help_txt = """A parsed revision specification.
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
120
121
    A revision specification can be an integer, in which case it is
122
    assumed to be a revno (though this will translate negative values
123
    into positive ones); or it can be a string, in which case it is
124
    parsed for something like 'date:' or 'revid:' etc.
125
126
    Revision specs are an UI element, and they have been moved out
127
    of the branch class to leave "back-end" classes unaware of such
128
    details.  Code that gets a revno or rev_id from other code should
129
    not be using revision specs - revnos and revision ids are the
130
    accepted ways to refer to revisions internally.
131
132
    (Equivalent to the old Branch method get_revision_info())
133
    """
134
135
    prefix = None
136
1948.4.27 by John Arbash Meinel
Deprecate calling RevisionSpec directly, and instead use a helper function. Also merge the old RevisionSpec_int class into RevisionSpec_revno
137
    def __new__(cls, spec, _internal=False):
138
        if _internal:
139
            return object.__new__(cls, spec, _internal=_internal)
140
141
        symbol_versioning.warn('Creating a RevisionSpec directly has'
142
                               ' been deprecated in version 0.11. Use'
1948.4.33 by John Arbash Meinel
Switch from get_revision_spec() to RevisionSpec.from_string() (as advised by Martin)
143
                               ' RevisionSpec.from_string()'
1948.4.27 by John Arbash Meinel
Deprecate calling RevisionSpec directly, and instead use a helper function. Also merge the old RevisionSpec_int class into RevisionSpec_revno
144
                               ' instead.',
145
                               DeprecationWarning, stacklevel=2)
1948.4.33 by John Arbash Meinel
Switch from get_revision_spec() to RevisionSpec.from_string() (as advised by Martin)
146
        return RevisionSpec.from_string(spec)
147
148
    @staticmethod
149
    def from_string(spec):
150
        """Parse a revision spec string into a RevisionSpec object.
151
152
        :param spec: A string specified by the user
153
        :return: A RevisionSpec object that understands how to parse the
154
            supplied notation.
155
        """
156
        if not isinstance(spec, (type(None), basestring)):
157
            raise TypeError('error')
158
159
        if spec is None:
160
            return RevisionSpec(None, _internal=True)
161
162
        assert isinstance(spec, basestring), \
163
            "You should only supply strings not %s" % (type(spec),)
164
165
        for spectype in SPEC_TYPES:
166
            if spec.startswith(spectype.prefix):
167
                trace.mutter('Returning RevisionSpec %s for %s',
168
                             spectype.__name__, spec)
169
                return spectype(spec, _internal=True)
170
        else:
171
            # RevisionSpec_revno is special cased, because it is the only
172
            # one that directly handles plain integers
1988.4.5 by Robert Collins
revisions can now be specified using dotted-decimal revision numbers.
173
            # TODO: This should not be special cased rather it should be
174
            # a method invocation on spectype.canparse()
1948.4.33 by John Arbash Meinel
Switch from get_revision_spec() to RevisionSpec.from_string() (as advised by Martin)
175
            global _revno_regex
176
            if _revno_regex is None:
1988.4.5 by Robert Collins
revisions can now be specified using dotted-decimal revision numbers.
177
                _revno_regex = re.compile(r'^(?:(\d+(\.\d+)*)|-\d+)(:.*)?$')
1948.4.33 by John Arbash Meinel
Switch from get_revision_spec() to RevisionSpec.from_string() (as advised by Martin)
178
            if _revno_regex.match(spec) is not None:
179
                return RevisionSpec_revno(spec, _internal=True)
180
181
            raise errors.NoSuchRevisionSpec(spec)
1948.4.27 by John Arbash Meinel
Deprecate calling RevisionSpec directly, and instead use a helper function. Also merge the old RevisionSpec_int class into RevisionSpec_revno
182
183
    def __init__(self, spec, _internal=False):
184
        """Create a RevisionSpec referring to the Null revision.
185
186
        :param spec: The original spec supplied by the user
187
        :param _internal: Used to ensure that RevisionSpec is not being
1948.4.33 by John Arbash Meinel
Switch from get_revision_spec() to RevisionSpec.from_string() (as advised by Martin)
188
            called directly. Only from RevisionSpec.from_string()
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
189
        """
1948.4.27 by John Arbash Meinel
Deprecate calling RevisionSpec directly, and instead use a helper function. Also merge the old RevisionSpec_int class into RevisionSpec_revno
190
        if not _internal:
191
            # XXX: Update this after 0.10 is released
192
            symbol_versioning.warn('Creating a RevisionSpec directly has'
193
                                   ' been deprecated in version 0.11. Use'
1948.4.33 by John Arbash Meinel
Switch from get_revision_spec() to RevisionSpec.from_string() (as advised by Martin)
194
                                   ' RevisionSpec.from_string()'
1948.4.27 by John Arbash Meinel
Deprecate calling RevisionSpec directly, and instead use a helper function. Also merge the old RevisionSpec_int class into RevisionSpec_revno
195
                                   ' instead.',
196
                                   DeprecationWarning, stacklevel=2)
197
        self.user_spec = spec
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
198
        if self.prefix and spec.startswith(self.prefix):
199
            spec = spec[len(self.prefix):]
200
        self.spec = spec
201
202
    def _match_on(self, branch, revs):
1948.4.27 by John Arbash Meinel
Deprecate calling RevisionSpec directly, and instead use a helper function. Also merge the old RevisionSpec_int class into RevisionSpec_revno
203
        trace.mutter('Returning RevisionSpec._match_on: None')
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
204
        return RevisionInfo(branch, 0, None)
205
206
    def _match_on_and_check(self, branch, revs):
207
        info = self._match_on(branch, revs)
208
        if info:
209
            return info
210
        elif info == (0, None):
211
            # special case - the empty tree
212
            return info
213
        elif self.prefix:
1948.4.27 by John Arbash Meinel
Deprecate calling RevisionSpec directly, and instead use a helper function. Also merge the old RevisionSpec_int class into RevisionSpec_revno
214
            raise errors.InvalidRevisionSpec(self.user_spec, branch)
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
215
        else:
1948.4.2 by John Arbash Meinel
Update _match_on_and_check to raise the right error
216
            raise errors.InvalidRevisionSpec(self.spec, branch)
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
217
218
    def in_history(self, branch):
1732.3.1 by Matthieu Moy
Implementation of -r revno:N:/path/to/branch
219
        if branch:
220
            revs = branch.revision_history()
221
        else:
1988.4.5 by Robert Collins
revisions can now be specified using dotted-decimal revision numbers.
222
            # this should never trigger.
223
            # TODO: make it a deprecated code path. RBC 20060928
1732.3.1 by Matthieu Moy
Implementation of -r revno:N:/path/to/branch
224
            revs = None
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
225
        return self._match_on_and_check(branch, revs)
226
1432 by Robert Collins
branch: namespace
227
        # FIXME: in_history is somewhat broken,
228
        # it will return non-history revisions in many
229
        # circumstances. The expected facility is that
230
        # in_history only returns revision-history revs,
231
        # in_store returns any rev. RBC 20051010
232
    # aliases for now, when we fix the core logic, then they
233
    # will do what you expect.
234
    in_store = in_history
235
    in_branch = in_store
236
        
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
237
    def __repr__(self):
238
        # 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/
239
        return '<%s %s>' % (self.__class__.__name__,
240
                              self.user_spec)
1881.1.1 by Matthieu Moy
Fixed and tested "bzr diff" outside a working tree.
241
    
1881.1.4 by Matthieu Moy
needs_tree -> needs_branch
242
    def needs_branch(self):
243
        """Whether this revision spec needs a branch.
244
1711.2.99 by John Arbash Meinel
minor typo fix
245
        Set this to False the branch argument of _match_on is not used.
246
        """
1881.1.1 by Matthieu Moy
Fixed and tested "bzr diff" outside a working tree.
247
        return True
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
248
1907.4.1 by Matthieu Moy
Fixed merge to work nicely with -r revno:N:path
249
    def get_branch(self):
250
        """When the revision specifier contains a branch location, return it.
251
        
252
        Otherwise, return None.
253
        """
254
        return None
255
1907.4.9 by Matthieu Moy
missing newline
256
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
257
# private API
258
259
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
260
    """Selects a revision using a number."""
261
262
    help_txt = """Selects a revision using a number.
2023.1.1 by ghigo
add topics help
263
264
    Use an integer to specify a revision in the history of the branch.
265
    Optionally a branch can be specified. The 'revno:' prefix is optional.
266
    A negative number will count from the end of the branch (-1 is the
267
    last revision, -2 the previous one). If the negative number is larger
268
    than the branch's history, the first revision is returned.
269
    examples:
270
      revno:1                   -> return the first revision
271
      revno:3:/path/to/branch   -> return the 3rd revision of
272
                                   the branch '/path/to/branch'
273
      revno:-1                  -> The last revision in a branch.
274
      -2:http://other/branch    -> The second to last revision in the
275
                                   remote branch.
276
      -1000000                  -> Most likely the first revision, unless
277
                                   your history is very long.
278
    """
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
279
    prefix = 'revno:'
280
281
    def _match_on(self, branch, revs):
282
        """Lookup a revision by revision number"""
1948.4.1 by John Arbash Meinel
Update number parsers to raise InvalidRevisionSpec. Update revno: itself so it supports negative numbers
283
        loc = self.spec.find(':')
284
        if loc == -1:
285
            revno_spec = self.spec
286
            branch_spec = None
287
        else:
288
            revno_spec = self.spec[:loc]
289
            branch_spec = self.spec[loc+1:]
290
291
        if revno_spec == '':
1948.4.6 by John Arbash Meinel
A small bugfix, and more tests for revno:
292
            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
293
                raise errors.InvalidRevisionSpec(self.user_spec,
1948.4.5 by John Arbash Meinel
Fix tests for negative entries, and add tests for revno:
294
                        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
295
            revno = None
296
        else:
297
            try:
298
                revno = int(revno_spec)
1988.4.5 by Robert Collins
revisions can now be specified using dotted-decimal revision numbers.
299
                dotted = False
300
            except ValueError:
301
                # dotted decimal. This arguably should not be here
302
                # but the from_string method is a little primitive 
303
                # right now - RBC 20060928
304
                try:
305
                    match_revno = tuple((int(number) for number in revno_spec.split('.')))
306
                except ValueError, e:
307
                    raise errors.InvalidRevisionSpec(self.user_spec, branch, e)
308
309
                dotted = True
1948.4.1 by John Arbash Meinel
Update number parsers to raise InvalidRevisionSpec. Update revno: itself so it supports negative numbers
310
1948.4.6 by John Arbash Meinel
A small bugfix, and more tests for revno:
311
        if branch_spec:
1988.4.5 by Robert Collins
revisions can now be specified using dotted-decimal revision numbers.
312
            # the user has override the branch to look in.
313
            # we need to refresh the revision_history map and
314
            # the branch object.
1948.4.1 by John Arbash Meinel
Update number parsers to raise InvalidRevisionSpec. Update revno: itself so it supports negative numbers
315
            from bzrlib.branch import Branch
316
            branch = Branch.open(branch_spec)
1948.4.22 by John Arbash Meinel
Refactor common code from integer revno handlers
317
            # Need to use a new revision history
318
            # because we are using a specific branch
319
            revs = branch.revision_history()
320
1988.4.5 by Robert Collins
revisions can now be specified using dotted-decimal revision numbers.
321
        if dotted:
322
            branch.lock_read()
323
            try:
324
                last_rev = branch.last_revision()
325
                merge_sorted_revisions = tsort.merge_sort(
326
                    branch.repository.get_revision_graph(last_rev),
327
                    last_rev,
328
                    generate_revno=True)
329
                def match(item):
330
                    return item[3] == match_revno
331
                revisions = filter(match, merge_sorted_revisions)
332
            finally:
333
                branch.unlock()
334
            if len(revisions) != 1:
335
                return RevisionInfo(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
336
            else:
1988.4.5 by Robert Collins
revisions can now be specified using dotted-decimal revision numbers.
337
                # there is no traditional 'revno' for dotted-decimal revnos.
338
                # so for  API compatability we return None.
339
                return RevisionInfo(branch, None, revisions[0][1])
340
        else:
341
            if revno < 0:
2249.4.2 by Wouter van Heyst
Convert callers of Branch.revision_history() to Branch.last_revision_info() where sensible.
342
                # if get_rev_id supported negative revnos, there would not be a
343
                # need for this special case.
1988.4.5 by Robert Collins
revisions can now be specified using dotted-decimal revision numbers.
344
                if (-revno) >= len(revs):
345
                    revno = 1
346
                else:
347
                    revno = len(revs) + revno + 1
348
            try:
349
                revision_id = branch.get_rev_id(revno, revs)
350
            except errors.NoSuchRevision:
351
                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
352
        return RevisionInfo(branch, revno, revision_id)
1881.1.1 by Matthieu Moy
Fixed and tested "bzr diff" outside a working tree.
353
        
1881.1.4 by Matthieu Moy
needs_tree -> needs_branch
354
    def needs_branch(self):
1881.1.1 by Matthieu Moy
Fixed and tested "bzr diff" outside a working tree.
355
        return self.spec.find(':') == -1
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
356
1907.4.1 by Matthieu Moy
Fixed merge to work nicely with -r revno:N:path
357
    def get_branch(self):
358
        if self.spec.find(':') == -1:
359
            return None
360
        else:
361
            return self.spec[self.spec.find(':')+1:]
362
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
363
# Old compatibility 
364
RevisionSpec_int = RevisionSpec_revno
365
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
366
SPEC_TYPES.append(RevisionSpec_revno)
367
368
369
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
370
    """Selects a revision using the revision id."""
371
372
    help_txt = """Selects a revision using the revision id.
2023.1.1 by ghigo
add topics help
373
374
    Supply a specific revision id, that can be used to specify any
375
    revision id in the ancestry of the branch. 
376
    Including merges, and pending merges.
377
    examples:
2070.4.7 by ghigo
Updates on the basis of the Richard Wilbur suggestions
378
      revid:aaaa@bbbb-123456789 -> Select revision 'aaaa@bbbb-123456789'
2023.1.1 by ghigo
add topics help
379
    """    
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
380
    prefix = 'revid:'
381
382
    def _match_on(self, branch, revs):
2325.2.5 by Marien Zwart
Call osutils.safe_revision_id instead of duplicating it.
383
        # self.spec comes straight from parsing the command line arguments,
384
        # so we expect it to be a Unicode string. Switch it to the internal
385
        # representation.
386
        revision_id = osutils.safe_revision_id(self.spec, warn=False)
2325.2.3 by Marien Zwart
Make the revid RevisionSpec also support utf8-encoded bytestrings.
387
        return RevisionInfo.from_revision_id(branch, revision_id, revs)
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
388
389
SPEC_TYPES.append(RevisionSpec_revid)
390
391
392
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
393
    """Selects the nth revision from the end."""
394
395
    help_txt = """Selects the nth revision from the end.
2023.1.1 by ghigo
add topics help
396
397
    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
398
    This is the same as supplying negative numbers to the 'revno:' spec.
2023.1.1 by ghigo
add topics help
399
    examples:
400
      last:1        -> return the last revision
401
      last:3        -> return the revision 2 before the end.
402
    """    
1185.1.39 by Robert Collins
Robey Pointers before: namespace to clear up usage of dates in revision parameters
403
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
404
    prefix = 'last:'
405
406
    def _match_on(self, branch, revs):
1948.4.9 by John Arbash Meinel
Cleanup and test last:
407
        if self.spec == '':
408
            if not revs:
1948.4.26 by John Arbash Meinel
Get rid of direct imports of exceptions
409
                raise errors.NoCommits(branch)
1948.4.9 by John Arbash Meinel
Cleanup and test last:
410
            return RevisionInfo(branch, len(revs), revs[-1])
411
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
412
        try:
413
            offset = int(self.spec)
1948.4.9 by John Arbash Meinel
Cleanup and test last:
414
        except ValueError, e:
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
415
            raise errors.InvalidRevisionSpec(self.user_spec, branch, e)
1948.4.9 by John Arbash Meinel
Cleanup and test last:
416
417
        if offset <= 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
418
            raise errors.InvalidRevisionSpec(self.user_spec, branch,
1948.4.9 by John Arbash Meinel
Cleanup and test last:
419
                                             'you must supply a positive value')
420
        revno = len(revs) - offset + 1
421
        try:
422
            revision_id = branch.get_rev_id(revno, revs)
423
        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
424
            raise errors.InvalidRevisionSpec(self.user_spec, branch)
1948.4.9 by John Arbash Meinel
Cleanup and test last:
425
        return RevisionInfo(branch, revno, revision_id)
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
426
427
SPEC_TYPES.append(RevisionSpec_last)
428
429
1185.1.39 by Robert Collins
Robey Pointers before: namespace to clear up usage of dates in revision parameters
430
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
431
    """Selects the parent of the revision specified."""
432
433
    help_txt = """Selects the parent of the revision specified.
2023.1.1 by ghigo
add topics help
434
435
    Supply any revision spec to return the parent of that revision.
436
    It is an error to request the parent of the null revision (before:0).
437
    This is mostly useful when inspecting revisions that are not in the
438
    revision history of a branch.
439
440
    examples:
441
      before:1913    -> Return the parent of revno 1913 (revno 1912)
442
      before:revid:aaaa@bbbb-1234567890  -> return the parent of revision
2070.4.7 by ghigo
Updates on the basis of the Richard Wilbur suggestions
443
                                            aaaa@bbbb-1234567890
2023.1.1 by ghigo
add topics help
444
      bzr diff -r before:revid:aaaa..revid:aaaa
445
            -> Find the changes between revision 'aaaa' and its parent.
446
               (what changes did 'aaaa' introduce)
447
    """
1185.1.39 by Robert Collins
Robey Pointers before: namespace to clear up usage of dates in revision parameters
448
449
    prefix = 'before:'
450
    
451
    def _match_on(self, branch, revs):
1948.4.33 by John Arbash Meinel
Switch from get_revision_spec() to RevisionSpec.from_string() (as advised by Martin)
452
        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
453
        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
454
            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
455
                                         'cannot go before the null: revision')
456
        if r.revno is None:
457
            # We need to use the repository history here
458
            rev = branch.repository.get_revision(r.rev_id)
459
            if not rev.parent_ids:
460
                revno = 0
461
                revision_id = None
462
            else:
463
                revision_id = rev.parent_ids[0]
464
                try:
465
                    revno = revs.index(revision_id) + 1
466
                except ValueError:
467
                    revno = None
468
        else:
469
            revno = r.revno - 1
470
            try:
471
                revision_id = branch.get_rev_id(revno, revs)
1948.4.26 by John Arbash Meinel
Get rid of direct imports of exceptions
472
            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
473
                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
474
                                                 branch)
475
        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
476
477
SPEC_TYPES.append(RevisionSpec_before)
478
479
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
480
class RevisionSpec_tag(RevisionSpec):
2220.2.3 by Martin Pool
Add tag: revision namespace.
481
    """Select a revision identified by tag name"""
482
483
    help_txt = """Selects a revision identified by a tag name.
484
485
    Tags are stored in the repository and created by the 'tag'
486
    command.
487
    """
2070.4.14 by John Arbash Meinel
Switch revisionspec to use the help defined as help_txt rather than the doc string
488
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
489
    prefix = 'tag:'
490
491
    def _match_on(self, branch, revs):
2220.2.3 by Martin Pool
Add tag: revision namespace.
492
        # Can raise tags not supported, NoSuchTag, etc
493
        return RevisionInfo.from_revision_id(branch,
2220.2.20 by Martin Pool
Tag methods now available through Branch.tags.add_tag, etc
494
            branch.tags.lookup_tag(self.spec),
2220.2.3 by Martin Pool
Add tag: revision namespace.
495
            revs)
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
496
497
SPEC_TYPES.append(RevisionSpec_tag)
498
499
1948.4.12 by John Arbash Meinel
Some tests for the date: spec
500
class _RevListToTimestamps(object):
501
    """This takes a list of revisions, and allows you to bisect by date"""
502
503
    __slots__ = ['revs', 'branch']
504
1688.2.2 by Guillaume Pinot
Binary search for 'date:' revision.
505
    def __init__(self, revs, branch):
506
        self.revs = revs
507
        self.branch = branch
1948.4.12 by John Arbash Meinel
Some tests for the date: spec
508
1688.2.2 by Guillaume Pinot
Binary search for 'date:' revision.
509
    def __getitem__(self, index):
1948.4.12 by John Arbash Meinel
Some tests for the date: spec
510
        """Get the date of the index'd item"""
1688.2.2 by Guillaume Pinot
Binary search for 'date:' revision.
511
        r = self.branch.repository.get_revision(self.revs[index])
512
        # TODO: Handle timezone.
513
        return datetime.datetime.fromtimestamp(r.timestamp)
1948.4.12 by John Arbash Meinel
Some tests for the date: spec
514
1688.2.2 by Guillaume Pinot
Binary search for 'date:' revision.
515
    def __len__(self):
516
        return len(self.revs)
517
518
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
519
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
520
    """Selects a revision on the basis of a datestamp."""
521
522
    help_txt = """Selects a revision on the basis of a datestamp.
2023.1.1 by ghigo
add topics help
523
524
    Supply a datestamp to select the first revision that matches the date.
525
    Date can be 'yesterday', 'today', 'tomorrow' or a YYYY-MM-DD string.
526
    Matches the first entry after a given date (either at midnight or
527
    at a specified time).
528
529
    One way to display all the changes since yesterday would be:
530
        bzr log -r date:yesterday..-1
531
532
    examples:
533
      date:yesterday            -> select the first revision since yesterday
534
      date:2006-08-14,17:10:14  -> select the first revision after
535
                                   August 14th, 2006 at 5:10pm.
536
    """    
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
537
    prefix = 'date:'
538
    _date_re = re.compile(
539
            r'(?P<date>(?P<year>\d\d\d\d)-(?P<month>\d\d)-(?P<day>\d\d))?'
540
            r'(,|T)?\s*'
541
            r'(?P<time>(?P<hour>\d\d):(?P<minute>\d\d)(:(?P<second>\d\d))?)?'
542
        )
543
544
    def _match_on(self, branch, revs):
2023.1.1 by ghigo
add topics help
545
        """Spec for date revisions:
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
546
          date:value
547
          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
548
          matches the first entry after a given date (either at midnight or
549
          at a specified time).
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
550
        """
2070.4.3 by John Arbash Meinel
code and doc cleanup
551
        #  XXX: This doesn't actually work
552
        #  So the proper way of saying 'give me all entries for today' is:
553
        #      -r date:yesterday..date:today
1185.1.39 by Robert Collins
Robey Pointers before: namespace to clear up usage of dates in revision parameters
554
        today = datetime.datetime.fromordinal(datetime.date.today().toordinal())
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
555
        if self.spec.lower() == 'yesterday':
556
            dt = today - datetime.timedelta(days=1)
557
        elif self.spec.lower() == 'today':
558
            dt = today
559
        elif self.spec.lower() == 'tomorrow':
560
            dt = today + datetime.timedelta(days=1)
561
        else:
562
            m = self._date_re.match(self.spec)
563
            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
564
                raise errors.InvalidRevisionSpec(self.user_spec,
1948.4.12 by John Arbash Meinel
Some tests for the date: spec
565
                                                 branch, 'invalid date')
566
567
            try:
568
                if m.group('date'):
569
                    year = int(m.group('year'))
570
                    month = int(m.group('month'))
571
                    day = int(m.group('day'))
572
                else:
573
                    year = today.year
574
                    month = today.month
575
                    day = today.day
576
577
                if m.group('time'):
578
                    hour = int(m.group('hour'))
579
                    minute = int(m.group('minute'))
580
                    if m.group('second'):
581
                        second = int(m.group('second'))
582
                    else:
583
                        second = 0
584
                else:
585
                    hour, minute, second = 0,0,0
586
            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
587
                raise errors.InvalidRevisionSpec(self.user_spec,
1948.4.12 by John Arbash Meinel
Some tests for the date: spec
588
                                                 branch, 'invalid date')
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
589
590
            dt = datetime.datetime(year=year, month=month, day=day,
591
                    hour=hour, minute=minute, second=second)
1704.2.27 by Martin Pool
Run bisection search for revision date with lock held. (Robert Widhopf-Frenk)
592
        branch.lock_read()
593
        try:
1948.4.12 by John Arbash Meinel
Some tests for the date: spec
594
            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)
595
        finally:
596
            branch.unlock()
1688.2.2 by Guillaume Pinot
Binary search for 'date:' revision.
597
        if rev == len(revs):
598
            return RevisionInfo(branch, None)
599
        else:
600
            return RevisionInfo(branch, rev + 1)
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
601
602
SPEC_TYPES.append(RevisionSpec_date)
603
604
605
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
606
    """Selects a common ancestor with a second branch."""
607
608
    help_txt = """Selects a common ancestor with a second branch.
2023.1.1 by ghigo
add topics help
609
610
    Supply the path to a branch to select the common ancestor.
611
612
    The common ancestor is the last revision that existed in both
613
    branches. Usually this is the branch point, but it could also be
614
    a revision that was merged.
615
616
    This is frequently used with 'diff' to return all of the changes
617
    that your branch introduces, while excluding the changes that you
618
    have not merged from the remote branch.
619
620
    examples:
621
      ancestor:/path/to/branch
2070.4.7 by ghigo
Updates on the basis of the Richard Wilbur suggestions
622
      $ bzr diff -r ancestor:../../mainline/branch
2023.1.1 by ghigo
add topics help
623
    """
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
624
    prefix = 'ancestor:'
625
626
    def _match_on(self, branch, revs):
1948.4.16 by John Arbash Meinel
Move the tests into the associated tester, remove redundant tests, some small PEP8 changes
627
        from bzrlib.branch import Branch
1948.4.18 by John Arbash Meinel
Update branch: spec and tests
628
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
629
        trace.mutter('matching ancestor: on: %s, %s', self.spec, branch)
1948.4.17 by John Arbash Meinel
Update tests for ancestor: spec
630
        other_branch = Branch.open(self.spec)
1390 by Robert Collins
pair programming worx... merge integration and weave
631
        revision_a = branch.last_revision()
632
        revision_b = other_branch.last_revision()
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
633
        for r, b in ((revision_a, branch), (revision_b, other_branch)):
1948.4.18 by John Arbash Meinel
Update branch: spec and tests
634
            if r in (None, revision.NULL_REVISION):
1948.4.26 by John Arbash Meinel
Get rid of direct imports of exceptions
635
                raise errors.NoCommits(b)
1948.4.18 by John Arbash Meinel
Update branch: spec and tests
636
        revision_source = revision.MultipleRevisionSources(
637
                branch.repository, other_branch.repository)
638
        rev_id = revision.common_ancestor(revision_a, revision_b,
639
                                          revision_source)
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
640
        try:
641
            revno = branch.revision_id_to_revno(rev_id)
1948.4.26 by John Arbash Meinel
Get rid of direct imports of exceptions
642
        except errors.NoSuchRevision:
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
643
            revno = None
644
        return RevisionInfo(branch, revno, rev_id)
645
        
646
SPEC_TYPES.append(RevisionSpec_ancestor)
1432 by Robert Collins
branch: namespace
647
1948.4.16 by John Arbash Meinel
Move the tests into the associated tester, remove redundant tests, some small PEP8 changes
648
1432 by Robert Collins
branch: namespace
649
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
650
    """Selects the last revision of a specified branch."""
651
652
    help_txt = """Selects the last revision of a specified branch.
2023.1.1 by ghigo
add topics help
653
654
    Supply the path to a branch to select its last revision.
655
656
    examples:
657
      branch:/path/to/branch
1432 by Robert Collins
branch: namespace
658
    """
659
    prefix = 'branch:'
660
661
    def _match_on(self, branch, revs):
1948.4.18 by John Arbash Meinel
Update branch: spec and tests
662
        from bzrlib.branch import Branch
663
        other_branch = Branch.open(self.spec)
1432 by Robert Collins
branch: namespace
664
        revision_b = other_branch.last_revision()
1948.4.18 by John Arbash Meinel
Update branch: spec and tests
665
        if revision_b in (None, revision.NULL_REVISION):
1948.4.26 by John Arbash Meinel
Get rid of direct imports of exceptions
666
            raise errors.NoCommits(other_branch)
1432 by Robert Collins
branch: namespace
667
        # 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.
668
        branch.fetch(other_branch, revision_b)
1432 by Robert Collins
branch: namespace
669
        try:
670
            revno = branch.revision_id_to_revno(revision_b)
1948.4.26 by John Arbash Meinel
Get rid of direct imports of exceptions
671
        except errors.NoSuchRevision:
1432 by Robert Collins
branch: namespace
672
            revno = None
673
        return RevisionInfo(branch, revno, revision_b)
674
        
675
SPEC_TYPES.append(RevisionSpec_branch)