1
# Copyright (C) 2005 Canonical Ltd
 
 
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.
 
 
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.
 
 
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
 
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
 
19
"""Code to show logs of changes.
 
 
21
Various flavors of log can be produced:
 
 
23
* for one file, or the whole tree, and (not done yet) for
 
 
24
  files in a given directory
 
 
26
* in "verbose" mode with a description of what changed from one
 
 
29
* with file-ids and revision-ids shown
 
 
31
Logs are actually written out through an abstract LogFormatter
 
 
32
interface, which allows for different preferred formats.  Plugins can
 
 
35
Logs can be produced in either forward (oldest->newest) or reverse
 
 
36
(newest->oldest) order.
 
 
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
 
 
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
 
 
45
relative to its mainline parent, not the delta relative to the last
 
 
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.
 
 
52
# TODO: option to show delta summaries for merged-in revisions
 
 
54
from itertools import izip
 
 
57
from bzrlib.delta import compare_trees
 
 
58
import bzrlib.errors as errors
 
 
59
from bzrlib.trace import mutter
 
 
60
from bzrlib.tree import EmptyTree
 
 
61
from bzrlib.tsort import merge_sort
 
 
64
def find_touching_revisions(branch, file_id):
 
 
65
    """Yield a description of revisions which affect the file_id.
 
 
67
    Each returned element is (revno, revision_id, description)
 
 
69
    This is the list of revisions where the file is either added,
 
 
70
    modified, renamed or deleted.
 
 
72
    TODO: Perhaps some way to limit this to only particular revisions,
 
 
73
    or to traverse a non-mainline set of revisions?
 
 
78
    for revision_id in branch.revision_history():
 
 
79
        this_inv = branch.repository.get_revision_inventory(revision_id)
 
 
80
        if file_id in this_inv:
 
 
81
            this_ie = this_inv[file_id]
 
 
82
            this_path = this_inv.id2path(file_id)
 
 
84
            this_ie = this_path = None
 
 
86
        # now we know how it was last time, and how it is in this revision.
 
 
87
        # are those two states effectively the same or not?
 
 
89
        if not this_ie and not last_ie:
 
 
90
            # not present in either
 
 
92
        elif this_ie and not last_ie:
 
 
93
            yield revno, revision_id, "added " + this_path
 
 
94
        elif not this_ie and last_ie:
 
 
96
            yield revno, revision_id, "deleted " + last_path
 
 
97
        elif this_path != last_path:
 
 
98
            yield revno, revision_id, ("renamed %s => %s" % (last_path, this_path))
 
 
99
        elif (this_ie.text_size != last_ie.text_size
 
 
100
              or this_ie.text_sha1 != last_ie.text_sha1):
 
 
101
            yield revno, revision_id, "modified " + this_path
 
 
104
        last_path = this_path
 
 
109
def _enumerate_history(branch):
 
 
112
    for rev_id in branch.revision_history():
 
 
113
        rh.append((revno, rev_id))
 
 
118
def _get_revision_delta(branch, revno):
 
 
119
    """Return the delta for a mainline revision.
 
 
121
    This is used to show summaries in verbose logs, and also for finding 
 
 
122
    revisions which touch a given file."""
 
 
123
    # XXX: What are we supposed to do when showing a summary for something 
 
 
124
    # other than a mainline revision.  The delta to it's first parent, or
 
 
125
    # (more useful) the delta to a nominated other revision.
 
 
126
    return branch.get_revision_delta(revno)
 
 
131
             specific_fileid=None,
 
 
137
    """Write out human-readable log of commits to this branch.
 
 
140
        LogFormatter object to show the output.
 
 
143
        If true, list only the commits affecting the specified
 
 
144
        file, rather than all commits.
 
 
147
        If true show added/changed/deleted/renamed files.
 
 
150
        'reverse' (default) is latest to earliest;
 
 
151
        'forward' is earliest to latest.
 
 
154
        If not None, only show revisions >= start_revision
 
 
157
        If not None, only show revisions <= end_revision
 
 
161
        _show_log(branch, lf, specific_fileid, verbose, direction,
 
 
162
                  start_revision, end_revision, search)
 
 
166
def _show_log(branch,
 
 
168
             specific_fileid=None,
 
 
174
    """Worker function for show_log - see show_log."""
 
 
175
    from bzrlib.osutils import format_date
 
 
176
    from bzrlib.errors import BzrCheckError
 
 
177
    from bzrlib.textui import show_status
 
 
179
    from warnings import warn
 
 
181
    if not isinstance(lf, LogFormatter):
 
 
182
        warn("not a LogFormatter instance: %r" % lf)
 
 
185
        mutter('get log for file_id %r', specific_fileid)
 
 
187
    if search is not None:
 
 
189
        searchRE = re.compile(search, re.IGNORECASE)
 
 
193
    which_revs = _enumerate_history(branch)
 
 
195
    if start_revision is None:
 
 
198
        branch.check_real_revno(start_revision)
 
 
200
    if end_revision is None:
 
 
201
        end_revision = len(which_revs)
 
 
203
        branch.check_real_revno(end_revision)
 
 
205
    # list indexes are 0-based; revisions are 1-based
 
 
206
    cut_revs = which_revs[(start_revision-1):(end_revision)]
 
 
209
    # override the mainline to look like the revision history.
 
 
210
    mainline_revs = [revision_id for index, revision_id in cut_revs]
 
 
211
    if cut_revs[0][0] == 1:
 
 
212
        mainline_revs.insert(0, None)
 
 
214
        mainline_revs.insert(0, which_revs[start_revision-2][1])
 
 
216
    merge_sorted_revisions = merge_sort(
 
 
217
        branch.repository.get_revision_graph(mainline_revs[-1]),
 
 
221
    if direction == 'reverse':
 
 
223
    elif direction == 'forward':
 
 
224
        # forward means oldest first.
 
 
225
        merge_sorted_revisions.reverse()
 
 
227
        raise ValueError('invalid direction %r' % direction)
 
 
229
    revision_history = branch.revision_history()
 
 
231
    # convert the revision history to a dictionary:
 
 
233
    for index, rev_id in cut_revs:
 
 
234
        rev_nos[rev_id] = index
 
 
236
    def iter_revisions():
 
 
237
        revision_ids = [r for s, r, m, e in merge_sorted_revisions]
 
 
240
            revisions = branch.repository.get_revisions(revision_ids[:num])
 
 
241
            for revision in revisions:
 
 
243
            revision_ids  = revision_ids[num:]
 
 
246
        revisions = branch.repository.get_revisions()
 
 
247
        for revision in revisions:
 
 
249
    # now we just print all the revisions
 
 
250
    for ((sequence, rev_id, merge_depth, end_of_merge), rev) in \
 
 
251
        izip(merge_sorted_revisions, iter_revisions()):
 
 
254
            if not searchRE.search(rev.message):
 
 
258
            # a mainline revision.
 
 
259
            if verbose or specific_fileid:
 
 
260
                delta = _get_revision_delta(branch, rev_nos[rev_id])
 
 
263
                if not delta.touches_file_id(specific_fileid):
 
 
267
                # although we calculated it, throw it away without display
 
 
270
            lf.show(rev_nos[rev_id], rev, delta)
 
 
271
        elif hasattr(lf, 'show_merge'):
 
 
272
            lf.show_merge(rev, merge_depth)
 
 
275
class LogFormatter(object):
 
 
276
    """Abstract class to display log messages."""
 
 
278
    def __init__(self, to_file, show_ids=False, show_timezone='original'):
 
 
279
        self.to_file = to_file
 
 
280
        self.show_ids = show_ids
 
 
281
        self.show_timezone = show_timezone
 
 
283
    def show(self, revno, rev, delta):
 
 
284
        raise NotImplementedError('not implemented in abstract base')
 
 
286
    def short_committer(self, rev):
 
 
287
        return re.sub('<.*@.*>', '', rev.committer).strip(' ')
 
 
290
class LongLogFormatter(LogFormatter):
 
 
291
    def show(self, revno, rev, delta):
 
 
292
        return self._show_helper(revno=revno, rev=rev, delta=delta)
 
 
294
    def show_merge(self, rev, merge_depth):
 
 
295
        return self._show_helper(rev=rev, indent='    '*merge_depth, merged=True, delta=None)
 
 
297
    def _show_helper(self, rev=None, revno=None, indent='', merged=False, delta=None):
 
 
298
        """Show a revision, either merged or not."""
 
 
299
        from bzrlib.osutils import format_date
 
 
300
        to_file = self.to_file
 
 
301
        print >>to_file,  indent+'-' * 60
 
 
302
        if revno is not None:
 
 
303
            print >>to_file,  'revno:', revno
 
 
305
            print >>to_file,  indent+'merged:', rev.revision_id
 
 
307
            print >>to_file,  indent+'revision-id:', rev.revision_id
 
 
309
            for parent_id in rev.parent_ids:
 
 
310
                print >>to_file, indent+'parent:', parent_id
 
 
311
        print >>to_file,  indent+'committer:', rev.committer
 
 
313
            print >>to_file, indent+'branch nick: %s' % \
 
 
314
                rev.properties['branch-nick']
 
 
317
        date_str = format_date(rev.timestamp,
 
 
320
        print >>to_file,  indent+'timestamp: %s' % date_str
 
 
322
        print >>to_file,  indent+'message:'
 
 
324
            print >>to_file,  indent+'  (no message)'
 
 
326
            message = rev.message.rstrip('\r\n')
 
 
327
            for l in message.split('\n'):
 
 
328
                print >>to_file,  indent+'  ' + l
 
 
330
            delta.show(to_file, self.show_ids)
 
 
333
class ShortLogFormatter(LogFormatter):
 
 
334
    def show(self, revno, rev, delta):
 
 
335
        from bzrlib.osutils import format_date
 
 
337
        to_file = self.to_file
 
 
338
        date_str = format_date(rev.timestamp, rev.timezone or 0,
 
 
340
        print >>to_file, "%5d %s\t%s" % (revno, self.short_committer(rev),
 
 
341
                format_date(rev.timestamp, rev.timezone or 0,
 
 
342
                            self.show_timezone, date_fmt="%Y-%m-%d",
 
 
345
            print >>to_file,  '      revision-id:', rev.revision_id
 
 
347
            print >>to_file,  '      (no message)'
 
 
349
            message = rev.message.rstrip('\r\n')
 
 
350
            for l in message.split('\n'):
 
 
351
                print >>to_file,  '      ' + l
 
 
353
        # TODO: Why not show the modified files in a shorter form as
 
 
354
        # well? rewrap them single lines of appropriate length
 
 
356
            delta.show(to_file, self.show_ids)
 
 
360
class LineLogFormatter(LogFormatter):
 
 
361
    def truncate(self, str, max_len):
 
 
362
        if len(str) <= max_len:
 
 
364
        return str[:max_len-3]+'...'
 
 
366
    def date_string(self, rev):
 
 
367
        from bzrlib.osutils import format_date
 
 
368
        return format_date(rev.timestamp, rev.timezone or 0, 
 
 
369
                           self.show_timezone, date_fmt="%Y-%m-%d",
 
 
372
    def message(self, rev):
 
 
374
            return '(no message)'
 
 
378
    def show(self, revno, rev, delta):
 
 
379
        from bzrlib.osutils import terminal_width
 
 
380
        print >> self.to_file, self.log_string(revno, rev, terminal_width()-1)
 
 
382
    def log_string(self, revno, rev, max_chars):
 
 
383
        """Format log info into one string. Truncate tail of string
 
 
384
        :param  revno:      revision number (int) or None.
 
 
385
                            Revision numbers counts from 1.
 
 
386
        :param  rev:        revision info object
 
 
387
        :param  max_chars:  maximum length of resulting string
 
 
388
        :return:            formatted truncated string
 
 
392
            # show revno only when is not None
 
 
393
            out.append("%d:" % revno)
 
 
394
        out.append(self.truncate(self.short_committer(rev), 20))
 
 
395
        out.append(self.date_string(rev))
 
 
396
        out.append(rev.get_summary())
 
 
397
        return self.truncate(" ".join(out).rstrip('\n'), max_chars)
 
 
400
def line_log(rev, max_chars):
 
 
401
    lf = LineLogFormatter(None)
 
 
402
    return lf.log_string(None, rev, max_chars)
 
 
405
              'long': LongLogFormatter,
 
 
406
              'short': ShortLogFormatter,
 
 
407
              'line': LineLogFormatter,
 
 
410
def register_formatter(name, formatter):
 
 
411
    FORMATTERS[name] = formatter
 
 
413
def log_formatter(name, *args, **kwargs):
 
 
414
    """Construct a formatter from arguments.
 
 
416
    name -- Name of the formatter to construct; currently 'long', 'short' and
 
 
417
        'line' are supported.
 
 
419
    from bzrlib.errors import BzrCommandError
 
 
421
        return FORMATTERS[name](*args, **kwargs)
 
 
423
        raise BzrCommandError("unknown log formatter: %r" % name)
 
 
425
def show_one_log(revno, rev, delta, verbose, to_file, show_timezone):
 
 
426
    # deprecated; for compatibility
 
 
427
    lf = LongLogFormatter(to_file=to_file, show_timezone=show_timezone)
 
 
428
    lf.show(revno, rev, delta)
 
 
430
def show_changed_revisions(branch, old_rh, new_rh, to_file=None, log_format='long'):
 
 
431
    """Show the change in revision history comparing the old revision history to the new one.
 
 
433
    :param branch: The branch where the revisions exist
 
 
434
    :param old_rh: The old revision history
 
 
435
    :param new_rh: The new revision history
 
 
436
    :param to_file: A file to write the results to. If None, stdout will be used
 
 
442
        to_file = codecs.getwriter(bzrlib.user_encoding)(sys.stdout, errors='replace')
 
 
443
    lf = log_formatter(log_format,
 
 
446
                       show_timezone='original')
 
 
448
    # This is the first index which is different between
 
 
451
    for i in xrange(max(len(new_rh),
 
 
455
            or new_rh[i] != old_rh[i]):
 
 
460
        to_file.write('Nothing seems to have changed\n')
 
 
462
    ## TODO: It might be nice to do something like show_log
 
 
463
    ##       and show the merged entries. But since this is the
 
 
464
    ##       removed revisions, it shouldn't be as important
 
 
465
    if base_idx < len(old_rh):
 
 
466
        to_file.write('*'*60)
 
 
467
        to_file.write('\nRemoved Revisions:\n')
 
 
468
        for i in range(base_idx, len(old_rh)):
 
 
469
            rev = branch.repository.get_revision(old_rh[i])
 
 
470
            lf.show(i+1, rev, None)
 
 
471
        to_file.write('*'*60)
 
 
472
        to_file.write('\n\n')
 
 
473
    if base_idx < len(new_rh):
 
 
474
        to_file.write('Added Revisions:\n')
 
 
480
                 start_revision=base_idx+1,
 
 
481
                 end_revision=len(new_rh),