1 # Copyright (C) 2021 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
4 # front-end for the "lei import" sub-command
5 package PublicInbox::LeiImport;
8 use parent qw(PublicInbox::IPC);
9 use PublicInbox::MboxReader;
12 sub _import_eml { # MboxReader callback
13 my ($eml, $sto, $set_kw) = @_;
14 $sto->ipc_do('set_eml', $eml, $set_kw ? $sto->mbox_keywords($eml) : ());
17 sub import_done { # EOF callback for main daemon
19 my $imp = delete $lei->{imp};
20 $imp->wq_wait_old($lei) if $imp;
21 my $wait = $lei->{sto}->ipc_do('done');
25 sub call { # the main "lei import" method
26 my ($cls, $lei, @argv) = @_;
27 my $sto = $lei->_lei_store(1);
28 $sto->write_prepare($lei);
29 $lei->{opt}->{kw} //= 1;
30 my $fmt = $lei->{opt}->{'format'};
31 my $self = $lei->{imp} = bless {}, $cls;
32 return $lei->fail('--format unspecified') if !$fmt;
33 $self->{0} = $lei->{0} if $lei->{opt}->{stdin};
35 '!' => [ $lei->can('fail_handler'), $lei ],
36 'x_it' => [ $lei->can('x_it'), $lei ],
37 'child_error' => [ $lei->can('child_error'), $lei ],
38 '' => [ \&import_done, $lei ],
40 ($lei->{pkt_op_c}, $lei->{pkt_op_p}) = PublicInbox::PktOp->pair($ops);
41 my $j = $lei->{opt}->{jobs} // scalar(@argv) || 1;
42 my $nproc = $self->detect_nproc;
43 $j = $nproc if $j > $nproc;
44 $self->wq_workers_start('lei_import', $j, $lei->oldset, {lei => $lei});
45 my $op = delete $lei->{pkt_op_c};
46 delete $lei->{pkt_op_p};
47 $self->wq_do('import_stdin', []) if $self->{0};
49 $self->wq_do('import_path_url', [], $x);
52 $lei->event_step_init; # wait for shutdowns
53 if ($lei->{oneshot}) {
54 while ($op->{sock}) { $op->event_step }
58 sub ipc_atfork_child {
60 $self->{lei}->lei_atfork_child;
61 $self->SUPER::ipc_atfork_child;
65 my ($lei, $fh, $x) = @_;
66 my $set_kw = $lei->{opt}->{kw};
67 my $fmt = $lei->{opt}->{'format'};
70 my $buf = do { local $/; <$fh> } //
71 return $lei->child_error(1 >> 8, <<"");
74 my $eml = PublicInbox::Eml->new(\$buf);
75 _import_eml($eml, $lei->{sto}, $set_kw);
77 my $cb = PublicInbox::MboxReader->can($fmt);
78 $cb or return $lei->child_error(1 >> 8, <<"");
79 --format $fmt unsupported for $x
81 $cb->(undef, $fh, \&_import_eml, $lei->{sto}, $set_kw);
84 $lei->child_error(1 >> 8, "<stdin>: $@") if $@;
89 my $lei = $self->{lei};
92 open my $fh, '<', $x or return $lei->child_error(1 >> 8, <<"");
95 _import_fh($lei, $fh, $x);
97 $lei->fail("$x unsupported (TODO)");
103 _import_fh($self->{lei}, $self->{0}, '<stdin>');