/brz/remove-bazaar

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