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 # parent class for LeiImport, LeiConvert
5 package PublicInbox::LeiInput;
9 sub check_input_format ($;$) {
10 my ($lei, $files) = @_;
11 my $opt_key = 'in-format';
12 my $fmt = $lei->{opt}->{$opt_key};
14 my $err = $files ? "regular file(s):\n@$files" : '--stdin';
15 return $lei->fail("--$opt_key unset for $err");
17 require PublicInbox::MboxLock if $files;
18 require PublicInbox::MboxReader;
19 return 1 if $fmt eq 'eml';
20 # XXX: should this handle {gz,bz2,xz}? that's currently in LeiToMail
21 PublicInbox::MboxReader->reads($fmt) or
22 return $lei->fail("--$opt_key=$fmt unrecognized");
26 # import a single file handle of $name
27 # Subclass must define ->eml_cb and ->mbox_cb
29 my ($self, $ifmt, $fh, $name, @args) = @_;
31 my $buf = do { local $/; <$fh> } //
32 return $self->{lei}->child_error(1 << 8, <<"");
33 error reading $name: $!
35 $self->eml_cb(PublicInbox::Eml->new(\$buf), @args);
37 # prepare_inputs already validated $ifmt
38 my $cb = PublicInbox::MboxReader->reads($ifmt) //
39 die "BUG: bad fmt=$ifmt";
40 $cb->(undef, $fh, $self->can('mbox_cb'), $self, @args);
45 my ($self, $lei, $inputs) = @_;
46 my $in_fmt = $lei->{opt}->{'in-format'};
47 if ($lei->{opt}->{stdin}) {
49 $lei->fail("--stdin and @$inputs do not mix");
50 check_input_format($lei) or return;
51 $self->{0} = $lei->{0};
53 my $net = $lei->{net}; # NetWriter may be created by l2m
54 my $fmt = $lei->{opt}->{'in-format'};
56 # e.g. Maildir:/home/user/Mail/ or imaps://example.com/INBOX
57 for my $input (@$inputs) {
58 my $input_path = $input;
59 if ($input =~ m!\A(?:imaps?|nntps?|s?news)://!i) {
60 require PublicInbox::NetReader;
61 $net //= PublicInbox::NetReader->new;
62 $net->add_url($input);
63 } elsif ($input_path =~ s/\A([a-z0-9]+)://is) {
65 if (($in_fmt // $ifmt) ne $ifmt) {
66 return $lei->fail(<<"");
67 --in-format=$in_fmt and `$ifmt:' conflict
71 require PublicInbox::MboxLock;
72 require PublicInbox::MboxReader;
73 PublicInbox::MboxReader->reads($ifmt) or return
74 $lei->fail("$ifmt not supported");
76 require PublicInbox::MdirReader;
77 $ifmt eq 'maildir' or return
78 $lei->fail("$ifmt not supported");
80 return $lei->fail("Unable to handle $input");
82 } elsif (-f $input) { push @f, $input }
83 elsif (-d _) { push @d, $input }
84 else { return $lei->fail("Unable to handle $input") }
86 if (@f) { check_input_format($lei, \@f) or return }
87 if (@d) { # TODO: check for MH vs Maildir, here
88 require PublicInbox::MdirReader;
91 if (my $err = $net->errors) {
92 return $lei->fail($err);
94 $net->{quiet} = $lei->{opt}->{quiet};
95 require PublicInbox::LeiAuth;
96 $lei->{auth} //= PublicInbox::LeiAuth->new;
99 $self->{inputs} = $inputs;