~bzr-pqm/bzr/bzr.dev

5752.3.8 by John Arbash Meinel
Merge bzr.dev 5764 to resolve release-notes (aka NEWS) conflicts
1
# Copyright (C) 2005-2011 Canonical Ltd
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
2
#
369 by Martin Pool
- Split out log printing into new show_log function
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
#
369 by Martin Pool
- Split out log printing into new show_log function
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
#
369 by Martin Pool
- Split out log printing into new show_log function
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
4183.7.1 by Sabin Iacob
update FSF mailing address
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
369 by Martin Pool
- Split out log printing into new show_log function
16
375 by Martin Pool
- New command touching-revisions and function to trace
17
18
527 by Martin Pool
- refactor log command
19
"""Code to show logs of changes.
20
21
Various flavors of log can be produced:
22
23
* for one file, or the whole tree, and (not done yet) for
24
  files in a given directory
25
26
* in "verbose" mode with a description of what changed from one
27
  version to the next
28
29
* with file-ids and revision-ids shown
30
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
31
Logs are actually written out through an abstract LogFormatter
32
interface, which allows for different preferred formats.  Plugins can
33
register formats too.
34
35
Logs can be produced in either forward (oldest->newest) or reverse
36
(newest->oldest) order.
37
38
Logs can be filtered to show only revisions matching a particular
39
search string, or within a particular range of revisions.  The range
40
can be given as date/times, which are reduced to revisions before
41
calling in here.
42
43
In verbose mode we show a summary of what changed in each particular
44
revision.  Note that this is the delta for changes in that revision
2466.12.2 by Kent Gibson
shift log output with only merge revisions to the left margin
45
relative to its left-most parent, not the delta relative to the last
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
46
logged revision.  So for example if you ask for a verbose log of
47
changes touching hello.c you will get a list of those revisions also
48
listing other things that were changed in the same revision, but not
49
all the changes since the previous revision that touched hello.c.
527 by Martin Pool
- refactor log command
50
"""
51
2997.1.2 by Kent Gibson
Move all imports to top of log.py
52
import codecs
3943.5.1 by Ian Clatworthy
first cut at log --show-diff
53
from cStringIO import StringIO
2997.1.2 by Kent Gibson
Move all imports to top of log.py
54
from itertools import (
3936.3.32 by Ian Clatworthy
always delay merge graph generation until necessary
55
    chain,
2997.1.2 by Kent Gibson
Move all imports to top of log.py
56
    izip,
57
    )
1624.1.3 by Robert Collins
Convert log to use the new tsort.merge_sort routine.
58
import re
2997.1.2 by Kent Gibson
Move all imports to top of log.py
59
import sys
60
from warnings import (
61
    warn,
62
    )
1185.33.41 by Martin Pool
Fix regression of 'bzr log -v' - it wasn't showing changed files at all. (#4676)
63
3224.5.1 by Andrew Bennetts
Lots of assorted hackery to reduce the number of imports for common operations. Improves 'rocks', 'st' and 'help' times by ~50ms on my laptop.
64
from bzrlib.lazy_import import lazy_import
65
lazy_import(globals(), """
3535.5.1 by John Arbash Meinel
cleanup a few imports to be lazily loaded.
66
3224.5.1 by Andrew Bennetts
Lots of assorted hackery to reduce the number of imports for common operations. Improves 'rocks', 'st' and 'help' times by ~50ms on my laptop.
67
from bzrlib import (
4202.2.1 by Ian Clatworthy
get directory logging working again
68
    bzrdir,
3063.3.2 by Lukáš Lalinský
Move the name and e-mail address extraction logic to config.parse_username.
69
    config,
3943.5.1 by Ian Clatworthy
first cut at log --show-diff
70
    diff,
3224.5.1 by Andrew Bennetts
Lots of assorted hackery to reduce the number of imports for common operations. Improves 'rocks', 'st' and 'help' times by ~50ms on my laptop.
71
    errors,
4393.1.2 by Jelmer Vernooij
Move showing of foreign revision info onto log, for better performance.
72
    foreign,
3535.5.1 by John Arbash Meinel
cleanup a few imports to be lazily loaded.
73
    repository as _mod_repository,
74
    revision as _mod_revision,
3224.5.1 by Andrew Bennetts
Lots of assorted hackery to reduce the number of imports for common operations. Improves 'rocks', 'st' and 'help' times by ~50ms on my laptop.
75
    revisionspec,
76
    tsort,
5971.1.48 by Jonathan Riddell
i18n the signature message
77
    i18n,
3224.5.1 by Andrew Bennetts
Lots of assorted hackery to reduce the number of imports for common operations. Improves 'rocks', 'st' and 'help' times by ~50ms on my laptop.
78
    )
79
""")
80
3535.5.1 by John Arbash Meinel
cleanup a few imports to be lazily loaded.
81
from bzrlib import (
5967.9.4 by Martin Pool
log filtering also explicitly needs a lazy_regex
82
    lazy_regex,
2221.4.10 by Aaron Bentley
Implement log options using RegistryOption
83
    registry,
2997.1.2 by Kent Gibson
Move all imports to top of log.py
84
    )
85
from bzrlib.osutils import (
86
    format_date,
4379.4.1 by Ian Clatworthy
make log --long faster
87
    format_date_with_offset_in_original_timezone,
5753.2.2 by Jelmer Vernooij
Remove some unnecessary imports, clean up lazy imports.
88
    get_diff_header_encoding,
2997.1.3 by Alexander Belchenko
file wrapper around stdout should use terminal encoding, not user_encoding.
89
    get_terminal_encoding,
2997.1.2 by Kent Gibson
Move all imports to top of log.py
90
    terminal_width,
91
    )
4955.4.5 by Vincent Ladeuil
Start reproducing the problems reported in the bug.
92
from bzrlib.symbol_versioning import (
93
    deprecated_function,
94
    deprecated_in,
95
    )
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
96
375 by Martin Pool
- New command touching-revisions and function to trace
97
98
def find_touching_revisions(branch, file_id):
99
    """Yield a description of revisions which affect the file_id.
100
101
    Each returned element is (revno, revision_id, description)
102
103
    This is the list of revisions where the file is either added,
104
    modified, renamed or deleted.
105
106
    TODO: Perhaps some way to limit this to only particular revisions,
522 by Martin Pool
todo
107
    or to traverse a non-mainline set of revisions?
375 by Martin Pool
- New command touching-revisions and function to trace
108
    """
109
    last_ie = None
110
    last_path = None
111
    revno = 1
112
    for revision_id in branch.revision_history():
5035.3.1 by Jelmer Vernooij
Remove Repository.get_revision_inventory.
113
        this_inv = branch.repository.get_inventory(revision_id)
5967.7.3 by Martin Pool
Fix up additional callers that count on inventory.__contains__
114
        if this_inv.has_id(file_id):
375 by Martin Pool
- New command touching-revisions and function to trace
115
            this_ie = this_inv[file_id]
116
            this_path = this_inv.id2path(file_id)
117
        else:
118
            this_ie = this_path = None
119
120
        # now we know how it was last time, and how it is in this revision.
121
        # are those two states effectively the same or not?
122
123
        if not this_ie and not last_ie:
124
            # not present in either
125
            pass
126
        elif this_ie and not last_ie:
127
            yield revno, revision_id, "added " + this_path
128
        elif not this_ie and last_ie:
129
            # deleted here
130
            yield revno, revision_id, "deleted " + last_path
131
        elif this_path != last_path:
132
            yield revno, revision_id, ("renamed %s => %s" % (last_path, this_path))
133
        elif (this_ie.text_size != last_ie.text_size
134
              or this_ie.text_sha1 != last_ie.text_sha1):
135
            yield revno, revision_id, "modified " + this_path
136
137
        last_ie = this_ie
138
        last_path = this_path
139
        revno += 1
140
141
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
142
def _enumerate_history(branch):
143
    rh = []
144
    revno = 1
145
    for rev_id in branch.revision_history():
146
        rh.append((revno, rev_id))
147
        revno += 1
148
    return rh
149
150
4202.2.3 by Ian Clatworthy
replace show_log_request with a Logger class
151
def show_log(branch,
152
             lf,
153
             specific_fileid=None,
154
             verbose=False,
155
             direction='reverse',
156
             start_revision=None,
157
             end_revision=None,
158
             search=None,
159
             limit=None,
160
             show_diff=False):
161
    """Write out human-readable log of commits to this branch.
162
163
    This function is being retained for backwards compatibility but
164
    should not be extended with new parameters. Use the new Logger class
165
    instead, eg. Logger(branch, rqst).show(lf), adding parameters to the
4205.1.1 by Ian Clatworthy
log multiple files and directories (Ian Clatworthy)
166
    make_log_request_dict function.
4202.2.3 by Ian Clatworthy
replace show_log_request with a Logger class
167
168
    :param lf: The LogFormatter object showing the output.
169
170
    :param specific_fileid: If not None, list only the commits affecting the
171
        specified file, rather than all commits.
172
173
    :param verbose: If True show added/changed/deleted/renamed files.
174
175
    :param direction: 'reverse' (default) is latest to earliest; 'forward' is
176
        earliest to latest.
177
178
    :param start_revision: If not None, only show revisions >= start_revision
179
180
    :param end_revision: If not None, only show revisions <= end_revision
181
182
    :param search: If not None, only show revisions with matching commit
183
        messages
184
185
    :param limit: If set, shows only 'limit' revisions, all revisions are shown
186
        if None or 0.
187
188
    :param show_diff: If True, output a diff after each revision.
189
    """
190
    # Convert old-style parameters to new-style parameters
191
    if specific_fileid is not None:
192
        file_ids = [specific_fileid]
193
    else:
194
        file_ids = None
195
    if verbose:
196
        if file_ids:
197
            delta_type = 'partial'
198
        else:
199
            delta_type = 'full'
200
    else:
201
        delta_type = None
202
    if show_diff:
203
        if file_ids:
204
            diff_type = 'partial'
205
        else:
206
            diff_type = 'full'
207
    else:
208
        diff_type = None
209
210
    # Build the request and execute it
4202.2.5 by Ian Clatworthy
apply review tweaks & update help
211
    rqst = make_log_request_dict(direction=direction, specific_fileids=file_ids,
4202.2.3 by Ian Clatworthy
replace show_log_request with a Logger class
212
        start_revision=start_revision, end_revision=end_revision,
213
        limit=limit, message_search=search,
214
        delta_type=delta_type, diff_type=diff_type)
215
    Logger(branch, rqst).show(lf)
216
217
4202.2.5 by Ian Clatworthy
apply review tweaks & update help
218
# Note: This needs to be kept this in sync with the defaults in
219
# make_log_request_dict() below
220
_DEFAULT_REQUEST_PARAMS = {
221
    'direction': 'reverse',
222
    'levels': 1,
223
    'generate_tags': True,
5097.1.12 by Vincent Ladeuil
Implement the --exclude-common-ancestry log option.
224
    'exclude_common_ancestry': False,
4202.2.5 by Ian Clatworthy
apply review tweaks & update help
225
    '_match_using_deltas': True,
226
    }
227
228
229
def make_log_request_dict(direction='reverse', specific_fileids=None,
5097.1.12 by Vincent Ladeuil
Implement the --exclude-common-ancestry log option.
230
                          start_revision=None, end_revision=None, limit=None,
231
                          message_search=None, levels=1, generate_tags=True,
232
                          delta_type=None,
233
                          diff_type=None, _match_using_deltas=True,
234
                          exclude_common_ancestry=False,
5971.1.39 by Jonathan Riddell
add signature verification to log option, alas breaks write lock
235
                          signature=False,
5097.1.12 by Vincent Ladeuil
Implement the --exclude-common-ancestry log option.
236
                          ):
4202.2.5 by Ian Clatworthy
apply review tweaks & update help
237
    """Convenience function for making a logging request dictionary.
238
239
    Using this function may make code slightly safer by ensuring
240
    parameters have the correct names. It also provides a reference
241
    point for documenting the supported parameters.
242
243
    :param direction: 'reverse' (default) is latest to earliest;
244
      'forward' is earliest to latest.
245
246
    :param specific_fileids: If not None, only include revisions
247
      affecting the specified files, rather than all revisions.
248
249
    :param start_revision: If not None, only generate
250
      revisions >= start_revision
251
252
    :param end_revision: If not None, only generate
253
      revisions <= end_revision
254
255
    :param limit: If set, generate only 'limit' revisions, all revisions
256
      are shown if None or 0.
257
258
    :param message_search: If not None, only include revisions with
259
      matching commit messages
260
261
    :param levels: the number of levels of revisions to
262
      generate; 1 for just the mainline; 0 for all levels.
263
264
    :param generate_tags: If True, include tags for matched revisions.
5971.1.39 by Jonathan Riddell
add signature verification to log option, alas breaks write lock
265
`
4202.2.5 by Ian Clatworthy
apply review tweaks & update help
266
    :param delta_type: Either 'full', 'partial' or None.
267
      'full' means generate the complete delta - adds/deletes/modifies/etc;
268
      'partial' means filter the delta using specific_fileids;
269
      None means do not generate any delta.
270
271
    :param diff_type: Either 'full', 'partial' or None.
272
      'full' means generate the complete diff - adds/deletes/modifies/etc;
273
      'partial' means filter the diff using specific_fileids;
274
      None means do not generate any diff.
275
276
    :param _match_using_deltas: a private parameter controlling the
277
      algorithm used for matching specific_fileids. This parameter
278
      may be removed in the future so bzrlib client code should NOT
279
      use it.
5097.1.12 by Vincent Ladeuil
Implement the --exclude-common-ancestry log option.
280
281
    :param exclude_common_ancestry: Whether -rX..Y should be interpreted as a
282
      range operator or as a graph difference.
5971.1.39 by Jonathan Riddell
add signature verification to log option, alas breaks write lock
283
284
    :param signature: show digital signature information
4202.2.5 by Ian Clatworthy
apply review tweaks & update help
285
    """
286
    return {
287
        'direction': direction,
288
        'specific_fileids': specific_fileids,
289
        'start_revision': start_revision,
290
        'end_revision': end_revision,
291
        'limit': limit,
292
        'message_search': message_search,
293
        'levels': levels,
294
        'generate_tags': generate_tags,
295
        'delta_type': delta_type,
296
        'diff_type': diff_type,
5097.1.12 by Vincent Ladeuil
Implement the --exclude-common-ancestry log option.
297
        'exclude_common_ancestry': exclude_common_ancestry,
5971.1.39 by Jonathan Riddell
add signature verification to log option, alas breaks write lock
298
        'signature': signature,
4202.2.1 by Ian Clatworthy
get directory logging working again
299
        # Add 'private' attributes for features that may be deprecated
4202.2.5 by Ian Clatworthy
apply review tweaks & update help
300
        '_match_using_deltas': _match_using_deltas,
301
    }
302
303
304
def _apply_log_request_defaults(rqst):
305
    """Apply default values to a request dictionary."""
5753.3.1 by Andrew Bennetts
Quick fix for an obvious glitch in bzrlib.log: _DEFAULT_REQUEST_PARAMS was being mutated accidentally.
306
    result = _DEFAULT_REQUEST_PARAMS.copy()
4202.2.5 by Ian Clatworthy
apply review tweaks & update help
307
    if rqst:
308
        result.update(rqst)
309
    return result
4202.2.1 by Ian Clatworthy
get directory logging working again
310
311
5971.1.54 by Jonathan Riddell
make format_signature_validity() global for use by qbzr
312
def format_signature_validity(rev_id, repo):
313
    """get the signature validity
314
    
315
    :param rev_id: revision id to validate
316
    :param repo: repository of revision
317
    :return: human readable string to print to log
318
    """
319
    from bzrlib import gpg
320
321
    gpg_strategy = gpg.GPGStrategy(None)
322
    result = repo.verify_revision(rev_id, gpg_strategy)
323
    if result[0] == gpg.SIGNATURE_VALID:
5971.1.78 by Jonathan Riddell
apparantly we have no translation support
324
        return "valid signature from {0}".format(result[1])
5971.1.54 by Jonathan Riddell
make format_signature_validity() global for use by qbzr
325
    if result[0] == gpg.SIGNATURE_KEY_MISSING:
5971.1.78 by Jonathan Riddell
apparantly we have no translation support
326
        return "unknown key {0}".format(result[1])
5971.1.54 by Jonathan Riddell
make format_signature_validity() global for use by qbzr
327
    if result[0] == gpg.SIGNATURE_NOT_VALID:
5971.1.78 by Jonathan Riddell
apparantly we have no translation support
328
        return "invalid signature!"
5971.1.54 by Jonathan Riddell
make format_signature_validity() global for use by qbzr
329
    if result[0] == gpg.SIGNATURE_NOT_SIGNED:
5971.1.78 by Jonathan Riddell
apparantly we have no translation support
330
        return "no signature"
5971.1.54 by Jonathan Riddell
make format_signature_validity() global for use by qbzr
331
332
4202.2.3 by Ian Clatworthy
replace show_log_request with a Logger class
333
class LogGenerator(object):
334
    """A generator of log revisions."""
335
336
    def iter_log_revisions(self):
337
        """Iterate over LogRevision objects.
338
339
        :return: An iterator yielding LogRevision objects.
340
        """
341
        raise NotImplementedError(self.iter_log_revisions)
342
343
344
class Logger(object):
4955.5.3 by Vincent Ladeuil
Cleanup.
345
    """An object that generates, formats and displays a log."""
4202.2.3 by Ian Clatworthy
replace show_log_request with a Logger class
346
347
    def __init__(self, branch, rqst):
348
        """Create a Logger.
349
350
        :param branch: the branch to log
4202.2.5 by Ian Clatworthy
apply review tweaks & update help
351
        :param rqst: A dictionary specifying the query parameters.
352
          See make_log_request_dict() for supported values.
4202.2.3 by Ian Clatworthy
replace show_log_request with a Logger class
353
        """
354
        self.branch = branch
4202.2.5 by Ian Clatworthy
apply review tweaks & update help
355
        self.rqst = _apply_log_request_defaults(rqst)
4202.2.3 by Ian Clatworthy
replace show_log_request with a Logger class
356
357
    def show(self, lf):
358
        """Display the log.
359
360
        :param lf: The LogFormatter object to send the output to.
361
        """
362
        if not isinstance(lf, LogFormatter):
363
            warn("not a LogFormatter instance: %r" % lf)
364
365
        self.branch.lock_read()
366
        try:
367
            if getattr(lf, 'begin_log', None):
368
                lf.begin_log()
369
            self._show_body(lf)
370
            if getattr(lf, 'end_log', None):
371
                lf.end_log()
372
        finally:
373
            self.branch.unlock()
374
375
    def _show_body(self, lf):
376
        """Show the main log output.
377
378
        Subclasses may wish to override this.
379
        """
380
        # Tweak the LogRequest based on what the LogFormatter can handle.
381
        # (There's no point generating stuff if the formatter can't display it.)
382
        rqst = self.rqst
4202.2.5 by Ian Clatworthy
apply review tweaks & update help
383
        rqst['levels'] = lf.get_levels()
4202.2.3 by Ian Clatworthy
replace show_log_request with a Logger class
384
        if not getattr(lf, 'supports_tags', False):
4202.2.5 by Ian Clatworthy
apply review tweaks & update help
385
            rqst['generate_tags'] = False
4202.2.3 by Ian Clatworthy
replace show_log_request with a Logger class
386
        if not getattr(lf, 'supports_delta', False):
4202.2.5 by Ian Clatworthy
apply review tweaks & update help
387
            rqst['delta_type'] = None
4202.2.3 by Ian Clatworthy
replace show_log_request with a Logger class
388
        if not getattr(lf, 'supports_diff', False):
4202.2.5 by Ian Clatworthy
apply review tweaks & update help
389
            rqst['diff_type'] = None
5971.1.39 by Jonathan Riddell
add signature verification to log option, alas breaks write lock
390
        if not getattr(lf, 'supports_signatures', False):
391
            rqst['signature'] = False
4202.2.3 by Ian Clatworthy
replace show_log_request with a Logger class
392
393
        # Find and print the interesting revisions
394
        generator = self._generator_factory(self.branch, rqst)
395
        for lr in generator.iter_log_revisions():
396
            lf.log_revision(lr)
4208.2.1 by Ian Clatworthy
merge indicators in log --long
397
        lf.show_advice()
4202.2.3 by Ian Clatworthy
replace show_log_request with a Logger class
398
399
    def _generator_factory(self, branch, rqst):
400
        """Make the LogGenerator object to use.
401
        
402
        Subclasses may wish to override this.
403
        """
404
        return _DefaultLogGenerator(branch, rqst)
3943.5.2 by Ian Clatworthy
hand control of diff formatting to the log formatter
405
406
3936.3.36 by Ian Clatworthy
minor comment polish & refactoring
407
class _StartNotLinearAncestor(Exception):
408
    """Raised when a start revision is not found walking left-hand history."""
409
410
4202.2.5 by Ian Clatworthy
apply review tweaks & update help
411
class _DefaultLogGenerator(LogGenerator):
412
    """The default generator of log revisions."""
4202.2.1 by Ian Clatworthy
get directory logging working again
413
414
    def __init__(self, branch, rqst):
415
        self.branch = branch
416
        self.rqst = rqst
4202.2.5 by Ian Clatworthy
apply review tweaks & update help
417
        if rqst.get('generate_tags') and branch.supports_tags():
4202.2.1 by Ian Clatworthy
get directory logging working again
418
            self.rev_tag_dict = branch.tags.get_reverse_tag_dict()
419
        else:
420
            self.rev_tag_dict = {}
421
422
    def iter_log_revisions(self):
423
        """Iterate over LogRevision objects.
424
425
        :return: An iterator yielding LogRevision objects.
426
        """
427
        rqst = self.rqst
4379.4.1 by Ian Clatworthy
make log --long faster
428
        levels = rqst.get('levels')
429
        limit = rqst.get('limit')
430
        diff_type = rqst.get('diff_type')
5971.1.39 by Jonathan Riddell
add signature verification to log option, alas breaks write lock
431
        show_signature = rqst.get('signature')
4202.2.1 by Ian Clatworthy
get directory logging working again
432
        log_count = 0
433
        revision_iterator = self._create_log_revision_iterator()
434
        for revs in revision_iterator:
435
            for (rev_id, revno, merge_depth), rev, delta in revs:
436
                # 0 levels means show everything; merge_depth counts from 0
4202.2.5 by Ian Clatworthy
apply review tweaks & update help
437
                if levels != 0 and merge_depth >= levels:
4202.2.1 by Ian Clatworthy
get directory logging working again
438
                    continue
4379.4.1 by Ian Clatworthy
make log --long faster
439
                if diff_type is None:
440
                    diff = None
441
                else:
442
                    diff = self._format_diff(rev, rev_id, diff_type)
5971.1.39 by Jonathan Riddell
add signature verification to log option, alas breaks write lock
443
                if show_signature:
5971.1.54 by Jonathan Riddell
make format_signature_validity() global for use by qbzr
444
                    signature = format_signature_validity(rev_id,
445
                                                self.branch.repository)
5971.1.39 by Jonathan Riddell
add signature verification to log option, alas breaks write lock
446
                else:
447
                    signature = None
4202.2.1 by Ian Clatworthy
get directory logging working again
448
                yield LogRevision(rev, revno, merge_depth, delta,
5971.1.39 by Jonathan Riddell
add signature verification to log option, alas breaks write lock
449
                    self.rev_tag_dict.get(rev_id), diff, signature)
4202.2.5 by Ian Clatworthy
apply review tweaks & update help
450
                if limit:
4202.2.1 by Ian Clatworthy
get directory logging working again
451
                    log_count += 1
4202.2.5 by Ian Clatworthy
apply review tweaks & update help
452
                    if log_count >= limit:
4202.2.1 by Ian Clatworthy
get directory logging working again
453
                        return
454
4379.4.1 by Ian Clatworthy
make log --long faster
455
    def _format_diff(self, rev, rev_id, diff_type):
4202.2.1 by Ian Clatworthy
get directory logging working again
456
        repo = self.branch.repository
457
        if len(rev.parent_ids) == 0:
458
            ancestor_id = _mod_revision.NULL_REVISION
459
        else:
460
            ancestor_id = rev.parent_ids[0]
461
        tree_1 = repo.revision_tree(ancestor_id)
462
        tree_2 = repo.revision_tree(rev_id)
4202.2.5 by Ian Clatworthy
apply review tweaks & update help
463
        file_ids = self.rqst.get('specific_fileids')
4202.2.1 by Ian Clatworthy
get directory logging working again
464
        if diff_type == 'partial' and file_ids is not None:
465
            specific_files = [tree_2.id2path(id) for id in file_ids]
466
        else:
467
            specific_files = None
468
        s = StringIO()
5753.2.2 by Jelmer Vernooij
Remove some unnecessary imports, clean up lazy imports.
469
        path_encoding = get_diff_header_encoding()
4202.2.1 by Ian Clatworthy
get directory logging working again
470
        diff.show_diff_trees(tree_1, tree_2, s, specific_files, old_label='',
4797.57.9 by Alexander Belchenko
using terminal_encoding for log -p
471
            new_label='', path_encoding=path_encoding)
4202.2.1 by Ian Clatworthy
get directory logging working again
472
        return s.getvalue()
473
474
    def _create_log_revision_iterator(self):
475
        """Create a revision iterator for log.
476
477
        :return: An iterator over lists of ((rev_id, revno, merge_depth), rev,
478
            delta).
479
        """
480
        self.start_rev_id, self.end_rev_id = _get_revision_limits(
4202.2.5 by Ian Clatworthy
apply review tweaks & update help
481
            self.branch, self.rqst.get('start_revision'),
482
            self.rqst.get('end_revision'))
483
        if self.rqst.get('_match_using_deltas'):
4202.2.1 by Ian Clatworthy
get directory logging working again
484
            return self._log_revision_iterator_using_delta_matching()
485
        else:
486
            # We're using the per-file-graph algorithm. This scales really
487
            # well but only makes sense if there is a single file and it's
488
            # not a directory
4202.2.5 by Ian Clatworthy
apply review tweaks & update help
489
            file_count = len(self.rqst.get('specific_fileids'))
4202.2.1 by Ian Clatworthy
get directory logging working again
490
            if file_count != 1:
491
                raise BzrError("illegal LogRequest: must match-using-deltas "
492
                    "when logging %d files" % file_count)
493
            return self._log_revision_iterator_using_per_file_graph()
494
495
    def _log_revision_iterator_using_delta_matching(self):
496
        # Get the base revisions, filtering by the revision range
497
        rqst = self.rqst
4202.2.5 by Ian Clatworthy
apply review tweaks & update help
498
        generate_merge_revisions = rqst.get('levels') != 1
499
        delayed_graph_generation = not rqst.get('specific_fileids') and (
500
                rqst.get('limit') or self.start_rev_id or self.end_rev_id)
5097.1.12 by Vincent Ladeuil
Implement the --exclude-common-ancestry log option.
501
        view_revisions = _calc_view_revisions(
502
            self.branch, self.start_rev_id, self.end_rev_id,
503
            rqst.get('direction'),
504
            generate_merge_revisions=generate_merge_revisions,
505
            delayed_graph_generation=delayed_graph_generation,
506
            exclude_common_ancestry=rqst.get('exclude_common_ancestry'))
4202.2.1 by Ian Clatworthy
get directory logging working again
507
508
        # Apply the other filters
509
        return make_log_rev_iterator(self.branch, view_revisions,
4202.2.5 by Ian Clatworthy
apply review tweaks & update help
510
            rqst.get('delta_type'), rqst.get('message_search'),
511
            file_ids=rqst.get('specific_fileids'),
512
            direction=rqst.get('direction'))
4202.2.1 by Ian Clatworthy
get directory logging working again
513
514
    def _log_revision_iterator_using_per_file_graph(self):
515
        # Get the base revisions, filtering by the revision range.
516
        # Note that we always generate the merge revisions because
517
        # filter_revisions_touching_file_id() requires them ...
518
        rqst = self.rqst
5097.1.12 by Vincent Ladeuil
Implement the --exclude-common-ancestry log option.
519
        view_revisions = _calc_view_revisions(
520
            self.branch, self.start_rev_id, self.end_rev_id,
521
            rqst.get('direction'), generate_merge_revisions=True,
522
            exclude_common_ancestry=rqst.get('exclude_common_ancestry'))
3936.3.37 by Ian Clatworthy
selectively delay graph generation, not always
523
        if not isinstance(view_revisions, list):
524
            view_revisions = list(view_revisions)
4202.2.1 by Ian Clatworthy
get directory logging working again
525
        view_revisions = _filter_revisions_touching_file_id(self.branch,
4202.2.5 by Ian Clatworthy
apply review tweaks & update help
526
            rqst.get('specific_fileids')[0], view_revisions,
527
            include_merges=rqst.get('levels') != 1)
4202.2.1 by Ian Clatworthy
get directory logging working again
528
        return make_log_rev_iterator(self.branch, view_revisions,
4202.2.5 by Ian Clatworthy
apply review tweaks & update help
529
            rqst.get('delta_type'), rqst.get('message_search'))
3936.3.12 by Ian Clatworthy
more single revision & sequence tuning
530
531
3936.3.34 by Ian Clatworthy
return _mainline_revs() API as used in missing.py
532
def _calc_view_revisions(branch, start_rev_id, end_rev_id, direction,
5097.1.12 by Vincent Ladeuil
Implement the --exclude-common-ancestry log option.
533
                         generate_merge_revisions,
534
                         delayed_graph_generation=False,
535
                         exclude_common_ancestry=False,
536
                         ):
3936.3.3 by Ian Clatworthy
add --strict and more refactoring
537
    """Calculate the revisions to view.
538
539
    :return: An iterator of (revision_id, dotted_revno, merge_depth) tuples OR
540
             a list of the same tuples.
541
    """
5097.1.13 by Vincent Ladeuil
Add more tests.
542
    if (exclude_common_ancestry and start_rev_id == end_rev_id):
543
        raise errors.BzrCommandError(
544
            '--exclude-common-ancestry requires two different revisions')
5097.1.12 by Vincent Ladeuil
Implement the --exclude-common-ancestry log option.
545
    if direction not in ('reverse', 'forward'):
546
        raise ValueError('invalid direction %r' % direction)
3936.3.34 by Ian Clatworthy
return _mainline_revs() API as used in missing.py
547
    br_revno, br_rev_id = branch.last_revision_info()
3936.3.3 by Ian Clatworthy
add --strict and more refactoring
548
    if br_revno == 0:
549
        return []
550
5097.1.12 by Vincent Ladeuil
Implement the --exclude-common-ancestry log option.
551
    if (end_rev_id and start_rev_id == end_rev_id
5129.1.3 by Vincent Ladeuil
Slightly refactor the direction handling in log.
552
        and (not generate_merge_revisions
553
             or not _has_merges(branch, end_rev_id))):
5097.1.13 by Vincent Ladeuil
Add more tests.
554
        # If a single revision is requested, check we can handle it
5097.1.12 by Vincent Ladeuil
Implement the --exclude-common-ancestry log option.
555
        iter_revs = _generate_one_revision(branch, end_rev_id, br_rev_id,
556
                                           br_revno)
557
    elif not generate_merge_revisions:
558
        # If we only want to see linear revisions, we can iterate ...
559
        iter_revs = _generate_flat_revisions(branch, start_rev_id, end_rev_id,
5268.4.3 by Vincent Ladeuil
Respect --exclude-common-ancestry for linear ancestries.
560
                                             direction, exclude_common_ancestry)
5097.1.12 by Vincent Ladeuil
Implement the --exclude-common-ancestry log option.
561
        if direction == 'forward':
562
            iter_revs = reversed(iter_revs)
4202.2.1 by Ian Clatworthy
get directory logging working again
563
    else:
5097.1.12 by Vincent Ladeuil
Implement the --exclude-common-ancestry log option.
564
        iter_revs = _generate_all_revisions(branch, start_rev_id, end_rev_id,
565
                                            direction, delayed_graph_generation,
566
                                            exclude_common_ancestry)
567
        if direction == 'forward':
568
            iter_revs = _rebase_merge_depth(reverse_by_depth(list(iter_revs)))
569
    return iter_revs
4202.2.1 by Ian Clatworthy
get directory logging working again
570
571
4215.1.1 by Ian Clatworthy
remove supports_single_merge_revision
572
def _generate_one_revision(branch, rev_id, br_rev_id, br_revno):
4202.2.1 by Ian Clatworthy
get directory logging working again
573
    if rev_id == br_rev_id:
574
        # It's the tip
575
        return [(br_rev_id, br_revno, 0)]
576
    else:
5728.5.1 by Matt Giuca
log no longer raises NoSuchRevision against revisions in the
577
        revno_str = _compute_revno_str(branch, rev_id)
4202.2.1 by Ian Clatworthy
get directory logging working again
578
        return [(rev_id, revno_str, 0)]
579
580
5268.4.3 by Vincent Ladeuil
Respect --exclude-common-ancestry for linear ancestries.
581
def _generate_flat_revisions(branch, start_rev_id, end_rev_id, direction,
582
                             exclude_common_ancestry=False):
583
    result = _linear_view_revisions(
584
        branch, start_rev_id, end_rev_id,
585
        exclude_common_ancestry=exclude_common_ancestry)
4202.2.1 by Ian Clatworthy
get directory logging working again
586
    # If a start limit was given and it's not obviously an
587
    # ancestor of the end limit, check it before outputting anything
588
    if direction == 'forward' or (start_rev_id
589
        and not _is_obvious_ancestor(branch, start_rev_id, end_rev_id)):
590
        try:
591
            result = list(result)
592
        except _StartNotLinearAncestor:
593
            raise errors.BzrCommandError('Start revision not found in'
594
                ' left-hand history of end revision.')
595
    return result
596
597
598
def _generate_all_revisions(branch, start_rev_id, end_rev_id, direction,
5097.1.12 by Vincent Ladeuil
Implement the --exclude-common-ancestry log option.
599
                            delayed_graph_generation,
600
                            exclude_common_ancestry=False):
3936.3.36 by Ian Clatworthy
minor comment polish & refactoring
601
    # On large trees, generating the merge graph can take 30-60 seconds
3936.3.32 by Ian Clatworthy
always delay merge graph generation until necessary
602
    # so we delay doing it until a merge is detected, incrementally
4955.7.5 by Vincent Ladeuil
Fixed as per Ian's review.
603
    # returning initial (non-merge) revisions while we can.
4955.7.3 by Vincent Ladeuil
Check ancestry so we don't output random revisions.
604
605
    # The above is only true for old formats (<= 0.92), for newer formats, a
606
    # couple of seconds only should be needed to load the whole graph and the
607
    # other graph operations needed are even faster than that -- vila 100201
3936.3.32 by Ian Clatworthy
always delay merge graph generation until necessary
608
    initial_revisions = []
3936.3.37 by Ian Clatworthy
selectively delay graph generation, not always
609
    if delayed_graph_generation:
610
        try:
4955.7.3 by Vincent Ladeuil
Check ancestry so we don't output random revisions.
611
            for rev_id, revno, depth in  _linear_view_revisions(
5268.4.3 by Vincent Ladeuil
Respect --exclude-common-ancestry for linear ancestries.
612
                branch, start_rev_id, end_rev_id, exclude_common_ancestry):
3936.3.37 by Ian Clatworthy
selectively delay graph generation, not always
613
                if _has_merges(branch, rev_id):
4955.7.3 by Vincent Ladeuil
Check ancestry so we don't output random revisions.
614
                    # The end_rev_id can be nested down somewhere. We need an
615
                    # explicit ancestry check. There is an ambiguity here as we
616
                    # may not raise _StartNotLinearAncestor for a revision that
617
                    # is an ancestor but not a *linear* one. But since we have
618
                    # loaded the graph to do the check (or calculate a dotted
5092.1.4 by Vincent Ladeuil
Fixed as per Andrew's review.
619
                    # revno), we may as well accept to show the log...  We need
620
                    # the check only if start_rev_id is not None as all
621
                    # revisions have _mod_revision.NULL_REVISION as an ancestor
622
                    # -- vila 20100319
4955.7.3 by Vincent Ladeuil
Check ancestry so we don't output random revisions.
623
                    graph = branch.repository.get_graph()
5092.1.4 by Vincent Ladeuil
Fixed as per Andrew's review.
624
                    if (start_rev_id is not None
625
                        and not graph.is_ancestor(start_rev_id, end_rev_id)):
626
                        raise _StartNotLinearAncestor()
5097.1.1 by Vincent Ladeuil
Reduce duplication.
627
                    # Since we collected the revisions so far, we need to
628
                    # adjust end_rev_id.
3936.3.37 by Ian Clatworthy
selectively delay graph generation, not always
629
                    end_rev_id = rev_id
630
                    break
631
                else:
632
                    initial_revisions.append((rev_id, revno, depth))
633
            else:
634
                # No merged revisions found
5097.1.12 by Vincent Ladeuil
Implement the --exclude-common-ancestry log option.
635
                return initial_revisions
3936.3.37 by Ian Clatworthy
selectively delay graph generation, not always
636
        except _StartNotLinearAncestor:
637
            # A merge was never detected so the lower revision limit can't
638
            # be nested down somewhere
639
            raise errors.BzrCommandError('Start revision not found in'
640
                ' history of end revision.')
3936.3.15 by Ian Clatworthy
faster long log for a limited range with no merges
641
5097.1.1 by Vincent Ladeuil
Reduce duplication.
642
    # We exit the loop above because we encounter a revision with merges, from
643
    # this revision, we need to switch to _graph_view_revisions.
644
3936.3.30 by Ian Clatworthy
use iter_merge_sorted_revisions() with stop_range feature
645
    # A log including nested merges is required. If the direction is reverse,
646
    # we rebase the initial merge depths so that the development line is
3936.3.36 by Ian Clatworthy
minor comment polish & refactoring
647
    # shown naturally, i.e. just like it is for linear logging. We can easily
3936.3.30 by Ian Clatworthy
use iter_merge_sorted_revisions() with stop_range feature
648
    # make forward the exact opposite display, but showing the merge revisions
649
    # indented at the end seems slightly nicer in that case.
3936.3.32 by Ian Clatworthy
always delay merge graph generation until necessary
650
    view_revisions = chain(iter(initial_revisions),
651
        _graph_view_revisions(branch, start_rev_id, end_rev_id,
5097.1.12 by Vincent Ladeuil
Implement the --exclude-common-ancestry log option.
652
                              rebase_initial_depths=(direction == 'reverse'),
653
                              exclude_common_ancestry=exclude_common_ancestry))
654
    return view_revisions
2466.8.1 by Kent Gibson
Reworked LogFormatter API to simplify extending the attributes of the revision being logged. Added support for begin_log() and end_log() hooks in LogFormatters.
655
530 by Martin Pool
- put back verbose log support for reversed logs
656
3936.3.12 by Ian Clatworthy
more single revision & sequence tuning
657
def _has_merges(branch, rev_id):
658
    """Does a revision have multiple parents or not?"""
3936.3.40 by Ian Clatworthy
review feedback from jam
659
    parents = branch.repository.get_parent_map([rev_id]).get(rev_id, [])
660
    return len(parents) > 1
3936.3.12 by Ian Clatworthy
more single revision & sequence tuning
661
662
5728.5.1 by Matt Giuca
log no longer raises NoSuchRevision against revisions in the
663
def _compute_revno_str(branch, rev_id):
664
    """Compute the revno string from a rev_id.
665
5728.5.5 by Matt Giuca
log: If a revision is not in the branch, it now sets its revno to None
666
    :return: The revno string, or None if the revision is not in the supplied
667
        branch.
5728.5.1 by Matt Giuca
log no longer raises NoSuchRevision against revisions in the
668
    """
669
    try:
670
        revno = branch.revision_id_to_dotted_revno(rev_id)
671
    except errors.NoSuchRevision:
5728.5.5 by Matt Giuca
log: If a revision is not in the branch, it now sets its revno to None
672
        # The revision must be outside of this branch
673
        return None
5728.5.1 by Matt Giuca
log no longer raises NoSuchRevision against revisions in the
674
    else:
675
        return '.'.join(str(n) for n in revno)
676
677
3936.3.31 by Ian Clatworthy
nicer obvious ancestor checking
678
def _is_obvious_ancestor(branch, start_rev_id, end_rev_id):
679
    """Is start_rev_id an obvious ancestor of end_rev_id?"""
680
    if start_rev_id and end_rev_id:
5728.5.1 by Matt Giuca
log no longer raises NoSuchRevision against revisions in the
681
        try:
682
            start_dotted = branch.revision_id_to_dotted_revno(start_rev_id)
683
            end_dotted = branch.revision_id_to_dotted_revno(end_rev_id)
684
        except errors.NoSuchRevision:
685
            # one or both is not in the branch; not obvious
686
            return False
3936.3.31 by Ian Clatworthy
nicer obvious ancestor checking
687
        if len(start_dotted) == 1 and len(end_dotted) == 1:
688
            # both on mainline
689
            return start_dotted[0] <= end_dotted[0]
690
        elif (len(start_dotted) == 3 and len(end_dotted) == 3 and
691
            start_dotted[0:1] == end_dotted[0:1]):
692
            # both on same development line
693
            return start_dotted[2] <= end_dotted[2]
694
        else:
695
            # not obvious
3936.3.18 by Ian Clatworthy
faster incremental results for FILE logging
696
            return False
4955.5.3 by Vincent Ladeuil
Cleanup.
697
    # if either start or end is not specified then we use either the first or
698
    # the last revision and *they* are obvious ancestors.
3936.3.18 by Ian Clatworthy
faster incremental results for FILE logging
699
    return True
700
701
5268.4.3 by Vincent Ladeuil
Respect --exclude-common-ancestry for linear ancestries.
702
def _linear_view_revisions(branch, start_rev_id, end_rev_id,
703
                           exclude_common_ancestry=False):
3936.3.12 by Ian Clatworthy
more single revision & sequence tuning
704
    """Calculate a sequence of revisions to view, newest to oldest.
3936.3.3 by Ian Clatworthy
add --strict and more refactoring
705
3936.3.32 by Ian Clatworthy
always delay merge graph generation until necessary
706
    :param start_rev_id: the lower revision-id
707
    :param end_rev_id: the upper revision-id
5268.4.3 by Vincent Ladeuil
Respect --exclude-common-ancestry for linear ancestries.
708
    :param exclude_common_ancestry: Whether the start_rev_id should be part of
709
        the iterated revisions.
3936.3.3 by Ian Clatworthy
add --strict and more refactoring
710
    :return: An iterator of (revision_id, dotted_revno, merge_depth) tuples.
3936.3.12 by Ian Clatworthy
more single revision & sequence tuning
711
    :raises _StartNotLinearAncestor: if a start_rev_id is specified but
5268.4.3 by Vincent Ladeuil
Respect --exclude-common-ancestry for linear ancestries.
712
        is not found walking the left-hand history
3936.3.3 by Ian Clatworthy
add --strict and more refactoring
713
    """
3936.3.32 by Ian Clatworthy
always delay merge graph generation until necessary
714
    br_revno, br_rev_id = branch.last_revision_info()
3943.4.5 by John Arbash Meinel
Restore _linear_view_revisions.
715
    repo = branch.repository
5972.2.1 by Jelmer Vernooij
Deprecate Repository.iter_reverse_revision_history.
716
    graph = repo.get_graph()
3936.3.6 by Ian Clatworthy
add & use _NonMainlineRevisionLimit exception
717
    if start_rev_id is None and end_rev_id is None:
3936.3.12 by Ian Clatworthy
more single revision & sequence tuning
718
        cur_revno = br_revno
5972.2.1 by Jelmer Vernooij
Deprecate Repository.iter_reverse_revision_history.
719
        for revision_id in graph.iter_lefthand_ancestry(br_rev_id,
720
            (_mod_revision.NULL_REVISION,)):
3936.3.3 by Ian Clatworthy
add --strict and more refactoring
721
            yield revision_id, str(cur_revno), 0
3936.3.6 by Ian Clatworthy
add & use _NonMainlineRevisionLimit exception
722
            cur_revno -= 1
3936.3.14 by Ian Clatworthy
bug fix
723
    else:
724
        if end_rev_id is None:
725
            end_rev_id = br_rev_id
3936.3.6 by Ian Clatworthy
add & use _NonMainlineRevisionLimit exception
726
        found_start = start_rev_id is None
5972.2.1 by Jelmer Vernooij
Deprecate Repository.iter_reverse_revision_history.
727
        for revision_id in graph.iter_lefthand_ancestry(end_rev_id,
728
                (_mod_revision.NULL_REVISION,)):
5728.5.1 by Matt Giuca
log no longer raises NoSuchRevision against revisions in the
729
            revno_str = _compute_revno_str(branch, revision_id)
3936.3.12 by Ian Clatworthy
more single revision & sequence tuning
730
            if not found_start and revision_id == start_rev_id:
5268.4.3 by Vincent Ladeuil
Respect --exclude-common-ancestry for linear ancestries.
731
                if not exclude_common_ancestry:
732
                    yield revision_id, revno_str, 0
3936.3.12 by Ian Clatworthy
more single revision & sequence tuning
733
                found_start = True
3936.3.6 by Ian Clatworthy
add & use _NonMainlineRevisionLimit exception
734
                break
3936.3.12 by Ian Clatworthy
more single revision & sequence tuning
735
            else:
736
                yield revision_id, revno_str, 0
3936.3.6 by Ian Clatworthy
add & use _NonMainlineRevisionLimit exception
737
        else:
3936.3.12 by Ian Clatworthy
more single revision & sequence tuning
738
            if not found_start:
739
                raise _StartNotLinearAncestor()
3302.1.3 by Aaron Bentley
Add optimization of the simple case of generating view revisions
740
741
3936.3.32 by Ian Clatworthy
always delay merge graph generation until necessary
742
def _graph_view_revisions(branch, start_rev_id, end_rev_id,
5097.1.12 by Vincent Ladeuil
Implement the --exclude-common-ancestry log option.
743
                          rebase_initial_depths=True,
744
                          exclude_common_ancestry=False):
3936.3.30 by Ian Clatworthy
use iter_merge_sorted_revisions() with stop_range feature
745
    """Calculate revisions to view including merges, newest to oldest.
746
747
    :param branch: the branch
3936.3.32 by Ian Clatworthy
always delay merge graph generation until necessary
748
    :param start_rev_id: the lower revision-id
749
    :param end_rev_id: the upper revision-id
3936.3.30 by Ian Clatworthy
use iter_merge_sorted_revisions() with stop_range feature
750
    :param rebase_initial_depth: should depths be rebased until a mainline
751
      revision is found?
752
    :return: An iterator of (revision_id, dotted_revno, merge_depth) tuples.
753
    """
5097.1.12 by Vincent Ladeuil
Implement the --exclude-common-ancestry log option.
754
    if exclude_common_ancestry:
755
        stop_rule = 'with-merges-without-common-ancestry'
756
    else:
757
        stop_rule = 'with-merges'
3936.3.30 by Ian Clatworthy
use iter_merge_sorted_revisions() with stop_range feature
758
    view_revisions = branch.iter_merge_sorted_revisions(
759
        start_revision_id=end_rev_id, stop_revision_id=start_rev_id,
5097.1.12 by Vincent Ladeuil
Implement the --exclude-common-ancestry log option.
760
        stop_rule=stop_rule)
3936.3.30 by Ian Clatworthy
use iter_merge_sorted_revisions() with stop_range feature
761
    if not rebase_initial_depths:
762
        for (rev_id, merge_depth, revno, end_of_merge
763
             ) in view_revisions:
764
            yield rev_id, '.'.join(map(str, revno)), merge_depth
765
    else:
766
        # We're following a development line starting at a merged revision.
767
        # We need to adjust depths down by the initial depth until we find
768
        # a depth less than it. Then we use that depth as the adjustment.
769
        # If and when we reach the mainline, depth adjustment ends.
770
        depth_adjustment = None
771
        for (rev_id, merge_depth, revno, end_of_merge
772
             ) in view_revisions:
773
            if depth_adjustment is None:
774
                depth_adjustment = merge_depth
775
            if depth_adjustment:
776
                if merge_depth < depth_adjustment:
4955.5.3 by Vincent Ladeuil
Cleanup.
777
                    # From now on we reduce the depth adjustement, this can be
778
                    # surprising for users. The alternative requires two passes
779
                    # which breaks the fast display of the first revision
780
                    # though.
3936.3.30 by Ian Clatworthy
use iter_merge_sorted_revisions() with stop_range feature
781
                    depth_adjustment = merge_depth
782
                merge_depth -= depth_adjustment
783
            yield rev_id, '.'.join(map(str, revno)), merge_depth
784
785
4955.4.14 by Vincent Ladeuil
Properly deprecate log.calculate_view_revisions.
786
@deprecated_function(deprecated_in((2, 2, 0)))
3936.3.13 by Ian Clatworthy
feedback from jameinel
787
def calculate_view_revisions(branch, start_revision, end_revision, direction,
4215.1.1 by Ian Clatworthy
remove supports_single_merge_revision
788
        specific_fileid, generate_merge_revisions):
3936.3.13 by Ian Clatworthy
feedback from jameinel
789
    """Calculate the revisions to view.
790
791
    :return: An iterator of (revision_id, dotted_revno, merge_depth) tuples OR
792
             a list of the same tuples.
793
    """
3936.3.34 by Ian Clatworthy
return _mainline_revs() API as used in missing.py
794
    start_rev_id, end_rev_id = _get_revision_limits(branch, start_revision,
795
        end_revision)
796
    view_revisions = list(_calc_view_revisions(branch, start_rev_id, end_rev_id,
4215.1.1 by Ian Clatworthy
remove supports_single_merge_revision
797
        direction, generate_merge_revisions or specific_fileid))
3936.3.13 by Ian Clatworthy
feedback from jameinel
798
    if specific_fileid:
799
        view_revisions = _filter_revisions_touching_file_id(branch,
800
            specific_fileid, view_revisions,
801
            include_merges=generate_merge_revisions)
3936.3.28 by Ian Clatworthy
api compatibility: calculate_view_revisions rebases merge depth again
802
    return _rebase_merge_depth(view_revisions)
3936.3.13 by Ian Clatworthy
feedback from jameinel
803
804
3936.3.30 by Ian Clatworthy
use iter_merge_sorted_revisions() with stop_range feature
805
def _rebase_merge_depth(view_revisions):
806
    """Adjust depths upwards so the top level is 0."""
807
    # If either the first or last revision have a merge_depth of 0, we're done
808
    if view_revisions and view_revisions[0][2] and view_revisions[-1][2]:
809
        min_depth = min([d for r,n,d in view_revisions])
810
        if min_depth != 0:
811
            view_revisions = [(r,n,d-min_depth) for r,n,d in view_revisions]
812
    return view_revisions
813
814
3936.3.16 by Ian Clatworthy
use deltas to match files in selected use cases
815
def make_log_rev_iterator(branch, view_revisions, generate_delta, search,
3936.3.33 by Ian Clatworthy
only generate deltas for file matching as long as necessary
816
        file_ids=None, direction='reverse'):
3642.1.1 by Robert Collins
Refactoring in log towards more pluggable revision selection.
817
    """Create a revision iterator for log.
818
819
    :param branch: The branch being logged.
820
    :param view_revisions: The revisions being viewed.
821
    :param generate_delta: Whether to generate a delta for each revision.
4202.2.1 by Ian Clatworthy
get directory logging working again
822
      Permitted values are None, 'full' and 'partial'.
3642.1.1 by Robert Collins
Refactoring in log towards more pluggable revision selection.
823
    :param search: A user text search string.
3936.3.33 by Ian Clatworthy
only generate deltas for file matching as long as necessary
824
    :param file_ids: If non empty, only revisions matching one or more of
825
      the file-ids are to be kept.
826
    :param direction: the direction in which view_revisions is sorted
3642.1.7 by Robert Collins
Review feedback.
827
    :return: An iterator over lists of ((rev_id, revno, merge_depth), rev,
3642.1.2 by Robert Collins
Setup a log iterator that more closely matches what the code tries to do with repository operations.
828
        delta).
3642.1.1 by Robert Collins
Refactoring in log towards more pluggable revision selection.
829
    """
3642.1.5 by Robert Collins
Separate out batching of revisions.
830
    # Convert view_revisions into (view, None, None) groups to fit with
831
    # the standard interface here.
832
    if type(view_revisions) == list:
3642.1.7 by Robert Collins
Review feedback.
833
        # A single batch conversion is faster than many incremental ones.
834
        # As we have all the data, do a batch conversion.
3642.1.5 by Robert Collins
Separate out batching of revisions.
835
        nones = [None] * len(view_revisions)
836
        log_rev_iterator = iter([zip(view_revisions, nones, nones)])
837
    else:
838
        def _convert():
839
            for view in view_revisions:
840
                yield (view, None, None)
841
        log_rev_iterator = iter([_convert()])
3642.1.6 by Robert Collins
Make log revision filtering pluggable.
842
    for adapter in log_adapters:
3936.3.36 by Ian Clatworthy
minor comment polish & refactoring
843
        # It would be nicer if log adapters were first class objects
3936.3.33 by Ian Clatworthy
only generate deltas for file matching as long as necessary
844
        # with custom parameters. This will do for now. IGC 20090127
845
        if adapter == _make_delta_filter:
846
            log_rev_iterator = adapter(branch, generate_delta,
847
                search, log_rev_iterator, file_ids, direction)
848
        else:
849
            log_rev_iterator = adapter(branch, generate_delta,
850
                search, log_rev_iterator)
3642.1.1 by Robert Collins
Refactoring in log towards more pluggable revision selection.
851
    return log_rev_iterator
852
853
3642.1.7 by Robert Collins
Review feedback.
854
def _make_search_filter(branch, generate_delta, search, log_rev_iterator):
3642.1.1 by Robert Collins
Refactoring in log towards more pluggable revision selection.
855
    """Create a filtered iterator of log_rev_iterator matching on a regex.
856
857
    :param branch: The branch being logged.
858
    :param generate_delta: Whether to generate a delta for each revision.
859
    :param search: A user text search string.
860
    :param log_rev_iterator: An input iterator containing all revisions that
3642.1.2 by Robert Collins
Setup a log iterator that more closely matches what the code tries to do with repository operations.
861
        could be displayed, in lists.
3642.1.7 by Robert Collins
Review feedback.
862
    :return: An iterator over lists of ((rev_id, revno, merge_depth), rev,
3642.1.2 by Robert Collins
Setup a log iterator that more closely matches what the code tries to do with repository operations.
863
        delta).
3642.1.1 by Robert Collins
Refactoring in log towards more pluggable revision selection.
864
    """
865
    if search is None:
866
        return log_rev_iterator
5967.9.4 by Martin Pool
log filtering also explicitly needs a lazy_regex
867
    searchRE = lazy_regex.lazy_compile(search, re.IGNORECASE)
3642.1.1 by Robert Collins
Refactoring in log towards more pluggable revision selection.
868
    return _filter_message_re(searchRE, log_rev_iterator)
869
870
871
def _filter_message_re(searchRE, log_rev_iterator):
3642.1.2 by Robert Collins
Setup a log iterator that more closely matches what the code tries to do with repository operations.
872
    for revs in log_rev_iterator:
3642.1.3 by Robert Collins
Split out delta generation from revision content reading, and structure it after message evaluation, increasing performance of log -v -m.
873
        new_revs = []
3642.1.2 by Robert Collins
Setup a log iterator that more closely matches what the code tries to do with repository operations.
874
        for (rev_id, revno, merge_depth), rev, delta in revs:
875
            if searchRE.search(rev.message):
3642.1.3 by Robert Collins
Split out delta generation from revision content reading, and structure it after message evaluation, increasing performance of log -v -m.
876
                new_revs.append(((rev_id, revno, merge_depth), rev, delta))
877
        yield new_revs
878
879
3936.3.33 by Ian Clatworthy
only generate deltas for file matching as long as necessary
880
def _make_delta_filter(branch, generate_delta, search, log_rev_iterator,
881
    fileids=None, direction='reverse'):
3642.1.3 by Robert Collins
Split out delta generation from revision content reading, and structure it after message evaluation, increasing performance of log -v -m.
882
    """Add revision deltas to a log iterator if needed.
883
884
    :param branch: The branch being logged.
885
    :param generate_delta: Whether to generate a delta for each revision.
4202.2.1 by Ian Clatworthy
get directory logging working again
886
      Permitted values are None, 'full' and 'partial'.
3642.1.3 by Robert Collins
Split out delta generation from revision content reading, and structure it after message evaluation, increasing performance of log -v -m.
887
    :param search: A user text search string.
888
    :param log_rev_iterator: An input iterator containing all revisions that
889
        could be displayed, in lists.
3936.3.36 by Ian Clatworthy
minor comment polish & refactoring
890
    :param fileids: If non empty, only revisions matching one or more of
3936.3.33 by Ian Clatworthy
only generate deltas for file matching as long as necessary
891
      the file-ids are to be kept.
892
    :param direction: the direction in which view_revisions is sorted
3642.1.7 by Robert Collins
Review feedback.
893
    :return: An iterator over lists of ((rev_id, revno, merge_depth), rev,
3642.1.3 by Robert Collins
Split out delta generation from revision content reading, and structure it after message evaluation, increasing performance of log -v -m.
894
        delta).
895
    """
3936.3.33 by Ian Clatworthy
only generate deltas for file matching as long as necessary
896
    if not generate_delta and not fileids:
3642.1.3 by Robert Collins
Split out delta generation from revision content reading, and structure it after message evaluation, increasing performance of log -v -m.
897
        return log_rev_iterator
3936.3.33 by Ian Clatworthy
only generate deltas for file matching as long as necessary
898
    return _generate_deltas(branch.repository, log_rev_iterator,
899
        generate_delta, fileids, direction)
900
901
4202.2.1 by Ian Clatworthy
get directory logging working again
902
def _generate_deltas(repository, log_rev_iterator, delta_type, fileids,
3936.3.33 by Ian Clatworthy
only generate deltas for file matching as long as necessary
903
    direction):
3936.3.36 by Ian Clatworthy
minor comment polish & refactoring
904
    """Create deltas for each batch of revisions in log_rev_iterator.
4032.1.1 by John Arbash Meinel
Merge the removal of all trailing whitespace, and resolve conflicts.
905
3936.3.36 by Ian Clatworthy
minor comment polish & refactoring
906
    If we're only generating deltas for the sake of filtering against
907
    file-ids, we stop generating deltas once all file-ids reach the
908
    appropriate life-cycle point. If we're receiving data newest to
909
    oldest, then that life-cycle point is 'add', otherwise it's 'remove'.
910
    """
3936.3.33 by Ian Clatworthy
only generate deltas for file matching as long as necessary
911
    check_fileids = fileids is not None and len(fileids) > 0
912
    if check_fileids:
913
        fileid_set = set(fileids)
914
        if direction == 'reverse':
915
            stop_on = 'add'
916
        else:
917
            stop_on = 'remove'
918
    else:
919
        fileid_set = None
3642.1.3 by Robert Collins
Split out delta generation from revision content reading, and structure it after message evaluation, increasing performance of log -v -m.
920
    for revs in log_rev_iterator:
3936.3.33 by Ian Clatworthy
only generate deltas for file matching as long as necessary
921
        # If we were matching against fileids and we've run out,
3936.3.40 by Ian Clatworthy
review feedback from jam
922
        # there's nothing left to do
3936.3.33 by Ian Clatworthy
only generate deltas for file matching as long as necessary
923
        if check_fileids and not fileid_set:
3936.3.40 by Ian Clatworthy
review feedback from jam
924
            return
3642.1.3 by Robert Collins
Split out delta generation from revision content reading, and structure it after message evaluation, increasing performance of log -v -m.
925
        revisions = [rev[1] for rev in revs]
3936.3.33 by Ian Clatworthy
only generate deltas for file matching as long as necessary
926
        new_revs = []
4202.2.1 by Ian Clatworthy
get directory logging working again
927
        if delta_type == 'full' and not check_fileids:
928
            deltas = repository.get_deltas_for_revisions(revisions)
929
            for rev, delta in izip(revs, deltas):
930
                new_revs.append((rev[0], rev[1], delta))
931
        else:
932
            deltas = repository.get_deltas_for_revisions(revisions, fileid_set)
933
            for rev, delta in izip(revs, deltas):
934
                if check_fileids:
935
                    if delta is None or not delta.has_changed():
936
                        continue
937
                    else:
938
                        _update_fileids(delta, fileid_set, stop_on)
939
                        if delta_type is None:
940
                            delta = None
941
                        elif delta_type == 'full':
942
                            # If the file matches all the time, rebuilding
943
                            # a full delta like this in addition to a partial
4202.2.4 by Ian Clatworthy
comment tweak from vila's review
944
                            # one could be slow. However, it's likely that
4202.2.1 by Ian Clatworthy
get directory logging working again
945
                            # most revisions won't get this far, making it
946
                            # faster to filter on the partial deltas and
947
                            # build the occasional full delta than always
948
                            # building full deltas and filtering those.
949
                            rev_id = rev[0][0]
950
                            delta = repository.get_revision_delta(rev_id)
951
                new_revs.append((rev[0], rev[1], delta))
3936.3.33 by Ian Clatworthy
only generate deltas for file matching as long as necessary
952
        yield new_revs
953
954
4202.2.1 by Ian Clatworthy
get directory logging working again
955
def _update_fileids(delta, fileids, stop_on):
956
    """Update the set of file-ids to search based on file lifecycle events.
957
    
958
    :param fileids: a set of fileids to update
3936.3.33 by Ian Clatworthy
only generate deltas for file matching as long as necessary
959
    :param stop_on: either 'add' or 'remove' - take file-ids out of the
960
      fileids set once their add or remove entry is detected respectively
961
    """
4202.2.1 by Ian Clatworthy
get directory logging working again
962
    if stop_on == 'add':
963
        for item in delta.added:
964
            if item[1] in fileids:
965
                fileids.remove(item[1])
966
    elif stop_on == 'delete':
967
        for item in delta.removed:
968
            if item[1] in fileids:
969
                fileids.remove(item[1])
3642.1.2 by Robert Collins
Setup a log iterator that more closely matches what the code tries to do with repository operations.
970
971
3642.1.7 by Robert Collins
Review feedback.
972
def _make_revision_objects(branch, generate_delta, search, log_rev_iterator):
3642.1.4 by Robert Collins
Factor out revision object extraction from revision batching.
973
    """Extract revision objects from the repository
974
975
    :param branch: The branch being logged.
976
    :param generate_delta: Whether to generate a delta for each revision.
977
    :param search: A user text search string.
978
    :param log_rev_iterator: An input iterator containing all revisions that
979
        could be displayed, in lists.
3642.1.7 by Robert Collins
Review feedback.
980
    :return: An iterator over lists of ((rev_id, revno, merge_depth), rev,
3642.1.4 by Robert Collins
Factor out revision object extraction from revision batching.
981
        delta).
982
    """
3642.1.5 by Robert Collins
Separate out batching of revisions.
983
    repository = branch.repository
3642.1.4 by Robert Collins
Factor out revision object extraction from revision batching.
984
    for revs in log_rev_iterator:
985
        # r = revision_id, n = revno, d = merge depth
986
        revision_ids = [view[0] for view, _, _ in revs]
987
        revisions = repository.get_revisions(revision_ids)
988
        revs = [(rev[0], revision, rev[2]) for rev, revision in
989
            izip(revs, revisions)]
990
        yield revs
991
992
3642.1.7 by Robert Collins
Review feedback.
993
def _make_batch_filter(branch, generate_delta, search, log_rev_iterator):
3642.1.5 by Robert Collins
Separate out batching of revisions.
994
    """Group up a single large batch into smaller ones.
3642.1.2 by Robert Collins
Setup a log iterator that more closely matches what the code tries to do with repository operations.
995
996
    :param branch: The branch being logged.
997
    :param generate_delta: Whether to generate a delta for each revision.
998
    :param search: A user text search string.
3642.1.5 by Robert Collins
Separate out batching of revisions.
999
    :param log_rev_iterator: An input iterator containing all revisions that
1000
        could be displayed, in lists.
3874.2.4 by Vincent Ladeuil
Fix too long lines.
1001
    :return: An iterator over lists of ((rev_id, revno, merge_depth), rev,
1002
        delta).
3642.1.2 by Robert Collins
Setup a log iterator that more closely matches what the code tries to do with repository operations.
1003
    """
1004
    repository = branch.repository
3302.1.1 by Aaron Bentley
Split out _iter_revision, allow view_revisions to be an iterator
1005
    num = 9
3642.1.5 by Robert Collins
Separate out batching of revisions.
1006
    for batch in log_rev_iterator:
1007
        batch = iter(batch)
1008
        while True:
1009
            step = [detail for _, detail in zip(range(num), batch)]
1010
            if len(step) == 0:
1011
                break
1012
            yield step
1013
            num = min(int(num * 1.5), 200)
3302.1.1 by Aaron Bentley
Split out _iter_revision, allow view_revisions to be an iterator
1014
1015
3936.3.3 by Ian Clatworthy
add --strict and more refactoring
1016
def _get_revision_limits(branch, start_revision, end_revision):
1017
    """Get and check revision limits.
1018
4032.1.1 by John Arbash Meinel
Merge the removal of all trailing whitespace, and resolve conflicts.
1019
    :param  branch: The branch containing the revisions.
2466.12.1 by Kent Gibson
Fix ``bzr log -r`` to support selecting merge revisions.
1020
1021
    :param  start_revision: The first revision to be logged.
1022
            For backwards compatibility this may be a mainline integer revno,
1023
            but for merge revision support a RevisionInfo is expected.
1024
1025
    :param  end_revision: The last revision to be logged.
1026
            For backwards compatibility this may be a mainline integer revno,
1027
            but for merge revision support a RevisionInfo is expected.
1028
3936.3.34 by Ian Clatworthy
return _mainline_revs() API as used in missing.py
1029
    :return: (start_rev_id, end_rev_id) tuple.
2466.12.1 by Kent Gibson
Fix ``bzr log -r`` to support selecting merge revisions.
1030
    """
3936.3.3 by Ian Clatworthy
add --strict and more refactoring
1031
    branch_revno, branch_rev_id = branch.last_revision_info()
3842.2.4 by Vincent Ladeuil
Superficial fix for bug #300055.
1032
    start_rev_id = None
2466.12.1 by Kent Gibson
Fix ``bzr log -r`` to support selecting merge revisions.
1033
    if start_revision is None:
1034
        start_revno = 1
1035
    else:
3224.5.1 by Andrew Bennetts
Lots of assorted hackery to reduce the number of imports for common operations. Improves 'rocks', 'st' and 'help' times by ~50ms on my laptop.
1036
        if isinstance(start_revision, revisionspec.RevisionInfo):
2466.12.1 by Kent Gibson
Fix ``bzr log -r`` to support selecting merge revisions.
1037
            start_rev_id = start_revision.rev_id
1038
            start_revno = start_revision.revno or 1
1039
        else:
1040
            branch.check_real_revno(start_revision)
1041
            start_revno = start_revision
3936.3.25 by Ian Clatworthy
fix bug when start/end revision are integers
1042
            start_rev_id = branch.get_rev_id(start_revno)
3842.2.4 by Vincent Ladeuil
Superficial fix for bug #300055.
1043
2466.12.1 by Kent Gibson
Fix ``bzr log -r`` to support selecting merge revisions.
1044
    end_rev_id = None
1045
    if end_revision is None:
3449.2.5 by John Arbash Meinel
Stop referencing the variable I removed.
1046
        end_revno = branch_revno
2466.12.1 by Kent Gibson
Fix ``bzr log -r`` to support selecting merge revisions.
1047
    else:
3224.5.1 by Andrew Bennetts
Lots of assorted hackery to reduce the number of imports for common operations. Improves 'rocks', 'st' and 'help' times by ~50ms on my laptop.
1048
        if isinstance(end_revision, revisionspec.RevisionInfo):
2466.12.1 by Kent Gibson
Fix ``bzr log -r`` to support selecting merge revisions.
1049
            end_rev_id = end_revision.rev_id
3449.2.5 by John Arbash Meinel
Stop referencing the variable I removed.
1050
            end_revno = end_revision.revno or branch_revno
2466.12.1 by Kent Gibson
Fix ``bzr log -r`` to support selecting merge revisions.
1051
        else:
1052
            branch.check_real_revno(end_revision)
1053
            end_revno = end_revision
3936.3.25 by Ian Clatworthy
fix bug when start/end revision are integers
1054
            end_rev_id = branch.get_rev_id(end_revno)
2466.12.1 by Kent Gibson
Fix ``bzr log -r`` to support selecting merge revisions.
1055
3936.3.4 by Ian Clatworthy
fix empty_branch log
1056
    if branch_revno != 0:
1057
        if (start_rev_id == _mod_revision.NULL_REVISION
1058
            or end_rev_id == _mod_revision.NULL_REVISION):
1059
            raise errors.BzrCommandError('Logging revision 0 is invalid.')
1060
        if start_revno > end_revno:
1061
            raise errors.BzrCommandError("Start revision must be older than "
1062
                                         "the end revision.")
3936.3.34 by Ian Clatworthy
return _mainline_revs() API as used in missing.py
1063
    return (start_rev_id, end_rev_id)
1064
1065
1066
def _get_mainline_revs(branch, start_revision, end_revision):
3936.3.3 by Ian Clatworthy
add --strict and more refactoring
1067
    """Get the mainline revisions from the branch.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1068
3936.3.34 by Ian Clatworthy
return _mainline_revs() API as used in missing.py
1069
    Generates the list of mainline revisions for the branch.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1070
1071
    :param  branch: The branch containing the revisions.
3936.3.34 by Ian Clatworthy
return _mainline_revs() API as used in missing.py
1072
1073
    :param  start_revision: The first revision to be logged.
1074
            For backwards compatibility this may be a mainline integer revno,
1075
            but for merge revision support a RevisionInfo is expected.
1076
1077
    :param  end_revision: The last revision to be logged.
1078
            For backwards compatibility this may be a mainline integer revno,
1079
            but for merge revision support a RevisionInfo is expected.
1080
1081
    :return: A (mainline_revs, rev_nos, start_rev_id, end_rev_id) tuple.
3936.3.3 by Ian Clatworthy
add --strict and more refactoring
1082
    """
3936.3.34 by Ian Clatworthy
return _mainline_revs() API as used in missing.py
1083
    branch_revno, branch_last_revision = branch.last_revision_info()
1084
    if branch_revno == 0:
1085
        return None, None, None, None
1086
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1087
    # For mainline generation, map start_revision and end_revision to
1088
    # mainline revnos. If the revision is not on the mainline choose the
1089
    # appropriate extreme of the mainline instead - the extra will be
3936.3.34 by Ian Clatworthy
return _mainline_revs() API as used in missing.py
1090
    # filtered later.
1091
    # Also map the revisions to rev_ids, to be used in the later filtering
1092
    # stage.
1093
    start_rev_id = None
1094
    if start_revision is None:
1095
        start_revno = 1
1096
    else:
1097
        if isinstance(start_revision, revisionspec.RevisionInfo):
1098
            start_rev_id = start_revision.rev_id
1099
            start_revno = start_revision.revno or 1
1100
        else:
1101
            branch.check_real_revno(start_revision)
1102
            start_revno = start_revision
1103
1104
    end_rev_id = None
1105
    if end_revision is None:
1106
        end_revno = branch_revno
1107
    else:
1108
        if isinstance(end_revision, revisionspec.RevisionInfo):
1109
            end_rev_id = end_revision.rev_id
1110
            end_revno = end_revision.revno or branch_revno
1111
        else:
1112
            branch.check_real_revno(end_revision)
1113
            end_revno = end_revision
1114
1115
    if ((start_rev_id == _mod_revision.NULL_REVISION)
1116
        or (end_rev_id == _mod_revision.NULL_REVISION)):
1117
        raise errors.BzrCommandError('Logging revision 0 is invalid.')
1118
    if start_revno > end_revno:
1119
        raise errors.BzrCommandError("Start revision must be older than "
1120
                                     "the end revision.")
1121
1122
    if end_revno < start_revno:
1123
        return None, None, None, None
1124
    cur_revno = branch_revno
3449.2.1 by John Arbash Meinel
bzr uncommit doesn't need to work in terms of 'revision_history()'
1125
    rev_nos = {}
1126
    mainline_revs = []
5972.2.1 by Jelmer Vernooij
Deprecate Repository.iter_reverse_revision_history.
1127
    graph = branch.repository.get_graph()
1128
    for revision_id in graph.iter_lefthand_ancestry(
1129
            branch_last_revision, (_mod_revision.NULL_REVISION,)):
3449.2.1 by John Arbash Meinel
bzr uncommit doesn't need to work in terms of 'revision_history()'
1130
        if cur_revno < start_revno:
3449.2.2 by John Arbash Meinel
Fix bug #172649. Cleanup, and handle the case where we are logging to the first revision.
1131
            # We have gone far enough, but we always add 1 more revision
3449.2.1 by John Arbash Meinel
bzr uncommit doesn't need to work in terms of 'revision_history()'
1132
            rev_nos[revision_id] = cur_revno
1133
            mainline_revs.append(revision_id)
1134
            break
1135
        if cur_revno <= end_revno:
1136
            rev_nos[revision_id] = cur_revno
1137
            mainline_revs.append(revision_id)
1138
        cur_revno -= 1
3449.2.2 by John Arbash Meinel
Fix bug #172649. Cleanup, and handle the case where we are logging to the first revision.
1139
    else:
1140
        # We walked off the edge of all revisions, so we add a 'None' marker
1141
        mainline_revs.append(None)
2466.12.1 by Kent Gibson
Fix ``bzr log -r`` to support selecting merge revisions.
1142
3449.2.1 by John Arbash Meinel
bzr uncommit doesn't need to work in terms of 'revision_history()'
1143
    mainline_revs.reverse()
2466.12.1 by Kent Gibson
Fix ``bzr log -r`` to support selecting merge revisions.
1144
1145
    # override the mainline to look like the revision history.
3936.3.34 by Ian Clatworthy
return _mainline_revs() API as used in missing.py
1146
    return mainline_revs, rev_nos, start_rev_id, end_rev_id
2466.12.1 by Kent Gibson
Fix ``bzr log -r`` to support selecting merge revisions.
1147
1148
4955.4.20 by Vincent Ladeuil
Properly deprecate dead code.
1149
@deprecated_function(deprecated_in((2, 2, 0)))
2466.12.1 by Kent Gibson
Fix ``bzr log -r`` to support selecting merge revisions.
1150
def _filter_revision_range(view_revisions, start_rev_id, end_rev_id):
1151
    """Filter view_revisions based on revision ranges.
1152
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1153
    :param view_revisions: A list of (revision_id, dotted_revno, merge_depth)
2466.12.1 by Kent Gibson
Fix ``bzr log -r`` to support selecting merge revisions.
1154
            tuples to be filtered.
1155
1156
    :param start_rev_id: If not NONE specifies the first revision to be logged.
1157
            If NONE then all revisions up to the end_rev_id are logged.
1158
1159
    :param end_rev_id: If not NONE specifies the last revision to be logged.
1160
            If NONE then all revisions up to the end of the log are logged.
1161
1162
    :return: The filtered view_revisions.
1163
    """
3842.2.4 by Vincent Ladeuil
Superficial fix for bug #300055.
1164
    if start_rev_id or end_rev_id:
2466.12.1 by Kent Gibson
Fix ``bzr log -r`` to support selecting merge revisions.
1165
        revision_ids = [r for r, n, d in view_revisions]
1166
        if start_rev_id:
1167
            start_index = revision_ids.index(start_rev_id)
1168
        else:
1169
            start_index = 0
1170
        if start_rev_id == end_rev_id:
1171
            end_index = start_index
1172
        else:
1173
            if end_rev_id:
1174
                end_index = revision_ids.index(end_rev_id)
1175
            else:
1176
                end_index = len(view_revisions) - 1
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1177
        # To include the revisions merged into the last revision,
2466.12.1 by Kent Gibson
Fix ``bzr log -r`` to support selecting merge revisions.
1178
        # extend end_rev_id down to, but not including, the next rev
1179
        # with the same or lesser merge_depth
1180
        end_merge_depth = view_revisions[end_index][2]
1181
        try:
1182
            for index in xrange(end_index+1, len(view_revisions)+1):
1183
                if view_revisions[index][2] <= end_merge_depth:
1184
                    end_index = index - 1
1185
                    break
1186
        except IndexError:
1187
            # if the search falls off the end then log to the end as well
1188
            end_index = len(view_revisions) - 1
1189
        view_revisions = view_revisions[start_index:end_index+1]
1190
    return view_revisions
1191
1192
3940.1.3 by Ian Clatworthy
fix code
1193
def _filter_revisions_touching_file_id(branch, file_id, view_revisions,
1194
    include_merges=True):
3711.3.23 by John Arbash Meinel
Documentation and cleanup.
1195
    r"""Return the list of revision ids which touch a given file id.
2359.1.4 by John Arbash Meinel
Refactor the specific revisions for file id into a helper function.
1196
2466.12.1 by Kent Gibson
Fix ``bzr log -r`` to support selecting merge revisions.
1197
    The function filters view_revisions and returns a subset.
2359.1.4 by John Arbash Meinel
Refactor the specific revisions for file id into a helper function.
1198
    This includes the revisions which directly change the file id,
1199
    and the revisions which merge these changes. So if the
1200
    revision graph is::
5891.1.3 by Andrew Bennetts
Move docstring formatting fixes.
1201
3711.3.23 by John Arbash Meinel
Documentation and cleanup.
1202
        A-.
1203
        |\ \
1204
        B C E
1205
        |/ /
1206
        D |
1207
        |\|
1208
        | F
2359.1.4 by John Arbash Meinel
Refactor the specific revisions for file id into a helper function.
1209
        |/
3711.3.23 by John Arbash Meinel
Documentation and cleanup.
1210
        G
1211
1212
    And 'C' changes a file, then both C and D will be returned. F will not be
1213
    returned even though it brings the changes to C into the branch starting
1214
    with E. (Note that if we were using F as the tip instead of G, then we
1215
    would see C, D, F.)
1216
1217
    This will also be restricted based on a subset of the mainline.
1218
1219
    :param branch: The branch where we can get text revision information.
3842.2.5 by Vincent Ladeuil
Better fix for bug #300055.
1220
3711.3.23 by John Arbash Meinel
Documentation and cleanup.
1221
    :param file_id: Filter out revisions that do not touch file_id.
3842.2.5 by Vincent Ladeuil
Better fix for bug #300055.
1222
3711.3.23 by John Arbash Meinel
Documentation and cleanup.
1223
    :param view_revisions: A list of (revision_id, dotted_revno, merge_depth)
1224
        tuples. This is the list of revisions which will be filtered. It is
3842.2.5 by Vincent Ladeuil
Better fix for bug #300055.
1225
        assumed that view_revisions is in merge_sort order (i.e. newest
1226
        revision first ).
1227
3940.1.3 by Ian Clatworthy
fix code
1228
    :param include_merges: include merge revisions in the result or not
1229
2359.1.8 by John Arbash Meinel
doc
1230
    :return: A list of (revision_id, dotted_revno, merge_depth) tuples.
2359.1.4 by John Arbash Meinel
Refactor the specific revisions for file id into a helper function.
1231
    """
3711.3.23 by John Arbash Meinel
Documentation and cleanup.
1232
    # Lookup all possible text keys to determine which ones actually modified
1233
    # the file.
5815.5.12 by Jelmer Vernooij
Fix use of file graph.
1234
    graph = branch.repository.get_file_graph()
5815.5.10 by Jelmer Vernooij
Fix two issues pointed out by John.
1235
    get_parent_map = graph.get_parent_map
5815.5.8 by Jelmer Vernooij
Use traditional (fileid, revision) entries in file graph.
1236
    text_keys = [(file_id, rev_id) for rev_id, revno, depth in view_revisions]
4183.3.1 by Vincent Ladeuil
Fix bug #346431 by allowing log._filter_revisions_touching_file_id to be
1237
    next_keys = None
3711.3.16 by John Arbash Meinel
Doc update.
1238
    # Looking up keys in batches of 1000 can cut the time in half, as well as
1239
    # memory consumption. GraphIndex *does* like to look for a few keys in
1240
    # parallel, it just doesn't like looking for *lots* of keys in parallel.
3711.3.19 by John Arbash Meinel
Add a TODO discussing how our index requests should evolve.
1241
    # TODO: This code needs to be re-evaluated periodically as we tune the
1242
    #       indexing layer. We might consider passing in hints as to the known
1243
    #       access pattern (sparse/clustered, high success rate/low success
1244
    #       rate). This particular access is clustered with a low success rate.
3711.3.15 by John Arbash Meinel
Work around GraphIndex inefficiencies by requesting keys 1000 at a time.
1245
    modified_text_revisions = set()
1246
    chunk_size = 1000
1247
    for start in xrange(0, len(text_keys), chunk_size):
1248
        next_keys = text_keys[start:start + chunk_size]
3711.3.23 by John Arbash Meinel
Documentation and cleanup.
1249
        # Only keep the revision_id portion of the key
3711.3.15 by John Arbash Meinel
Work around GraphIndex inefficiencies by requesting keys 1000 at a time.
1250
        modified_text_revisions.update(
5815.5.10 by Jelmer Vernooij
Fix two issues pointed out by John.
1251
            [k[1] for k in get_parent_map(next_keys)])
3711.3.15 by John Arbash Meinel
Work around GraphIndex inefficiencies by requesting keys 1000 at a time.
1252
    del text_keys, next_keys
3711.3.14 by John Arbash Meinel
Change the per-file log algorithm dramatically.
1253
1254
    result = []
1255
    # Track what revisions will merge the current revision, replace entries
1256
    # with 'None' when they have been added to result
1257
    current_merge_stack = [None]
3711.3.23 by John Arbash Meinel
Documentation and cleanup.
1258
    for info in view_revisions:
3711.3.14 by John Arbash Meinel
Change the per-file log algorithm dramatically.
1259
        rev_id, revno, depth = info
1260
        if depth == len(current_merge_stack):
1261
            current_merge_stack.append(info)
1262
        else:
1263
            del current_merge_stack[depth + 1:]
1264
            current_merge_stack[-1] = info
1265
1266
        if rev_id in modified_text_revisions:
1267
            # This needs to be logged, along with the extra revisions
1268
            for idx in xrange(len(current_merge_stack)):
1269
                node = current_merge_stack[idx]
1270
                if node is not None:
3940.1.3 by Ian Clatworthy
fix code
1271
                    if include_merges or node[2] == 0:
1272
                        result.append(node)
1273
                        current_merge_stack[idx] = None
3711.3.4 by John Arbash Meinel
Significantly faster, but consuming more memory.
1274
    return result
2359.1.4 by John Arbash Meinel
Refactor the specific revisions for file id into a helper function.
1275
1276
4955.4.20 by Vincent Ladeuil
Properly deprecate dead code.
1277
@deprecated_function(deprecated_in((2, 2, 0)))
1756.2.20 by Aaron Bentley
Optimize log formats that don't show merges
1278
def get_view_revisions(mainline_revs, rev_nos, branch, direction,
1756.2.22 by Aaron Bentley
Apply review comments
1279
                       include_merges=True):
1756.2.18 by Aaron Bentley
Factor out the revision list generation
1280
    """Produce an iterator of revisions to show
1281
    :return: an iterator of (revision_id, revno, merge_depth)
1282
    (if there is no revno for a revision, None is supplied)
1283
    """
3943.5.2 by Ian Clatworthy
hand control of diff formatting to the log formatter
1284
    if not include_merges:
1756.2.20 by Aaron Bentley
Optimize log formats that don't show merges
1285
        revision_ids = mainline_revs[1:]
1286
        if direction == 'reverse':
1287
            revision_ids.reverse()
1288
        for revision_id in revision_ids:
1988.4.2 by Robert Collins
``bzr log`` Now shows dotted-decimal revision numbers for all revisions,
1289
            yield revision_id, str(rev_nos[revision_id]), 0
1756.2.20 by Aaron Bentley
Optimize log formats that don't show merges
1290
        return
3287.6.1 by Robert Collins
* ``VersionedFile.get_graph`` is deprecated, with no replacement method.
1291
    graph = branch.repository.get_graph()
1292
    # This asks for all mainline revisions, which means we only have to spider
1293
    # sideways, rather than depth history. That said, its still size-of-history
1294
    # and should be addressed.
3373.5.4 by John Arbash Meinel
Track down another bogus location. Only triggered with --long
1295
    # mainline_revisions always includes an extra revision at the beginning, so
1296
    # don't request it.
3287.6.8 by Robert Collins
Reduce code duplication as per review.
1297
    parent_map = dict(((key, value) for key, value in
3373.5.4 by John Arbash Meinel
Track down another bogus location. Only triggered with --long
1298
        graph.iter_ancestry(mainline_revs[1:]) if value is not None))
3287.6.1 by Robert Collins
* ``VersionedFile.get_graph`` is deprecated, with no replacement method.
1299
    # filter out ghosts; merge_sort errors on ghosts.
3535.5.1 by John Arbash Meinel
cleanup a few imports to be lazily loaded.
1300
    rev_graph = _mod_repository._strip_NULL_ghosts(parent_map)
3224.5.1 by Andrew Bennetts
Lots of assorted hackery to reduce the number of imports for common operations. Improves 'rocks', 'st' and 'help' times by ~50ms on my laptop.
1301
    merge_sorted_revisions = tsort.merge_sort(
3287.6.1 by Robert Collins
* ``VersionedFile.get_graph`` is deprecated, with no replacement method.
1302
        rev_graph,
1756.2.18 by Aaron Bentley
Factor out the revision list generation
1303
        mainline_revs[-1],
1988.4.2 by Robert Collins
``bzr log`` Now shows dotted-decimal revision numbers for all revisions,
1304
        mainline_revs,
1305
        generate_revno=True)
1756.2.18 by Aaron Bentley
Factor out the revision list generation
1306
1307
    if direction == 'forward':
1308
        # forward means oldest first.
1756.2.25 by Aaron Bentley
Sort revisions at each depth, instead of just mainline revisions.
1309
        merge_sorted_revisions = reverse_by_depth(merge_sorted_revisions)
1756.2.18 by Aaron Bentley
Factor out the revision list generation
1310
    elif direction != 'reverse':
1311
        raise ValueError('invalid direction %r' % direction)
1312
3874.2.4 by Vincent Ladeuil
Fix too long lines.
1313
    for (sequence, rev_id, merge_depth, revno, end_of_merge
1314
         ) in merge_sorted_revisions:
1988.4.2 by Robert Collins
``bzr log`` Now shows dotted-decimal revision numbers for all revisions,
1315
        yield rev_id, '.'.join(map(str, revno)), merge_depth
1756.2.18 by Aaron Bentley
Factor out the revision list generation
1316
1317
1756.2.25 by Aaron Bentley
Sort revisions at each depth, instead of just mainline revisions.
1318
def reverse_by_depth(merge_sorted_revisions, _depth=0):
1319
    """Reverse revisions by depth.
1756.2.24 by Aaron Bentley
Forward sorting shows merges under mainline revision
1320
1756.2.25 by Aaron Bentley
Sort revisions at each depth, instead of just mainline revisions.
1321
    Revisions with a different depth are sorted as a group with the previous
1322
    revision of that depth.  There may be no topological justification for this,
1756.2.24 by Aaron Bentley
Forward sorting shows merges under mainline revision
1323
    but it looks much nicer.
1324
    """
3842.2.6 by Vincent Ladeuil
Fix typo.
1325
    # Add a fake revision at start so that we can always attach sub revisions
3842.2.4 by Vincent Ladeuil
Superficial fix for bug #300055.
1326
    merge_sorted_revisions = [(None, None, _depth)] + merge_sorted_revisions
1756.2.24 by Aaron Bentley
Forward sorting shows merges under mainline revision
1327
    zd_revisions = []
1328
    for val in merge_sorted_revisions:
1756.2.25 by Aaron Bentley
Sort revisions at each depth, instead of just mainline revisions.
1329
        if val[2] == _depth:
3842.2.4 by Vincent Ladeuil
Superficial fix for bug #300055.
1330
            # Each revision at the current depth becomes a chunk grouping all
1331
            # higher depth revisions.
1756.2.24 by Aaron Bentley
Forward sorting shows merges under mainline revision
1332
            zd_revisions.append([val])
1333
        else:
1334
            zd_revisions[-1].append(val)
1756.2.25 by Aaron Bentley
Sort revisions at each depth, instead of just mainline revisions.
1335
    for revisions in zd_revisions:
1336
        if len(revisions) > 1:
3842.2.4 by Vincent Ladeuil
Superficial fix for bug #300055.
1337
            # We have higher depth revisions, let reverse them locally
1756.2.25 by Aaron Bentley
Sort revisions at each depth, instead of just mainline revisions.
1338
            revisions[1:] = reverse_by_depth(revisions[1:], _depth + 1)
1756.2.24 by Aaron Bentley
Forward sorting shows merges under mainline revision
1339
    zd_revisions.reverse()
1340
    result = []
1341
    for chunk in zd_revisions:
1342
        result.extend(chunk)
3842.2.4 by Vincent Ladeuil
Superficial fix for bug #300055.
1343
    if _depth == 0:
1344
        # Top level call, get rid of the fake revisions that have been added
1345
        result = [r for r in result if r[0] is not None and r[1] is not None]
1756.2.24 by Aaron Bentley
Forward sorting shows merges under mainline revision
1346
    return result
1347
1348
2466.8.1 by Kent Gibson
Reworked LogFormatter API to simplify extending the attributes of the revision being logged. Added support for begin_log() and end_log() hooks in LogFormatters.
1349
class LogRevision(object):
1350
    """A revision to be logged (by LogFormatter.log_revision).
1351
1352
    A simple wrapper for the attributes of a revision to be logged.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1353
    The attributes may or may not be populated, as determined by the
2466.8.1 by Kent Gibson
Reworked LogFormatter API to simplify extending the attributes of the revision being logged. Added support for begin_log() and end_log() hooks in LogFormatters.
1354
    logging options and the log formatter capabilities.
1355
    """
1356
2490.1.2 by John Arbash Meinel
Cleanup according to PEP8 and some other small whitespace fixes
1357
    def __init__(self, rev=None, revno=None, merge_depth=0, delta=None,
5971.1.39 by Jonathan Riddell
add signature verification to log option, alas breaks write lock
1358
                 tags=None, diff=None, signature=None):
2466.8.1 by Kent Gibson
Reworked LogFormatter API to simplify extending the attributes of the revision being logged. Added support for begin_log() and end_log() hooks in LogFormatters.
1359
        self.rev = rev
5728.5.7 by Matt Giuca
log: Avoid using a conditional expression for Python 2.4 compatibility.
1360
        if revno is None:
1361
            self.revno = None
1362
        else:
1363
            self.revno = str(revno)
2466.8.1 by Kent Gibson
Reworked LogFormatter API to simplify extending the attributes of the revision being logged. Added support for begin_log() and end_log() hooks in LogFormatters.
1364
        self.merge_depth = merge_depth
1365
        self.delta = delta
1366
        self.tags = tags
3943.5.2 by Ian Clatworthy
hand control of diff formatting to the log formatter
1367
        self.diff = diff
5971.1.39 by Jonathan Riddell
add signature verification to log option, alas breaks write lock
1368
        self.signature = signature
2466.8.1 by Kent Gibson
Reworked LogFormatter API to simplify extending the attributes of the revision being logged. Added support for begin_log() and end_log() hooks in LogFormatters.
1369
1370
794 by Martin Pool
- Merge John's nice short-log format.
1371
class LogFormatter(object):
2466.8.1 by Kent Gibson
Reworked LogFormatter API to simplify extending the attributes of the revision being logged. Added support for begin_log() and end_log() hooks in LogFormatters.
1372
    """Abstract class to display log messages.
1373
1374
    At a minimum, a derived class must implement the log_revision method.
1375
1376
    If the LogFormatter needs to be informed of the beginning or end of
1377
    a log it should implement the begin_log and/or end_log hook methods.
1378
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1379
    A LogFormatter should define the following supports_XXX flags
2466.8.1 by Kent Gibson
Reworked LogFormatter API to simplify extending the attributes of the revision being logged. Added support for begin_log() and end_log() hooks in LogFormatters.
1380
    to indicate which LogRevision attributes it supports:
1381
1382
    - supports_delta must be True if this log formatter supports delta.
5891.1.3 by Andrew Bennetts
Move docstring formatting fixes.
1383
      Otherwise the delta attribute may not be populated.  The 'delta_format'
1384
      attribute describes whether the 'short_status' format (1) or the long
1385
      one (2) should be used.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1386
1387
    - supports_merge_revisions must be True if this log formatter supports
5891.1.3 by Andrew Bennetts
Move docstring formatting fixes.
1388
      merge revisions.  If not, then only mainline revisions will be passed
1389
      to the formatter.
3943.5.2 by Ian Clatworthy
hand control of diff formatting to the log formatter
1390
3947.1.6 by Ian Clatworthy
log -n/--level-count N option
1391
    - preferred_levels is the number of levels this formatter defaults to.
5891.1.3 by Andrew Bennetts
Move docstring formatting fixes.
1392
      The default value is zero meaning display all levels.
1393
      This value is only relevant if supports_merge_revisions is True.
3947.1.1 by Ian Clatworthy
add --merge-revisions to log
1394
2466.8.1 by Kent Gibson
Reworked LogFormatter API to simplify extending the attributes of the revision being logged. Added support for begin_log() and end_log() hooks in LogFormatters.
1395
    - supports_tags must be True if this log formatter supports tags.
5891.1.3 by Andrew Bennetts
Move docstring formatting fixes.
1396
      Otherwise the tags attribute may not be populated.
3144.7.1 by Guillermo Gonzalez
* added show_properties to LonLogFormat and the hooks to register custom functions
1397
3943.5.2 by Ian Clatworthy
hand control of diff formatting to the log formatter
1398
    - supports_diff must be True if this log formatter supports diffs.
5891.1.3 by Andrew Bennetts
Move docstring formatting fixes.
1399
      Otherwise the diff attribute may not be populated.
3943.5.2 by Ian Clatworthy
hand control of diff formatting to the log formatter
1400
5971.1.39 by Jonathan Riddell
add signature verification to log option, alas breaks write lock
1401
    - supports_signatures must be True if this log formatter supports GPG
1402
      signatures.
1403
3144.7.1 by Guillermo Gonzalez
* added show_properties to LonLogFormat and the hooks to register custom functions
1404
    Plugins can register functions to show custom revision properties using
3144.7.13 by Guillermo Gonzalez
* fixed typo LogFormatter.show_properties in docstring
1405
    the properties_handler_registry. The registered function
5891.1.3 by Andrew Bennetts
Move docstring formatting fixes.
1406
    must respect the following interface description::
1407
3144.7.2 by Guillermo Gonzalez
* cleanup a bit the interface
1408
        def my_show_properties(properties_dict):
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1409
            # code that returns a dict {'name':'value'} of the properties
3144.7.2 by Guillermo Gonzalez
* cleanup a bit the interface
1410
            # to be shown
2466.8.1 by Kent Gibson
Reworked LogFormatter API to simplify extending the attributes of the revision being logged. Added support for begin_log() and end_log() hooks in LogFormatters.
1411
    """
3947.1.10 by Ian Clatworthy
review feedback from vila
1412
    preferred_levels = 0
1704.2.20 by Martin Pool
log --line shows revision numbers (Alexander)
1413
3874.1.4 by Vincent Ladeuil
Fixed as per Aarons' comment.
1414
    def __init__(self, to_file, show_ids=False, show_timezone='original',
4955.4.5 by Vincent Ladeuil
Start reproducing the problems reported in the bug.
1415
                 delta_format=None, levels=None, show_advice=False,
4081.3.10 by Martin von Gagern
Renamed "authors" to "author_list_handler" in several places.
1416
                 to_exact_file=None, author_list_handler=None):
3947.1.1 by Ian Clatworthy
add --merge-revisions to log
1417
        """Create a LogFormatter.
1418
1419
        :param to_file: the file to output to
4792.8.11 by Martin Pool
Give LogFormatters a second byte output stream for their diffs
1420
        :param to_exact_file: if set, gives an output stream to which 
1421
             non-Unicode diffs are written.
3947.1.1 by Ian Clatworthy
add --merge-revisions to log
1422
        :param show_ids: if True, revision-ids are to be displayed
1423
        :param show_timezone: the timezone to use
1424
        :param delta_format: the level of delta information to display
4221.2.3 by Ian Clatworthy
jam feedback: don't show advice if --levels explicitly given
1425
          or None to leave it to the formatter to decide
3947.1.6 by Ian Clatworthy
log -n/--level-count N option
1426
        :param levels: the number of levels to display; None or -1 to
1427
          let the log formatter decide.
4221.2.3 by Ian Clatworthy
jam feedback: don't show advice if --levels explicitly given
1428
        :param show_advice: whether to show advice at the end of the
1429
          log or not
4081.3.10 by Martin von Gagern
Renamed "authors" to "author_list_handler" in several places.
1430
        :param author_list_handler: callable generating a list of
1431
          authors to display for a given revision
3947.1.1 by Ian Clatworthy
add --merge-revisions to log
1432
        """
794 by Martin Pool
- Merge John's nice short-log format.
1433
        self.to_file = to_file
4110.1.1 by Alexander Belchenko
Fixed problem with `log -p` and non-ascii content of files: show_diff should write the diff to exact [stdout] stream.
1434
        # 'exact' stream used to show diff, it should print content 'as is'
1435
        # and should not try to decode/encode it to unicode to avoid bug #328007
4792.8.11 by Martin Pool
Give LogFormatters a second byte output stream for their diffs
1436
        if to_exact_file is not None:
1437
            self.to_exact_file = to_exact_file
1438
        else:
4792.8.12 by Martin Pool
comment
1439
            # XXX: somewhat hacky; this assumes it's a codec writer; it's better
1440
            # for code that expects to get diffs to pass in the exact file
1441
            # stream
4792.8.11 by Martin Pool
Give LogFormatters a second byte output stream for their diffs
1442
            self.to_exact_file = getattr(to_file, 'stream', to_file)
794 by Martin Pool
- Merge John's nice short-log format.
1443
        self.show_ids = show_ids
1444
        self.show_timezone = show_timezone
3874.1.4 by Vincent Ladeuil
Fixed as per Aarons' comment.
1445
        if delta_format is None:
1446
            # Ensures backward compatibility
1447
            delta_format = 2 # long format
1448
        self.delta_format = delta_format
3947.1.6 by Ian Clatworthy
log -n/--level-count N option
1449
        self.levels = levels
4221.2.3 by Ian Clatworthy
jam feedback: don't show advice if --levels explicitly given
1450
        self._show_advice = show_advice
4208.2.1 by Ian Clatworthy
merge indicators in log --long
1451
        self._merge_count = 0
4081.3.10 by Martin von Gagern
Renamed "authors" to "author_list_handler" in several places.
1452
        self._author_list_handler = author_list_handler
3947.1.6 by Ian Clatworthy
log -n/--level-count N option
1453
3947.1.10 by Ian Clatworthy
review feedback from vila
1454
    def get_levels(self):
1455
        """Get the number of levels to display or 0 for all."""
3947.1.6 by Ian Clatworthy
log -n/--level-count N option
1456
        if getattr(self, 'supports_merge_revisions', False):
1457
            if self.levels is None or self.levels == -1:
4217.2.1 by Ian Clatworthy
fix log advice when the # of levels is implicit
1458
                self.levels = self.preferred_levels
1459
        else:
1460
            self.levels = 1
1461
        return self.levels
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
1462
3947.1.10 by Ian Clatworthy
review feedback from vila
1463
    def log_revision(self, revision):
1464
        """Log a revision.
1465
1466
        :param  revision:   The LogRevision to be logged.
1467
        """
1468
        raise NotImplementedError('not implemented in abstract base')
2466.8.1 by Kent Gibson
Reworked LogFormatter API to simplify extending the attributes of the revision being logged. Added support for begin_log() and end_log() hooks in LogFormatters.
1469
4208.2.1 by Ian Clatworthy
merge indicators in log --long
1470
    def show_advice(self):
1471
        """Output user advice, if any, when the log is completed."""
4221.2.3 by Ian Clatworthy
jam feedback: don't show advice if --levels explicitly given
1472
        if self._show_advice and self.levels == 1 and self._merge_count > 0:
4208.2.1 by Ian Clatworthy
merge indicators in log --long
1473
            advice_sep = self.get_advice_separator()
1474
            if advice_sep:
1475
                self.to_file.write(advice_sep)
4208.2.2 by Ian Clatworthy
show --levels 0 in advice, not just -n0
1476
            self.to_file.write(
4221.2.1 by Ian Clatworthy
--include-merges as an alias for --levels 0 in log
1477
                "Use --include-merges or -n0 to see merged revisions.\n")
4208.2.1 by Ian Clatworthy
merge indicators in log --long
1478
1479
    def get_advice_separator(self):
1480
        """Get the text separating the log from the closing advice."""
1481
        return ''
1482
1185.35.19 by Aaron Bentley
Tweaked short-log as Meinel suggested
1483
    def short_committer(self, rev):
3063.3.2 by Lukáš Lalinský
Move the name and e-mail address extraction logic to config.parse_username.
1484
        name, address = config.parse_username(rev.committer)
1485
        if name:
3063.3.1 by Lukáš Lalinský
Fall back to showing e-mail in ``log --short/--line`` if the committer/author has only e-mail.
1486
            return name
3063.3.2 by Lukáš Lalinský
Move the name and e-mail address extraction logic to config.parse_username.
1487
        return address
2388.1.11 by Alexander Belchenko
changes after John's review
1488
2671.5.4 by Lukáš Lalinsky
Replace the committer with the author in log, the committer is displayed only in the long format and only if it's different from the author.
1489
    def short_author(self, rev):
4081.3.14 by Martin von Gagern
Pass keyword arguments of authors method by name.
1490
        return self.authors(rev, 'first', short=True, sep=', ')
4081.3.2 by Martin von Gagern
Provide --authors argument to log command.
1491
1492
    def authors(self, rev, who, short=False, sep=None):
4081.3.13 by Martin von Gagern
Added extensive docstring and comments to authors method.
1493
        """Generate list of authors, taking --authors option into account.
1494
1495
        The caller has to specify the name of a author list handler,
1496
        as provided by the author list registry, using the ``who``
1497
        argument.  That name only sets a default, though: when the
1498
        user selected a different author list generation using the
1499
        ``--authors`` command line switch, as represented by the
1500
        ``author_list_handler`` constructor argument, that value takes
1501
        precedence.
1502
1503
        :param rev: The revision for which to generate the list of authors.
1504
        :param who: Name of the default handler.
1505
        :param short: Whether to shorten names to either name or address.
1506
        :param sep: What separator to use for automatic concatenation.
1507
        """
4081.3.10 by Martin von Gagern
Renamed "authors" to "author_list_handler" in several places.
1508
        if self._author_list_handler is not None:
4081.3.13 by Martin von Gagern
Added extensive docstring and comments to authors method.
1509
            # The user did specify --authors, which overrides the default
4081.3.10 by Martin von Gagern
Renamed "authors" to "author_list_handler" in several places.
1510
            author_list_handler = self._author_list_handler
4081.3.2 by Martin von Gagern
Provide --authors argument to log command.
1511
        else:
4081.3.13 by Martin von Gagern
Added extensive docstring and comments to authors method.
1512
            # The user didn't specify --authors, so we use the caller's default
4081.3.9 by Martin von Gagern
Use proper registry for --authors option.
1513
            author_list_handler = author_list_registry.get(who)
1514
        names = author_list_handler(rev)
4081.3.2 by Martin von Gagern
Provide --authors argument to log command.
1515
        if short:
1516
            for i in range(len(names)):
1517
                name, address = config.parse_username(names[i])
1518
                if name:
1519
                    names[i] = name
1520
                else:
1521
                    names[i] = address
1522
        if sep is not None:
1523
            names = sep.join(names)
1524
        return names
2671.5.4 by Lukáš Lalinsky
Replace the committer with the author in log, the committer is displayed only in the long format and only if it's different from the author.
1525
4208.2.1 by Ian Clatworthy
merge indicators in log --long
1526
    def merge_marker(self, revision):
4213.1.1 by Ian Clatworthy
merge indicators in log --long (Ian Clatworthy)
1527
        """Get the merge marker to include in the output or '' if none."""
4208.2.1 by Ian Clatworthy
merge indicators in log --long
1528
        if len(revision.rev.parent_ids) > 1:
1529
            self._merge_count += 1
1530
            return ' [merge]'
1531
        else:
1532
            return ''
1533
3144.7.9 by Guillermo Gonzalez
* bzrlib.log.show_roperties don't hide handler errors
1534
    def show_properties(self, revision, indent):
3144.7.8 by Guillermo Gonzalez
* added error handling (and logging) to LogFormatter.show_properties when a handler raise an error
1535
        """Displays the custom properties returned by each registered handler.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1536
3144.7.13 by Guillermo Gonzalez
* fixed typo LogFormatter.show_properties in docstring
1537
        If a registered handler raises an error it is propagated.
3144.7.5 by Guillermo Gonzalez
* some improvements to the doctstring in show_properties method and in LogFormatter
1538
        """
4379.4.1 by Ian Clatworthy
make log --long faster
1539
        for line in self.custom_properties(revision):
1540
            self.to_file.write("%s%s\n" % (indent, line))
1541
1542
    def custom_properties(self, revision):
1543
        """Format the custom properties returned by each registered handler.
1544
1545
        If a registered handler raises an error it is propagated.
1546
1547
        :return: a list of formatted lines (excluding trailing newlines)
1548
        """
4379.4.3 by Ian Clatworthy
merge bzr.dev r4426
1549
        lines = self._foreign_info_properties(revision)
1550
        for key, handler in properties_handler_registry.iteritems():
1551
            lines.extend(self._format_properties(handler(revision)))
1552
        return lines
1553
1554
    def _foreign_info_properties(self, rev):
4393.1.2 by Jelmer Vernooij
Move showing of foreign revision info onto log, for better performance.
1555
        """Custom log displayer for foreign revision identifiers.
1556
1557
        :param rev: Revision object.
1558
        """
1559
        # Revision comes directly from a foreign repository
1560
        if isinstance(rev, foreign.ForeignRevision):
5092.1.2 by Vincent Ladeuil
Fix bug #519862.
1561
            return self._format_properties(
1562
                rev.mapping.vcs.show_foreign_revid(rev.foreign_revid))
4393.1.2 by Jelmer Vernooij
Move showing of foreign revision info onto log, for better performance.
1563
1564
        # Imported foreign revision revision ids always contain :
1565
        if not ":" in rev.revision_id:
4379.4.3 by Ian Clatworthy
merge bzr.dev r4426
1566
            return []
4393.1.2 by Jelmer Vernooij
Move showing of foreign revision info onto log, for better performance.
1567
1568
        # Revision was once imported from a foreign repository
1569
        try:
1570
            foreign_revid, mapping = \
1571
                foreign.foreign_vcs_registry.parse_revision_id(rev.revision_id)
1572
        except errors.InvalidRevisionId:
4379.4.3 by Ian Clatworthy
merge bzr.dev r4426
1573
            return []
4393.1.2 by Jelmer Vernooij
Move showing of foreign revision info onto log, for better performance.
1574
4379.4.3 by Ian Clatworthy
merge bzr.dev r4426
1575
        return self._format_properties(
4393.1.2 by Jelmer Vernooij
Move showing of foreign revision info onto log, for better performance.
1576
            mapping.vcs.show_foreign_revid(foreign_revid))
1577
4379.4.3 by Ian Clatworthy
merge bzr.dev r4426
1578
    def _format_properties(self, properties):
4379.4.1 by Ian Clatworthy
make log --long faster
1579
        lines = []
4393.1.2 by Jelmer Vernooij
Move showing of foreign revision info onto log, for better performance.
1580
        for key, value in properties.items():
4379.4.3 by Ian Clatworthy
merge bzr.dev r4426
1581
            lines.append(key + ': ' + value)
4379.4.1 by Ian Clatworthy
make log --long faster
1582
        return lines
3144.7.8 by Guillermo Gonzalez
* added error handling (and logging) to LogFormatter.show_properties when a handler raise an error
1583
3943.5.2 by Ian Clatworthy
hand control of diff formatting to the log formatter
1584
    def show_diff(self, to_file, diff, indent):
1585
        for l in diff.rstrip().split('\n'):
1586
            to_file.write(indent + '%s\n' % (l,))
1587
2388.1.11 by Alexander Belchenko
changes after John's review
1588
4379.4.1 by Ian Clatworthy
make log --long faster
1589
# Separator between revisions in long format
1590
_LONG_SEP = '-' * 60
1591
1592
794 by Martin Pool
- Merge John's nice short-log format.
1593
class LongLogFormatter(LogFormatter):
2388.1.11 by Alexander Belchenko
changes after John's review
1594
2466.8.1 by Kent Gibson
Reworked LogFormatter API to simplify extending the attributes of the revision being logged. Added support for begin_log() and end_log() hooks in LogFormatters.
1595
    supports_merge_revisions = True
4206.1.1 by Ian Clatworthy
log mainline by default
1596
    preferred_levels = 1
2466.8.1 by Kent Gibson
Reworked LogFormatter API to simplify extending the attributes of the revision being logged. Added support for begin_log() and end_log() hooks in LogFormatters.
1597
    supports_delta = True
1598
    supports_tags = True
3943.5.2 by Ian Clatworthy
hand control of diff formatting to the log formatter
1599
    supports_diff = True
5971.1.39 by Jonathan Riddell
add signature verification to log option, alas breaks write lock
1600
    supports_signatures = True
2388.1.10 by Alexander Belchenko
Slightly reworked: use None instead of [] as default tags list; PEP-8
1601
4379.4.1 by Ian Clatworthy
make log --long faster
1602
    def __init__(self, *args, **kwargs):
1603
        super(LongLogFormatter, self).__init__(*args, **kwargs)
1604
        if self.show_timezone == 'original':
1605
            self.date_string = self._date_string_original_timezone
1606
        else:
1607
            self.date_string = self._date_string_with_timezone
1608
1609
    def _date_string_with_timezone(self, rev):
1610
        return format_date(rev.timestamp, rev.timezone or 0,
1611
                           self.show_timezone)
1612
1613
    def _date_string_original_timezone(self, rev):
1614
        return format_date_with_offset_in_original_timezone(rev.timestamp,
1615
            rev.timezone or 0)
1616
2466.8.1 by Kent Gibson
Reworked LogFormatter API to simplify extending the attributes of the revision being logged. Added support for begin_log() and end_log() hooks in LogFormatters.
1617
    def log_revision(self, revision):
1618
        """Log a revision, either merged or not."""
2671.2.5 by Lukáš Lalinský
Fixes for comments from the mailing list.
1619
        indent = '    ' * revision.merge_depth
4379.4.1 by Ian Clatworthy
make log --long faster
1620
        lines = [_LONG_SEP]
2466.8.1 by Kent Gibson
Reworked LogFormatter API to simplify extending the attributes of the revision being logged. Added support for begin_log() and end_log() hooks in LogFormatters.
1621
        if revision.revno is not None:
4379.4.1 by Ian Clatworthy
make log --long faster
1622
            lines.append('revno: %s%s' % (revision.revno,
4208.2.1 by Ian Clatworthy
merge indicators in log --long
1623
                self.merge_marker(revision)))
2466.8.1 by Kent Gibson
Reworked LogFormatter API to simplify extending the attributes of the revision being logged. Added support for begin_log() and end_log() hooks in LogFormatters.
1624
        if revision.tags:
4379.4.1 by Ian Clatworthy
make log --long faster
1625
            lines.append('tags: %s' % (', '.join(revision.tags)))
5728.5.6 by Matt Giuca
log: 'long' and 'short' log formats now always show the revision-id for any
1626
        if self.show_ids or revision.revno is None:
4379.4.1 by Ian Clatworthy
make log --long faster
1627
            lines.append('revision-id: %s' % (revision.rev.revision_id,))
5728.5.6 by Matt Giuca
log: 'long' and 'short' log formats now always show the revision-id for any
1628
        if self.show_ids:
2466.8.1 by Kent Gibson
Reworked LogFormatter API to simplify extending the attributes of the revision being logged. Added support for begin_log() and end_log() hooks in LogFormatters.
1629
            for parent_id in revision.rev.parent_ids:
4379.4.1 by Ian Clatworthy
make log --long faster
1630
                lines.append('parent: %s' % (parent_id,))
1631
        lines.extend(self.custom_properties(revision.rev))
2671.2.2 by Lukáš Lalinský
Move setting of the author revision property to MutableTree.commit. Don't use try/except KeyError in LongLogFormatter to display authors and branch-nicks. Removed warning about missing e-mail in the authors name.
1632
4056.2.3 by James Westby
Use a new "authors" revision property to allow multiple authors
1633
        committer = revision.rev.committer
4081.3.2 by Martin von Gagern
Provide --authors argument to log command.
1634
        authors = self.authors(revision.rev, 'all')
4056.2.3 by James Westby
Use a new "authors" revision property to allow multiple authors
1635
        if authors != [committer]:
4379.4.1 by Ian Clatworthy
make log --long faster
1636
            lines.append('author: %s' % (", ".join(authors),))
1637
        lines.append('committer: %s' % (committer,))
2671.2.2 by Lukáš Lalinský
Move setting of the author revision property to MutableTree.commit. Don't use try/except KeyError in LongLogFormatter to display authors and branch-nicks. Removed warning about missing e-mail in the authors name.
1638
1639
        branch_nick = revision.rev.properties.get('branch-nick', None)
1640
        if branch_nick is not None:
4379.4.1 by Ian Clatworthy
make log --long faster
1641
            lines.append('branch nick: %s' % (branch_nick,))
1642
1643
        lines.append('timestamp: %s' % (self.date_string(revision.rev),))
1644
5971.1.39 by Jonathan Riddell
add signature verification to log option, alas breaks write lock
1645
        if revision.signature is not None:
1646
            lines.append('signature: ' + revision.signature)
1647
4379.4.1 by Ian Clatworthy
make log --long faster
1648
        lines.append('message:')
2466.8.1 by Kent Gibson
Reworked LogFormatter API to simplify extending the attributes of the revision being logged. Added support for begin_log() and end_log() hooks in LogFormatters.
1649
        if not revision.rev.message:
4379.4.1 by Ian Clatworthy
make log --long faster
1650
            lines.append('  (no message)')
1433 by Robert Collins
merge in and make incremental Gustavo Niemeyers nested log patch, and remove all bare exceptions in store and transport packages.
1651
        else:
2466.8.1 by Kent Gibson
Reworked LogFormatter API to simplify extending the attributes of the revision being logged. Added support for begin_log() and end_log() hooks in LogFormatters.
1652
            message = revision.rev.message.rstrip('\r\n')
1185.31.20 by John Arbash Meinel
Stripping trailing newlines when displaying log messages
1653
            for l in message.split('\n'):
4379.4.1 by Ian Clatworthy
make log --long faster
1654
                lines.append('  %s' % (l,))
1655
1656
        # Dump the output, appending the delta and diff if requested
1657
        to_file = self.to_file
1658
        to_file.write("%s%s\n" % (indent, ('\n' + indent).join(lines)))
2466.8.1 by Kent Gibson
Reworked LogFormatter API to simplify extending the attributes of the revision being logged. Added support for begin_log() and end_log() hooks in LogFormatters.
1659
        if revision.delta is not None:
5076.4.2 by Arnaud Jeansen
Create a short show callback using the previously removed short code (it was not dead, only not used by status). Port log to directly call the callbacks.
1660
            # Use the standard status output to display changes
5076.4.4 by Arnaud Jeansen
Add a unified report_delta method
1661
            from bzrlib.delta import report_delta
1662
            report_delta(to_file, revision.delta, short_status=False, 
1663
                         show_ids=self.show_ids, indent=indent)
3943.5.2 by Ian Clatworthy
hand control of diff formatting to the log formatter
1664
        if revision.diff is not None:
1665
            to_file.write(indent + 'diff:\n')
4792.8.11 by Martin Pool
Give LogFormatters a second byte output stream for their diffs
1666
            to_file.flush()
3943.5.6 by Ian Clatworthy
feedback from jam's review
1667
            # Note: we explicitly don't indent the diff (relative to the
1668
            # revision information) so that the output can be fed to patch -p0
4110.1.1 by Alexander Belchenko
Fixed problem with `log -p` and non-ascii content of files: show_diff should write the diff to exact [stdout] stream.
1669
            self.show_diff(self.to_exact_file, revision.diff, indent)
4792.8.11 by Martin Pool
Give LogFormatters a second byte output stream for their diffs
1670
            self.to_exact_file.flush()
794 by Martin Pool
- Merge John's nice short-log format.
1671
4208.2.1 by Ian Clatworthy
merge indicators in log --long
1672
    def get_advice_separator(self):
1673
        """Get the text separating the log from the closing advice."""
1674
        return '-' * 60 + '\n'
1675
794 by Martin Pool
- Merge John's nice short-log format.
1676
1677
class ShortLogFormatter(LogFormatter):
2466.8.1 by Kent Gibson
Reworked LogFormatter API to simplify extending the attributes of the revision being logged. Added support for begin_log() and end_log() hooks in LogFormatters.
1678
3947.1.1 by Ian Clatworthy
add --merge-revisions to log
1679
    supports_merge_revisions = True
3947.1.6 by Ian Clatworthy
log -n/--level-count N option
1680
    preferred_levels = 1
2466.8.1 by Kent Gibson
Reworked LogFormatter API to simplify extending the attributes of the revision being logged. Added support for begin_log() and end_log() hooks in LogFormatters.
1681
    supports_delta = True
3946.3.1 by Ian Clatworthy
extend ShortLogFormatter & LineLogFormatter to support tags
1682
    supports_tags = True
3943.5.2 by Ian Clatworthy
hand control of diff formatting to the log formatter
1683
    supports_diff = True
2466.8.1 by Kent Gibson
Reworked LogFormatter API to simplify extending the attributes of the revision being logged. Added support for begin_log() and end_log() hooks in LogFormatters.
1684
3947.1.9 by Ian Clatworthy
get offset right when dotted-revno in column 1
1685
    def __init__(self, *args, **kwargs):
1686
        super(ShortLogFormatter, self).__init__(*args, **kwargs)
1687
        self.revno_width_by_depth = {}
1688
2466.8.1 by Kent Gibson
Reworked LogFormatter API to simplify extending the attributes of the revision being logged. Added support for begin_log() and end_log() hooks in LogFormatters.
1689
    def log_revision(self, revision):
3947.1.7 by Ian Clatworthy
tweak indenting/offsetting for --short given dotted revno lengths
1690
        # We need two indents: one per depth and one for the information
1691
        # relative to that indent. Most mainline revnos are 5 chars or
3970.1.1 by Ian Clatworthy
log -n/--levels (Ian Clatworthy)
1692
        # less while dotted revnos are typically 11 chars or less. Once
3947.1.9 by Ian Clatworthy
get offset right when dotted-revno in column 1
1693
        # calculated, we need to remember the offset for a given depth
1694
        # as we might be starting from a dotted revno in the first column
1695
        # and we want subsequent mainline revisions to line up.
1696
        depth = revision.merge_depth
1697
        indent = '    ' * depth
1698
        revno_width = self.revno_width_by_depth.get(depth)
1699
        if revno_width is None:
5728.5.5 by Matt Giuca
log: If a revision is not in the branch, it now sets its revno to None
1700
            if revision.revno is None or revision.revno.find('.') == -1:
3947.1.10 by Ian Clatworthy
review feedback from vila
1701
                # mainline revno, e.g. 12345
3947.1.9 by Ian Clatworthy
get offset right when dotted-revno in column 1
1702
                revno_width = 5
1703
            else:
3947.1.10 by Ian Clatworthy
review feedback from vila
1704
                # dotted revno, e.g. 12345.10.55
1705
                revno_width = 11
3947.1.9 by Ian Clatworthy
get offset right when dotted-revno in column 1
1706
            self.revno_width_by_depth[depth] = revno_width
3947.1.7 by Ian Clatworthy
tweak indenting/offsetting for --short given dotted revno lengths
1707
        offset = ' ' * (revno_width + 1)
1708
794 by Martin Pool
- Merge John's nice short-log format.
1709
        to_file = self.to_file
3946.3.1 by Ian Clatworthy
extend ShortLogFormatter & LineLogFormatter to support tags
1710
        tags = ''
1711
        if revision.tags:
3946.3.2 by Ian Clatworthy
add tests & NEWS item
1712
            tags = ' {%s}' % (', '.join(revision.tags))
3947.1.8 by Ian Clatworthy
merge bzr.dev r3954
1713
        to_file.write(indent + "%*s %s\t%s%s%s\n" % (revno_width,
5728.5.5 by Matt Giuca
log: If a revision is not in the branch, it now sets its revno to None
1714
                revision.revno or "", self.short_author(revision.rev),
2483.2.5 by John Arbash Meinel
[merge] bzr.dev 2501
1715
                format_date(revision.rev.timestamp,
2466.8.1 by Kent Gibson
Reworked LogFormatter API to simplify extending the attributes of the revision being logged. Added support for begin_log() and end_log() hooks in LogFormatters.
1716
                            revision.rev.timezone or 0,
1185.35.19 by Aaron Bentley
Tweaked short-log as Meinel suggested
1717
                            self.show_timezone, date_fmt="%Y-%m-%d",
2483.2.5 by John Arbash Meinel
[merge] bzr.dev 2501
1718
                            show_offset=False),
4208.2.1 by Ian Clatworthy
merge indicators in log --long
1719
                tags, self.merge_marker(revision)))
3976.3.1 by Neil Martinsen-Burrell
Add custom properties handling to short log format
1720
        self.show_properties(revision.rev, indent+offset)
5728.5.6 by Matt Giuca
log: 'long' and 'short' log formats now always show the revision-id for any
1721
        if self.show_ids or revision.revno is None:
3947.1.7 by Ian Clatworthy
tweak indenting/offsetting for --short given dotted revno lengths
1722
            to_file.write(indent + offset + 'revision-id:%s\n'
3874.1.4 by Vincent Ladeuil
Fixed as per Aarons' comment.
1723
                          % (revision.rev.revision_id,))
2466.8.1 by Kent Gibson
Reworked LogFormatter API to simplify extending the attributes of the revision being logged. Added support for begin_log() and end_log() hooks in LogFormatters.
1724
        if not revision.rev.message:
3947.1.7 by Ian Clatworthy
tweak indenting/offsetting for --short given dotted revno lengths
1725
            to_file.write(indent + offset + '(no message)\n')
794 by Martin Pool
- Merge John's nice short-log format.
1726
        else:
2466.8.1 by Kent Gibson
Reworked LogFormatter API to simplify extending the attributes of the revision being logged. Added support for begin_log() and end_log() hooks in LogFormatters.
1727
            message = revision.rev.message.rstrip('\r\n')
1185.31.20 by John Arbash Meinel
Stripping trailing newlines when displaying log messages
1728
            for l in message.split('\n'):
3947.1.7 by Ian Clatworthy
tweak indenting/offsetting for --short given dotted revno lengths
1729
                to_file.write(indent + offset + '%s\n' % (l,))
794 by Martin Pool
- Merge John's nice short-log format.
1730
2466.8.1 by Kent Gibson
Reworked LogFormatter API to simplify extending the attributes of the revision being logged. Added support for begin_log() and end_log() hooks in LogFormatters.
1731
        if revision.delta is not None:
5076.4.2 by Arnaud Jeansen
Create a short show callback using the previously removed short code (it was not dead, only not used by status). Port log to directly call the callbacks.
1732
            # Use the standard status output to display changes
5076.4.4 by Arnaud Jeansen
Add a unified report_delta method
1733
            from bzrlib.delta import report_delta
5076.4.6 by Arnaud Jeansen
Go back to unified report_delta method (i.e. former TreeDelta.show())
1734
            report_delta(to_file, revision.delta, 
1735
                         short_status=self.delta_format==1, 
5076.4.4 by Arnaud Jeansen
Add a unified report_delta method
1736
                         show_ids=self.show_ids, indent=indent + offset)
3943.5.2 by Ian Clatworthy
hand control of diff formatting to the log formatter
1737
        if revision.diff is not None:
4110.1.1 by Alexander Belchenko
Fixed problem with `log -p` and non-ascii content of files: show_diff should write the diff to exact [stdout] stream.
1738
            self.show_diff(self.to_exact_file, revision.diff, '      ')
2911.6.1 by Blake Winton
Change 'print >> f,'s to 'f.write('s.
1739
        to_file.write('\n')
794 by Martin Pool
- Merge John's nice short-log format.
1740
1704.2.20 by Martin Pool
log --line shows revision numbers (Alexander)
1741
1185.12.25 by Aaron Bentley
Added one-line log format
1742
class LineLogFormatter(LogFormatter):
2466.8.1 by Kent Gibson
Reworked LogFormatter API to simplify extending the attributes of the revision being logged. Added support for begin_log() and end_log() hooks in LogFormatters.
1743
3947.1.1 by Ian Clatworthy
add --merge-revisions to log
1744
    supports_merge_revisions = True
3947.1.6 by Ian Clatworthy
log -n/--level-count N option
1745
    preferred_levels = 1
3946.3.1 by Ian Clatworthy
extend ShortLogFormatter & LineLogFormatter to support tags
1746
    supports_tags = True
2997.1.1 by Kent Gibson
Support logging single merge revisions with short and line log formatters.
1747
2466.8.1 by Kent Gibson
Reworked LogFormatter API to simplify extending the attributes of the revision being logged. Added support for begin_log() and end_log() hooks in LogFormatters.
1748
    def __init__(self, *args, **kwargs):
1749
        super(LineLogFormatter, self).__init__(*args, **kwargs)
4747.3.6 by Vincent Ladeuil
terminal_width can now returns None.
1750
        width = terminal_width()
1751
        if width is not None:
1752
            # we need one extra space for terminals that wrap on last char
1753
            width = width - 1
1754
        self._max_chars = width
2466.8.1 by Kent Gibson
Reworked LogFormatter API to simplify extending the attributes of the revision being logged. Added support for begin_log() and end_log() hooks in LogFormatters.
1755
1185.12.25 by Aaron Bentley
Added one-line log format
1756
    def truncate(self, str, max_len):
4747.3.6 by Vincent Ladeuil
terminal_width can now returns None.
1757
        if max_len is None or len(str) <= max_len:
1185.12.25 by Aaron Bentley
Added one-line log format
1758
            return str
4747.3.6 by Vincent Ladeuil
terminal_width can now returns None.
1759
        return str[:max_len-3] + '...'
1185.12.25 by Aaron Bentley
Added one-line log format
1760
1761
    def date_string(self, rev):
3842.2.4 by Vincent Ladeuil
Superficial fix for bug #300055.
1762
        return format_date(rev.timestamp, rev.timezone or 0,
1185.12.25 by Aaron Bentley
Added one-line log format
1763
                           self.show_timezone, date_fmt="%Y-%m-%d",
1764
                           show_offset=False)
1765
1766
    def message(self, rev):
1767
        if not rev.message:
1768
            return '(no message)'
1769
        else:
1770
            return rev.message
1771
2466.8.1 by Kent Gibson
Reworked LogFormatter API to simplify extending the attributes of the revision being logged. Added support for begin_log() and end_log() hooks in LogFormatters.
1772
    def log_revision(self, revision):
3947.1.1 by Ian Clatworthy
add --merge-revisions to log
1773
        indent = '  ' * revision.merge_depth
2911.6.1 by Blake Winton
Change 'print >> f,'s to 'f.write('s.
1774
        self.to_file.write(self.log_string(revision.revno, revision.rev,
3947.1.8 by Ian Clatworthy
merge bzr.dev r3954
1775
            self._max_chars, revision.tags, indent))
2911.6.1 by Blake Winton
Change 'print >> f,'s to 'f.write('s.
1776
        self.to_file.write('\n')
2466.8.1 by Kent Gibson
Reworked LogFormatter API to simplify extending the attributes of the revision being logged. Added support for begin_log() and end_log() hooks in LogFormatters.
1777
3947.1.8 by Ian Clatworthy
merge bzr.dev r3954
1778
    def log_string(self, revno, rev, max_chars, tags=None, prefix=''):
1704.2.20 by Martin Pool
log --line shows revision numbers (Alexander)
1779
        """Format log info into one string. Truncate tail of string
5891.1.3 by Andrew Bennetts
Move docstring formatting fixes.
1780
1781
        :param revno:      revision number or None.
1782
                           Revision numbers counts from 1.
1783
        :param rev:        revision object
1784
        :param max_chars:  maximum length of resulting string
1785
        :param tags:       list of tags or None
1786
        :param prefix:     string to prefix each line
1787
        :return:           formatted truncated string
1704.2.20 by Martin Pool
log --line shows revision numbers (Alexander)
1788
        """
1789
        out = []
1790
        if revno:
1791
            # show revno only when is not None
3946.3.4 by Ian Clatworthy
minor cleanup
1792
            out.append("%s:" % revno)
5725.1.1 by Neil Martinsen-Burrell
Scale author field with length of line in LineLogFormatter
1793
        if max_chars is not None:
5725.1.2 by Neil Martinsen-Burrell
keep current behavior the same by rounding up
1794
            out.append(self.truncate(self.short_author(rev), (max_chars+3)/4))
5725.1.1 by Neil Martinsen-Burrell
Scale author field with length of line in LineLogFormatter
1795
        else:
1796
            out.append(self.short_author(rev))
1185.12.25 by Aaron Bentley
Added one-line log format
1797
        out.append(self.date_string(rev))
3983.2.1 by Neil Martinsen-Burrell
add merge indication to the line format
1798
        if len(rev.parent_ids) > 1:
1799
            out.append('[merge]')
3946.3.3 by Ian Clatworthy
feedback from jelmer re position of tags in --line
1800
        if tags:
1801
            tag_str = '{%s}' % (', '.join(tags))
1802
            out.append(tag_str)
1740.2.5 by Aaron Bentley
Merge from bzr.dev
1803
        out.append(rev.get_summary())
3947.1.1 by Ian Clatworthy
add --merge-revisions to log
1804
        return self.truncate(prefix + " ".join(out).rstrip('\n'), max_chars)
794 by Martin Pool
- Merge John's nice short-log format.
1805
1704.2.20 by Martin Pool
log --line shows revision numbers (Alexander)
1806
4129.1.1 by Andrea Bolognani
Renamed the ChangeLogLogFormatter class to GnuChangelogLogFormatter.
1807
class GnuChangelogLogFormatter(LogFormatter):
4070.4.1 by Andrea Bolognani
New GNU Changelog log format
1808
1809
    supports_merge_revisions = True
1810
    supports_delta = True
1811
1812
    def log_revision(self, revision):
1813
        """Log a revision, either merged or not."""
1814
        to_file = self.to_file
1815
1816
        date_str = format_date(revision.rev.timestamp,
1817
                               revision.rev.timezone or 0,
1818
                               self.show_timezone,
1819
                               date_fmt='%Y-%m-%d',
1820
                               show_offset=False)
4081.3.2 by Martin von Gagern
Provide --authors argument to log command.
1821
        committer_str = self.authors(revision.rev, 'first', sep=', ')
4081.3.6 by Martin von Gagern
Drop space to make John happy.
1822
        committer_str = committer_str.replace(' <', '  <')
4070.4.1 by Andrea Bolognani
New GNU Changelog log format
1823
        to_file.write('%s  %s\n\n' % (date_str,committer_str))
1824
4137.1.1 by James Westby
Small improvements to the GNU ChangeLog formatter.
1825
        if revision.delta is not None and revision.delta.has_changed():
4070.4.1 by Andrea Bolognani
New GNU Changelog log format
1826
            for c in revision.delta.added + revision.delta.removed + revision.delta.modified:
1827
                path, = c[:1]
1828
                to_file.write('\t* %s:\n' % (path,))
1829
            for c in revision.delta.renamed:
1830
                oldpath,newpath = c[:2]
1831
                # For renamed files, show both the old and the new path
1832
                to_file.write('\t* %s:\n\t* %s:\n' % (oldpath,newpath))
1833
            to_file.write('\n')
1834
1835
        if not revision.rev.message:
1836
            to_file.write('\tNo commit message\n')
1837
        else:
1838
            message = revision.rev.message.rstrip('\r\n')
1839
            for l in message.split('\n'):
1840
                to_file.write('\t%s\n' % (l.lstrip(),))
1841
            to_file.write('\n')
1842
1843
1185.12.27 by Aaron Bentley
Use line log for pending merges
1844
def line_log(rev, max_chars):
1845
    lf = LineLogFormatter(None)
1704.2.20 by Martin Pool
log --line shows revision numbers (Alexander)
1846
    return lf.log_string(None, rev, max_chars)
1185.12.27 by Aaron Bentley
Use line log for pending merges
1847
2221.4.10 by Aaron Bentley
Implement log options using RegistryOption
1848
1849
class LogFormatterRegistry(registry.Registry):
1850
    """Registry for log formatters"""
1851
1852
    def make_formatter(self, name, *args, **kwargs):
1853
        """Construct a formatter from arguments.
1854
1855
        :param name: Name of the formatter to construct.  'short', 'long' and
1856
            'line' are built-in.
1857
        """
1858
        return self.get(name)(*args, **kwargs)
1859
1860
    def get_default(self, branch):
1861
        return self.get(branch.get_config().log_format())
1862
1863
1864
log_formatter_registry = LogFormatterRegistry()
1865
1866
1867
log_formatter_registry.register('short', ShortLogFormatter,
1868
                                'Moderately short log format')
1869
log_formatter_registry.register('long', LongLogFormatter,
1870
                                'Detailed log format')
1871
log_formatter_registry.register('line', LineLogFormatter,
1872
                                'Log format with one line per revision')
4129.1.1 by Andrea Bolognani
Renamed the ChangeLogLogFormatter class to GnuChangelogLogFormatter.
1873
log_formatter_registry.register('gnu-changelog', GnuChangelogLogFormatter,
1874
                                'Format used by GNU ChangeLog files')
2221.4.10 by Aaron Bentley
Implement log options using RegistryOption
1875
794 by Martin Pool
- Merge John's nice short-log format.
1876
1553.2.1 by Erik Bågfors
Support for plugins to register log formatters and set default formatter
1877
def register_formatter(name, formatter):
2221.4.10 by Aaron Bentley
Implement log options using RegistryOption
1878
    log_formatter_registry.register(name, formatter)
1879
1553.2.1 by Erik Bågfors
Support for plugins to register log formatters and set default formatter
1880
794 by Martin Pool
- Merge John's nice short-log format.
1881
def log_formatter(name, *args, **kwargs):
1393.1.56 by Martin Pool
- doc and small refactoring of log code
1882
    """Construct a formatter from arguments.
1883
1185.12.27 by Aaron Bentley
Use line log for pending merges
1884
    name -- Name of the formatter to construct; currently 'long', 'short' and
1885
        'line' are supported.
1393.1.56 by Martin Pool
- doc and small refactoring of log code
1886
    """
794 by Martin Pool
- Merge John's nice short-log format.
1887
    try:
2221.4.10 by Aaron Bentley
Implement log options using RegistryOption
1888
        return log_formatter_registry.make_formatter(name, *args, **kwargs)
1553.2.2 by Erik Bågfors
Made "unknown log formatter" error message work
1889
    except KeyError:
3224.5.1 by Andrew Bennetts
Lots of assorted hackery to reduce the number of imports for common operations. Improves 'rocks', 'st' and 'help' times by ~50ms on my laptop.
1890
        raise errors.BzrCommandError("unknown log formatter: %r" % name)
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
1891
4081.3.12 by Martin von Gagern
Separate top level functions with two blank lines.
1892
4081.3.9 by Martin von Gagern
Use proper registry for --authors option.
1893
def author_list_all(rev):
1894
    return rev.get_apparent_authors()[:]
1895
4081.3.12 by Martin von Gagern
Separate top level functions with two blank lines.
1896
4081.3.9 by Martin von Gagern
Use proper registry for --authors option.
1897
def author_list_first(rev):
1898
    lst = rev.get_apparent_authors()
1899
    try:
1900
        return [lst[0]]
1901
    except IndexError:
1902
        return []
1903
4081.3.12 by Martin von Gagern
Separate top level functions with two blank lines.
1904
4081.3.9 by Martin von Gagern
Use proper registry for --authors option.
1905
def author_list_committer(rev):
1906
    return [rev.committer]
1907
4081.3.12 by Martin von Gagern
Separate top level functions with two blank lines.
1908
4081.3.9 by Martin von Gagern
Use proper registry for --authors option.
1909
author_list_registry = registry.Registry()
1910
1911
author_list_registry.register('all', author_list_all,
1912
                              'All authors')
1913
1914
author_list_registry.register('first', author_list_first,
1915
                              'The first author')
1916
1917
author_list_registry.register('committer', author_list_committer,
1918
                              'The committer')
2221.4.10 by Aaron Bentley
Implement log options using RegistryOption
1919
4081.3.12 by Martin von Gagern
Separate top level functions with two blank lines.
1920
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
1921
def show_one_log(revno, rev, delta, verbose, to_file, show_timezone):
1759.2.1 by Jelmer Vernooij
Fix some types (found using aspell).
1922
    # deprecated; for compatibility
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
1923
    lf = LongLogFormatter(to_file=to_file, show_timezone=show_timezone)
1924
    lf.show(revno, rev, delta)
1185.32.2 by John Arbash Meinel
Refactor pull --verbose into a log.py function, add tests.
1925
2490.1.4 by John Arbash Meinel
Update bzrlib.log.show_changed_revisions to use the new api
1926
1551.17.2 by Aaron Bentley
Stop showing deltas in pull -v output
1927
def show_changed_revisions(branch, old_rh, new_rh, to_file=None,
1928
                           log_format='long'):
1185.32.2 by John Arbash Meinel
Refactor pull --verbose into a log.py function, add tests.
1929
    """Show the change in revision history comparing the old revision history to the new one.
1930
1931
    :param branch: The branch where the revisions exist
1932
    :param old_rh: The old revision history
1933
    :param new_rh: The new revision history
1934
    :param to_file: A file to write the results to. If None, stdout will be used
1935
    """
1936
    if to_file is None:
2997.1.3 by Alexander Belchenko
file wrapper around stdout should use terminal encoding, not user_encoding.
1937
        to_file = codecs.getwriter(get_terminal_encoding())(sys.stdout,
1938
            errors='replace')
1185.32.2 by John Arbash Meinel
Refactor pull --verbose into a log.py function, add tests.
1939
    lf = log_formatter(log_format,
1940
                       show_ids=False,
1941
                       to_file=to_file,
1942
                       show_timezone='original')
1943
1944
    # This is the first index which is different between
1945
    # old and new
1946
    base_idx = None
1947
    for i in xrange(max(len(new_rh),
1948
                        len(old_rh))):
1949
        if (len(new_rh) <= i
1950
            or len(old_rh) <= i
1951
            or new_rh[i] != old_rh[i]):
1952
            base_idx = i
1953
            break
1954
1955
    if base_idx is None:
1956
        to_file.write('Nothing seems to have changed\n')
1957
        return
1958
    ## TODO: It might be nice to do something like show_log
1959
    ##       and show the merged entries. But since this is the
1960
    ##       removed revisions, it shouldn't be as important
1961
    if base_idx < len(old_rh):
1962
        to_file.write('*'*60)
1963
        to_file.write('\nRemoved Revisions:\n')
1964
        for i in range(base_idx, len(old_rh)):
1185.67.2 by Aaron Bentley
Renamed Branch.storage to Branch.repository
1965
            rev = branch.repository.get_revision(old_rh[i])
2490.1.4 by John Arbash Meinel
Update bzrlib.log.show_changed_revisions to use the new api
1966
            lr = LogRevision(rev, i+1, 0, None)
1967
            lf.log_revision(lr)
1185.32.2 by John Arbash Meinel
Refactor pull --verbose into a log.py function, add tests.
1968
        to_file.write('*'*60)
1969
        to_file.write('\n\n')
1970
    if base_idx < len(new_rh):
1971
        to_file.write('Added Revisions:\n')
1972
        show_log(branch,
1973
                 lf,
1974
                 None,
1551.17.2 by Aaron Bentley
Stop showing deltas in pull -v output
1975
                 verbose=False,
1185.32.2 by John Arbash Meinel
Refactor pull --verbose into a log.py function, add tests.
1976
                 direction='forward',
1977
                 start_revision=base_idx+1,
1978
                 end_revision=len(new_rh),
1979
                 search=None)
1980
3144.7.4 by Guillermo Gonzalez
* move the function regisstry into a real Registry instead of a list
1981
3848.1.7 by Aaron Bentley
Use repository in get_history_change
1982
def get_history_change(old_revision_id, new_revision_id, repository):
3848.1.11 by Aaron Bentley
Cleanup and use of show_branch_change
1983
    """Calculate the uncommon lefthand history between two revisions.
1984
1985
    :param old_revision_id: The original revision id.
1986
    :param new_revision_id: The new revision id.
3848.1.22 by Aaron Bentley
Fix spelling
1987
    :param repository: The repository to use for the calculation.
3848.1.11 by Aaron Bentley
Cleanup and use of show_branch_change
1988
1989
    return old_history, new_history
1990
    """
3848.1.6 by Aaron Bentley
Implement get_history_change
1991
    old_history = []
1992
    old_revisions = set()
1993
    new_history = []
1994
    new_revisions = set()
5972.2.1 by Jelmer Vernooij
Deprecate Repository.iter_reverse_revision_history.
1995
    graph = repository.get_graph()
1996
    new_iter = graph.iter_lefthand_ancestry(new_revision_id)
1997
    old_iter = graph.iter_lefthand_ancestry(old_revision_id)
3848.1.6 by Aaron Bentley
Implement get_history_change
1998
    stop_revision = None
1999
    do_old = True
2000
    do_new = True
2001
    while do_new or do_old:
2002
        if do_new:
2003
            try:
2004
                new_revision = new_iter.next()
2005
            except StopIteration:
2006
                do_new = False
2007
            else:
2008
                new_history.append(new_revision)
2009
                new_revisions.add(new_revision)
2010
                if new_revision in old_revisions:
2011
                    stop_revision = new_revision
2012
                    break
2013
        if do_old:
2014
            try:
2015
                old_revision = old_iter.next()
2016
            except StopIteration:
2017
                do_old = False
2018
            else:
2019
                old_history.append(old_revision)
2020
                old_revisions.add(old_revision)
2021
                if old_revision in new_revisions:
2022
                    stop_revision = old_revision
2023
                    break
2024
    new_history.reverse()
2025
    old_history.reverse()
2026
    if stop_revision is not None:
2027
        new_history = new_history[new_history.index(stop_revision) + 1:]
2028
        old_history = old_history[old_history.index(stop_revision) + 1:]
2029
    return old_history, new_history
2030
2031
3848.1.11 by Aaron Bentley
Cleanup and use of show_branch_change
2032
def show_branch_change(branch, output, old_revno, old_revision_id):
2033
    """Show the changes made to a branch.
2034
2035
    :param branch: The branch to show changes about.
2036
    :param output: A file-like object to write changes to.
2037
    :param old_revno: The revno of the old tip.
2038
    :param old_revision_id: The revision_id of the old tip.
2039
    """
3848.1.8 by Aaron Bentley
Implement basic show_branch_change
2040
    new_revno, new_revision_id = branch.last_revision_info()
2041
    old_history, new_history = get_history_change(old_revision_id,
2042
                                                  new_revision_id,
2043
                                                  branch.repository)
2044
    if old_history == [] and new_history == []:
2045
        output.write('Nothing seems to have changed\n')
2046
        return
2047
3848.1.10 by Aaron Bentley
Move log display into show_flat_log
2048
    log_format = log_formatter_registry.get_default(branch)
2049
    lf = log_format(show_ids=False, to_file=output, show_timezone='original')
3848.1.8 by Aaron Bentley
Implement basic show_branch_change
2050
    if old_history != []:
2051
        output.write('*'*60)
2052
        output.write('\nRemoved Revisions:\n')
3848.1.10 by Aaron Bentley
Move log display into show_flat_log
2053
        show_flat_log(branch.repository, old_history, old_revno, lf)
3848.1.8 by Aaron Bentley
Implement basic show_branch_change
2054
        output.write('*'*60)
2055
        output.write('\n\n')
2056
    if new_history != []:
3848.1.9 by Aaron Bentley
new/old sections are omitted as appropriate.
2057
        output.write('Added Revisions:\n')
3848.1.8 by Aaron Bentley
Implement basic show_branch_change
2058
        start_revno = new_revno - len(new_history) + 1
2059
        show_log(branch, lf, None, verbose=False, direction='forward',
2060
                 start_revision=start_revno,)
2061
2062
3848.1.10 by Aaron Bentley
Move log display into show_flat_log
2063
def show_flat_log(repository, history, last_revno, lf):
3848.1.11 by Aaron Bentley
Cleanup and use of show_branch_change
2064
    """Show a simple log of the specified history.
2065
2066
    :param repository: The repository to retrieve revisions from.
2067
    :param history: A list of revision_ids indicating the lefthand history.
2068
    :param last_revno: The revno of the last revision_id in the history.
2069
    :param lf: The log formatter to use.
2070
    """
3848.1.10 by Aaron Bentley
Move log display into show_flat_log
2071
    start_revno = last_revno - len(history) + 1
2072
    revisions = repository.get_revisions(history)
2073
    for i, rev in enumerate(revisions):
2074
        lr = LogRevision(rev, i + last_revno, 0, None)
2075
        lf.log_revision(lr)
2076
2077
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
2078
def _get_info_for_log_files(revisionspec_list, file_list, add_cleanup):
4202.2.1 by Ian Clatworthy
get directory logging working again
2079
    """Find file-ids and kinds given a list of files and a revision range.
2080
2081
    We search for files at the end of the range. If not found there,
2082
    we try the start of the range.
2083
2084
    :param revisionspec_list: revision range as parsed on the command line
2085
    :param file_list: the list of paths given on the command line;
2086
      the first of these can be a branch location or a file path,
2087
      the remainder must be file paths
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
2088
    :param add_cleanup: When the branch returned is read locked,
2089
      an unlock call will be queued to the cleanup.
4202.2.1 by Ian Clatworthy
get directory logging working again
2090
    :return: (branch, info_list, start_rev_info, end_rev_info) where
2091
      info_list is a list of (relative_path, file_id, kind) tuples where
2092
      kind is one of values 'directory', 'file', 'symlink', 'tree-reference'.
4634.90.1 by Andrew Bennetts
Fix ObjectNotLocked error during 'bzr log' by acquiring branch read lock as soon as cmd_log acquires the branch, only releasing it at the end.
2093
      branch will be read-locked.
3943.6.4 by Ian Clatworthy
review feedback from vila
2094
    """
5346.4.2 by Martin Pool
Move internal_tree_files and safe_relpath_files onto WorkingTree
2095
    from builtins import _get_revision_range
4202.2.1 by Ian Clatworthy
get directory logging working again
2096
    tree, b, path = bzrdir.BzrDir.open_containing_tree_or_branch(file_list[0])
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
2097
    add_cleanup(b.lock_read().unlock)
4202.2.1 by Ian Clatworthy
get directory logging working again
2098
    # XXX: It's damn messy converting a list of paths to relative paths when
2099
    # those paths might be deleted ones, they might be on a case-insensitive
2100
    # filesystem and/or they might be in silly locations (like another branch).
2101
    # For example, what should "log bzr://branch/dir/file1 file2" do? (Is
2102
    # file2 implicitly in the same dir as file1 or should its directory be
2103
    # taken from the current tree somehow?) For now, this solves the common
2104
    # case of running log in a nested directory, assuming paths beyond the
2105
    # first one haven't been deleted ...
2106
    if tree:
5346.4.2 by Martin Pool
Move internal_tree_files and safe_relpath_files onto WorkingTree
2107
        relpaths = [path] + tree.safe_relpath_files(file_list[1:])
4202.2.1 by Ian Clatworthy
get directory logging working again
2108
    else:
2109
        relpaths = [path] + file_list[1:]
2110
    info_list = []
2111
    start_rev_info, end_rev_info = _get_revision_range(revisionspec_list, b,
2112
        "log")
4296.2.1 by Jelmer Vernooij
Don't retrieve the tree if log is called on the root.
2113
    if relpaths in ([], [u'']):
2114
        return b, [], start_rev_info, end_rev_info
4202.2.1 by Ian Clatworthy
get directory logging working again
2115
    if start_rev_info is None and end_rev_info is None:
3943.6.4 by Ian Clatworthy
review feedback from vila
2116
        if tree is None:
2117
            tree = b.basis_tree()
4202.2.1 by Ian Clatworthy
get directory logging working again
2118
        tree1 = None
2119
        for fp in relpaths:
2120
            file_id = tree.path2id(fp)
2121
            kind = _get_kind_for_file_id(tree, file_id)
2122
            if file_id is None:
2123
                # go back to when time began
2124
                if tree1 is None:
2125
                    try:
2126
                        rev1 = b.get_rev_id(1)
2127
                    except errors.NoSuchRevision:
2128
                        # No history at all
2129
                        file_id = None
2130
                        kind = None
2131
                    else:
2132
                        tree1 = b.repository.revision_tree(rev1)
2133
                if tree1:
2134
                    file_id = tree1.path2id(fp)
2135
                    kind = _get_kind_for_file_id(tree1, file_id)
2136
            info_list.append((fp, file_id, kind))
3943.6.4 by Ian Clatworthy
review feedback from vila
2137
4202.2.1 by Ian Clatworthy
get directory logging working again
2138
    elif start_rev_info == end_rev_info:
3943.6.4 by Ian Clatworthy
review feedback from vila
2139
        # One revision given - file must exist in it
4202.2.1 by Ian Clatworthy
get directory logging working again
2140
        tree = b.repository.revision_tree(end_rev_info.rev_id)
2141
        for fp in relpaths:
2142
            file_id = tree.path2id(fp)
2143
            kind = _get_kind_for_file_id(tree, file_id)
2144
            info_list.append((fp, file_id, kind))
3943.6.4 by Ian Clatworthy
review feedback from vila
2145
4202.2.1 by Ian Clatworthy
get directory logging working again
2146
    else:
3943.6.4 by Ian Clatworthy
review feedback from vila
2147
        # Revision range given. Get the file-id from the end tree.
2148
        # If that fails, try the start tree.
4202.2.1 by Ian Clatworthy
get directory logging working again
2149
        rev_id = end_rev_info.rev_id
3943.6.4 by Ian Clatworthy
review feedback from vila
2150
        if rev_id is None:
2151
            tree = b.basis_tree()
2152
        else:
4202.2.1 by Ian Clatworthy
get directory logging working again
2153
            tree = b.repository.revision_tree(rev_id)
2154
        tree1 = None
2155
        for fp in relpaths:
3943.6.4 by Ian Clatworthy
review feedback from vila
2156
            file_id = tree.path2id(fp)
4202.2.1 by Ian Clatworthy
get directory logging working again
2157
            kind = _get_kind_for_file_id(tree, file_id)
2158
            if file_id is None:
2159
                if tree1 is None:
2160
                    rev_id = start_rev_info.rev_id
2161
                    if rev_id is None:
2162
                        rev1 = b.get_rev_id(1)
2163
                        tree1 = b.repository.revision_tree(rev1)
2164
                    else:
2165
                        tree1 = b.repository.revision_tree(rev_id)
2166
                file_id = tree1.path2id(fp)
2167
                kind = _get_kind_for_file_id(tree1, file_id)
2168
            info_list.append((fp, file_id, kind))
2169
    return b, info_list, start_rev_info, end_rev_info
2170
2171
2172
def _get_kind_for_file_id(tree, file_id):
2173
    """Return the kind of a file-id or None if it doesn't exist."""
2174
    if file_id is not None:
2175
        return tree.kind(file_id)
3943.6.4 by Ian Clatworthy
review feedback from vila
2176
    else:
4202.2.1 by Ian Clatworthy
get directory logging working again
2177
        return None
3943.6.4 by Ian Clatworthy
review feedback from vila
2178
2179
3144.7.9 by Guillermo Gonzalez
* bzrlib.log.show_roperties don't hide handler errors
2180
properties_handler_registry = registry.Registry()
3830.4.1 by Jelmer Vernooij
Add base classes for foreign branches.
2181
4921.2.1 by Neil Martinsen-Burrell
include bug fixes in log output
2182
# Use the properties handlers to print out bug information if available
2183
def _bugs_properties_handler(revision):
2184
    if revision.properties.has_key('bugs'):
4921.2.2 by Neil Martinsen-Burrell
from review comments: improve splitting, add test that handler is present, use build_tree in tests
2185
        bug_lines = revision.properties['bugs'].split('\n')
2186
        bug_rows = [line.split(' ', 1) for line in bug_lines]
2187
        fixed_bug_urls = [row[0] for row in bug_rows if
2188
                          len(row) > 1 and row[1] == 'fixed']
5092.1.2 by Vincent Ladeuil
Fix bug #519862.
2189
4921.2.2 by Neil Martinsen-Burrell
from review comments: improve splitting, add test that handler is present, use build_tree in tests
2190
        if fixed_bug_urls:
2191
            return {'fixes bug(s)': ' '.join(fixed_bug_urls)}
4921.2.1 by Neil Martinsen-Burrell
include bug fixes in log output
2192
    return {}
2193
2194
properties_handler_registry.register('bugs_properties_handler',
2195
                                     _bugs_properties_handler)
2196
3642.1.6 by Robert Collins
Make log revision filtering pluggable.
2197
2198
# adapters which revision ids to log are filtered. When log is called, the
2199
# log_rev_iterator is adapted through each of these factory methods.
2200
# Plugins are welcome to mutate this list in any way they like - as long
2201
# as the overall behaviour is preserved. At this point there is no extensible
2202
# mechanism for getting parameters to each factory method, and until there is
2203
# this won't be considered a stable api.
2204
log_adapters = [
2205
    # core log logic
3642.1.7 by Robert Collins
Review feedback.
2206
    _make_batch_filter,
3642.1.6 by Robert Collins
Make log revision filtering pluggable.
2207
    # read revision objects
3642.1.7 by Robert Collins
Review feedback.
2208
    _make_revision_objects,
3642.1.6 by Robert Collins
Make log revision filtering pluggable.
2209
    # filter on log messages
3642.1.7 by Robert Collins
Review feedback.
2210
    _make_search_filter,
3642.1.6 by Robert Collins
Make log revision filtering pluggable.
2211
    # generate deltas for things we will show
3642.1.7 by Robert Collins
Review feedback.
2212
    _make_delta_filter
3642.1.6 by Robert Collins
Make log revision filtering pluggable.
2213
    ]