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