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