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