~bzr-pqm/bzr/bzr.dev

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
# Copyright (C) 2005, 2006, 2007 Canonical Ltd
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

import os
from cStringIO import StringIO

from bzrlib import log, registry
from bzrlib.tests import TestCase, TestCaseWithTransport
from bzrlib.log import (show_log,
                        get_view_revisions,
                        LogRevision,
                        LogFormatter,
                        LongLogFormatter,
                        ShortLogFormatter,
                        LineLogFormatter)
from bzrlib.branch import Branch
from bzrlib.errors import (
    BzrCommandError,
    InvalidRevisionNumber,
    )
from bzrlib.revision import Revision
from bzrlib.revisionspec import (
    RevisionInfo,
    RevisionSpec,
    )


class TestCaseWithoutPropsHandler(TestCaseWithTransport):

    def setUp(self):
        super(TestCaseWithoutPropsHandler, self).setUp()
        # keep a reference to the "current" custom prop. handler registry
        self.properties_handler_registry = \
            log.properties_handler_registry
        # clean up the registry in log
        log.properties_handler_registry = registry.Registry()
        
    def _cleanup(self):
        super(TestCaseWithoutPropsHandler, self)._cleanup()
        # restore the custom properties handler registry
        log.properties_handler_registry = \
            self.properties_handler_registry


class LogCatcher(LogFormatter):
    """Pull log messages into list rather than displaying them.

    For ease of testing we save log messages here rather than actually
    formatting them, so that we can precisely check the result without
    being too dependent on the exact formatting.

    We should also test the LogFormatter.
    """

    supports_delta = True

    def __init__(self):
        super(LogCatcher, self).__init__(to_file=None)
        self.logs = []

    def log_revision(self, revision):
        self.logs.append(revision)


class TestShowLog(TestCaseWithTransport):

    def checkDelta(self, delta, **kw):
        """Check the filenames touched by a delta are as expected."""
        for n in 'added', 'removed', 'renamed', 'modified', 'unchanged':
            expected = kw.get(n, [])
            # strip out only the path components
            got = [x[0] for x in getattr(delta, n)]
            self.assertEquals(expected, got)

    def test_cur_revno(self):
        wt = self.make_branch_and_tree('.')
        b = wt.branch

        lf = LogCatcher()
        wt.commit('empty commit')
        show_log(b, lf, verbose=True, start_revision=1, end_revision=1)
        self.assertRaises(InvalidRevisionNumber, show_log, b, lf,
                          start_revision=2, end_revision=1) 
        self.assertRaises(InvalidRevisionNumber, show_log, b, lf,
                          start_revision=1, end_revision=2) 
        self.assertRaises(InvalidRevisionNumber, show_log, b, lf,
                          start_revision=0, end_revision=2) 
        self.assertRaises(InvalidRevisionNumber, show_log, b, lf,
                          start_revision=1, end_revision=0) 
        self.assertRaises(InvalidRevisionNumber, show_log, b, lf,
                          start_revision=-1, end_revision=1) 
        self.assertRaises(InvalidRevisionNumber, show_log, b, lf,
                          start_revision=1, end_revision=-1) 

    def test_simple_log(self):
        eq = self.assertEquals
        
        wt = self.make_branch_and_tree('.')
        b = wt.branch

        lf = LogCatcher()
        show_log(b, lf)
        # no entries yet
        eq(lf.logs, [])

        wt.commit('empty commit')
        lf = LogCatcher()
        show_log(b, lf, verbose=True)
        eq(len(lf.logs), 1)
        eq(lf.logs[0].revno, '1')
        eq(lf.logs[0].rev.message, 'empty commit')
        d = lf.logs[0].delta
        self.log('log delta: %r' % d)
        self.checkDelta(d)

        self.build_tree(['hello'])
        wt.add('hello')
        wt.commit('add one file',
                  committer=u'\u013d\xf3r\xe9m \xcdp\u0161\xfam '
                            u'<test@example.com>')

        lf = self.make_utf8_encoded_stringio()
        # log using regular thing
        show_log(b, LongLogFormatter(lf))
        lf.seek(0)
        for l in lf.readlines():
            self.log(l)

        # get log as data structure
        lf = LogCatcher()
        show_log(b, lf, verbose=True)
        eq(len(lf.logs), 2)
        self.log('log entries:')
        for logentry in lf.logs:
            self.log('%4s %s' % (logentry.revno, logentry.rev.message))
        
        # first one is most recent
        logentry = lf.logs[0]
        eq(logentry.revno, '2')
        eq(logentry.rev.message, 'add one file')
        d = logentry.delta
        self.log('log 2 delta: %r' % d)
        self.checkDelta(d, added=['hello'])
        
        # commit a log message with control characters
        msg = "All 8-bit chars: " +  ''.join([unichr(x) for x in range(256)])
        self.log("original commit message: %r", msg)
        wt.commit(msg)
        lf = LogCatcher()
        show_log(b, lf, verbose=True)
        committed_msg = lf.logs[0].rev.message
        self.log("escaped commit message: %r", committed_msg)
        self.assert_(msg != committed_msg)
        self.assert_(len(committed_msg) > len(msg))

        # Check that log message with only XML-valid characters isn't
        # escaped.  As ElementTree apparently does some kind of
        # newline conversion, neither LF (\x0A) nor CR (\x0D) are
        # included in the test commit message, even though they are
        # valid XML 1.0 characters.
        msg = "\x09" + ''.join([unichr(x) for x in range(0x20, 256)])
        self.log("original commit message: %r", msg)
        wt.commit(msg)
        lf = LogCatcher()
        show_log(b, lf, verbose=True)
        committed_msg = lf.logs[0].rev.message
        self.log("escaped commit message: %r", committed_msg)
        self.assert_(msg == committed_msg)

    def test_deltas_in_merge_revisions(self):
        """Check deltas created for both mainline and merge revisions"""
        eq = self.assertEquals
        wt = self.make_branch_and_tree('parent')
        self.build_tree(['parent/file1', 'parent/file2', 'parent/file3'])
        wt.add('file1')
        wt.add('file2')
        wt.commit(message='add file1 and file2')
        self.run_bzr('branch parent child')
        os.unlink('child/file1')
        file('child/file2', 'wb').write('hello\n')
        self.run_bzr(['commit', '-m', 'remove file1 and modify file2',
            'child'])
        os.chdir('parent')
        self.run_bzr('merge ../child')
        wt.commit('merge child branch')
        os.chdir('..')
        b = wt.branch
        lf = LogCatcher()
        lf.supports_merge_revisions = True
        show_log(b, lf, verbose=True)
        eq(len(lf.logs),3)
        logentry = lf.logs[0]
        eq(logentry.revno, '2')
        eq(logentry.rev.message, 'merge child branch')
        d = logentry.delta
        self.checkDelta(d, removed=['file1'], modified=['file2'])
        logentry = lf.logs[1]
        eq(logentry.revno, '1.1.1')
        eq(logentry.rev.message, 'remove file1 and modify file2')
        d = logentry.delta
        self.checkDelta(d, removed=['file1'], modified=['file2'])
        logentry = lf.logs[2]
        eq(logentry.revno, '1')
        eq(logentry.rev.message, 'add file1 and file2')
        d = logentry.delta
        self.checkDelta(d, added=['file1', 'file2'])

    def test_merges_nonsupporting_formatter(self):
        """Tests that show_log will raise if the formatter doesn't
        support merge revisions."""
        wt = self.make_branch_and_memory_tree('.')
        wt.lock_write()
        try:
            wt.add('')
            wt.commit('rev-1', rev_id='rev-1',
                      timestamp=1132586655, timezone=36000,
                      committer='Joe Foo <joe@foo.com>')
            wt.commit('rev-merged', rev_id='rev-2a',
                      timestamp=1132586700, timezone=36000,
                      committer='Joe Foo <joe@foo.com>')
            wt.set_parent_ids(['rev-1', 'rev-2a'])
            wt.branch.set_last_revision_info(1, 'rev-1')
            wt.commit('rev-2', rev_id='rev-2b',
                      timestamp=1132586800, timezone=36000,
                      committer='Joe Foo <joe@foo.com>')
            logfile = self.make_utf8_encoded_stringio()
            formatter = ShortLogFormatter(to_file=logfile)
            wtb = wt.branch
            lf = LogCatcher()
            revspec = RevisionSpec.from_string('1.1.1')
            rev = revspec.in_history(wtb)
            self.assertRaises(BzrCommandError, show_log, wtb, lf,
                              start_revision=rev, end_revision=rev)
        finally:
            wt.unlock()


def make_commits_with_trailing_newlines(wt):
    """Helper method for LogFormatter tests"""    
    b = wt.branch
    b.nick='test'
    open('a', 'wb').write('hello moto\n')
    wt.add('a')
    wt.commit('simple log message', rev_id='a1',
              timestamp=1132586655.459960938, timezone=-6*3600,
              committer='Joe Foo <joe@foo.com>')
    open('b', 'wb').write('goodbye\n')
    wt.add('b')
    wt.commit('multiline\nlog\nmessage\n', rev_id='a2',
              timestamp=1132586842.411175966, timezone=-6*3600,
              committer='Joe Foo <joe@foo.com>',
              author='Joe Bar <joe@bar.com>')

    open('c', 'wb').write('just another manic monday\n')
    wt.add('c')
    wt.commit('single line with trailing newline\n', rev_id='a3',
              timestamp=1132587176.835228920, timezone=-6*3600,
              committer = 'Joe Foo <joe@foo.com>')
    return b


def normalize_log(log):
    """Replaces the variable lines of logs with fixed lines"""
    author = 'author: Dolor Sit <test@example.com>'
    committer = 'committer: Lorem Ipsum <test@example.com>'
    lines = log.splitlines(True)
    for idx,line in enumerate(lines):
        stripped_line = line.lstrip()
        indent = ' ' * (len(line) - len(stripped_line))
        if stripped_line.startswith('author:'):
            lines[idx] = indent + author + '\n'
        elif stripped_line.startswith('committer:'):
            lines[idx] = indent + committer + '\n'
        elif stripped_line.startswith('timestamp:'):
            lines[idx] = indent + 'timestamp: Just now\n'
    return ''.join(lines)


class TestShortLogFormatter(TestCaseWithTransport):

    def test_trailing_newlines(self):
        wt = self.make_branch_and_tree('.')
        b = make_commits_with_trailing_newlines(wt)
        sio = self.make_utf8_encoded_stringio()
        lf = ShortLogFormatter(to_file=sio)
        show_log(b, lf)
        self.assertEqualDiff(sio.getvalue(), """\
    3 Joe Foo\t2005-11-21
      single line with trailing newline

    2 Joe Bar\t2005-11-21
      multiline
      log
      message

    1 Joe Foo\t2005-11-21
      simple log message

""")

    def test_short_log_with_merges(self):
        wt = self.make_branch_and_memory_tree('.')
        wt.lock_write()
        try:
            wt.add('')
            wt.commit('rev-1', rev_id='rev-1',
                      timestamp=1132586655, timezone=36000,
                      committer='Joe Foo <joe@foo.com>')
            wt.commit('rev-merged', rev_id='rev-2a',
                      timestamp=1132586700, timezone=36000,
                      committer='Joe Foo <joe@foo.com>')
            wt.set_parent_ids(['rev-1', 'rev-2a'])
            wt.branch.set_last_revision_info(1, 'rev-1')
            wt.commit('rev-2', rev_id='rev-2b',
                      timestamp=1132586800, timezone=36000,
                      committer='Joe Foo <joe@foo.com>')
            logfile = self.make_utf8_encoded_stringio()
            formatter = ShortLogFormatter(to_file=logfile)
            show_log(wt.branch, formatter)
            self.assertEqualDiff(logfile.getvalue(), """\
    2 Joe Foo\t2005-11-22 [merge]
      rev-2

    1 Joe Foo\t2005-11-22
      rev-1

""")
        finally:
            wt.unlock()

    def test_short_log_single_merge_revision(self):
        wt = self.make_branch_and_memory_tree('.')
        wt.lock_write()
        try:
            wt.add('')
            wt.commit('rev-1', rev_id='rev-1',
                      timestamp=1132586655, timezone=36000,
                      committer='Joe Foo <joe@foo.com>')
            wt.commit('rev-merged', rev_id='rev-2a',
                      timestamp=1132586700, timezone=36000,
                      committer='Joe Foo <joe@foo.com>')
            wt.set_parent_ids(['rev-1', 'rev-2a'])
            wt.branch.set_last_revision_info(1, 'rev-1')
            wt.commit('rev-2', rev_id='rev-2b',
                      timestamp=1132586800, timezone=36000,
                      committer='Joe Foo <joe@foo.com>')
            logfile = self.make_utf8_encoded_stringio()
            formatter = ShortLogFormatter(to_file=logfile)
            revspec = RevisionSpec.from_string('1.1.1')
            wtb = wt.branch
            rev = revspec.in_history(wtb)
            show_log(wtb, formatter, start_revision=rev, end_revision=rev)
            self.assertEqualDiff(logfile.getvalue(), """\
1.1.1 Joe Foo\t2005-11-22
      rev-merged

""")
        finally:
            wt.unlock()


class TestLongLogFormatter(TestCaseWithoutPropsHandler):

    def test_verbose_log(self):
        """Verbose log includes changed files
        
        bug #4676
        """
        wt = self.make_branch_and_tree('.')
        b = wt.branch
        self.build_tree(['a'])
        wt.add('a')
        # XXX: why does a longer nick show up?
        b.nick = 'test_verbose_log'
        wt.commit(message='add a', 
                  timestamp=1132711707, 
                  timezone=36000,
                  committer='Lorem Ipsum <test@example.com>')
        logfile = file('out.tmp', 'w+')
        formatter = LongLogFormatter(to_file=logfile)
        show_log(b, formatter, verbose=True)
        logfile.flush()
        logfile.seek(0)
        log_contents = logfile.read()
        self.assertEqualDiff(log_contents, '''\
------------------------------------------------------------
revno: 1
committer: Lorem Ipsum <test@example.com>
branch nick: test_verbose_log
timestamp: Wed 2005-11-23 12:08:27 +1000
message:
  add a
added:
  a
''')

    def test_merges_are_indented_by_level(self):
        wt = self.make_branch_and_tree('parent')
        wt.commit('first post')
        self.run_bzr('branch parent child')
        self.run_bzr(['commit', '-m', 'branch 1', '--unchanged', 'child'])
        self.run_bzr('branch child smallerchild')
        self.run_bzr(['commit', '-m', 'branch 2', '--unchanged',
            'smallerchild'])
        os.chdir('child')
        self.run_bzr('merge ../smallerchild')
        self.run_bzr(['commit', '-m', 'merge branch 2'])
        os.chdir('../parent')
        self.run_bzr('merge ../child')
        wt.commit('merge branch 1')
        b = wt.branch
        sio = self.make_utf8_encoded_stringio()
        lf = LongLogFormatter(to_file=sio)
        show_log(b, lf, verbose=True)
        log = normalize_log(sio.getvalue())
        self.assertEqualDiff(log, """\
------------------------------------------------------------
revno: 2
committer: Lorem Ipsum <test@example.com>
branch nick: parent
timestamp: Just now
message:
  merge branch 1
    ------------------------------------------------------------
    revno: 1.1.2
    committer: Lorem Ipsum <test@example.com>
    branch nick: child
    timestamp: Just now
    message:
      merge branch 2
        ------------------------------------------------------------
        revno: 1.2.1
        committer: Lorem Ipsum <test@example.com>
        branch nick: smallerchild
        timestamp: Just now
        message:
          branch 2
    ------------------------------------------------------------
    revno: 1.1.1
    committer: Lorem Ipsum <test@example.com>
    branch nick: child
    timestamp: Just now
    message:
      branch 1
------------------------------------------------------------
revno: 1
committer: Lorem Ipsum <test@example.com>
branch nick: parent
timestamp: Just now
message:
  first post
""")

    def test_verbose_merge_revisions_contain_deltas(self):
        wt = self.make_branch_and_tree('parent')
        self.build_tree(['parent/f1', 'parent/f2'])
        wt.add(['f1','f2'])
        wt.commit('first post')
        self.run_bzr('branch parent child')
        os.unlink('child/f1')
        file('child/f2', 'wb').write('hello\n')
        self.run_bzr(['commit', '-m', 'removed f1 and modified f2',
            'child'])
        os.chdir('parent')
        self.run_bzr('merge ../child')
        wt.commit('merge branch 1')
        b = wt.branch
        sio = self.make_utf8_encoded_stringio()
        lf = LongLogFormatter(to_file=sio)
        show_log(b, lf, verbose=True)
        log = normalize_log(sio.getvalue())
        self.assertEqualDiff(log, """\
------------------------------------------------------------
revno: 2
committer: Lorem Ipsum <test@example.com>
branch nick: parent
timestamp: Just now
message:
  merge branch 1
removed:
  f1
modified:
  f2
    ------------------------------------------------------------
    revno: 1.1.1
    committer: Lorem Ipsum <test@example.com>
    branch nick: child
    timestamp: Just now
    message:
      removed f1 and modified f2
    removed:
      f1
    modified:
      f2
------------------------------------------------------------
revno: 1
committer: Lorem Ipsum <test@example.com>
branch nick: parent
timestamp: Just now
message:
  first post
added:
  f1
  f2
""")

    def test_trailing_newlines(self):
        wt = self.make_branch_and_tree('.')
        b = make_commits_with_trailing_newlines(wt)
        sio = self.make_utf8_encoded_stringio()
        lf = LongLogFormatter(to_file=sio)
        show_log(b, lf)
        self.assertEqualDiff(sio.getvalue(), """\
------------------------------------------------------------
revno: 3
committer: Joe Foo <joe@foo.com>
branch nick: test
timestamp: Mon 2005-11-21 09:32:56 -0600
message:
  single line with trailing newline
------------------------------------------------------------
revno: 2
author: Joe Bar <joe@bar.com>
committer: Joe Foo <joe@foo.com>
branch nick: test
timestamp: Mon 2005-11-21 09:27:22 -0600
message:
  multiline
  log
  message
------------------------------------------------------------
revno: 1
committer: Joe Foo <joe@foo.com>
branch nick: test
timestamp: Mon 2005-11-21 09:24:15 -0600
message:
  simple log message
""")

    def test_author_in_log(self):
        """Log includes the author name if it's set in
        the revision properties
        """
        wt = self.make_branch_and_tree('.')
        b = wt.branch
        self.build_tree(['a'])
        wt.add('a')
        b.nick = 'test_author_log'
        wt.commit(message='add a',
                  timestamp=1132711707,
                  timezone=36000,
                  committer='Lorem Ipsum <test@example.com>',
                  author='John Doe <jdoe@example.com>')
        sio = StringIO()
        formatter = LongLogFormatter(to_file=sio)
        show_log(b, formatter)
        self.assertEqualDiff(sio.getvalue(), '''\
------------------------------------------------------------
revno: 1
author: John Doe <jdoe@example.com>
committer: Lorem Ipsum <test@example.com>
branch nick: test_author_log
timestamp: Wed 2005-11-23 12:08:27 +1000
message:
  add a
''')

    def test_properties_in_log(self):
        """Log includes the custom properties returned by the registered 
        handlers.
        """
        wt = self.make_branch_and_tree('.')
        b = wt.branch
        self.build_tree(['a'])
        wt.add('a')
        b.nick = 'test_properties_in_log'
        wt.commit(message='add a',
                  timestamp=1132711707,
                  timezone=36000,
                  committer='Lorem Ipsum <test@example.com>',
                  author='John Doe <jdoe@example.com>')
        sio = StringIO()
        formatter = LongLogFormatter(to_file=sio)
        try:
            def trivial_custom_prop_handler(revision):
                return {'test_prop':'test_value'}
            
            log.properties_handler_registry.register(
                'trivial_custom_prop_handler', 
                trivial_custom_prop_handler)
            show_log(b, formatter)
        finally:
            log.properties_handler_registry.remove(
                'trivial_custom_prop_handler')
            self.assertEqualDiff(sio.getvalue(), '''\
------------------------------------------------------------
revno: 1
test_prop: test_value
author: John Doe <jdoe@example.com>
committer: Lorem Ipsum <test@example.com>
branch nick: test_properties_in_log
timestamp: Wed 2005-11-23 12:08:27 +1000
message:
  add a
''')

    def test_error_in_properties_handler(self):
        """Log includes the custom properties returned by the registered 
        handlers.
        """
        wt = self.make_branch_and_tree('.')
        b = wt.branch
        self.build_tree(['a'])
        wt.add('a')
        b.nick = 'test_author_log'
        wt.commit(message='add a',
                  timestamp=1132711707,
                  timezone=36000,
                  committer='Lorem Ipsum <test@example.com>',
                  author='John Doe <jdoe@example.com>',
                  revprops={'first_prop':'first_value'})
        sio = StringIO()
        formatter = LongLogFormatter(to_file=sio)
        try:
            def trivial_custom_prop_handler(revision):
                raise StandardError("a test error")
            
            log.properties_handler_registry.register(
                'trivial_custom_prop_handler', 
                trivial_custom_prop_handler)
            self.assertRaises(StandardError, show_log, b, formatter,)
        finally:
            log.properties_handler_registry.remove(
                'trivial_custom_prop_handler')
                
    def test_properties_handler_bad_argument(self):
        wt = self.make_branch_and_tree('.')
        b = wt.branch
        self.build_tree(['a'])
        wt.add('a')
        b.nick = 'test_author_log'
        wt.commit(message='add a',
                  timestamp=1132711707,
                  timezone=36000,
                  committer='Lorem Ipsum <test@example.com>',
                  author='John Doe <jdoe@example.com>',
                  revprops={'a_prop':'test_value'})
        sio = StringIO()
        formatter = LongLogFormatter(to_file=sio)
        try:
            def bad_argument_prop_handler(revision):
                return {'custom_prop_name':revision.properties['a_prop']}
                
            log.properties_handler_registry.register(
                'bad_argument_prop_handler', 
                bad_argument_prop_handler)
            
            self.assertRaises(AttributeError, formatter.show_properties, 
                'a revision', '')
            
            revision = b.repository.get_revision(b.last_revision())
            formatter.show_properties(revision, '')
            self.assertEqualDiff(sio.getvalue(),
                '''custom_prop_name: test_value\n''')
        finally:
            log.properties_handler_registry.remove(
                'bad_argument_prop_handler')


class TestLineLogFormatter(TestCaseWithTransport):

    def test_line_log(self):
        """Line log should show revno
        
        bug #5162
        """
        wt = self.make_branch_and_tree('.')
        b = wt.branch
        self.build_tree(['a'])
        wt.add('a')
        b.nick = 'test-line-log'
        wt.commit(message='add a',
                  timestamp=1132711707,
                  timezone=36000,
                  committer='Line-Log-Formatter Tester <test@line.log>')
        logfile = file('out.tmp', 'w+')
        formatter = LineLogFormatter(to_file=logfile)
        show_log(b, formatter)
        logfile.flush()
        logfile.seek(0)
        log_contents = logfile.read()
        self.assertEqualDiff(log_contents,
            '1: Line-Log-Formatte... 2005-11-23 add a\n')

    def test_trailing_newlines(self):
        wt = self.make_branch_and_tree('.')
        b = make_commits_with_trailing_newlines(wt)
        sio = self.make_utf8_encoded_stringio()
        lf = LineLogFormatter(to_file=sio)
        show_log(b, lf)
        self.assertEqualDiff(sio.getvalue(), """\
3: Joe Foo 2005-11-21 single line with trailing newline
2: Joe Bar 2005-11-21 multiline
1: Joe Foo 2005-11-21 simple log message
""")

    def test_line_log_single_merge_revision(self):
        wt = self.make_branch_and_memory_tree('.')
        wt.lock_write()
        try:
            wt.add('')
            wt.commit('rev-1', rev_id='rev-1',
                      timestamp=1132586655, timezone=36000,
                      committer='Joe Foo <joe@foo.com>')
            wt.commit('rev-merged', rev_id='rev-2a',
                      timestamp=1132586700, timezone=36000,
                      committer='Joe Foo <joe@foo.com>')
            wt.set_parent_ids(['rev-1', 'rev-2a'])
            wt.branch.set_last_revision_info(1, 'rev-1')
            wt.commit('rev-2', rev_id='rev-2b',
                      timestamp=1132586800, timezone=36000,
                      committer='Joe Foo <joe@foo.com>')
            logfile = self.make_utf8_encoded_stringio()
            formatter = LineLogFormatter(to_file=logfile)
            revspec = RevisionSpec.from_string('1.1.1')
            wtb = wt.branch
            rev = revspec.in_history(wtb)
            show_log(wtb, formatter, start_revision=rev, end_revision=rev)
            self.assertEqualDiff(logfile.getvalue(), """\
1.1.1: Joe Foo 2005-11-22 rev-merged
""")
        finally:
            wt.unlock()



class TestGetViewRevisions(TestCaseWithTransport):

    def make_tree_with_commits(self):
        """Create a tree with well-known revision ids"""
        wt = self.make_branch_and_tree('tree1')
        wt.commit('commit one', rev_id='1')
        wt.commit('commit two', rev_id='2')
        wt.commit('commit three', rev_id='3')
        mainline_revs = [None, '1', '2', '3']
        rev_nos = {'1': 1, '2': 2, '3': 3}
        return mainline_revs, rev_nos, wt

    def make_tree_with_merges(self):
        """Create a tree with well-known revision ids and a merge"""
        mainline_revs, rev_nos, wt = self.make_tree_with_commits()
        tree2 = wt.bzrdir.sprout('tree2').open_workingtree()
        tree2.commit('four-a', rev_id='4a')
        wt.merge_from_branch(tree2.branch)
        wt.commit('four-b', rev_id='4b')
        mainline_revs.append('4b')
        rev_nos['4b'] = 4
        # 4a: 3.1.1
        return mainline_revs, rev_nos, wt

    def make_tree_with_many_merges(self):
        """Create a tree with well-known revision ids"""
        wt = self.make_branch_and_tree('tree1')
        wt.commit('commit one', rev_id='1')
        wt.commit('commit two', rev_id='2')
        tree3 = wt.bzrdir.sprout('tree3').open_workingtree()
        tree3.commit('commit three a', rev_id='3a')
        tree2 = wt.bzrdir.sprout('tree2').open_workingtree()
        tree2.merge_from_branch(tree3.branch)
        tree2.commit('commit three b', rev_id='3b')
        wt.merge_from_branch(tree2.branch)
        wt.commit('commit three c', rev_id='3c')
        tree2.commit('four-a', rev_id='4a')
        wt.merge_from_branch(tree2.branch)
        wt.commit('four-b', rev_id='4b')
        mainline_revs = [None, '1', '2', '3c', '4b']
        rev_nos = {'1':1, '2':2, '3c': 3, '4b':4}
        full_rev_nos_for_reference = {
            '1': '1',
            '2': '2',
            '3a': '2.1.1', #first commit tree 3
            '3b': '2.2.1', # first commit tree 2
            '3c': '3', #merges 3b to main
            '4a': '2.2.2', # second commit tree 2
            '4b': '4', # merges 4a to main
            }
        return mainline_revs, rev_nos, wt

    def test_get_view_revisions_forward(self):
        """Test the get_view_revisions method"""
        mainline_revs, rev_nos, wt = self.make_tree_with_commits()
        wt.lock_read()
        self.addCleanup(wt.unlock)
        revisions = list(get_view_revisions(mainline_revs, rev_nos, wt.branch,
                                            'forward'))
        self.assertEqual([('1', '1', 0), ('2', '2', 0), ('3', '3', 0)],
            revisions)
        revisions2 = list(get_view_revisions(mainline_revs, rev_nos, wt.branch,
                                             'forward', include_merges=False))
        self.assertEqual(revisions, revisions2)

    def test_get_view_revisions_reverse(self):
        """Test the get_view_revisions with reverse"""
        mainline_revs, rev_nos, wt = self.make_tree_with_commits()
        wt.lock_read()
        self.addCleanup(wt.unlock)
        revisions = list(get_view_revisions(mainline_revs, rev_nos, wt.branch,
                                            'reverse'))
        self.assertEqual([('3', '3', 0), ('2', '2', 0), ('1', '1', 0), ],
            revisions)
        revisions2 = list(get_view_revisions(mainline_revs, rev_nos, wt.branch,
                                             'reverse', include_merges=False))
        self.assertEqual(revisions, revisions2)

    def test_get_view_revisions_merge(self):
        """Test get_view_revisions when there are merges"""
        mainline_revs, rev_nos, wt = self.make_tree_with_merges()
        wt.lock_read()
        self.addCleanup(wt.unlock)
        revisions = list(get_view_revisions(mainline_revs, rev_nos, wt.branch,
                                            'forward'))
        self.assertEqual([('1', '1', 0), ('2', '2', 0), ('3', '3', 0),
            ('4b', '4', 0), ('4a', '3.1.1', 1)],
            revisions)
        revisions = list(get_view_revisions(mainline_revs, rev_nos, wt.branch,
                                             'forward', include_merges=False))
        self.assertEqual([('1', '1', 0), ('2', '2', 0), ('3', '3', 0),
            ('4b', '4', 0)],
            revisions)

    def test_get_view_revisions_merge_reverse(self):
        """Test get_view_revisions in reverse when there are merges"""
        mainline_revs, rev_nos, wt = self.make_tree_with_merges()
        wt.lock_read()
        self.addCleanup(wt.unlock)
        revisions = list(get_view_revisions(mainline_revs, rev_nos, wt.branch,
                                            'reverse'))
        self.assertEqual([('4b', '4', 0), ('4a', '3.1.1', 1),
            ('3', '3', 0), ('2', '2', 0), ('1', '1', 0)],
            revisions)
        revisions = list(get_view_revisions(mainline_revs, rev_nos, wt.branch,
                                             'reverse', include_merges=False))
        self.assertEqual([('4b', '4', 0), ('3', '3', 0), ('2', '2', 0),
            ('1', '1', 0)],
            revisions)

    def test_get_view_revisions_merge2(self):
        """Test get_view_revisions when there are merges"""
        mainline_revs, rev_nos, wt = self.make_tree_with_many_merges()
        wt.lock_read()
        self.addCleanup(wt.unlock)
        revisions = list(get_view_revisions(mainline_revs, rev_nos, wt.branch,
                                            'forward'))
        expected = [('1', '1', 0), ('2', '2', 0), ('3c', '3', 0),
            ('3a', '2.1.1', 1), ('3b', '2.2.1', 1), ('4b', '4', 0),
            ('4a', '2.2.2', 1)]
        self.assertEqual(expected, revisions)
        revisions = list(get_view_revisions(mainline_revs, rev_nos, wt.branch,
                                             'forward', include_merges=False))
        self.assertEqual([('1', '1', 0), ('2', '2', 0), ('3c', '3', 0),
            ('4b', '4', 0)],
            revisions)


class TestGetRevisionsTouchingFileID(TestCaseWithTransport):

    def create_tree_with_single_merge(self):
        """Create a branch with a moderate layout.

        The revision graph looks like:

           A
           |\
           B C
           |/
           D

        In this graph, A introduced files f1 and f2 and f3.
        B modifies f1 and f3, and C modifies f2 and f3.
        D merges the changes from B and C and resolves the conflict for f3.
        """
        # TODO: jam 20070218 This seems like it could really be done
        #       with make_branch_and_memory_tree() if we could just
        #       create the content of those files.
        # TODO: jam 20070218 Another alternative is that we would really
        #       like to only create this tree 1 time for all tests that
        #       use it. Since 'log' only uses the tree in a readonly
        #       fashion, it seems a shame to regenerate an identical
        #       tree for each test.
        tree = self.make_branch_and_tree('tree')
        tree.lock_write()
        self.addCleanup(tree.unlock)

        self.build_tree_contents([('tree/f1', 'A\n'),
                                  ('tree/f2', 'A\n'),
                                  ('tree/f3', 'A\n'),
                                 ])
        tree.add(['f1', 'f2', 'f3'], ['f1-id', 'f2-id', 'f3-id'])
        tree.commit('A', rev_id='A')

        self.build_tree_contents([('tree/f2', 'A\nC\n'),
                                  ('tree/f3', 'A\nC\n'),
                                 ])
        tree.commit('C', rev_id='C')
        # Revert back to A to build the other history.
        tree.set_last_revision('A')
        tree.branch.set_last_revision_info(1, 'A')
        self.build_tree_contents([('tree/f1', 'A\nB\n'),
                                  ('tree/f2', 'A\n'),
                                  ('tree/f3', 'A\nB\n'),
                                 ])
        tree.commit('B', rev_id='B')
        tree.set_parent_ids(['B', 'C'])
        self.build_tree_contents([('tree/f1', 'A\nB\n'),
                                  ('tree/f2', 'A\nC\n'),
                                  ('tree/f3', 'A\nB\nC\n'),
                                 ])
        tree.commit('D', rev_id='D')

        # Switch to a read lock for this tree.
        # We still have addCleanup(unlock)
        tree.unlock()
        tree.lock_read()
        return tree

    def test_tree_with_single_merge(self):
        """Make sure the tree layout is correct."""
        tree = self.create_tree_with_single_merge()
        rev_A_tree = tree.branch.repository.revision_tree('A')
        rev_B_tree = tree.branch.repository.revision_tree('B')

        f1_changed = (u'f1', 'f1-id', 'file', True, False)
        f2_changed = (u'f2', 'f2-id', 'file', True, False)
        f3_changed = (u'f3', 'f3-id', 'file', True, False)

        delta = rev_B_tree.changes_from(rev_A_tree)
        self.assertEqual([f1_changed, f3_changed], delta.modified)
        self.assertEqual([], delta.renamed)
        self.assertEqual([], delta.added)
        self.assertEqual([], delta.removed)

        rev_C_tree = tree.branch.repository.revision_tree('C')
        delta = rev_C_tree.changes_from(rev_A_tree)
        self.assertEqual([f2_changed, f3_changed], delta.modified)
        self.assertEqual([], delta.renamed)
        self.assertEqual([], delta.added)
        self.assertEqual([], delta.removed)

        rev_D_tree = tree.branch.repository.revision_tree('D')
        delta = rev_D_tree.changes_from(rev_B_tree)
        self.assertEqual([f2_changed, f3_changed], delta.modified)
        self.assertEqual([], delta.renamed)
        self.assertEqual([], delta.added)
        self.assertEqual([], delta.removed)

        delta = rev_D_tree.changes_from(rev_C_tree)
        self.assertEqual([f1_changed, f3_changed], delta.modified)
        self.assertEqual([], delta.renamed)
        self.assertEqual([], delta.added)
        self.assertEqual([], delta.removed)

    def assertAllRevisionsForFileID(self, tree, file_id, revisions):
        """Make sure _filter_revisions_touching_file_id returns the right values.

        Get the return value from _filter_revisions_touching_file_id and make
        sure they are correct.
        """
        # The api for _get_revisions_touching_file_id is a little crazy,
        # So we do the setup here.
        mainline = tree.branch.revision_history()
        mainline.insert(0, None)
        revnos = dict((rev, idx+1) for idx, rev in enumerate(mainline))
        view_revs_iter = log.get_view_revisions(mainline, revnos, tree.branch,
                                                'reverse', True)
        actual_revs = log._filter_revisions_touching_file_id(
                            tree.branch, 
                            file_id,
                            mainline,
                            list(view_revs_iter))
        self.assertEqual(revisions, [r for r, revno, depth in actual_revs])

    def test_file_id_f1(self):
        tree = self.create_tree_with_single_merge()
        # f1 should be marked as modified by revisions A and B
        self.assertAllRevisionsForFileID(tree, 'f1-id', ['B', 'A'])

    def test_file_id_f2(self):
        tree = self.create_tree_with_single_merge()
        # f2 should be marked as modified by revisions A, C, and D
        # because D merged the changes from C.
        self.assertAllRevisionsForFileID(tree, 'f2-id', ['D', 'C', 'A'])

    def test_file_id_f3(self):
        tree = self.create_tree_with_single_merge()
        # f3 should be marked as modified by revisions A, B, C, and D
        self.assertAllRevisionsForFileID(tree, 'f2-id', ['D', 'C', 'A'])

    def test_file_id_with_ghosts(self):
        # This is testing bug #209948, where having a ghost would cause
        # _filter_revisions_touching_file_id() to fail.
        tree = self.create_tree_with_single_merge()
        # We need to add a revision, so switch back to a write-locked tree
        tree.unlock()
        tree.lock_write()
        first_parent = tree.last_revision()
        tree.set_parent_ids([first_parent, 'ghost-revision-id'])
        self.build_tree_contents([('tree/f1', 'A\nB\nXX\n')])
        tree.commit('commit with a ghost', rev_id='XX')
        self.assertAllRevisionsForFileID(tree, 'f1-id', ['XX', 'B', 'A'])
        self.assertAllRevisionsForFileID(tree, 'f2-id', ['D', 'C', 'A'])


class TestShowChangedRevisions(TestCaseWithTransport):

    def test_show_changed_revisions_verbose(self):
        tree = self.make_branch_and_tree('tree_a')
        self.build_tree(['tree_a/foo'])
        tree.add('foo')
        tree.commit('bar', rev_id='bar-id')
        s = self.make_utf8_encoded_stringio()
        log.show_changed_revisions(tree.branch, [], ['bar-id'], s)
        self.assertContainsRe(s.getvalue(), 'bar')
        self.assertNotContainsRe(s.getvalue(), 'foo')


class TestLogFormatter(TestCase):

    def test_short_committer(self):
        rev = Revision('a-id')
        rev.committer = 'John Doe <jdoe@example.com>'
        lf = LogFormatter(None)
        self.assertEqual('John Doe', lf.short_committer(rev))
        rev.committer = 'John Smith <jsmith@example.com>'
        self.assertEqual('John Smith', lf.short_committer(rev))
        rev.committer = 'John Smith'
        self.assertEqual('John Smith', lf.short_committer(rev))
        rev.committer = 'jsmith@example.com'
        self.assertEqual('jsmith@example.com', lf.short_committer(rev))
        rev.committer = '<jsmith@example.com>'
        self.assertEqual('jsmith@example.com', lf.short_committer(rev))
        rev.committer = 'John Smith jsmith@example.com'
        self.assertEqual('John Smith', lf.short_committer(rev))

    def test_short_author(self):
        rev = Revision('a-id')
        rev.committer = 'John Doe <jdoe@example.com>'
        lf = LogFormatter(None)
        self.assertEqual('John Doe', lf.short_author(rev))
        rev.properties['author'] = 'John Smith <jsmith@example.com>'
        self.assertEqual('John Smith', lf.short_author(rev))
        rev.properties['author'] = 'John Smith'
        self.assertEqual('John Smith', lf.short_author(rev))
        rev.properties['author'] = 'jsmith@example.com'
        self.assertEqual('jsmith@example.com', lf.short_author(rev))
        rev.properties['author'] = '<jsmith@example.com>'
        self.assertEqual('jsmith@example.com', lf.short_author(rev))
        rev.properties['author'] = 'John Smith jsmith@example.com'
        self.assertEqual('John Smith', lf.short_author(rev))