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