File: salsa

package info (click to toggle)
pkg-perl-tools 0.85
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 796 kB
  • sloc: perl: 3,254; sh: 3,244; makefile: 144; python: 18
file content (1212 lines) | stat: -rwxr-xr-x 35,246 bytes parent folder | download
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
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
#!/usr/bin/perl

use strict;
use warnings;
use 5.010;
use File::Spec;
use Getopt::Long;
use Git;
use GitLab::API::v4::Constants 0.11 qw( :all );
use GitLab::API::v4 0.13;
use JSON;
use Pod::Usage qw( pod2usage );
use Try::Tiny;
use utf8::all;
use Term::ANSIColor;

# honour CLICOLOR; NO_COLOR is automatically honoured
if ( exists( $ENV{CLICOLOR} ) && $ENV{CLICOLOR} == 0 ) {
    if ( !$ENV{CLICOLOR_FORCE} ) {
        $ENV{ANSI_COLORS_DISABLED} = 1;
    }
}
# also disable colors if STDOUT is not a tty
$ENV{ANSI_COLORS_DISABLED} = 1 unless -t STDOUT;

# config
## defaults
my %config = (
    api_url                         => 'https://salsa.debian.org/api/v4',
    private_token                   => '',
    perl_team_path                  => 'perl-team',
    perl_team_id                    => 2663,
    perl_team_interpreter_path      => 'perl-team/interpreter',
    perl_team_interpreter_id        => 2664,
    perl_team_modules_path          => 'perl-team/modules',
    perl_team_modules_id            => 2665,
    perl_team_modules_packages_path => 'perl-team/modules/packages',
    perl_team_modules_packages_id   => 2666,
    perl_team_modules_attic_path    => 'perl-team/modules/attic',
    perl_team_modules_attic_id      => 2667,
    perl_team_modules_meta_path     => 'perl-team/modules/meta',
    perl_team_modules_meta_id       => 13881,
    perl_team_pages_path            => 'perl-team/perl-team.pages.debian.net',
    perl_team_pages_id              => 13873,
    perl_team_scripts_path          => 'perl-team/scripts',
    perl_team_scripts_id            => 13429,
    packages                        => '',
);

## update from environment / config file
## this is also exported by dpt(1) from ~/.dpt.conf / ~/.config/dpt.conf
## use DPT_SALSA_FOO as $config{foo}
foreach ( keys %config ) {
    my $KEY = 'DPT_SALSA_' . uc($_);
    $config{$_} = $ENV{$KEY} if $ENV{$KEY};
}
## also read DPT_PACKAGES
$config{packages} = $ENV{DPT_PACKAGES};

# commandline
## options
my %opts;
GetOptions(
    \%opts,         'help|?', 'man', 'json',
    'all',          'attic',  'on',  'off',
    'parallel|j=i', 'verbose',
) or pod2usage(2);
pod2usage(1) if $opts{help};
pod2usage( -exitval => 0, -verbose => 2 ) if $opts{man};
pod2usage(    # don't check earlier to allow for --help/--man
    -msg      => "E: DPT_SALSA_PRIVATE_TOKEN not set.\n",
    -exitval  => 2,
    -verbose  => 99,
    -sections => "SYNOPSIS|CONFIGURATION",
) unless $config{private_token};

my $jobs = $opts{parallel} || 1;
$jobs = 0 unless $jobs =~ /^\d{1,3}$/ and $jobs > 1;

## subcommand and arguments
my $command = shift @ARGV;
pod2usage("E: No subcommand given.\n") unless $command;
my @args = @ARGV;

# our API object
my $api = GitLab::API::v4->new(
    url           => $config{api_url},
    private_token => $config{private_token},
);

# data
my %levels_name = (
    no_access  => $GITLAB_ACCESS_LEVEL_NO_ACCESS,
    guest      => $GITLAB_ACCESS_LEVEL_GUEST,
    reporter   => $GITLAB_ACCESS_LEVEL_REPORTER,
    developer  => $GITLAB_ACCESS_LEVEL_DEVELOPER,
    maintainer => $GITLAB_ACCESS_LEVEL_MASTER,
    owner      => $GITLAB_ACCESS_LEVEL_OWNER,
);

my %levels_code = (
    $GITLAB_ACCESS_LEVEL_NO_ACCESS => 'no access',
    $GITLAB_ACCESS_LEVEL_GUEST     => 'guest',
    $GITLAB_ACCESS_LEVEL_REPORTER  => 'reporter',
    $GITLAB_ACCESS_LEVEL_DEVELOPER => 'developer',
    $GITLAB_ACCESS_LEVEL_MASTER    => 'maintainer',
    $GITLAB_ACCESS_LEVEL_OWNER     => 'owner',
);

# run command
if ( $command eq 'version' ) {
    version();
} elsif ( $command eq 'current_user' ) {
    current_user();
} elsif ( $command eq 'adduser' ) {
    adduser();
} elsif ( $command eq 'removeuser'
    or $command eq 'rmuser'
    or $command eq 'deluser' )
{
    removeuser();
} elsif ( $command eq 'changeuser' ) {
    changeuser();
} elsif ( $command eq 'listmembers'
    or $command eq 'listmember'
    or $command eq 'lsmembers'
    or $command eq 'lsmember'
    or $command eq 'listusers'
    or $command eq 'listuser'
    or $command eq 'lsusers'
    or $command eq 'lsuser' )
{
    listmembers();
} elsif ( $command eq 'listrepos'
    or $command eq 'lsrepos'
    or $command eq 'listrepo'
    or $command eq 'lsrepo' )
{
    listrepos();
} elsif ( $command eq 'createrepo' ) {
    createrepo();
} elsif ( $command eq 'pushrepo' ) {
    pushrepo();
} elsif ( $command eq 'configurerepo' ) {
    configurerepo();
} elsif ( $command eq 'changerepo' ) {
    changerepo();
} elsif ( $command eq 'deleterepo' ) {
    deleterepo();
} elsif ( $command eq 'kgb' ) {
    kgb();
} elsif ( $command eq 'mrconfig' ) {
    mrconfig();
} elsif ( $command eq 'toattic' ) {
    toattic();
} elsif ( $command eq 'fromattic' ) {
    fromattic();
} elsif ( $command eq 'help' ) {
    pod2usage(1);
} else {
    pod2usage("E: Unknown subcommand: $command.\n");
}
exit;

# subcommand implementations
## version()
sub version {
    my $version = $api->version();
    if ( $opts{json} ) {
        say prettyjson($version);
    } else {
        say "Version:  " . $version->{version};
        say "Revision: " . $version->{revision};
    }
}

## current_user()
sub current_user {
    my $current_user = $api->current_user();
    if ( $opts{json} ) {
        say prettyjson($current_user);
    } else {
        say "Username: " . $current_user->{username};
        say "Name:     " . $current_user->{name};
        say "Email:    " . $current_user->{email};
    }
}

## adduser()
sub adduser {
    my ( $user, $level ) = @args;
    die 'Required parameter username|userid missing.' unless $user;
    $level ||= 'maintainer';

    my $user_id = user2userid($user);

    my $access_level = $levels_name{ lc($level) };
    die "Unknown access level '$level'." unless $access_level;

    $api->add_group_member( $config{perl_team_modules_id},
        { user_id => $user_id, access_level => $access_level } );
}

## changeuser()
sub changeuser {
    my ( $level, $user ) = @args;
    die 'Required parameter "access level" missing.' unless $level;
    die 'Required parameter username|userid missing.'
        unless ( $user or $opts{all} );
    my @userids = $opts{all} ? listmembers() : $user;

    foreach (@userids) {
        my $user_id = user2userid($_);

        my $access_level = $levels_name{ lc($level) };
        die "Unknown access level '$level'." unless $access_level;

        $api->update_group_member(
            $config{perl_team_modules_id},
            $user_id, { access_level => $access_level },
        );
    }
}

## removeuser()
sub removeuser {
    my ($user) = @args;
    die 'Required parameter username|userid missing.' unless $user;
    my $user_id = user2userid($user);
    $api->remove_group_member( $config{perl_team_modules_id}, $user_id );
}

## listmembers()
sub listmembers {
    my $paginator
        = $api->paginator( 'group_members', $config{perl_team_modules_id} );
    my @userids;
    while ( my $user = trypaginator($paginator) ) {
        push @userids, $user->{id};
        next if $opts{all};
        if ( $opts{json} ) {
            say prettyjson($user);
        } else {
            my $access_level = $levels_code{ $user->{access_level} };
            say "Id:           " . $user->{id};
            say "Username:     " . $user->{username};
            say "Name:         " . $user->{name};
            say "Access level: " . $access_level;
        }
    }
    return @userids;
}

## listrepos()
sub listrepos {
    my $paginator = $api->paginator(
        'group_projects',
        $opts{attic}
        ? $config{perl_team_modules_attic_id}
        : $config{perl_team_modules_packages_id},
        { order_by => 'name', sort => 'asc', simple => $opts{all}, }
    );
    my @repoids;
    while ( my $repo = trypaginator($paginator) ) {
        push @repoids, $repo->{id};
        next if $opts{all};
        if ( $opts{json} ) {
            say prettyjson($repo);
        } else {
            say "Id:   " . $repo->{id};
            say "Name: " . $repo->{name};
            say "URL:  " . $repo->{web_url};
        }
    }
    return @repoids;
}

## createrepo()
sub createrepo {
    my ($reponame) = shift || @args;
    die 'Required parameter repositoryname missing.' unless $reponame;

    my $repo = $api->create_project(
        {   name         => $reponame,
            namespace_id => $config{perl_team_modules_packages_id},
            visibility   => 'public',
        }
    );
    configurerepo( $repo->{id} );
}

## pushrepo()
sub pushrepo {
    my $pkg = qx/dh_testdir && dpkg-parsechangelog --show-field Source/;
    die "Can't find the name of this source package." unless $pkg;
    chomp $pkg;

    my $localrepo = Git->repository();
    my %remotes = map { my ( $name, $url ) = split ' '; $name => $url; }
        $localrepo->command( 'remote', '--verbose', 'show' );
    my $salsaurl
        = 'git@salsa.debian.org:'
        . $config{perl_team_modules_packages_path}
        . "/$pkg.git";
    if ( !$remotes{'origin'} ) {
        $localrepo->command( 'remote', 'add', 'origin', $salsaurl );
    } elsif ( $remotes{'origin'}
        !~ m!^git\@salsa\.debian\.org:$config{perl_team_modules_packages_path}/$pkg\.git$!
        )
    {
        $localrepo->command( 'remote', 'set-url', 'origin', $salsaurl );
    }

    createrepo($pkg)
        unless $api->project(
        $config{perl_team_modules_packages_path} . '/' . $pkg );

    # or --mirror instead of the two? also pushes origin/ branches
    $localrepo->command( 'push', '--all', '--verbose', '--set-upstream',
        'origin' );
    $localrepo->command( 'push', '--tags', '--verbose', 'origin' );
}

## configurerepo()
sub configurerepo {
    my ($repo) = shift || @args;
    die 'Required parameter reponame|repoid missing.'
        unless ( $repo or $opts{all} );
    my @repoids = $opts{all} ? listrepos() : $repo;

    my %failures;
    my $access_level = get_access_level();

    # parallel
    my $pm;
    if ($jobs) {
        eval {
            require Parallel::ForkManager;
            $pm = Parallel::ForkManager->new($jobs);
        }
            or warn "Parallel::ForkManager not found. "
            . " apt install libparallel-forkmanager-perl ?\n"
            . "Continuing in a single process.\n";
    }

    foreach (@repoids) {
        my $repo_name = $_; # set to id for error message when getting the name fails

        if ($pm) {
            $pm->start and next;
        }

        try {
            my $repo_path = repo2repopath($_);
            $repo_name = $api->project($repo_path)->{name};

            # basic settings
            my $configparams = {
                description  => "Debian package $repo_name",
                wiki_enabled => 0,
                tag_list => ['dpt-salsa-configured'],
            };
            # changing visibility needs owner permissions
            $configparams->{visibility} = 'public'
                if defined $access_level
                && $access_level >= $GITLAB_ACCESS_LEVEL_OWNER;
            $api->edit_project( $repo_path, $configparams );

            # webhooks: cleanup and set: tagpending and kgb
            my $hooks = $api->project_hooks($repo_path);
            $api->delete_project_hook( $repo_path, $_->{id} ) foreach @{$hooks};

            $api->create_project_hook(
                $repo_path,
                {   url =>
                        "https://webhook.salsa.debian.org/tagpending/$repo_name",
                    push_events => 1,
                }
            );
            $api->create_project_hook(
                $repo_path,
                {   url =>
                        'https://kgb.debian.net/webhook/?channel=debian-perl-changes&pipeline_only_status=success&pipeline_only_status=failed',
                    push_events                  => 1,
                    # push_events_branch_filter  => 'string',
                    issues_events                => 1,
                    confidential_issues_events   => 0,
                    merge_requests_events        => 1,
                    tag_push_events              => 1,
                    note_events                  => 1,
                    confidential_notes_events    => 0, # or _comments_? not exposed by Gitlab::API::v4 or Gitlab API yet
                    job_events                   => 0,
                    pipeline_events              => 1,
                    wiki_page_events             => 1,
                }
            );
            say colored( "I: repository '$repo_name' configured.", 'green' )
                if $opts{verbose};
        }
        catch {
            say STDERR colored(
                "W: repository '$repo_name' configuration failed: '$_'.",
                'yellow' )
                if $opts{verbose};
            $failures{$repo_name} = $_;
        }
        finally {
            $pm->finish() if $pm;
        };
    }

    $pm->wait_all_children if $pm;

    say STDERR colored( "E: configurerepo() failed for $_: " . $failures{$_},
        'red' )
        foreach sort keys %failures;
}

## kgb()
sub kgb {
    my ($repo) = shift || @args;
    die 'Required parameter reponame|repoid missing.'
        unless ( $repo or $opts{all} );
    my @repoids = $opts{all} ? listrepos() : $repo;

    ( $opts{on} xor $opts{off} )
        or die "Exactly on of --on or --off is required";

    foreach (@repoids) {
        my $repo_path = repo2repopath($_);
        my $repo_name = $api->project($repo_path)->{name};

        my $hooks = $api->project_hooks($repo_path);

        if ($opts{off}) {
            foreach ( @{$hooks} ) {
                $api->delete_project_hook( $repo_path, $_->{id} )
                    if $_->{url} =~ m{^https?://kgb\.debian\.net(?::\d+)?/};
            }
        }

        if ( $opts{on} ) {
            my $already_present;

            foreach ( @{$hooks} ) {
                $already_present = 1, last
                    if $_->{url} =~ m{^https://kgb\.debian\.net/};

                # remove legacy hooks
                $api->delete_project_hook( $repo_path, $_->{id} )
                    if $_->{url} =~ m{^https?://kgb\.debian\.net(?::\d+)?/};
            }

            unless ($already_present) {
                $api->create_project_hook(
                    $repo_path,
                    {   url =>
                            'https://kgb.debian.net/webhook/?channel=debian-perl-changes&pipeline_only_status=success&pipeline_only_status=failed',
                        push_events                  => 1,
                        # push_events_branch_filter  => 'string',
                        issues_events                => 1,
                        confidential_issues_events   => 0,
                        merge_requests_events        => 1,
                        tag_push_events              => 1,
                        note_events                  => 1,
                        confidential_notes_events    => 0, # or _comments_? not exposed by Gitlab::API::v4 or Gitlab API yet
                        job_events                   => 0,
                        pipeline_events              => 1,
                        wiki_page_events             => 1,
                    }
                );
            }
        }
    }
}

## changerepo()
sub changerepo {
    my ( $repo, $property, $value ) = @args;
    die 'Required parameter reponame|repoid missing.'  unless $repo;
    die 'Required parameter name|description missing.' unless $property;
    die "Unknown property '$property'. Valid cases: 'name' or 'description'."
        unless ( $property eq 'name' or $property eq 'description' );
    die 'Required parameter "new value" missing.' unless $value;

    my $repo_path = repo2repopath($repo);
    $api->edit_project( $repo_path, { $property => $value } );
    $api->edit_project( $repo_path, { path      => $value } )
        if $property eq 'name';
}

## deleterepo()
sub deleterepo {
    my ($repo) = shift || @args;
    die 'Required parameter reponame|repoid missing.' unless $repo;

    my $access_level = get_access_level();
    die 'Deleting a project needs owner privileges.'
        unless defined $access_level
        && $access_level >= $GITLAB_ACCESS_LEVEL_OWNER;

    my $repo_path = repo2repopath($repo);
    $api->delete_project($repo_path);
}

## mrconfig()
sub mrconfig {
    die 'DPT_PACKAGES not set.' unless $config{packages};

    # mrconfig
    my $mroutdir = File::Spec->catdir( $config{packages}, '..' );
    die "Can't find directory '$mroutdir'." unless -d $mroutdir;

    my $mrconfig = File::Spec->catfile( $mroutdir, '.mrconfig' );
    die "Can't find '.mrconfig' in '$mroutdir'" unless -f $mrconfig;

    my $mroutfile = File::Spec->catfile( $mroutdir, '.mrconfig.packages' );
    open( my $mrfh, '>', "$mroutfile.new" )
        or die "Can't open '$mroutfile.new': $!";
    my @mrstanzas;

    # lastactivity
    my $lastactivityoutdir
        = File::Spec->catdir( $config{packages}, '..', '.lastactivity' );
    -d $lastactivityoutdir
        or mkdir($lastactivityoutdir)
        or die "Can't find or create directory '$lastactivityoutdir': $!";

    my @currentlastactivityfiles = glob("$lastactivityoutdir/*");
    s{$lastactivityoutdir/}{}o for @currentlastactivityfiles;
    my %currentlastactivityfiles
        = map( ( $_ => 1 ), @currentlastactivityfiles );

    # parallel
    my $pm;
    if ($jobs) {
        eval {
            require Parallel::ForkManager;
            $pm = Parallel::ForkManager->new($jobs);
            $pm->run_on_finish(
                sub {
                    my ( $pid, $exit_code, $ident, $exit_signal, $core_dump,
                        $data_structure_reference )
                        = @_;
                    push @mrstanzas, ${$data_structure_reference}
                        if defined($data_structure_reference);
                }
            );
        }
            or warn "Parallel::ForkManager not found. "
            . " apt install libparallel-forkmanager-perl ?\n"
            . "Continuing in a single process.\n";
    }

    my $paginator = $api->paginator(
        'group_projects',
        $config{perl_team_modules_packages_id},
        { order_by => 'name', sort => 'asc', simple => 1, }
    );
    my @misconfigrepos;
    my @dirtyrepos;
    my $num_repos = 0;
    while ( my $repo = trypaginator($paginator) ) {
        my $reponame = $repo->{name};
        delete $currentlastactivityfiles{$reponame};
        my $tag_list = $repo->{tag_list};
        push @misconfigrepos, $reponame
            unless grep( /dpt-salsa-configured/, @{$tag_list} );
        push @dirtyrepos, $reponame if repoisdirty($reponame);

        if ($pm) {
            # progress indicator
            print STDERR colored( '.', 'green' ) unless $num_repos++ % 50;

            $pm->start and next;
        }

        # mrconfig
        my $mrstanza
            = "[packages/$reponame]\ncheckout = git_checkout $reponame\n\n";
        # without Parallel::ForkManager or $jobs=0, output directly
        # with Parallel::ForkManager, return $mrstanza at the end
        if ( !$pm ) {
            ## stdout
            say $mrstanza;
            ## file
            say $mrfh $mrstanza;
        }

        # lastactivity
        my $lastactivityoutfile
            = File::Spec->catfile( $lastactivityoutdir, $reponame );
        my $lastactivity = $repo->{last_activity_at};
        if ($lastactivity) {
            open( my $lastactivityfh, '>', "$lastactivityoutfile.new" )
                or die "Can't open '$lastactivityoutfile.new': $!";
            print $lastactivityfh $lastactivity;
            close $lastactivityfh;
            rename "$lastactivityoutfile.new", "$lastactivityoutfile"
                or die
                "Can't rename '$lastactivityoutfile.new' to '$lastactivityoutfile': $!";
        } else {
            if ( -f "$lastactivityoutfile" ) {
                unlink "$lastactivityoutfile"
                    or die "Can't delete stale '$lastactivityoutfile': $!";
            }
        }

        $pm->finish( 0, \$mrstanza ) if $pm;
    }

    $pm->wait_all_children if $pm;

    print STDERR "\n" if $pm; # end progress indicator output

    # mrconfig
    # parallel case
    if ($pm) {
        ## stdout
        say @mrstanzas;
        ## file
        say $mrfh @mrstanzas;
    }
    close $mrfh;
    rename "$mroutfile.new", "$mroutfile"
        or die "Can't rename '$mroutfile.new' to '$mroutfile': $!";

    # lastactivity
    unlink "$lastactivityoutdir/$_" for keys %currentlastactivityfiles;

    # potentially misconfigured repos
    if (scalar @misconfigrepos) {
        say STDERR colored( "W: Potentially misconfigured perl-team repos:",
            'yellow' );
        say STDERR colored( "W: " . join( " ", @misconfigrepos ),
            'yellow' );
        say STDERR colored( "W: Maybe run 'dpt salsa configurerepo' on them.",
            'yellow' ), "\n";
    }

    # dirty repos
    if (scalar @dirtyrepos) {
        say STDERR colored( "W: Dirty repos:",
            'yellow' );
        say STDERR colored( "W: " . join( " ", @dirtyrepos ),
            'yellow' );
        say STDERR colored( "W: Please fix, 'gbp pull' will fail.",
            'yellow' ), "\n";
    }
}

## toattic()
sub toattic {
    my ($repo) = shift || @args;
    die 'Required parameter reponame|repoid missing.' unless $repo;
    my $repo_path = repo2repopath($repo);
    $api->transfer_project_to_namespace( $repo_path,
        { namespace => $config{perl_team_modules_attic_id} } );
}

## fromattic()
sub fromattic {
    my ($repo) = shift || @args;
    die 'Required parameter reponame|repoid missing.' unless $repo;
    my $repo_path = repo2repopath($repo);
    $api->transfer_project_to_namespace( $repo_path,
        { namespace => $config{perl_team_modules_packages_id} } );
    configurerepo($repo);
}

# helper functions
## prettyjson($data)
sub prettyjson {
    my $data = shift;
    my $json = JSON->new->utf8->pretty->canonical->allow_nonref();
    $json->encode($data);
}

## username2userid($username)
sub username2userid {
    my $username = shift;
    my $users = $api->users( { username => $username } );
    die "More than one user with username '$username'."
        if scalar @{$users} > 1;
    die "Username '$username' not found." if scalar @{$users} < 1;
    return $users->[0]->{id};
}

## user2userid($string)
sub user2userid {
    my $user = shift;
    return $user if $user =~ /^\d+$/;
    return username2userid($user) if $user =~ /^[\w-]+$/;
    die "Parameter '$user' doesn't look like a userid or a username.";
}

## get_access_level
sub get_access_level {
    my $user_id = $api->current_user()->{id};
    # group_member() is undef for non-members who still have access via groups (DDs)
    my $access_level;
    my $group_membership
        = $api->group_member( $config{perl_team_modules_path}, $user_id );
    $access_level = $group_membership->{access_level}
        if defined $group_membership;
}

## reponame2repoid($reponame)
## XXX unused
sub reponame2repoid {
    my $reponame = shift;
    my $repos = $api->projects( { search => $reponame } );
    die "More than one repository with name '$reponame'."
        if scalar @{$repos} > 1;
    die "Repository name '$reponame' not found." if scalar @{$repos} < 1;
    return $repos->[0]->{id};
}

## repo2repoid($string)
## XXX unused
sub repo2repoid {
    my $repo = shift;
    return $repo if $repo =~ /^\d+$/;
    return reponame2repoid($repo) if $repo =~ /^\w+$/;
    die
        "Parameter '$repo' doesn't look like a repositoryid or a repositoryname.";
}

## reponame2repopath($reponame)
sub reponame2repopath {
    my $reponame = shift;
    my $repopath_packages
        = $config{perl_team_modules_packages_path} . '/' . $reponame;
    my $repopath_attic
        = $config{perl_team_modules_attic_path} . '/' . $reponame;
    my $repo
        = $api->project($repopath_packages) || $api->project($repopath_attic);
    die
        "Repository name '$reponame' not found in '$config{perl_team_modules_packages_path}' or '$config{perl_team_modules_attic_path}'."
        unless $repo;
    return $repo->{path_with_namespace};
}

## repo2repopath($string)
sub repo2repopath {
    my $repo = shift;
    return $repo if $repo =~ /^\d+$/;
    return reponame2repopath($repo) if $repo =~ /^[\w-]+$/;
    die
        "Parameter '$repo' doesn't look like a repositoryid or a repositoryname.";
}

## repoisdirty
sub repoisdirty {
    my $reponame = shift;
    my $repodir  = File::Spec->catdir( $config{packages}, $reponame );
    return 0 unless -d $repodir; # don't bail out for not-yet-cloned repos
    my $repo = Git->repository($repodir);
    die "Can't create repo object from '$reponame': $!\n" unless $repo;

    # inspired by https://metacpan.org/dist/Git-Repository-Plugin-Dirty/source/lib/Git/Repository/Plugin/Dirty.pm
    # note: `gbp pull' doesn't directly fail on staged/unpushed changes but the merge might
    # question: best order of staged/unstaged/untracked? untracked is more expensive but is staged or unstaged more common?
    eval { $repo->command_oneline( 'diff', '--quiet', '--cached' ) };
    my $staged = $?;
    return 1 if $staged;

    eval { $repo->command_oneline( 'diff', '--quiet' ) };
    my $unstaged = $?;
    return 1 if $unstaged;

    my @untracked
        = grep {m/^\?\? /}
        $repo->command( 'status', '--untracked-files', '--short', '--porcelain' );
    return 1 if scalar @untracked;

    # else
    return 0;
}

## trypaginator($paginator)
sub trypaginator {
    my $paginator = shift;
    my $trials    = 1;
    my $record;
    use constant MAXTRIALS => 5;
    while ( !defined $record && $trials <= MAXTRIALS ) {
        $record = try {
            $paginator->next();
        }
        catch {
            STDERR->autoflush(1);
            say STDERR colored( "W: Error at try $trials: $_", 'yellow' );
            if ( $trials < MAXTRIALS ) {
                my $delay = $trials * 2;
                print STDERR colored( "W: Retrying in $delay seconds ",
                    'yellow' );
                do { print STDERR '.'; sleep 1; } while --$delay;
                print STDERR "\n";
            } else {
                say STDERR colored( "E: Giving up.", 'red' );
            }
            undef;
        }
        finally {
            $trials++;
        }
    }
    return $record;
}

__END__

=head1 NAME

B<dpt-salsa> - manage repositories and members of the I<perl-team> on I<salsa.debian.org>

=head1 SYNOPSIS

B<dpt salsa> [--help|--man|--json|--verbose|--all|--attic] I<subcommand> [parameters]

=head1 DESCRIPTION

B<dpt-salsa> is basically a wrapper around L<GitLab::API::v4>, similar to
L<gitlab-api-v4(1)>, with various variables regarding I<salsa.debian.org>
and the I<modules> subgroup of the I<perl-team> group already preset and
typical method calls encapsulated.

It offers subcommands to manage repositories and members of the I<modules>
subgroup with hopefully less typing then calling the API manually each time.

Make sure to check the L</CONFIGURATION> section below if you use
B<dpt-salsa> for the first time.

=head1 SUBCOMMANDS

=head2 for managing repositories

=head3 I<pushrepo>

Creates a new repository in the I<modules> subgroup (with C<createrepo()> and
C<configurerepo()>) and pushes the local repository.

=head3 I<createrepo> I<repositoryname>

Creates a new empty repository in the I<modules> subgroup and calls C<configurerepo()>.

Parameters:

=over

=item repositoryname

Name of the repository to be added; usually the package name.
Required.

=back

=head3 I<configurerepo> I<repositoryid|repositoryname> [--verbose]

Sets up the default webhooks and services for one repository.

Parameters:

=over

=item repositoryid|repositoryname

The repository to be configured. Either its id (\d+) or name (\w+).
Required.

=back

Silent on success unless C<--verbose> is given.

=head3 I<configurerepo> I<--all> [--attic] [--verbose] [--parallel N] [-j N]

Sets up the default webhooks and services for all active (or, with
C<--attic>, archived) repositories.

Silent on success unless C<--verbose> is given.

With C<--parallel> L<Parallel::ForkManager> is employed for parallelism.

=head3 I<changerepo> I<repositoryid|repositoryname> I<"name"|"description"> C<"parameter">

Changes the name (and the path) or the description of a repository.

Parameters:

=over

=item repositoryid|repositoryname

The repository to be configured. Either its id (\d+) or name (\w+).
Required.

=item "name"|"description"

What should be changed? The "name" or the "description" of the repository.
Required.

=item parameter

The new name or description.
Required.

=back

=head3 I<deleterepo> I<repositoryid|repositoryname>

Delete a repository (a.k.a project).

Parameters:

=over

=item repositoryid|repositoryname

The repository to be deleted. Either its id (\d+) or name (\w+).
Required.

=back

=head3 I<listrepos> [--json] [--attic]

Show all active (or, with C<--attic>, archived) repositories in the
I<modules> subgroup.

If used with C<--all>, returns repository ids and does not output anything;
for internal use.

=head3 I<kgb> I<repositoryid|repositoryname>|I<--all> [--attic] I<--on|--off>

Install (C<--on>) or remove (C<--off>) the KGB IRC notification webhook
for the given, all active (C<--all>), or all
archived (C<--attic>) repositories.

C<--on> removes any legacy hooks (plain http, explicit port number) and
replaces them with the canonical one. If the repository already uses the right
hook, C<--on> does nothing.

Parameters:

=over

=item repositoryid|repositoryname

The repository to be configured. Either its id (\d+) or name (\w+).
Required unless C<--all> is used.

=back

=head3 I<toattic|fromattic> I<repositoryid|repositoryname>

Moves a repository to/from the I<attic> sub-group of the I<modules> sub-group.
Useful when a package is removed from the archive or added back.

Probably needs appropriate permissions.

=head2 for managing users

=head3 I<adduser> I<username|userid> [access_level]

Adds a user to the I<modules> subgroup of the I<perl-team> group.

Parameters:

=over

=item username|userid

The user to be added. Either their id (\d+) or their username (\w+).
Required.

=item access_level

One of I<GitLab>'s access levels: no_access, guest, reporter, developer, maintainer, owner.
Optional, defaults to C<maintainer>.

=back

=head3 I<removeuser> I<username|userid>

Removes a user from the I<modules> subgroup of the I<perl-team> group.

Parameters:

=over

=item username|userid

The user to be removed. Either their id (\d+) or their username (\w+).
Required.

=back

=head3 I<changeuser> I<access_level> I<username|userid>|I<--all>

Change the access level of one or all user(s) in the I<modules> subgroup of the
I<perl-team> group.

Parameters:

=over

=item access_level

One of I<GitLab>'s access levels: guest, reporter, developer, maintainer, owner.
Required.

=item username|userid

The user whose access level is to be changed. Either their id (\d+) or their
username (\w+).
Required, unless C<--all> is used.

=back

=head3 I<listmembers> [--json]

Show all members of the I<modules> subgroup of the I<perl-team> group.

If used with C<--all>, returns user ids and does not output anything; for
internal use.

=head2 others

=head3 I<mrconfig> [--parallel N] [-j N]

Helper for creating

=over

=item *

a F<.mrconfig.packages> file in the local clone of
C<meta.git> for all active packages of the I<modules> subgroup of the
I<perl-team> group. Also writes to stdout which can be included from
F<.mrconfig>.

=item *

F<.lastactivity/PKGNAME> files in the local clone of
C<meta.git> for all active packages of the I<modules> subgroup of the
I<perl-team> group which are then used by B<compare-lastactivity> in F<.mrconfig>.

=back

With C<--parallel> L<Parallel::ForkManager> is employed for parallelism.

Additionally, the option will also output a list of repositories
that potentially have not been configured with B<dpt-salsa>.

=head3 I<current_user> [--json]

Outputs information about the user whose I<GitLab> token is used.

=head3 I<help>

Same as option I<--help>.

=head3 I<version> [--json]

Returns the version of the I<GitLab> instance running on I<salsa.debian.org>.

This subcommand is pretty useless, the only excuse for its existence is the
ability to test if everything is working fine.

=head1 OPTIONS

=over

=item --help

Show short help.

=item --man

Show complete manpage.

=item --all

Act on all users or repositories, not a single named one.
Only for specific subcommands, as noted in their description.

=item --attic

Act on archived repositories instead of active ones.
Only for specific subcommands, as noted in their description.

=item --json

Format output as JSON instead of human-targeted text.
Only for specific subcommands, as noted in their description.

=item --verbose

Print output for otherwise silent and potentially long-running commands.
Only for specific subcommands, as noted in their description.

=back

=head1 CONFIGURATION

B<dpt-salsa> uses the following environment variables, set either directly
or via F<~/.dpt.conf> / F<~/.config/dpt.conf>:

=over

=item DPT_SALSA_PRIVATE_TOKEN

required, no default, obviously

These tokens are created at
L<https://salsa.debian.org/-/user_settings/personal_access_tokens>.
Note that the token needs B<api> and B<read_user> scope permissions.

=item DPT_SALSA_API_URL

optional, default: https://salsa.debian.org/api/v4

=item DPT_SALSA_PERL_TEAM_PATH

optional, default: perl-team

=item DPT_SALSA_PERL_TEAM_ID

optional, default: 2663

=item DPT_SALSA_PERL_TEAM_INTERPRETER_PATH

optional, default: perl-team/interpreter

=item DPT_SALSA_PERL_TEAM_INTERPRETER_ID

optional, default: 2664

=item DPT_SALSA_PERL_TEAM_MODULES_PATH

optional, default: perl-team/modules

=item DPT_SALSA_PERL_TEAM_MODULES_ID

optional, default: 2665

=item DPT_SALSA_PERL_TEAM_MODULES_PACKAGES_PATH

optional, default: perl-team/modules/packages

=item DPT_SALSA_PERL_TEAM_MODULES_PACKAGES_ID

optional, default: 2666

=item DPT_SALSA_PERL_TEAM_MODULES_ATTIC_PATH

optional, default: perl-team/modules/attic

=item DPT_SALSA_PERL_TEAM_MODULES_ATTIC_ID

optional, default: 2667

=item DPT_SALSA_PERL_TEAM_MODULES_META_PATH

optional, default: perl-team/modules/meta

=item DPT_SALSA_PERL_TEAM_MODULES_META_ID

optional, default: 13881

=item DPT_SALSA_PERL_TEAM_PAGES_PATH

optional, default: perl-team/perl-team.pages.debian.net

=item DPT_SALSA_PERL_TEAM_PAGES_ID

optional, default: 11266

=item DPT_SALSA_PERL_TEAM_SCRIPTS_PATH

optional, default: perl-team/scripts

=item DPT_SALSA_PERL_TEAM_SCRIPTS_ID

optional, default: 13429

=item DPT_PACKAGES

only used by the B<mrconfig> subcommand, no default;
most probably already set for use with other B<dpt> commands.

=back

Cf. L<dpt-config(5)>.

By default, the output of some subcommands uses colors, unless STDOUT is not
a tty or the environment variables CLICOLOR or NO_COLOR are set to false or
true, respectively.

=head1 SEE ALSO

L<https://salsa.debian.org/perl-team>

L<GitLab::API::v4>

L<https://docs.gitlab.com/ce/api/>

=head1 COPYRIGHT AND LICENSE

Copyright 2018-2025, gregor herrmann E<lt>gregoa@debian.orgE<gt>

Released under the same terms as Perl itself, i.e. Artistic or GPL-1+.