]> Sergey Matveev's repositories - public-inbox.git/blob - t/lei.t
lei add-external: completion for existing URL basenames
[public-inbox.git] / t / lei.t
1 #!perl -w
2 # Copyright (C) 2020-2021 all contributors <meta@public-inbox.org>
3 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
4 use strict;
5 use v5.10.1;
6 use Test::More;
7 use PublicInbox::TestCommon;
8 use PublicInbox::Config;
9 use File::Path qw(rmtree);
10 use Fcntl qw(SEEK_SET);
11 use PublicInbox::Spawn qw(which);
12 require_git 2.6;
13 require_mods(qw(json DBD::SQLite Search::Xapian));
14 my $opt = { 1 => \(my $out = ''), 2 => \(my $err = '') };
15 my ($home, $for_destroy) = tmpdir();
16 my $err_filter;
17 my $curl = which('curl');
18 my @onions = qw(http://hjrcffqmbrq6wope.onion/meta/
19         http://czquwvybam4bgbro.onion/meta/
20         http://ou63pmih66umazou.onion/meta/);
21 my $json = ref(PublicInbox::Config->json)->new->utf8->canonical;
22 my $lei = sub {
23         my ($cmd, $env, $xopt) = @_;
24         $out = $err = '';
25         if (!ref($cmd)) {
26                 ($env, $xopt) = grep { (!defined) || ref } @_;
27                 $cmd = [ grep { defined && !ref } @_ ];
28         }
29         my $res = run_script(['lei', @$cmd], $env, $xopt // $opt);
30         $err_filter and
31                 $err = join('', grep(!/$err_filter/, split(/^/m, $err)));
32         $res;
33 };
34
35 delete local $ENV{XDG_DATA_HOME};
36 delete local $ENV{XDG_CONFIG_HOME};
37 local $ENV{GIT_COMMITTER_EMAIL} = 'lei@example.com';
38 local $ENV{GIT_COMMITTER_NAME} = 'lei user';
39 local $ENV{XDG_RUNTIME_DIR} = "$home/xdg_run";
40 local $ENV{HOME} = $home;
41 local $ENV{FOO} = 'BAR';
42 mkdir "$home/xdg_run", 0700 or BAIL_OUT "mkdir: $!";
43 my $home_trash = [ "$home/.local", "$home/.config", "$home/junk" ];
44 my $cleanup = sub { rmtree([@$home_trash, @_]) };
45 my $config_file = "$home/.config/lei/config";
46 my $store_dir = "$home/.local/share/lei";
47
48 my $test_help = sub {
49         ok(!$lei->(), 'no args fails');
50         is($? >> 8, 1, '$? is 1');
51         is($out, '', 'nothing in stdout');
52         like($err, qr/^usage:/sm, 'usage in stderr');
53
54         for my $arg (['-h'], ['--help'], ['help'], [qw(daemon-pid --help)]) {
55                 ok($lei->($arg), "lei @$arg");
56                 like($out, qr/^usage:/sm, "usage in stdout (@$arg)");
57                 is($err, '', "nothing in stderr (@$arg)");
58         }
59
60         for my $arg ([''], ['--halp'], ['halp'], [qw(daemon-pid --halp)]) {
61                 ok(!$lei->($arg), "lei @$arg");
62                 is($? >> 8, 1, '$? set correctly');
63                 isnt($err, '', 'something in stderr');
64                 is($out, '', 'nothing in stdout');
65         }
66         ok($lei->(qw(init -h)), 'init -h');
67         like($out, qr! \Q$home\E/\.local/share/lei/store\b!,
68                 'actual path shown in init -h');
69         ok($lei->(qw(init -h), { XDG_DATA_HOME => '/XDH' }),
70                 'init with XDG_DATA_HOME');
71         like($out, qr! /XDH/lei/store\b!, 'XDG_DATA_HOME in init -h');
72         is($err, '', 'no errors from init -h');
73
74         ok($lei->(qw(config -h)), 'config-h');
75         like($out, qr! \Q$home\E/\.config/lei/config\b!,
76                 'actual path shown in config -h');
77         ok($lei->(qw(config -h), { XDG_CONFIG_HOME => '/XDC' }),
78                 'config with XDG_CONFIG_HOME');
79         like($out, qr! /XDC/lei/config\b!, 'XDG_CONFIG_HOME in config -h');
80         is($err, '', 'no errors from config -h');
81 };
82
83 my $ok_err_info = sub {
84         my ($msg) = @_;
85         is(grep(!/^I:/, split(/^/, $err)), 0, $msg) or
86                 diag "$msg: err=$err";
87 };
88
89 my $test_init = sub {
90         $cleanup->();
91         ok($lei->('init'), 'init w/o args');
92         $ok_err_info->('after init w/o args');
93         ok($lei->('init'), 'idempotent init w/o args');
94         $ok_err_info->('after idempotent init w/o args');
95
96         ok(!$lei->('init', "$home/x"), 'init conflict');
97         is(grep(/^E:/, split(/^/, $err)), 1, 'got error on conflict');
98         ok(!-e "$home/x", 'nothing created on conflict');
99         $cleanup->();
100
101         ok($lei->('init', "$home/x"), 'init conflict resolved');
102         $ok_err_info->('init w/ arg');
103         ok($lei->('init', "$home/x"), 'init idempotent w/ path');
104         $ok_err_info->('init idempotent w/ arg');
105         ok(-d "$home/x", 'created dir');
106         $cleanup->("$home/x");
107
108         ok(!$lei->('init', "$home/x", "$home/2"), 'too many args fails');
109         like($err, qr/too many/, 'noted excessive');
110         ok(!-e "$home/x", 'x not created on excessive');
111         for my $d (@$home_trash) {
112                 my $base = (split(m!/!, $d))[-1];
113                 ok(!-d $d, "$base not created");
114         }
115         is($out, '', 'nothing in stdout on init failure');
116 };
117
118 my $test_config = sub {
119         $cleanup->();
120         ok($lei->(qw(config a.b c)), 'config set var');
121         is($out.$err, '', 'no output on var set');
122         ok($lei->(qw(config -l)), 'config -l');
123         is($err, '', 'no errors on listing');
124         is($out, "a.b=c\n", 'got expected output');
125         ok(!$lei->(qw(config -f), "$home/.config/f", qw(x.y z)),
126                         'config set var with -f fails');
127         like($err, qr/not supported/, 'not supported noted');
128         ok(!-f "$home/config/f", 'no file created');
129 };
130
131 my $setup_publicinboxes = sub {
132         state $done = '';
133         return if $done eq $home;
134         use PublicInbox::InboxWritable;
135         for my $V (1, 2) {
136                 run_script([qw(-init), "-V$V", "t$V",
137                                 '--newsgroup', "t.$V",
138                                 "$home/t$V", "http://example.com/t$V",
139                                 "t$V\@example.com" ]) or BAIL_OUT "init v$V";
140         }
141         my $cfg = PublicInbox::Config->new;
142         my $seen = 0;
143         $cfg->each_inbox(sub {
144                 my ($ibx) = @_;
145                 my $im = PublicInbox::InboxWritable->new($ibx)->importer(0);
146                 my $V = $ibx->version;
147                 my @eml = (glob('t/*.eml'), 't/data/0001.patch');
148                 for (@eml) {
149                         next if $_ eq 't/psgi_v2-old.eml'; # dup mid
150                         $im->add(eml_load($_)) or BAIL_OUT "v$V add $_";
151                         $seen++;
152                 }
153                 $im->done;
154                 if ($V == 1) {
155                         run_script(['-index', $ibx->{inboxdir}]) or
156                                 BAIL_OUT 'index v1';
157                 }
158         });
159         $done = $home;
160         $seen || BAIL_OUT 'no imports';
161 };
162
163 my $test_external_remote = sub {
164         my ($url, $k) = @_;
165 SKIP: {
166         my $nr = 5;
167         skip "$k unset", $nr if !$url;
168         $curl or skip 'no curl', $nr;
169         which('torsocks') or skip 'no torsocks', $nr if $url =~ m!\.onion/!;
170         my $mid = '20140421094015.GA8962@dcvr.yhbt.net';
171         my @cmd = ('q', '--only', $url, '-q', "m:$mid");
172         ok($lei->(@cmd), "query $url");
173         is($err, '', "no errors on $url");
174         my $res = $json->decode($out);
175         is($res->[0]->{'m'}, "<$mid>", "got expected mid from $url");
176         ok($lei->(@cmd, 'd:..20101002'), 'no results, no error');
177         is($err, '', 'no output on 404, matching local FS behavior');
178         is($out, "[null]\n", 'got null results');
179 } # /SKIP
180 }; # /sub
181
182 my $test_external = sub {
183         $setup_publicinboxes->();
184         $cleanup->();
185         $lei->('ls-external');
186         is($out.$err, '', 'ls-external no output, yet');
187         ok(!-e $config_file && !-e $store_dir,
188                 'nothing created by ls-external');
189
190         ok(!$lei->('add-external', "$home/nonexistent"),
191                 "fails on non-existent dir");
192         $lei->('ls-external');
193         is($out.$err, '', 'ls-external still has no output');
194         my $cfg = PublicInbox::Config->new;
195         $cfg->each_inbox(sub {
196                 my ($ibx) = @_;
197                 ok($lei->(qw(add-external -q), $ibx->{inboxdir}),
198                         'added external');
199                 is($out.$err, '', 'no output');
200         });
201         ok(-s $config_file && -e $store_dir,
202                 'add-external created config + store');
203         my $lcfg = PublicInbox::Config->new($config_file);
204         $cfg->each_inbox(sub {
205                 my ($ibx) = @_;
206                 is($lcfg->{"external.$ibx->{inboxdir}.boost"}, 0,
207                         "configured boost on $ibx->{name}");
208         });
209         $lei->('ls-external');
210         like($out, qr/boost=0\n/s, 'ls-external has output');
211         ok($lei->(qw(add-external -q https://EXAMPLE.com/ibx)), 'add remote');
212         is($err, '', 'no warnings after add-external');
213
214         ok($lei->(qw(_complete lei forget-external)), 'complete for externals');
215         my %comp = map { $_ => 1 } split(/\s+/, $out);
216         ok($comp{'https://example.com/ibx/'}, 'forget external completion');
217         $cfg->each_inbox(sub {
218                 my ($ibx) = @_;
219                 ok($comp{$ibx->{inboxdir}}, "local $ibx->{name} completion");
220         });
221         for my $u (qw(h http https https: https:/ https:// https://e
222                         https://example https://example. https://example.co
223                         https://example.com https://example.com/
224                         https://example.com/i https://example.com/ibx)) {
225                 ok($lei->(qw(_complete lei forget-external), $u),
226                         "partial completion for URL $u");
227                 is($out, "https://example.com/ibx/\n",
228                         "completed partial URL $u");
229                 for my $qo (qw(-I --include --exclude --only)) {
230                         ok($lei->(qw(_complete lei q), $qo, $u),
231                                 "partial completion for URL q $qo $u");
232                         is($out, "https://example.com/ibx/\n",
233                                 "completed partial URL $u on q $qo");
234                 }
235         }
236         ok($lei->(qw(_complete lei add-external), 'https://'),
237                 'add-external hostname completion');
238         is($out, "https://example.com/\n", 'completed up to hostname');
239
240         $lei->('ls-external');
241         like($out, qr!https://example\.com/ibx/!s, 'added canonical URL');
242         is($err, '', 'no warnings on ls-external');
243         ok($lei->(qw(forget-external -q https://EXAMPLE.com/ibx)),
244                 'forget');
245         $lei->('ls-external');
246         unlike($out, qr!https://example\.com/ibx/!s, 'removed canonical URL');
247
248         ok(!$lei->(qw(q s:prefix -o /dev/null -f maildir)), 'bad maildir');
249         like($err, qr!/dev/null exists and is not a directory!,
250                 'error shown');
251         is($? >> 8, 1, 'errored out with exit 1');
252
253         ok(!$lei->(qw(q s:prefix -f mboxcl2 -o), $home), 'bad mbox');
254         like($err, qr!\Q$home\E exists and is not a writable file!,
255                 'error shown');
256         is($? >> 8, 1, 'errored out with exit 1');
257
258         ok(!$lei->(qw(q s:prefix -o /dev/stdout -f Mbox2)), 'bad format');
259         like($err, qr/bad mbox --format=mbox2/, 'error shown');
260         is($? >> 8, 1, 'errored out with exit 1');
261
262         # note, on a Bourne shell users should be able to use either:
263         #       s:"use boolean prefix"
264         #       "s:use boolean prefix"
265         # or use single quotes, it should not matter.  Users only need
266         # to know shell quoting rules, not Xapian quoting rules.
267         # No double-quoting should be imposed on users on the CLI
268         $lei->('q', 's:use boolean prefix');
269         like($out, qr/search: use boolean prefix/, 'phrase search got result');
270         my $res = $json->decode($out);
271         is(scalar(@$res), 2, 'only 2 element array (1 result)');
272         is($res->[1], undef, 'final element is undef'); # XXX should this be?
273         is(ref($res->[0]), 'HASH', 'first element is hashref');
274         $lei->('q', '--pretty', 's:use boolean prefix');
275         my $pretty = $json->decode($out);
276         is_deeply($res, $pretty, '--pretty is identical after decode');
277
278         for my $fmt (qw(ldjson ndjson jsonl)) {
279                 $lei->('q', '-f', $fmt, 's:use boolean prefix');
280                 is($out, $json->encode($pretty->[0])."\n", "-f $fmt");
281         }
282
283         require IO::Uncompress::Gunzip;
284         for my $sfx ('', '.gz') {
285                 my $f = "$home/mbox$sfx";
286                 $lei->('q', '-o', "mboxcl2:$f", 's:use boolean prefix');
287                 my $cat = $sfx eq '' ? sub {
288                         open my $mb, '<', $f or fail "no mbox: $!";
289                         <$mb>
290                 } : sub {
291                         my $z = IO::Uncompress::Gunzip->new($f, MultiStream=>1);
292                         <$z>;
293                 };
294                 my @s = grep(/^Subject:/, $cat->());
295                 is(scalar(@s), 1, "1 result in mbox$sfx");
296                 $lei->('q', '-a', '-o', "mboxcl2:$f", 's:see attachment');
297                 is(grep(!/^#/, $err), 0, 'no errors from augment');
298                 @s = grep(/^Subject:/, my @wtf = $cat->());
299                 is(scalar(@s), 2, "2 results in mbox$sfx");
300
301                 $lei->('q', '-a', '-o', "mboxcl2:$f", 's:nonexistent');
302                 is(grep(!/^#/, $err), 0, "no errors on no results ($sfx)");
303
304                 my @s2 = grep(/^Subject:/, $cat->());
305                 is_deeply(\@s2, \@s,
306                         "same 2 old results w/ --augment and bad search $sfx");
307
308                 $lei->('q', '-o', "mboxcl2:$f", 's:nonexistent');
309                 my @res = $cat->();
310                 is_deeply(\@res, [], "clobber w/o --augment $sfx");
311         }
312         ok(!$lei->('q', '-o', "$home/mbox", 's:nope'),
313                         'fails if mbox format unspecified');
314         ok(!$lei->(qw(q --no-local s:see)), '--no-local');
315         is($? >> 8, 1, 'proper exit code');
316         like($err, qr/no local or remote.+? to search/, 'no inbox');
317         my %e = (
318                 TEST_LEI_EXTERNAL_HTTPS => 'https://public-inbox.org/meta/',
319                 TEST_LEI_EXTERNAL_ONION => $onions[int(rand(scalar(@onions)))],
320         );
321         for my $k (keys %e) {
322                 my $url = $ENV{$k} // '';
323                 $url = $e{$k} if $url eq '1';
324                 $test_external_remote->($url, $k);
325         }
326 };
327
328 my $test_completion = sub {
329         ok($lei->(qw(_complete lei)), 'no errors on complete');
330         my %out = map { $_ => 1 } split(/\s+/s, $out);
331         ok($out{'q'}, "`lei q' offered as completion");
332         ok($out{'add-external'}, "`lei add-external' offered as completion");
333
334         ok($lei->(qw(_complete lei q)), 'complete q (no args)');
335         %out = map { $_ => 1 } split(/\s+/s, $out);
336         for my $sw (qw(-f --format -o --output --mfolder --augment -a
337                         --mua --mua-cmd --no-local --local --verbose -v
338                         --save-as --no-remote --remote --torsocks
339                         --reverse -r )) {
340                 ok($out{$sw}, "$sw offered as completion");
341         }
342
343         ok($lei->(qw(_complete lei q --form)), 'complete q --format');
344         is($out, "--format\n", 'complete lei q --format');
345         for my $sw (qw(-f --format)) {
346                 ok($lei->(qw(_complete lei q), $sw), "complete q $sw ARG");
347                 %out = map { $_ => 1 } split(/\s+/s, $out);
348                 for my $f (qw(mboxrd mboxcl2 mboxcl mboxo json jsonl
349                                 concatjson maildir)) {
350                         ok($out{$f}, "got $sw $f as output format");
351                 }
352         }
353 };
354
355 my $test_fail = sub {
356         $lei->(qw(q --only http://127.0.0.1:99999/bogus/ t:m));
357         is($? >> 8, 3, 'got curl exit for bogus URL');
358         $lei->(qw(q --only http://127.0.0.1:99999/bogus/ t:m -o), "$home/junk");
359         is($? >> 8, 3, 'got curl exit for bogus URL with Maildir');
360         is($out, '', 'no output');
361 };
362
363 my $test_lei_common = sub {
364         $test_help->();
365         $test_config->();
366         $test_init->();
367         $test_external->();
368         $test_completion->();
369         $test_fail->();
370 };
371
372 if ($ENV{TEST_LEI_ONESHOT}) {
373         require_ok 'PublicInbox::LEI';
374         # force sun_path[108] overflow, ($lei->() filters out this path)
375         my $xrd = "$home/1shot-test".('.sun_path' x 108);
376         local $ENV{XDG_RUNTIME_DIR} = $xrd;
377         $err_filter = qr!\Q$xrd!;
378         $test_lei_common->();
379 } else {
380 SKIP: { # real socket
381         eval { require Socket::MsgHdr; 1 } // do {
382                 require PublicInbox::Spawn;
383                 PublicInbox::Spawn->can('send_cmd4');
384         } // skip 'Socket::MsgHdr or Inline::C missing or unconfigured', 115;
385         local $ENV{XDG_RUNTIME_DIR} = "$home/xdg_run";
386         my $sock = "$ENV{XDG_RUNTIME_DIR}/lei/5.seq.sock";
387         my $err_log = "$ENV{XDG_RUNTIME_DIR}/lei/errors.log";
388
389         ok($lei->('daemon-pid'), 'daemon-pid');
390         is($err, '', 'no error from daemon-pid');
391         like($out, qr/\A[0-9]+\n\z/s, 'pid returned') or BAIL_OUT;
392         chomp(my $pid = $out);
393         ok(kill(0, $pid), 'pid is valid');
394         ok(-S $sock, 'sock created');
395
396         $test_lei_common->();
397         is(-s $err_log, 0, 'nothing in errors.log');
398         open my $efh, '>>', $err_log or BAIL_OUT $!;
399         print $efh "phail\n" or BAIL_OUT $!;
400         close $efh or BAIL_OUT $!;
401
402         ok($lei->('daemon-pid'), 'daemon-pid');
403         chomp(my $pid_again = $out);
404         is($pid, $pid_again, 'daemon-pid idempotent');
405         like($err, qr/phail/, 'got mock "phail" error previous run');
406
407         ok($lei->(qw(daemon-kill)), 'daemon-kill');
408         is($out, '', 'no output from daemon-kill');
409         is($err, '', 'no error from daemon-kill');
410         for (0..100) {
411                 kill(0, $pid) or last;
412                 tick();
413         }
414         ok(-S $sock, 'sock still exists');
415         ok(!kill(0, $pid), 'pid gone after stop');
416
417         ok($lei->(qw(daemon-pid)), 'daemon-pid');
418         chomp(my $new_pid = $out);
419         ok(kill(0, $new_pid), 'new pid is running');
420         ok(-S $sock, 'sock still exists');
421
422         for my $sig (qw(-0 -CHLD)) {
423                 ok($lei->('daemon-kill', $sig), "handles $sig");
424         }
425         is($out.$err, '', 'no output on innocuous signals');
426         ok($lei->('daemon-pid'), 'daemon-pid');
427         chomp $out;
428         is($out, $new_pid, 'PID unchanged after -0/-CHLD');
429
430         if ('socket inaccessible') {
431                 chmod 0000, $sock or BAIL_OUT "chmod 0000: $!";
432                 ok($lei->('help'), 'connect fail, one-shot fallback works');
433                 like($err, qr/\bconnect\(/, 'connect error noted');
434                 like($out, qr/^usage: /, 'help output works');
435                 chmod 0700, $sock or BAIL_OUT "chmod 0700: $!";
436         }
437         unlink $sock or BAIL_OUT "unlink($sock) $!";
438         for (0..100) {
439                 kill('CHLD', $new_pid) or last;
440                 tick();
441         }
442         ok(!kill(0, $new_pid), 'daemon exits after unlink');
443         # success over socket, can't test without
444 }; # SKIP
445 } # else
446
447 done_testing;