]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/LeiExternal.pm
lei ls-external: support --local and --remote
[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 $opt = $self->{opt};
105         my $do_glob = !$opt->{globoff}; # glob by default
106         my ($OFS, $ORS) = $opt->{z} ? ("\0", "\0\0") : (" ", "\n");
107         $filter //= '*';
108         my $re = $do_glob ? glob2re($filter) : undef;
109         $re //= index($filter, '/') < 0 ?
110                         qr!/\Q$filter\E/?\z! : # exact basename match
111                         qr/\Q$filter\E/; # grep -F semantics
112         my @ext = externals_each($self, my $boost = {});
113         @ext = $opt->{'invert-match'} ? grep(!/$re/, @ext)
114                                         : grep(/$re/, @ext);
115         if ($opt->{'local'} && !$opt->{remote}) {
116                 @ext = grep(!m!\A[a-z\+]+://!, @ext);
117         } elsif ($opt->{remote} && !$opt->{'local'}) {
118                 @ext = grep(m!\A[a-z\+]+://!, @ext);
119         }
120         for my $loc (@ext) {
121                 $self->out($loc, $OFS, 'boost=', $boost->{$loc}, $ORS);
122         }
123 }
124
125 sub add_external_finish {
126         my ($self, $location) = @_;
127         my $cfg = $self->_lei_cfg(1);
128         my $new_boost = $self->{opt}->{boost} // 0;
129         my $key = "external.$location.boost";
130         my $cur_boost = $cfg->{$key};
131         return if defined($cur_boost) && $cur_boost == $new_boost; # idempotent
132         $self->lei_config($key, $new_boost);
133 }
134
135 sub lei_add_external {
136         my ($self, $location) = @_;
137         $self->_lei_store(1)->write_prepare($self);
138         my $opt = $self->{opt};
139         my $mirror = $opt->{mirror} // do {
140                 my @fail;
141                 for my $sw ($self->index_opt, $self->curl_opt,
142                                 qw(c no-torsocks torsocks inbox-version)) {
143                         my ($f) = (split(/|/, $sw, 2))[0];
144                         next unless defined $opt->{$f};
145                         $f = length($f) == 1 ? "-$f" : "--$f";
146                         push @fail, $f;
147                 }
148                 if (scalar(@fail) == 1) {
149                         return $self->("@fail requires --mirror");
150                 } elsif (@fail) {
151                         my $last = pop @fail;
152                         my $fail = join(', ', @fail);
153                         return $self->("@fail and $last require --mirror");
154                 }
155                 undef;
156         };
157         my $new_boost = $opt->{boost} // 0;
158         $location = ext_canonicalize($location);
159         if (defined($mirror) && -d $location) {
160                 $self->fail(<<""); # TODO: did you mean "update-external?"
161 --mirror destination `$location' already exists
162
163         }
164         if ($location !~ m!\Ahttps?://! && !-d $location) {
165                 $mirror // return $self->fail("$location not a directory");
166                 $mirror = ext_canonicalize($mirror);
167                 require PublicInbox::LeiMirror;
168                 PublicInbox::LeiMirror->start($self, $mirror => $location);
169         } else {
170                 add_external_finish($self, $location);
171         }
172 }
173
174 sub lei_forget_external {
175         my ($self, @locations) = @_;
176         my $cfg = $self->_lei_cfg(1);
177         my $quiet = $self->{opt}->{quiet};
178         my %seen;
179         for my $loc (@locations) {
180                 my (@unset, @not_found);
181                 for my $l ($loc, ext_canonicalize($loc)) {
182                         next if $seen{$l}++;
183                         my $key = "external.$l.boost";
184                         delete($cfg->{$key});
185                         $self->_config('--unset', $key);
186                         if ($? == 0) {
187                                 push @unset, $l;
188                         } elsif (($? >> 8) == 5) {
189                                 push @not_found, $l;
190                         } else {
191                                 $self->err("# --unset $key error");
192                                 return $self->x_it($?);
193                         }
194                 }
195                 if (@unset) {
196                         next if $quiet;
197                         $self->err("# $_ gone") for @unset;
198                 } elsif (@not_found) {
199                         $self->err("# $_ not found") for @not_found;
200                 } # else { already exited
201         }
202 }
203
204 sub _complete_url_common ($) {
205         my ($argv) = @_;
206         # Workaround bash word-splitting URLs to ['https', ':', '//' ...]
207         # Maybe there's a better way to go about this in
208         # contrib/completion/lei-completion.bash
209         my $re = '';
210         my $cur = pop @$argv;
211         if (@$argv) {
212                 my @x = @$argv;
213                 if ($cur eq ':' && @x) {
214                         push @x, $cur;
215                         $cur = '';
216                 }
217                 while (@x > 2 && $x[0] !~ /\Ahttps?\z/ && $x[1] ne ':') {
218                         shift @x;
219                 }
220                 if (@x >= 2) { # qw(https : hostname : 443) or qw(http :)
221                         $re = join('', @x);
222                 } else { # just filter out the flags and hope for the best
223                         $re = join('', grep(!/^-/, @$argv));
224                 }
225                 $re = quotemeta($re);
226         }
227         ($cur, $re);
228 }
229
230 # shell completion helper called by lei__complete
231 sub _complete_forget_external {
232         my ($self, @argv) = @_;
233         my $cfg = $self->_lei_cfg(0);
234         my ($cur, $re) = _complete_url_common(\@argv);
235         # FIXME: bash completion off "http:" or "https:" when the last
236         # character is a colon doesn't work properly even if we're
237         # returning "//$HTTP_HOST/$PATH_INFO/", not sure why, could
238         # be a bash issue.
239         map {
240                 my $x = substr($_, length('external.'));
241                 # only return the part specified on the CLI
242                 # don't duplicate if already 100% completed
243                 $x =~ /\A$re(\Q$cur\E.*)/ ? ($cur eq $1 ? () : $1) : ();
244         } grep(/\Aexternal\.$re\Q$cur/, @{$cfg->{-section_order}});
245 }
246
247 sub _complete_add_external { # for bash, this relies on "compopt -o nospace"
248         my ($self, @argv) = @_;
249         my $cfg = $self->_lei_cfg(0);
250         my ($cur, $re) = _complete_url_common(\@argv);
251         require URI;
252         map {
253                 my $u = URI->new(substr($_, length('external.')));
254                 my ($base) = ($u->path =~ m!((?:/?.*)?/)[^/]+/?\z!);
255                 $u->path($base);
256                 $u = $u->as_string;
257                 $u =~ /\A$re(\Q$cur\E.*)/ ? ($cur eq $1 ? () : $1) : ();
258         } grep(m!\Aexternal\.https?://!, @{$cfg->{-section_order}});
259 }
260
261 1;