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