]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/LeiExternal.pm
b5dd85e158b18f007cf53f97e6e6c08f896430e0
[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;
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 # TODO: we will probably extract glob2re into a separate module for
48 # PublicInbox::Filter::Base and maybe other places
49 my %re_map = ( '*' => '[^/]*?', '?' => '[^/]',
50                 '[' => '[', ']' => ']', ',' => ',' );
51
52 sub glob2re {
53         my ($re) = @_;
54         my $p = '';
55         my $in_bracket = 0;
56         my $qm = 0;
57         my $schema_host_port = '';
58
59         # don't glob URL-looking things that look like IPv6
60         if ($re =~ s!\A([a-z0-9\+]+://\[[a-f0-9\:]+\](?::[0-9]+)?/)!!i) {
61                 $schema_host_port = quotemeta $1; # "http://[::1]:1234"
62         }
63         my $changes = ($re =~ s!(.)!
64                 $re_map{$p eq '\\' ? '' : do {
65                         if ($1 eq '[') { ++$in_bracket }
66                         elsif ($1 eq ']') { --$in_bracket }
67                         elsif ($1 eq ',') { ++$qm } # no change
68                         $p = $1;
69                 }} // do {
70                         $p = $1;
71                         ($p eq '-' && $in_bracket) ? $p : (++$qm, "\Q$p")
72                 }!sge);
73         # bashism (also supported by curl): {a,b,c} => (a|b|c)
74         $changes += ($re =~ s/([^\\]*)\\\{([^,]*,[^\\]*)\\\}/
75                         (my $in_braces = $2) =~ tr!,!|!;
76                         $1."($in_braces)";
77                         /sge);
78         ($changes - $qm) ? $schema_host_port.$re : undef;
79 }
80
81 # get canonicalized externals list matching $loc
82 # $is_exclude denotes it's for --exclude
83 # otherwise it's for --only/--include is assumed
84 sub get_externals {
85         my ($self, $loc, $is_exclude) = @_;
86         return (ext_canonicalize($loc)) if -e $loc;
87         my @m;
88         my @cur = externals_each($self);
89         my $do_glob = !$self->{opt}->{globoff}; # glob by default
90         if ($do_glob && (my $re = glob2re($loc))) {
91                 @m = grep(m!$re!, @cur);
92                 return @m if scalar(@m);
93         } elsif (index($loc, '/') < 0) { # exact basename match:
94                 @m = grep(m!/\Q$loc\E/?\z!, @cur);
95                 return @m if scalar(@m) == 1;
96         } elsif ($is_exclude) { # URL, maybe:
97                 my $canon = ext_canonicalize($loc);
98                 @m = grep(m!\A\Q$canon\E\z!, @cur);
99                 return @m if scalar(@m) == 1;
100         } else { # URL:
101                 return (ext_canonicalize($loc));
102         }
103         if (scalar(@m) == 0) {
104                 $self->fail("`$loc' is unknown");
105         } else {
106                 $self->fail("`$loc' is ambiguous:\n", map { "\t$_\n" } @m);
107         }
108         ();
109 }
110
111 # TODO: does this need JSON output?
112 sub lei_ls_external {
113         my ($self, $filter) = @_;
114         my $opt = $self->{opt};
115         my $do_glob = !$opt->{globoff}; # glob by default
116         my ($OFS, $ORS) = $opt->{z} ? ("\0", "\0\0") : (" ", "\n");
117         $filter //= '*';
118         my $re = $do_glob ? glob2re($filter) : undef;
119         $re //= index($filter, '/') < 0 ?
120                         qr!/\Q$filter\E/?\z! : # exact basename match
121                         qr/\Q$filter\E/; # grep -F semantics
122         my @ext = externals_each($self, my $boost = {});
123         @ext = $opt->{'invert-match'} ? grep(!/$re/, @ext)
124                                         : grep(/$re/, @ext);
125         if ($opt->{'local'} && !$opt->{remote}) {
126                 @ext = grep(!m!\A[a-z\+]+://!, @ext);
127         } elsif ($opt->{remote} && !$opt->{'local'}) {
128                 @ext = grep(m!\A[a-z\+]+://!, @ext);
129         }
130         for my $loc (@ext) {
131                 $self->out($loc, $OFS, 'boost=', $boost->{$loc}, $ORS);
132         }
133 }
134
135 sub add_external_finish {
136         my ($self, $location) = @_;
137         my $cfg = $self->_lei_cfg(1);
138         my $new_boost = $self->{opt}->{boost} // 0;
139         my $key = "external.$location.boost";
140         my $cur_boost = $cfg->{$key};
141         return if defined($cur_boost) && $cur_boost == $new_boost; # idempotent
142         $self->lei_config($key, $new_boost);
143 }
144
145 sub lei_add_external {
146         my ($self, $location) = @_;
147         $self->_lei_store(1)->write_prepare($self);
148         my $opt = $self->{opt};
149         my $mirror = $opt->{mirror} // do {
150                 my @fail;
151                 for my $sw ($self->index_opt, $self->curl_opt,
152                                 qw(c no-torsocks torsocks inbox-version)) {
153                         my ($f) = (split(/|/, $sw, 2))[0];
154                         next unless defined $opt->{$f};
155                         $f = length($f) == 1 ? "-$f" : "--$f";
156                         push @fail, $f;
157                 }
158                 if (scalar(@fail) == 1) {
159                         return $self->("@fail requires --mirror");
160                 } elsif (@fail) {
161                         my $last = pop @fail;
162                         my $fail = join(', ', @fail);
163                         return $self->("@fail and $last require --mirror");
164                 }
165                 undef;
166         };
167         my $new_boost = $opt->{boost} // 0;
168         $location = ext_canonicalize($location);
169         if (defined($mirror) && -d $location) {
170                 $self->fail(<<""); # TODO: did you mean "update-external?"
171 --mirror destination `$location' already exists
172
173         } elsif (-d $location) {
174                 index($location, "\n") >= 0 and
175                         return $self->fail("`\\n' not allowed in `$location'");
176         }
177         if ($location !~ m!\Ahttps?://! && !-d $location) {
178                 $mirror // return $self->fail("$location not a directory");
179                 index($location, "\n") >= 0 and
180                         return $self->fail("`\\n' not allowed in `$location'");
181                 $mirror = ext_canonicalize($mirror);
182                 require PublicInbox::LeiMirror;
183                 PublicInbox::LeiMirror->start($self, $mirror => $location);
184         } else {
185                 add_external_finish($self, $location);
186         }
187 }
188
189 sub lei_forget_external {
190         my ($self, @locations) = @_;
191         my $cfg = $self->_lei_cfg(1);
192         my $quiet = $self->{opt}->{quiet};
193         my %seen;
194         for my $loc (@locations) {
195                 my (@unset, @not_found);
196                 for my $l ($loc, ext_canonicalize($loc)) {
197                         next if $seen{$l}++;
198                         my $key = "external.$l.boost";
199                         delete($cfg->{$key});
200                         $self->_config('--unset', $key);
201                         if ($? == 0) {
202                                 push @unset, $l;
203                         } elsif (($? >> 8) == 5) {
204                                 push @not_found, $l;
205                         } else {
206                                 $self->err("# --unset $key error");
207                                 return $self->x_it($?);
208                         }
209                 }
210                 if (@unset) {
211                         next if $quiet;
212                         $self->err("# $_ gone") for @unset;
213                 } elsif (@not_found) {
214                         $self->err("# $_ not found") for @not_found;
215                 } # else { already exited
216         }
217 }
218
219 sub _complete_url_common ($) {
220         my ($argv) = @_;
221         # Workaround bash word-splitting URLs to ['https', ':', '//' ...]
222         # Maybe there's a better way to go about this in
223         # contrib/completion/lei-completion.bash
224         my $re = '';
225         my $cur = pop @$argv;
226         if (@$argv) {
227                 my @x = @$argv;
228                 if ($cur eq ':' && @x) {
229                         push @x, $cur;
230                         $cur = '';
231                 }
232                 while (@x > 2 && $x[0] !~ /\Ahttps?\z/ && $x[1] ne ':') {
233                         shift @x;
234                 }
235                 if (@x >= 2) { # qw(https : hostname : 443) or qw(http :)
236                         $re = join('', @x);
237                 } else { # just filter out the flags and hope for the best
238                         $re = join('', grep(!/^-/, @$argv));
239                 }
240                 $re = quotemeta($re);
241         }
242         ($cur, $re);
243 }
244
245 # shell completion helper called by lei__complete
246 sub _complete_forget_external {
247         my ($self, @argv) = @_;
248         my $cfg = $self->_lei_cfg;
249         my ($cur, $re) = _complete_url_common(\@argv);
250         # FIXME: bash completion off "http:" or "https:" when the last
251         # character is a colon doesn't work properly even if we're
252         # returning "//$HTTP_HOST/$PATH_INFO/", not sure why, could
253         # be a bash issue.
254         map {
255                 my $x = substr($_, length('external.'));
256                 # only return the part specified on the CLI
257                 # don't duplicate if already 100% completed
258                 $x =~ /\A$re(\Q$cur\E.*)/ ? ($cur eq $1 ? () : $1) : ();
259         } grep(/\Aexternal\.$re\Q$cur/, @{$cfg->{-section_order}});
260 }
261
262 sub _complete_add_external { # for bash, this relies on "compopt -o nospace"
263         my ($self, @argv) = @_;
264         my $cfg = $self->_lei_cfg;
265         my ($cur, $re) = _complete_url_common(\@argv);
266         require URI;
267         map {
268                 my $u = URI->new(substr($_, length('external.')));
269                 my ($base) = ($u->path =~ m!((?:/?.*)?/)[^/]+/?\z!);
270                 $u->path($base);
271                 $u = $u->as_string;
272                 $u =~ /\A$re(\Q$cur\E.*)/ ? ($cur eq $1 ? () : $1) : ();
273         } grep(m!\Aexternal\.https?://!, @{$cfg->{-section_order}});
274 }
275
276 1;