1 # Copyright (C) 2020-2021 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
4 # *-external commands of lei
5 package PublicInbox::LeiExternal;
8 use parent qw(Exporter);
9 our @EXPORT = qw(lei_ls_external lei_add_external lei_forget_external);
10 use PublicInbox::Config;
13 my ($self, $cb, @arg) = @_;
14 my $cfg = $self->_lei_cfg(0);
16 for my $sec (grep(/\Aexternal\./, @{$cfg->{-section_order}})) {
17 my $loc = substr($sec, length('external.'));
18 $boost{$loc} = $cfg->{"$sec.boost"};
20 return \%boost if !wantarray && !$cb;
22 # highest boost first, but stable for alphabetic tie break
24 my @order = sort { $boost{$b} <=> $boost{$a} } sort keys %boost;
25 return @order if !$cb;
26 for my $loc (@order) {
27 $cb->(@arg, $loc, $boost{$loc});
29 @order; # scalar or array
33 my ($self, @argv) = @_;
35 my ($OFS, $ORS) = $self->{opt}->{z} ? ("\0", "\0\0") : (" ", "\n");
36 $self->_externals_each(sub {
37 my ($loc, $boost_val) = @_;
38 print $out $loc, $OFS, 'boost=', $boost_val, $ORS;
44 if ($location !~ m!\Ahttps?://!) {
45 PublicInbox::Config::rel2abs_collapsed($location);
48 my $uri = URI->new($location)->canonical;
49 my $path = $uri->path . '/';
50 $path =~ tr!/!/!s; # squeeze redundant '/'
56 sub lei_add_external {
57 my ($self, $location) = @_;
58 my $cfg = $self->_lei_cfg(1);
59 my $new_boost = $self->{opt}->{boost} // 0;
60 $location = _canonicalize($location);
61 my $key = "external.$location.boost";
62 my $cur_boost = $cfg->{$key};
63 return if defined($cur_boost) && $cur_boost == $new_boost; # idempotent
64 $self->lei_config($key, $new_boost);
65 $self->_lei_store(1)->done; # just create the store
68 sub lei_forget_external {
69 my ($self, @locations) = @_;
70 my $cfg = $self->_lei_cfg(1);
71 my $quiet = $self->{opt}->{quiet};
72 for my $loc (@locations) {
73 my (@unset, @not_found);
74 for my $l ($loc, _canonicalize($loc)) {
75 my $key = "external.$l.boost";
77 $self->_config('--unset', $key);
80 } elsif (($? >> 8) == 5) {
81 push @not_found, $key;
83 $self->err("# --unset $key error");
84 return $self->x_it($?);
89 $self->err("# $_ unset") for @unset;
90 } elsif (@not_found) {
91 $self->err("# $_ not found") for @not_found;
92 } # else { already exited
96 # shell completion helper called by lei__complete
97 sub _complete_forget_external {
98 my ($self, @argv) = @_;
99 my $cfg = $self->_lei_cfg(0);
101 # Workaround bash word-splitting URLs to ['https', ':', '//' ...]
102 # Maybe there's a better way to go about this in
103 # contrib/completion/lei-completion.bash
104 my $colon = ($argv[-1] // '') eq ':';
105 my $re = $cur =~ /\A[\w-]/ ? '' : '.*';
107 my $x = substr($_, length('external.'));
108 # only return the part specified on the CLI
109 $colon && $x =~ /(\Q$cur\E.*)/ ? $1 : $x;
110 } grep(/\Aexternal\.$re\Q$cur/, @{$cfg->{-section_order}});