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