]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/LeiExternal.pm
lei_external: remove unnecessary Exporter use
[public-inbox.git] / lib / PublicInbox / LeiExternal.pm
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>
3
4 # *-external commands of lei
5 package PublicInbox::LeiExternal;
6 use strict;
7 use v5.10.1;
8 use PublicInbox::Config;
9
10 sub externals_each {
11         my ($self, $cb, @arg) = @_;
12         my $cfg = $self->_lei_cfg(0);
13         my %boost;
14         for my $sec (grep(/\Aexternal\./, @{$cfg->{-section_order}})) {
15                 my $loc = substr($sec, length('external.'));
16                 $boost{$loc} = $cfg->{"$sec.boost"};
17         }
18         return \%boost if !wantarray && !$cb;
19
20         # highest boost first, but stable for alphabetic tie break
21         use sort 'stable';
22         my @order = sort { $boost{$b} <=> $boost{$a} } sort keys %boost;
23         if (ref($cb) eq 'CODE') {
24                 for my $loc (@order) {
25                         $cb->(@arg, $loc, $boost{$loc});
26                 }
27         } elsif (ref($cb) eq 'HASH') {
28                 %$cb = %boost;
29         }
30         @order; # scalar or array
31 }
32
33 sub ext_canonicalize {
34         my ($location) = @_;
35         if ($location !~ m!\Ahttps?://!) {
36                 PublicInbox::Config::rel2abs_collapsed($location);
37         } else {
38                 require URI;
39                 my $uri = URI->new($location)->canonical;
40                 my $path = $uri->path . '/';
41                 $path =~ tr!/!/!s; # squeeze redundant '/'
42                 $uri->path($path);
43                 $uri->as_string;
44         }
45 }
46
47 my %re_map = ( '*' => '[^/]*?', '?' => '[^/]',
48                 '[' => '[', ']' => ']', ',' => ',' );
49
50 sub glob2re {
51         my ($re) = @_;
52         my $p = '';
53         my $in_bracket = 0;
54         my $qm = 0;
55         my $changes = ($re =~ s!(.)!
56                 $re_map{$p eq '\\' ? '' : do {
57                         if ($1 eq '[') { ++$in_bracket }
58                         elsif ($1 eq ']') { --$in_bracket }
59                         $p = $1;
60                 }} // do {
61                         $p = $1;
62                         ($p eq '-' && $in_bracket) ? $p : (++$qm, "\Q$p")
63                 }!sge);
64         # bashism (also supported by curl): {a,b,c} => (a|b|c)
65         $re =~ s/([^\\]*)\\\{([^,]*?,[^\\]*?)\\\}/
66                 (my $in_braces = $2) =~ tr!,!|!;
67                 $1."($in_braces)";
68                 /sge;
69         ($changes - $qm) ? $re : undef;
70 }
71
72 # get canonicalized externals list matching $loc
73 # $is_exclude denotes it's for --exclude
74 # otherwise it's for --only/--include is assumed
75 sub get_externals {
76         my ($self, $loc, $is_exclude) = @_;
77         return (ext_canonicalize($loc)) if -e $loc;
78         my @m;
79         my @cur = externals_each($self);
80         my $do_glob = !$self->{opt}->{globoff}; # glob by default
81         if ($do_glob && (my $re = glob2re($loc))) {
82                 @m = grep(m!$re!, @cur);
83                 return @m if scalar(@m);
84         } elsif (index($loc, '/') < 0) { # exact basename match:
85                 @m = grep(m!/\Q$loc\E/?\z!, @cur);
86                 return @m if scalar(@m) == 1;
87         } elsif ($is_exclude) { # URL, maybe:
88                 my $canon = ext_canonicalize($loc);
89                 @m = grep(m!\A\Q$canon\E\z!, @cur);
90                 return @m if scalar(@m) == 1;
91         } else { # URL:
92                 return (ext_canonicalize($loc));
93         }
94         if (scalar(@m) == 0) {
95                 $self->fail("`$loc' is unknown");
96         } else {
97                 $self->fail("`$loc' is ambiguous:\n", map { "\t$_\n" } @m);
98         }
99         ();
100 }
101
102 sub lei_ls_external {
103         my ($self, $filter) = @_;
104         my $do_glob = !$self->{opt}->{globoff}; # glob by default
105         my ($OFS, $ORS) = $self->{opt}->{z} ? ("\0", "\0\0") : (" ", "\n");
106         $filter //= '*';
107         my $re = $do_glob ? glob2re($filter) : undef;
108         $re //= index($filter, '/') < 0 ?
109                         qr!/\Q$filter\E/?\z! : # exact basename match
110                         qr/\Q$filter\E/; # grep -F semantics
111         my @ext = externals_each($self, my $boost = {});
112         @ext = $self->{opt}->{'invert-match'} ? grep(!/$re/, @ext)
113                                         : grep(/$re/, @ext);
114         for my $loc (@ext) {
115                 $self->out($loc, $OFS, 'boost=', $boost->{$loc}, $ORS);
116         }
117 }
118
119 sub add_external_finish {
120         my ($self, $location) = @_;
121         my $cfg = $self->_lei_cfg(1);
122         my $new_boost = $self->{opt}->{boost} // 0;
123         my $key = "external.$location.boost";
124         my $cur_boost = $cfg->{$key};
125         return if defined($cur_boost) && $cur_boost == $new_boost; # idempotent
126         $self->lei_config($key, $new_boost);
127 }
128
129 sub lei_add_external {
130         my ($self, $location) = @_;
131         $self->_lei_store(1)->write_prepare($self);
132         my $opt = $self->{opt};
133         my $mirror = $opt->{mirror} // do {
134                 my @fail;
135                 for my $sw ($self->index_opt, $self->curl_opt,
136                                 qw(c no-torsocks torsocks inbox-version)) {
137                         my ($f) = (split(/|/, $sw, 2))[0];
138                         next unless defined $opt->{$f};
139                         $f = length($f) == 1 ? "-$f" : "--$f";
140                         push @fail, $f;
141                 }
142                 if (scalar(@fail) == 1) {
143                         return $self->("@fail requires --mirror");
144                 } elsif (@fail) {
145                         my $last = pop @fail;
146                         my $fail = join(', ', @fail);
147                         return $self->("@fail and $last require --mirror");
148                 }
149                 undef;
150         };
151         my $new_boost = $opt->{boost} // 0;
152         $location = ext_canonicalize($location);
153         if (defined($mirror) && -d $location) {
154                 $self->fail(<<""); # TODO: did you mean "update-external?"
155 --mirror destination `$location' already exists
156
157         }
158         if ($location !~ m!\Ahttps?://! && !-d $location) {
159                 $mirror // return $self->fail("$location not a directory");
160                 $mirror = ext_canonicalize($mirror);
161                 require PublicInbox::LeiMirror;
162                 PublicInbox::LeiMirror->start($self, $mirror => $location);
163         } else {
164                 add_external_finish($self, $location);
165         }
166 }
167
168 sub lei_forget_external {
169         my ($self, @locations) = @_;
170         my $cfg = $self->_lei_cfg(1);
171         my $quiet = $self->{opt}->{quiet};
172         my %seen;
173         for my $loc (@locations) {
174                 my (@unset, @not_found);
175                 for my $l ($loc, ext_canonicalize($loc)) {
176                         next if $seen{$l}++;
177                         my $key = "external.$l.boost";
178                         delete($cfg->{$key});
179                         $self->_config('--unset', $key);
180                         if ($? == 0) {
181                                 push @unset, $l;
182                         } elsif (($? >> 8) == 5) {
183                                 push @not_found, $l;
184                         } else {
185                                 $self->err("# --unset $key error");
186                                 return $self->x_it($?);
187                         }
188                 }
189                 if (@unset) {
190                         next if $quiet;
191                         $self->err("# $_ gone") for @unset;
192                 } elsif (@not_found) {
193                         $self->err("# $_ not found") for @not_found;
194                 } # else { already exited
195         }
196 }
197
198 sub _complete_url_common ($) {
199         my ($argv) = @_;
200         # Workaround bash word-splitting URLs to ['https', ':', '//' ...]
201         # Maybe there's a better way to go about this in
202         # contrib/completion/lei-completion.bash
203         my $re = '';
204         my $cur = pop @$argv;
205         if (@$argv) {
206                 my @x = @$argv;
207                 if ($cur eq ':' && @x) {
208                         push @x, $cur;
209                         $cur = '';
210                 }
211                 while (@x > 2 && $x[0] !~ /\Ahttps?\z/ && $x[1] ne ':') {
212                         shift @x;
213                 }
214                 if (@x >= 2) { # qw(https : hostname : 443) or qw(http :)
215                         $re = join('', @x);
216                 } else { # just filter out the flags and hope for the best
217                         $re = join('', grep(!/^-/, @$argv));
218                 }
219                 $re = quotemeta($re);
220         }
221         ($cur, $re);
222 }
223
224 # shell completion helper called by lei__complete
225 sub _complete_forget_external {
226         my ($self, @argv) = @_;
227         my $cfg = $self->_lei_cfg(0);
228         my ($cur, $re) = _complete_url_common(\@argv);
229         # FIXME: bash completion off "http:" or "https:" when the last
230         # character is a colon doesn't work properly even if we're
231         # returning "//$HTTP_HOST/$PATH_INFO/", not sure why, could
232         # be a bash issue.
233         map {
234                 my $x = substr($_, length('external.'));
235                 # only return the part specified on the CLI
236                 # don't duplicate if already 100% completed
237                 $x =~ /\A$re(\Q$cur\E.*)/ ? ($cur eq $1 ? () : $1) : ();
238         } grep(/\Aexternal\.$re\Q$cur/, @{$cfg->{-section_order}});
239 }
240
241 sub _complete_add_external { # for bash, this relies on "compopt -o nospace"
242         my ($self, @argv) = @_;
243         my $cfg = $self->_lei_cfg(0);
244         my ($cur, $re) = _complete_url_common(\@argv);
245         require URI;
246         map {
247                 my $u = URI->new(substr($_, length('external.')));
248                 my ($base) = ($u->path =~ m!((?:/?.*)?/)[^/]+/?\z!);
249                 $u->path($base);
250                 $u = $u->as_string;
251                 $u =~ /\A$re(\Q$cur\E.*)/ ? ($cur eq $1 ? () : $1) : ();
252         } grep(m!\Aexternal\.https?://!, @{$cfg->{-section_order}});
253 }
254
255 1;