/brz/remove-bazaar

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