aboutsummaryrefslogtreecommitdiff
blob: 6cb1ff0a01ab87416636502a7c71d6577ac9492a (plain)
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
import os
import shutil
import textwrap
from datetime import datetime
from functools import partial
from io import StringIO
from unittest.mock import patch

import pytest
from pkgdev.mangle import copyright_regex, keywords_regex
from pkgdev.scripts import run
from snakeoil.contexts import chdir, os_environ
from snakeoil.osutils import pjoin


class TestPkgdevCommitParseArgs:

    def test_non_repo_cwd(self, capsys, tool):
        with pytest.raises(SystemExit) as excinfo:
            tool.parse_args(['commit'])
        assert excinfo.value.code == 2
        out, err = capsys.readouterr()
        assert err.strip() == 'pkgdev commit: error: not in ebuild repo'

    def test_bad_repo_cwd(self, make_repo, capsys, tool):
        repo = make_repo(masters=('nonexistent',))
        with pytest.raises(SystemExit) as excinfo, \
                chdir(repo.location):
            tool.parse_args(['commit'])
        assert excinfo.value.code == 2
        out, err = capsys.readouterr()
        assert err.strip().startswith('pkgdev commit: error: repo init failed')

    def test_non_git_repo_cwd(self, repo, capsys, tool):
        with pytest.raises(SystemExit) as excinfo, \
                chdir(repo.location):
            tool.parse_args(['commit'])
        assert excinfo.value.code == 2
        out, err = capsys.readouterr()
        assert err.strip() == 'pkgdev commit: error: not in git repo'

    def test_non_ebuild_git_repo_cwd(self, make_repo, git_repo, capsys, tool):
        os.mkdir(pjoin(git_repo.path, 'repo'))
        repo = make_repo(pjoin(git_repo.path, 'repo'))
        with pytest.raises(SystemExit) as excinfo, \
                chdir(repo.location):
            tool.parse_args(['commit'])
        assert excinfo.value.code == 2
        out, err = capsys.readouterr()
        assert err.strip() == 'pkgdev commit: error: not in ebuild git repo'

    def test_commit_signing(self, repo, make_git_repo, tool):
        git_repo = make_git_repo(repo.location)
        repo.create_ebuild('cat/pkg-0')
        git_repo.add_all('cat/pkg-0', commit=False)
        # signed commits aren't enabled by default
        with chdir(repo.location):
            options, _ = tool.parse_args(['commit', '-u'])
            assert '--signoff' not in options.commit_args
            assert '--gpg-sign' not in options.commit_args
        # signed commits enabled by layout.conf setting
        with open(pjoin(git_repo.path, 'metadata/layout.conf'), 'a+') as f:
            f.write('sign-commits = true\n')
        with chdir(repo.location):
            options, _ = tool.parse_args(['commit', '-u'])
            assert '--signoff' in options.commit_args
            assert '--gpg-sign' in options.commit_args

    def test_git_commit_args(self, repo, make_git_repo, tool):
        git_repo = make_git_repo(repo.location)
        repo.create_ebuild('cat/pkg-0')
        git_repo.add_all('cat/pkg-0', commit=False)
        with chdir(repo.location):
            for opt, expected in (
                    ('-n', '--dry-run'),
                    ('--dry-run', '--dry-run'),
                    ('-v', '-v'),
                    ('--verbose', '-v'),
                    ):
                options, _ = tool.parse_args(['commit', opt])
                assert expected in options.commit_args

    def test_git_commit_args_passthrough(self, repo, make_git_repo, tool):
        """Unknown arguments for ``pkgdev commit`` are passed to ``git commit``."""
        git_repo = make_git_repo(repo.location)
        repo.create_ebuild('cat/pkg-0')
        git_repo.add_all('cat/pkg-0', commit=False)
        with chdir(repo.location):
            for opt in ('--author="A U Thor <author@example.com>"', '-e'):
                options, _ = tool.parse_args(['commit', opt])
            assert options.commit_args == [opt]

    def test_scan_args(self, repo, make_git_repo, tool):
        git_repo = make_git_repo(repo.location)
        repo.create_ebuild('cat/pkg-0')
        git_repo.add_all('cat/pkg-0', commit=False)
        # pkgcheck isn't run in verbose mode by default
        with chdir(repo.location):
            options, _ = tool.parse_args(['commit'])
        assert '-v' not in options.scan_args
        # verbosity level is passed down to pkgcheck
        with chdir(repo.location):
            options, _ = tool.parse_args(['commit', '-v'])
        assert '-v' in options.scan_args

    def test_commit_tags(self, capsys, repo, make_git_repo, tool):
        git_repo = make_git_repo(repo.location)
        repo.create_ebuild('cat/pkg-0')
        git_repo.add_all('cat/pkg-0', commit=False)
        with chdir(repo.location):
            # bug IDs
            for opt in ('-b', '--bug'):
                options, _ = tool.parse_args(['commit', opt, '1'])
                assert options.footer == {('Bug', 'https://bugs.gentoo.org/1')}

            # bug URLs
            for opt in ('-b', '--bug'):
                options, _ = tool.parse_args(['commit', opt, 'https://bugs.gentoo.org/2'])
                assert options.footer == {('Bug', 'https://bugs.gentoo.org/2')}

            # bug IDs
            for opt in ('-c', '--closes'):
                options, _ = tool.parse_args(['commit', opt, '1'])
                assert options.footer == {('Closes', 'https://bugs.gentoo.org/1')}

            # bug URLs
            for opt in ('-c', '--closes'):
                options, _ = tool.parse_args(['commit', opt, 'https://bugs.gentoo.org/2'])
                assert options.footer == {('Closes', 'https://bugs.gentoo.org/2')}

            # bad URL
            for opt in ('-b', '-c'):
                with pytest.raises(SystemExit) as excinfo:
                    tool.parse_args(['commit', opt, 'bugs.gentoo.org/1'])
                assert excinfo.value.code == 2
                out, err = capsys.readouterr()
                assert not out
                assert 'invalid URL: bugs.gentoo.org/1' in err

            # generic tags
            for opt in ('-T', '--tag'):
                for value, expected in (
                        ('tag:value', ('Tag', 'value')),
                        ('tag:multiple values', ('Tag', 'multiple values')),
                        ('tag:multiple:values', ('Tag', 'multiple:values')),
                        ):
                    options, _ = tool.parse_args(['commit', opt, value])
                    assert options.footer == {expected}

            # bad tags
            for opt in ('-T', '--tag'):
                for value in ('', ':', 'tag:', ':value', 'tag'):
                    with pytest.raises(SystemExit) as excinfo:
                        tool.parse_args(['commit', opt, value])
                    assert excinfo.value.code == 2
                    out, err = capsys.readouterr()
                    assert not out
                    assert 'invalid commit tag' in err


class TestPkgdevCommit:

    script = partial(run, 'pkgdev')

    @pytest.fixture(autouse=True)
    def _setup(self, tmp_path):
        self.cache_dir = str(tmp_path)
        self.scan_args = ['--pkgcheck-scan', f'--config no --cache-dir {self.cache_dir}']
        # args for running pkgdev like a script
        self.args = ['pkgdev', 'commit'] + self.scan_args

    def test_empty_repo(self, capsys, repo, make_git_repo):
        git_repo = make_git_repo(repo.location, commit=True)
        with patch('sys.argv', self.args), \
                pytest.raises(SystemExit) as excinfo, \
                chdir(git_repo.path):
            self.script()
        assert excinfo.value.code == 2
        out, err = capsys.readouterr()
        assert not out
        assert err.strip() == 'pkgdev commit: error: no staged changes exist'

    def test_git_message_opts(self, repo, make_git_repo, tmp_path):
        """Verify message-related options are passed through to `git commit`."""
        git_repo = make_git_repo(repo.location, commit=True)
        repo.create_ebuild('cat/pkg-0')
        git_repo.add_all('cat/pkg-0', commit=False)
        path = str(tmp_path / 'msg')
        with open(path, 'w') as f:
            f.write('commit1')

        with patch('sys.argv', self.args + ['-u', '-F', path]), \
                pytest.raises(SystemExit) as excinfo, \
                chdir(git_repo.path):
            self.script()
        assert excinfo.value.code == 0
        commit_msg = git_repo.log(['-1', '--pretty=tformat:%B', 'HEAD'])
        assert commit_msg == ['commit1']

        repo.create_ebuild('cat/pkg-1')
        git_repo.add_all('cat/pkg-1', commit=False)
        with os_environ(GIT_EDITOR="sed -i '1s/1/2/'"), \
                patch('sys.argv', self.args + ['-u', '-t', path]), \
                pytest.raises(SystemExit) as excinfo, \
                chdir(git_repo.path):
            self.script()
        assert excinfo.value.code == 0
        commit_msg = git_repo.log(['-1', '--pretty=tformat:%B', 'HEAD'])
        assert commit_msg == ['commit2']

    def test_message_template(self, capsys, repo, make_git_repo, tmp_path):
        git_repo = make_git_repo(repo.location)
        repo.create_ebuild('cat/pkg-0')
        git_repo.add_all('cat/pkg-0')
        path = str(tmp_path / 'msg')

        # auto-generate prefix
        with open(path, 'w') as f:
            f.write(textwrap.dedent("""\
                *: summary

                body
            """))

        for i, opt in enumerate(['-M', '--message-template'], 1):
            repo.create_ebuild(f'cat/pkg-{i}')
            git_repo.add_all(f'cat/pkg-{i}', commit=False)
            with patch('sys.argv', self.args + ['-u', opt, path]), \
                    pytest.raises(SystemExit) as excinfo, \
                    chdir(git_repo.path):
                self.script()
            assert excinfo.value.code == 0
            commit_msg = git_repo.log(['-1', '--pretty=tformat:%B', 'HEAD'])
            assert commit_msg == ['cat/pkg: summary', '', 'body']

        # override prefix
        with open(path, 'w') as f:
            f.write(textwrap.dedent("""\
                prefix: summary

                body
            """))

        for i, opt in enumerate(['-M', '--message-template'], 3):
            repo.create_ebuild(f'cat/pkg-{i}')
            git_repo.add_all(f'cat/pkg-{i}', commit=False)
            with patch('sys.argv', self.args + ['-u', opt, path]), \
                    pytest.raises(SystemExit) as excinfo, \
                    chdir(git_repo.path):
                self.script()
            assert excinfo.value.code == 0
            commit_msg = git_repo.log(['-1', '--pretty=tformat:%B', 'HEAD'])
            assert commit_msg == ['prefix: summary', '', 'body']

        # empty message
        with open(path, 'w') as f:
            f.write('')

        for i, opt in enumerate(['-M', '--message-template'], 5):
            repo.create_ebuild(f'cat/pkg-{i}')
            git_repo.add_all(f'cat/pkg-{i}', commit=False)
            with patch('sys.argv', self.args + ['-u', opt, path]), \
                    pytest.raises(SystemExit) as excinfo, \
                    chdir(git_repo.path):
                self.script()
            assert excinfo.value.code == 2
            out, err = capsys.readouterr()
            assert not out
            assert err.strip().startswith('pkgdev commit: error: empty message template')

    def test_custom_unprefixed_message(self, capsys, repo, make_git_repo):
        git_repo = make_git_repo(repo.location)
        ebuild_path = repo.create_ebuild('cat/pkg-0')
        git_repo.add_all('cat/pkg-0')
        with open(ebuild_path, 'a+') as f:
            f.write('# comment\n')

        with patch('sys.argv', self.args + ['-u', '-m', 'msg']), \
                pytest.raises(SystemExit) as excinfo, \
                chdir(git_repo.path):
            self.script()
        assert excinfo.value.code == 0
        out, err = capsys.readouterr()
        assert err == out == ''

        commit_msg = git_repo.log(['-1', '--pretty=tformat:%B', 'HEAD'])
        assert commit_msg == ['cat/pkg: msg']

    def test_custom_prefixed_message(self, capsys, repo, make_git_repo):
        git_repo = make_git_repo(repo.location)
        ebuild_path = repo.create_ebuild('cat/pkg-0')
        git_repo.add_all('cat/pkg-0')
        with open(ebuild_path, 'a+') as f:
            f.write('# comment\n')

        with patch('sys.argv', self.args + ['-u', '-m', 'prefix: msg']), \
                pytest.raises(SystemExit) as excinfo, \
                chdir(git_repo.path):
            self.script()
        assert excinfo.value.code == 0
        out, err = capsys.readouterr()
        assert err == out == ''

        commit_msg = git_repo.log(['-1', '--pretty=tformat:%B', 'HEAD'])
        assert commit_msg == ['prefix: msg']

    def test_edited_commit_message(self, capsys, repo, make_git_repo):
        git_repo = make_git_repo(repo.location)
        ebuild_path = repo.create_ebuild('cat/pkg-0')
        git_repo.add_all('cat/pkg-0')
        with open(ebuild_path, 'a+') as f:
            f.write('# comment\n')

        with os_environ(GIT_EDITOR="sed -i '1s/$/commit/'"), \
                patch('sys.argv', self.args + ['-u']), \
                pytest.raises(SystemExit) as excinfo, \
                chdir(git_repo.path):
            self.script()
        assert excinfo.value.code == 0
        out, err = capsys.readouterr()
        assert err == out == ''

        commit_msg = git_repo.log(['-1', '--pretty=tformat:%B', 'HEAD'])
        assert commit_msg == ['cat/pkg: commit']

    def test_generated_commit_prefixes(self, capsys, repo, make_git_repo):
        git_repo = make_git_repo(repo.location)
        repo.create_ebuild('cat/pkg-0')
        git_repo.add_all('cat/pkg-0')

        def commit():
            with patch('sys.argv', self.args + ['-a', '-m', 'msg']), \
                    pytest.raises(SystemExit) as excinfo, \
                    chdir(git_repo.path):
                self.script()
            assert excinfo.value.code == 0
            out, err = capsys.readouterr()
            assert err == out == ''
            message = git_repo.log(['-1', '--pretty=tformat:%B', 'HEAD'])
            return message[0]

        # single package change
        repo.create_ebuild('cat/newpkg-0')
        assert commit().startswith('cat/newpkg: ')

        # multiple package changes in the same category
        repo.create_ebuild('cat/newpkg-1')
        repo.create_ebuild('cat/pkg-1')
        assert commit().startswith('cat/*: ')

        # multiple package changes in various categories
        repo.create_ebuild('cat/newpkg-2')
        repo.create_ebuild('cat/pkg-2')
        repo.create_ebuild('newcat/newpkg-1')
        assert commit().startswith('*/*: ')

        # single eclass change
        with open(pjoin(repo.location, 'eclass', 'foo.eclass'), 'a+') as f:
            f.write('# comment\n')
        assert commit().startswith('foo.eclass: ')

        # multiple eclass changes
        for eclass in ('foo.eclass', 'bar.eclass'):
            with open(pjoin(repo.location, 'eclass', eclass), 'a+') as f:
                f.write('# comment\n')
        assert commit().startswith('eclass: ')

        # single profiles/package.mask change
        with open(pjoin(repo.location, 'profiles', 'package.mask'), 'a+') as f:
            f.write('# comment\n')
        assert commit().startswith('profiles: ')

        amd64 = pjoin(repo.location, 'profiles', 'arch', 'amd64')
        os.makedirs(amd64)
        arm64 = pjoin(repo.location, 'profiles', 'arch', 'arm64')
        os.makedirs(arm64)

        # multiple profiles file changes in the same subdir
        for file in ('package.mask', 'package.mask'):
            with open(pjoin(amd64, file), 'a+') as f:
                f.write('# comment\n')
        assert commit().startswith('profiles/arch/amd64: ')

        # multiple profiles file changes in different subdirs
        for path in (amd64, arm64):
            with open(pjoin(path, 'package.use'), 'a+') as f:
                f.write('# comment\n')
        assert commit().startswith('profiles/arch: ')

        # single repo root file change
        with open(pjoin(repo.location, 'skel.ebuild'), 'a+') as f:
            f.write('# comment\n')
        assert commit().startswith('skel.ebuild: ')

        # multiple repo root file change (no commit message prefix)
        for file in ('skel.ebuild', 'header.txt'):
            with open(pjoin(repo.location, file), 'a+') as f:
                f.write('# comment\n')
        assert commit() == 'msg'

        # treewide changes (no commit message prefix)
        repo.create_ebuild('foo/bar-1')
        with open(pjoin(repo.location, 'eclass', 'foo.eclass'), 'a+') as f:
            f.write('# comment\n')
        with open(pjoin(repo.location, 'profiles', 'package.mask'), 'a+') as f:
            f.write('# comment\n')
        assert commit() == 'msg'

    def test_generated_commit_summaries(self, capsys, repo, make_git_repo):
        git_repo = make_git_repo(repo.location)
        repo.create_ebuild('cat/pkg-0')
        git_repo.add_all('cat/pkg-0')

        def commit():
            with os_environ(GIT_EDITOR="sed -i '1s/$/summary/'"), \
                    patch('sys.argv', self.args + ['-a']), \
                    pytest.raises(SystemExit) as excinfo, \
                    chdir(git_repo.path):
                self.script()
            assert excinfo.value.code == 0
            out, err = capsys.readouterr()
            assert err == out == ''
            message = git_repo.log(['-1', '--pretty=tformat:%B', 'HEAD'])
            return message[0]

        # initial package import
        repo.create_ebuild('cat/newpkg-0')
        assert commit() == 'cat/newpkg: new package, add 0'

        # initial package import, overflowed title truncated
        for i in range(10):
            repo.create_ebuild(f'cat/newpkg2-{i}.0.0')
        assert commit() == 'cat/newpkg2: new package'

        # single addition
        repo.create_ebuild('cat/pkg-1')
        assert commit() == 'cat/pkg: add 1'

        # multiple additions
        repo.create_ebuild('cat/pkg-2')
        repo.create_ebuild('cat/pkg-3')
        repo.create_ebuild('cat/pkg-4', eapi=6)
        assert commit() == 'cat/pkg: add 2, 3, 4'

        # revbump updating EAPI
        repo.create_ebuild('cat/pkg-4-r1', eapi=7)
        assert commit() == 'cat/pkg: update EAPI 6 -> 7'

        # single rename with no revisions
        git_repo.move(
            pjoin(git_repo.path, 'cat/pkg/pkg-4.ebuild'),
            pjoin(git_repo.path, 'cat/pkg/pkg-5.ebuild'),
            commit=False
        )
        assert commit() == 'cat/pkg: add 5, drop 4'

        # keyword version
        repo.create_ebuild('cat/pkg-6')
        git_repo.add_all('cat/pkg-6')
        repo.create_ebuild('cat/pkg-6', keywords=['~amd64'])
        assert commit() == 'cat/pkg: keyword 6 for ~amd64'

        # stabilize version
        repo.create_ebuild('cat/pkg-6', keywords=['amd64'])
        assert commit() == 'cat/pkg: stabilize 6 for amd64'

        # destabilize version
        repo.create_ebuild('cat/pkg-6', keywords=['~amd64'])
        assert commit() == 'cat/pkg: destabilize 6 for ~amd64'

        # unkeyword version
        repo.create_ebuild('cat/pkg-6', eapi='6')
        assert commit() == 'cat/pkg: unkeyword 6 for ~amd64'

        # bump EAPI
        repo.create_ebuild('cat/pkg-6', eapi='7')
        assert commit() == 'cat/pkg: update EAPI 6 -> 7'

        # multiple ebuild modifications don't get a generated summary
        repo.create_ebuild('cat/pkg-5', keywords=['~amd64'])
        repo.create_ebuild('cat/pkg-6', keywords=['~amd64'])
        assert commit() == 'cat/pkg: summary'

        # large number of additions in a single commit
        for v in range(10000, 10010):
            repo.create_ebuild(f'cat/pkg-{v}')
        assert commit() == 'cat/pkg: add versions'

        # create Manifest
        with open(pjoin(git_repo.path, 'cat/pkg/Manifest'), 'w') as f:
            f.write('DIST pkg-3.tar.gz 101 BLAKE2B deadbeef SHA512 deadbeef\n')
        assert commit() == 'cat/pkg: update Manifest'
        # update Manifest
        with open(pjoin(git_repo.path, 'cat/pkg/Manifest'), 'a+') as f:
            f.write('DIST pkg-2.tar.gz 101 BLAKE2B deadbeef SHA512 deadbeef\n')
        assert commit() == 'cat/pkg: update Manifest'
        # remove Manifest
        os.remove(pjoin(git_repo.path, 'cat/pkg/Manifest'))
        assert commit() == 'cat/pkg: update Manifest'

        # single removals
        os.remove(pjoin(git_repo.path, 'cat/pkg/pkg-4-r1.ebuild'))
        assert commit() == 'cat/pkg: drop 4-r1'
        os.remove(pjoin(git_repo.path, 'cat/pkg/pkg-3.ebuild'))
        assert commit() == 'cat/pkg: drop 3'

        # multiple removal
        os.remove(pjoin(git_repo.path, 'cat/pkg/pkg-2.ebuild'))
        os.remove(pjoin(git_repo.path, 'cat/pkg/pkg-1.ebuild'))
        assert commit() == 'cat/pkg: drop 1, 2'

        # large number of removals in a single commit
        for v in range(10000, 10010):
            os.remove(pjoin(git_repo.path, f'cat/pkg/pkg-{v}.ebuild'))
        assert commit() == 'cat/pkg: drop versions'

        # package rename
        shutil.copytree(pjoin(git_repo.path, 'cat/pkg'), pjoin(git_repo.path, 'newcat/pkg'))
        shutil.rmtree(pjoin(git_repo.path, 'cat/pkg'))
        assert commit() == 'newcat/pkg: rename cat/pkg'

        # treeclean
        shutil.rmtree(pjoin(git_repo.path, 'newcat/pkg'))
        assert commit() == 'newcat/pkg: treeclean'

    def test_metadata_summaries(self, capsys, repo, make_git_repo):
        git_repo = make_git_repo(repo.location)
        pkgdir = os.path.dirname(repo.create_ebuild('cat/pkg-0'))
        # stub metadata
        with open(pjoin(pkgdir, 'metadata.xml'), 'w') as f:
            f.write(textwrap.dedent("""\
                <?xml version="1.0" encoding="UTF-8"?>
                <!DOCTYPE pkgmetadata SYSTEM "http://www.gentoo.org/dtd/metadata.dtd">
                <pkgmetadata>
                    <maintainer type="person">
                        <email>person@email.com</email>
                        <name>Person</name>
                    </maintainer>
                </pkgmetadata>
            """))
        git_repo.add_all('cat/pkg-0')

        def commit():
            with os_environ(GIT_EDITOR="sed -i '1s/$/summary/'"), \
                    patch('sys.argv', self.args + ['-a']), \
                    pytest.raises(SystemExit) as excinfo, \
                    chdir(git_repo.path):
                self.script()
            assert excinfo.value.code == 0
            out, err = capsys.readouterr()
            assert err == out == ''
            message = git_repo.log(['-1', '--pretty=tformat:%B', 'HEAD'])
            return message[0]

        # add yourself
        with open(pjoin(pkgdir, 'metadata.xml'), 'w') as f:
            f.write(textwrap.dedent("""\
                <?xml version="1.0" encoding="UTF-8"?>
                <!DOCTYPE pkgmetadata SYSTEM "http://www.gentoo.org/dtd/metadata.dtd">
                <pkgmetadata>
                    <maintainer type="person">
                        <email>person@email.com</email>
                        <name>Person</name>
                    </maintainer>
                    <maintainer type="person">
                        <email>first.last@email.com</email>
                        <name>First Last</name>
                    </maintainer>
                </pkgmetadata>
            """))
        assert commit() == 'cat/pkg: add myself as a maintainer'

        # drop yourself
        with open(pjoin(pkgdir, 'metadata.xml'), 'w') as f:
            f.write(textwrap.dedent("""\
                <?xml version="1.0" encoding="UTF-8"?>
                <!DOCTYPE pkgmetadata SYSTEM "http://www.gentoo.org/dtd/metadata.dtd">
                <pkgmetadata>
                    <maintainer type="person">
                        <email>person@email.com</email>
                        <name>Person</name>
                    </maintainer>
                </pkgmetadata>
            """))
        assert commit() == 'cat/pkg: drop myself as a maintainer'

        # drop to maintainer-needed
        with open(pjoin(pkgdir, 'metadata.xml'), 'w') as f:
            f.write(textwrap.dedent("""\
                <?xml version="1.0" encoding="UTF-8"?>
                <!DOCTYPE pkgmetadata SYSTEM "http://www.gentoo.org/dtd/metadata.dtd">
                <pkgmetadata>
                </pkgmetadata>
            """))
        assert commit() == 'cat/pkg: drop to maintainer-needed'

        # add random maintainer
        with open(pjoin(pkgdir, 'metadata.xml'), 'w') as f:
            f.write(textwrap.dedent("""\
                <?xml version="1.0" encoding="UTF-8"?>
                <!DOCTYPE pkgmetadata SYSTEM "http://www.gentoo.org/dtd/metadata.dtd">
                <pkgmetadata>
                    <maintainer type="person">
                        <email>person@email.com</email>
                        <name>Person</name>
                    </maintainer>
                </pkgmetadata>
            """))
        assert commit() == 'cat/pkg: update maintainers'

        # add allarches tag
        with open(pjoin(pkgdir, 'metadata.xml'), 'w') as f:
            f.write(textwrap.dedent("""\
                <?xml version="1.0" encoding="UTF-8"?>
                <!DOCTYPE pkgmetadata SYSTEM "http://www.gentoo.org/dtd/metadata.dtd">
                <pkgmetadata>
                    <maintainer type="person">
                        <email>person@email.com</email>
                        <name>Person</name>
                    </maintainer>
                    <stabilize-allarches/>
                </pkgmetadata>
            """))
        assert commit() == 'cat/pkg: mark ALLARCHES'

        # drop allarches tag
        with open(pjoin(pkgdir, 'metadata.xml'), 'w') as f:
            f.write(textwrap.dedent("""\
                <?xml version="1.0" encoding="UTF-8"?>
                <!DOCTYPE pkgmetadata SYSTEM "http://www.gentoo.org/dtd/metadata.dtd">
                <pkgmetadata>
                    <maintainer type="person">
                        <email>person@email.com</email>
                        <name>Person</name>
                    </maintainer>
                </pkgmetadata>
            """))
        assert commit() == 'cat/pkg: drop ALLARCHES'

        # add upstream metadata
        with open(pjoin(pkgdir, 'metadata.xml'), 'w') as f:
            f.write(textwrap.dedent("""\
                <?xml version="1.0" encoding="UTF-8"?>
                <!DOCTYPE pkgmetadata SYSTEM "http://www.gentoo.org/dtd/metadata.dtd">
                <pkgmetadata>
                    <maintainer type="person">
                        <email>person@email.com</email>
                        <name>Person</name>
                    </maintainer>
                    <upstream>
                        <remote-id type="github">pkgcore/pkgdev</remote-id>
                        <remote-id type="pypi">pkgdev</remote-id>
                    </upstream>
                </pkgmetadata>
            """))
        assert commit() == 'cat/pkg: add github, pypi upstream metadata'

        # remove upstream metadata
        with open(pjoin(pkgdir, 'metadata.xml'), 'w') as f:
            f.write(textwrap.dedent("""\
                <?xml version="1.0" encoding="UTF-8"?>
                <!DOCTYPE pkgmetadata SYSTEM "http://www.gentoo.org/dtd/metadata.dtd">
                <pkgmetadata>
                    <maintainer type="person">
                        <email>person@email.com</email>
                        <name>Person</name>
                    </maintainer>
                    <upstream>
                        <remote-id type="github">pkgcore/pkgdev</remote-id>
                    </upstream>
                </pkgmetadata>
            """))
        assert commit() == 'cat/pkg: remove pypi upstream metadata'

        # update upstream metadata
        with open(pjoin(pkgdir, 'metadata.xml'), 'w') as f:
            f.write(textwrap.dedent("""\
                <?xml version="1.0" encoding="UTF-8"?>
                <!DOCTYPE pkgmetadata SYSTEM "http://www.gentoo.org/dtd/metadata.dtd">
                <pkgmetadata>
                    <maintainer type="person">
                        <email>person@email.com</email>
                        <name>Person</name>
                    </maintainer>
                    <upstream>
                        <remote-id type="github">pkgcore/pkgcheck</remote-id>
                    </upstream>
                </pkgmetadata>
            """))
        assert commit() == 'cat/pkg: update upstream metadata'

    def test_no_summary(self, capsys, repo, make_git_repo):
        git_repo = make_git_repo(repo.location)
        repo.create_ebuild('cat/pkg-0')
        git_repo.add_all('cat/pkg-0')

        def commit(args):
            with os_environ(GIT_EDITOR="sed -i '1s/$/summary/'"), \
                    patch('sys.argv', self.args + args), \
                    pytest.raises(SystemExit) as excinfo, \
                    chdir(git_repo.path):
                self.script()
            assert excinfo.value.code == 0
            out, err = capsys.readouterr()
            assert err == out == ''
            return git_repo.log(['-1', '--pretty=tformat:%B', 'HEAD'])

        # no commit message content
        for i in range(10):
            with open(pjoin(git_repo.path, f'file-a-{i}'), 'w') as f:
                f.write('stub\n')
        assert commit(['-a']) == ['summary']

        # footer exists with no generated summary
        for i in range(10):
            with open(pjoin(git_repo.path, f'file-b-{i}'), 'w') as f:
                f.write('stub\n')
        assert commit(['-a', '-T', 'tag:value']) == ['summary', '', 'Tag: value']

    def test_non_gentoo_file_mangling(self, repo, make_git_repo):
        git_repo = make_git_repo(repo.location)
        ebuild_path = repo.create_ebuild('cat/pkg-0')
        git_repo.add_all('cat/pkg-0')

        def commit(args):
            with patch('sys.argv', self.args + args), \
                    pytest.raises(SystemExit) as excinfo, \
                    chdir(git_repo.path):
                self.script()
            assert excinfo.value.code == 0

        # append line missing EOF newline to ebuild
        with open(ebuild_path, 'a+') as f:
            f.write('# comment')
        # verify file doesn't end with newline
        with open(ebuild_path) as f:
            assert f.read()[-1] != '\n'

        # non-gentoo repos aren't mangled by default
        commit(['-u', '-m', 'mangling'])
        with open(ebuild_path) as f:
            assert f.read()[-1] != '\n'

        # but they can be forcibly mangled
        with open(ebuild_path, 'a+') as f:
            f.write('# comment')
        commit(['--mangle', '-u', '-m', 'mangling'])
        # mangled pre-commit, file now ends with newline
        with open(ebuild_path) as f:
            assert f.read()[-1] == '\n'

        # FILESDIR content is ignored even when forced
        path = pjoin(os.path.dirname(ebuild_path), 'files', 'pkg.patch')
        os.makedirs(os.path.dirname(path))
        with open(path, 'w') as f:
            f.write('# comment')
        # verify file doesn't end with newline
        with open(path) as f:
            assert f.read()[-1] != '\n'

    def test_gentoo_file_mangling(self, make_repo, make_git_repo):
        repo = make_repo(repo_id='gentoo')
        git_repo = make_git_repo(repo.location)
        ebuild_path = repo.create_ebuild('cat/pkg-0')
        git_repo.add_all('cat/pkg-0')

        def commit(args):
            with patch('sys.argv', self.args + args), \
                    pytest.raises(SystemExit) as excinfo, \
                    chdir(git_repo.path):
                self.script()
            assert excinfo.value.code == 0

        # append line missing EOF newline to ebuild
        with open(ebuild_path, 'a+') as f:
            f.write('# comment')
        # verify file doesn't end with newline
        with open(ebuild_path) as f:
            assert f.read()[-1] != '\n'

        # gentoo repos are mangled by default
        commit(['-n', '-u', '-m', 'mangling'])
        with open(ebuild_path) as f:
            assert f.read()[-1] == '\n'

        # FILESDIR content is ignored
        path = pjoin(os.path.dirname(ebuild_path), 'files', 'pkg.patch')
        os.makedirs(os.path.dirname(path))
        with open(path, 'w') as f:
            f.write('# comment')
        # verify file doesn't end with newline
        with open(path) as f:
            assert f.read()[-1] != '\n'

        for years, org in (
                ('1999-2020', 'Gentoo Authors'),
                ('1999-2020', 'Gentoo Foundation'),
                ('2020', 'Gentoo Authors'),
                ('2020', 'Gentoo Foundation'),
                ):
            # munge the copyright header
            with open(ebuild_path, 'r+') as f:
                lines = f.read().splitlines()
                lines[0] = f'# Copyright {years} {org}\n'
                f.seek(0)
                f.truncate()
                f.write('\n'.join(lines) + '\n')
            commit(['-n', '-u', '-m', 'mangling'])
            # verify the copyright header was updated
            with open(ebuild_path) as f:
                lines = f.read().splitlines()
                mo = copyright_regex.match(lines[0])
                assert mo.group('end') == str(datetime.today().year)
                assert mo.group('begin') == years[:4] + '-'
                assert mo.group('holder') == 'Gentoo Authors'

        for original, expected in (
                ('"arm64 amd64 x86"', 'amd64 arm64 x86'),
                ('"arm64 amd64 ~x86"', 'amd64 arm64 ~x86'),
                ('"arm64 ~x86 amd64"', 'amd64 arm64 ~x86'),
                ('"arm64 ~x86 ~amd64"', '~amd64 arm64 ~x86'),
                ('arm64 ~x86 ~amd64', '~amd64 arm64 ~x86'),
                ):
            # munge the keywords
            with open(ebuild_path, 'r+') as f:
                lines = f.read().splitlines()
                lines[-1] = f'KEYWORDS={original}'
                f.seek(0)
                f.truncate()
                f.write('\n'.join(lines) + '\n')
            commit(['-n', '-u', '-m', 'mangling'])
            # verify the keywords were updated
            with open(ebuild_path) as f:
                lines = f.read().splitlines()
                mo = keywords_regex.match(lines[-1])
                assert mo.group('keywords') == expected

    def test_scan(self, capsys, repo, make_git_repo):
        git_repo = make_git_repo(repo.location)
        repo.create_ebuild('cat/pkg-0')
        git_repo.add_all('cat/pkg-0')

        for i, opt in enumerate(['-s', '--scan'], 1):
            repo.create_ebuild(f'cat/pkg-{i}')
            git_repo.add_all(f'cat/pkg-{i}', commit=False)
            with patch('sys.argv', self.args + [opt]), \
                    pytest.raises(SystemExit) as excinfo, \
                    chdir(git_repo.path):
                self.script()
            assert excinfo.value.code == 0
            out, err = capsys.readouterr()
            assert err == out == ''
            commit_msg = git_repo.log(['-1', '--pretty=tformat:%B', 'HEAD'])
            assert commit_msg == [f'cat/pkg: add {i}']

    def test_failed_scan(self, capsys, repo, make_git_repo):
        git_repo = make_git_repo(repo.location)
        repo.create_ebuild('cat/pkg-0')
        git_repo.add_all('cat/pkg-0')

        # verify staged changes via `pkgcheck scan` before creating commit
        repo.create_ebuild('cat/pkg-1', license='')
        git_repo.add_all('cat/pkg-1', commit=False)
        with patch('sys.argv', self.args + ['--scan']), \
                pytest.raises(SystemExit) as excinfo, \
                chdir(git_repo.path):
            self.script()
        assert excinfo.value.code == 1
        out, err = capsys.readouterr()
        assert not err
        assert out == textwrap.dedent("""\
            cat/pkg
              MissingLicense: version 1: no license defined

            FAILURES
            cat/pkg
              MissingLicense: version 1: no license defined
        """)

        # ignore failures to create the commit
        with patch('sys.argv', self.args + ['--scan', '--ask']), \
                patch('sys.stdin', StringIO('y\n')), \
                pytest.raises(SystemExit) as excinfo, \
                chdir(git_repo.path):
            self.script()
        assert excinfo.value.code == 0

    def test_failed_manifest(self, capsys, repo, make_git_repo):
        git_repo = make_git_repo(repo.location)
        repo.create_ebuild('cat/pkg-0')
        git_repo.add_all('cat/pkg-0')
        repo.create_ebuild('cat/pkg-1', eapi='-1')
        git_repo.add_all('cat/pkg-1', commit=False)
        with patch('sys.argv', self.args), \
                pytest.raises(SystemExit) as excinfo, \
                chdir(git_repo.path):
            self.script()
        assert excinfo.value.code == 1
        out, err = capsys.readouterr()
        assert not err
        assert out == " * cat/pkg-1: invalid EAPI '-1'\n"